 // jSnow, a jQuery Plugin v1.1.mod1  
 // Licensed under GPL licenses.  
 // Copyright (C) 2009 Nikos "DuMmWiaM" Kontis, dummwiam@gmail.com  
 // http://www.DuMmWiaM.com/jSnow  
 // Modified 2009~  
 (function ($) {  
   $.fn.jSnow = function (h) {  
     var j = $.extend({},  
     $.fn.jSnow.defaults, h);  
     var k, WIN_HEIGHT;  
     setWaH();  
     var l = j.flakes;  
     var m = j.flakeCode;  
     var n = j.flakeColor;  
     var o = j.flakeMinSize;  
     var p = j.flakeMaxSize;  
     var q = j.fallingSpeedMin;  
     var r = j.fallingSpeedMax;  
     var s = j.interval;  
     var t = j.zIndex;  
     var useGif = false;  
     if ($.browser.msie && (parseFloat($.browser.version) < 8))  
       useGif = true;  
     if ($.browser.msie && (parseFloat($.browser.version) < 8) && t == "auto")  
       t = 0;  
     var u = $("<div \/>");  
     u.css({  
       width: k + "px",  
       height: 1,  
       display: "block",  
       overflow: "visible",  
       position: "absolute",  
       top: $("html").scrollTop() + 1 + "px",  
       left: "1px",  
       zIndex: t  
     });  
     $("#telBanner").prepend(u);  
     $("html").css({  
       "overflow-y": "scroll",  
       "overflow-x": "hidden"  
     });    var v = Array();  
     generateFlake(l, false);  
     setInterval(animateFlakes, s);  
     window.onresize = setWaH;  
     function setWaH() {  
       k = $('body').width();  
       WIN_HEIGHT = window.innerHeight || document.documentElement.clientHeight  
       WIN_HEIGHT -= 50;  
     };  
       u.css({  
         top: "-100px"  
       })  
     function generateFlake(a, b) {  
       a = a || 1;  
       b = b || false;  
       var i = 0;  
       for (i = 0; i < a; i++) {  
         var c = $("<span \/>");  
         var d = o + Math.floor(Math.random() * p);  
         var e = m[Math.floor(Math.random() * m.length)];  
         if (e.indexOf(".gif") != -1 || e.indexOf(".png") != -1) {  
           var f = new Image();  
           if (useGif)  
             e = e.replace("png", "gif");  
           f.src = e;  
           e = "<img src='" + e + "' alt='jSnowFlake'>"  
         }  
         c.html(e).css({  
           color: n[Math.floor(Math.random() * n.length)],  
           fontSize: d + "px",  
           display: "block",  
           position: "absolute",  
           cursor: "default",  
           "z-index": t  
         });  
         $(u).append(c);  
         f_left = Math.floor(Math.random() * (k - c.width() - 50)) + 25;  
         f_top = (b) ? -1 * c.height() : Math.floor(Math.random() * (WIN_HEIGHT - 50));  
         var g = Math.floor(Math.random() * 90);  
         jQuery.data(c, "posData", {  
           top: f_top,  
           left: f_left,  
           rad: Math.random() * 50,  
           i: Math.ceil(q + Math.random() * (r - q)),  
           swingRange: g  
         });  
         c.css({  
           top: f_top + "px",  
           left: f_left + "px"  
         });  
         v.push(c)  
       }  
     };  
     function animateFlakes() {  
       var i = 0;  
       for (i = v.length - 1; i >= 0; i--) {  
         var f = v[i];  
         var a = jQuery.data(f, "posData");  
         a.top += a.i;  
         var b = Number();  
         b = Math.cos((a.rad / 180) * Math.PI);  
         a.rad += 2;  
         var X = a.left - b * a.swingRange;  
         f.css({  
           top: a.top + "px",  
           left: X + "px"  
         });  
         if (a.top > WIN_HEIGHT) {  
           jQuery.removeData(f);  
           f.remove();  
           v.splice(i, 1);  
           generateFlake(1, true)  
         }  
       }  
     };  
     return this  
   };  
   $.fn.jSnow.defaults = {  
     flakes: 30,  
     fallingSpeedMin: 1,  
     fallingSpeedMax: 3,  
     flakeMaxSize: 20,  
     flakeMinSize: 10,  
     flakeCode: ["&bull;"],  
     flakeColor: ["#fff"],  
     zIndex: "auto",  
     interval: 50  
   }  
 })(jQuery);  

var activeOverlay;

function modalDialog(dialogId) {

	var obj = this;

	this.appendOverlay = function() {
		var overlay = $('<div />', {
				id: dialogId + 'Overlay',
				'class': 'dialogOverlay'
		});
		if($('#' + activeOverlay).length) {
			obj.closeDialog(activeOverlay);
		}
		overlay.css('height', $('body').height());
		if ($('div.dialogOverlay').length) {
			overlay.css('z-index', '30')
		};
		overlay.appendTo('body');
		activeOverlay = dialogId;
	},
	this.show = function() {
		var dialog = $('<div />', {
				id: dialogId,
				'class': 'dialog'
		});
		if (dialogId.match(/iz-/)) {
			dialog.addClass('izLayer');
		}
		if (dialogId.match(/pf-/)) {
			dialog.addClass('pf');
		}
		this.appendOverlay();
		$.ajax({
			type: 'GET',
			url: 'static/html/' + dialogId + '.html',
			cache: false,
			dataType: 'text',
			success: function(response) {
				dialog.html(response);
				dialog.appendTo('body');
				obj.position(dialog);
				if (dialogId === 'tudtade') {
					swfobject.embedSWF('static/swf/cvitamin_demo_q3.swf', 'flashTudtade', '571', '370', '10', false, {}, {wmode: 'transparent'});
				}
			}
		});
		this.bindEvents();
	},
	this.position = function(dialog) {
		var topPos = $(window).height()/2 - dialog.outerHeight()/2, 
			leftPos = $(window).width()/2 - dialog.outerWidth()/2;
		dialog.css({
			top: topPos > 0 ? topPos : 0,
			left: leftPos > 0 ? leftPos : 0
		});
	},
	this.bindEvents = function() {
		$('#' + dialogId).find('a.closeDialog').live('click', function(e) {
			obj.closeDialog(dialogId);
			e.preventDefault();
		});
	},
	this.unbindEvents = function() {
		$('#' + dialogId).find('a.closeDialog').die('click');
	},
	this.closeDialog = function(id) {
		obj.unbindEvents();
		$('#' + id).remove();
		$('#' + id + 'Overlay').remove();
	}
	this.show();
}

function initVideok() {
	var videoList = $('#videoList'),
		mainId = 'ZjRaMRmNYOA',
		userVideos = [{yt_id: 'QPmVNiItDP4', title: 'Tél - Mindig minden körülmények között!'},
					{yt_id: '1giMj3uPPfw', title: 'Haverok, kabriók, actimel'},
					{yt_id: 'NpKA-f6V6zw', title: 'Avenger Production - Actimel'},
					{yt_id: 'X_oQksUEI9g', title: 'Actimelitikum - Az egészség korszaka'},
					{yt_id: 'QWyISaRY_Ek', title: 'Rocker Mikulás (Sosem Ugyanaz Comedy Klub )'},
					{yt_id: '3I-fHMEzr6E', title: 'Actimel-Mindentől megvéd'},
					{yt_id: 'r-RAkOyPCyA', title: 'Megcsináltuk!'},
					{yt_id: 'aQwpEEgs81k', title: 'Jump&like'},
					{yt_id: 'AS6x8TCafOk', title: 'Bikinis kocsi mosást vállalunk!'},
					{yt_id: 'PBoH9sBkMYg', title: 'Vízipisztolyozás mínusz 2 fokban'},
					{yt_id: 'pjDVxtqyW20', title: 'gyümölcsszezon télen is!'},
					{yt_id: 'wamIeG68jhk', title: 'Balatonszepezdi tükör jégkori 2011.01.08.dv'},
					{yt_id: '2IhMWRilqgc', title: 'Actimel Olaszországban is'},
					{yt_id: 'BYnZ9hRyFoQ', title: 'Parádfürdő hócsúszka'},
					{yt_id: '8LzwNCLvNYc', title: 'Bike hero'},
					{yt_id: 'PJ_-q7-IvD4', title: 'Napozás februárban'},
					{yt_id: '8s2TVbmFk4s', title: 'Tonale 2010 01 09 - BD.avi'}],
		params = {
			allowScriptAccess: 'always',
			allowfullscreen: 'true'
		},
		atts = { id: 'ytPlayer' };
	swfobject.embedSWF('http://www.youtube.com/e/' + mainId + '?enablejsapi=1&playerapiid=ytplayer&rel=0&autohide=1&showinfo=0&modestbranding=1', 'ytPlayer', '640', '363', '8', null, null, params, atts);
	$.ajax({
		url: 'http://gdata.youtube.com/feeds/api/users/actimelhu/uploads?v=2&alt=jsonc',
		dataType: 'jsonp',
		success: function(r) {
			var videos = r.data.items;
			for (var i=0, l=videos.length; i<l; i++) {
				var video = videos[i];
				videoList.append('<li><a href="#' + video.id  + '"><img src="http://i.ytimg.com/vi/' + video.id + '/hqdefault.jpg" alt="" width="85" height="58" />' + video.title + '</a></li>');
			}
			for (var i=0, l=userVideos.length; i<l; i++) {
				var video = userVideos[i];
				videoList.append('<li><a href="#' + video.yt_id  + '"><img src="http://i.ytimg.com/vi/' + video.yt_id + '/hqdefault.jpg" alt="" width="85" height="58" />' + video.title + '</a></li>');
			}
			videoList.find('li').eq(0).addClass('selected');
		}
	});
	
	videoList.delegate('a', 'click', function(e){
		var link = this.href,
			player = document.getElementById('ytPlayer');;
		player.cueVideoByUrl('http://www.youtube.com/e/' + link.substr(link.indexOf('#')+1) + '?enablejsapi=1&playerapiid=ytplayer&rel=0&autohide=1&showinfo=0&modestbranding=1');
		videoList.find('li.selected').removeClass('selected');
		$(this).parent('li').addClass('selected');
		e.preventDefault();
	});

}

function initTippek() {
	var images = $('#tippek').find('img.toCount'),
		tips = $('#tippek').find('p'),
		links = $('#tippek').find('a'),
		position = -849,
		actual = 0,
		showHideTip = function(p, dir, next, enableButtons) {
			p.filter(':visible').animate({
				opacity: dir
			}, {
				duration: 500,
				complete: function() {
					if (next) {
						showHideTip(next, 1, 0, true);
					}
					if (enableButtons) {
						links.removeClass('disabled');
					}
					
				}
			});
		};
	showHideTip(tips.eq(0), 1);
	links.bind('click', function(e){
		var dir = this.id,
			nextActual,
			nextActualImg;
		if (this.className !== 'disabled') {
			links.addClass('disabled');
			if (dir === 'prev') {
				nextActual = actual-1;
				if (nextActual === -1) {
					nextActual = 9;
				}
			}
			else {
				nextActual = actual+1;
				if (nextActual === 10) {
					nextActual = 0;
				}
			}
			showHideTip(tips.eq(actual), 0, tips.eq(nextActual));
			nextActualImg = images.eq(nextActual);
			position-=(nextActualImg.position()).left - (Math.round((873-nextActualImg.width())/2));
			$('#tippek').find('span').css('margin-left', position);
			actual = nextActual;
			}
		e.preventDefault();
	});
}

function onYouTubePlayerReady(playerId) {}

function initPage() {
	var pageId = document.body.id;

	$('#tabLink').bind('click', function(e){
		var cont = $('#fbCont'),
			toLeft = (cont.position().left == 0 ? '-182px' : 0);
		cont.animate({
			left: toLeft
		}, 500);
		e.preventDefault();
	});

	if (pageId === 'page-index') {
	     $().jSnow({  
	       flakes : 150,  
	       flakeCode : [  
	         "static/img/pic_pehely_07.png",
	         "static/img/pic_pehely_03.png",
	         "static/img/pic_pehely_07.png",
	         "static/img/pic_pehely_01.png",
	         "static/img/pic_pehely_05.png",
	         "static/img/pic_pehely_03.png",
	         "static/img/pic_pehely_02.png",
	         "static/img/pic_pehely_04.png",
	         "static/img/pic_pehely_06.png"
	       ],  
	       fallingSpeedMax : 2,
	       fallingSpeedMin : 0,
	       zIndex : 2,  
	       interval : 30  
	     });  
	}
	if (pageId === 'page-mivan') {
		$('#mivan, #mivan-pw').find('li').bind('mouseover', function(){
			var divs = $('#mivan, #mivan-pw').find('div');
			divs.css('display', 'none').eq(this.id.substr(10)).css('display', 'block');
		});
	}
	if (pageId === 'page-izek') {
		$('#izekLista').find('a').bind('click', function(e){
			var link = this.href;
			modalDialog(link.substr(link.indexOf('#')+1))
			e.preventDefault();
		});
	}
	if (pageId === 'page-videok') {
		initVideok();
	}
	if (pageId === 'page-tippek') {
		initTippek();
	}
	if (pageId === 'page-faq') {
		$('dt').bind('click', function(){
			var self = $(this);
			if (self.hasClass('active')) {
				self.removeClass();
				self.next().slideUp();
			}
			else {
				$('dt.active').removeClass();
				$('dd:visible').slideUp();
				self.addClass('active').next().slideDown();
			}
		});
	}
	if (pageId === 'page-powerfruit') {
		var params = {
				allowScriptAccess: 'always',
				allowfullscreen: 'true',
				wmode: 'transparent'
			},
			atts = { id: 'ytPlayer' };
		swfobject.embedSWF('static/swf/powerfruit_acerola_q3.swf', 'flashAcerola', '123', '100', '10', false, {}, {wmode: 'transparent'});
		swfobject.embedSWF('http://www.youtube.com/e/ZjRaMRmNYOA?enablejsapi=1&playerapiid=ytplayer&rel=0&autohide=1&showinfo=0&modestbranding=1&autoplay=1', 'ytPlayer', '640', '390', '8', null, null, params, atts);
		$('a.openDialog').live('click', function(e){
			var link = this.href;
			modalDialog(link.substr(link.indexOf('#')+1))
			e.preventDefault();
		});
	}

	if (pageId === 'page-roadshow') {
		var cityIds = {};

		function initMap() {
			var cities = {},
				bigMarkers = [],
				smallMarkers = [],
				zoomedMarkers = [];
			if (typeof google!='undefined' && google.maps.ZoomControlStyle) {
				$.ajax({
					url: '/ajax.php',
					type: 'get',
					data: 'action=getLocations',
					dataType: 'json',
					success: function(r) {
						if (r.status === 'ok') {
							var bigIcon = new google.maps.MarkerImage(
									'/static/img/pic_marker-big.png',
									new google.maps.Size(30,30),
									new google.maps.Point(0,0),
									new google.maps.Point(15,15)
								),
								smallIcon = new google.maps.MarkerImage(
									'/static/img/pic_marker-small.png',
									new google.maps.Size(15,15),
									new google.maps.Point(0,0),
									new google.maps.Point(8,8)
								);
							for (var i=0, l=r.locations.length; i<l; i++) {
								var loc = r.locations[i].location,
									city = loc.city;
								if (!cities[city]) {
									cities[city] = [];
								}
								cities[city].push(new google.maps.LatLng(loc.lat, loc.lng));
								cityIds[loc.id] = {
									name: loc.name,
									address: loc.address,
									lat: loc.lat,
									lng: loc.lng
								}
							}
							for (var c in cities) {
								var allPos = cities[c],
									pos = allPos[0],
									moreThanOne = allPos.length>1,
									marker = new google.maps.Marker({
										map: map,
										position: pos,
										icon: moreThanOne ? bigIcon : smallIcon
									});
								$(marker).data({
									pos: pos,
									city: c
								});
								if (moreThanOne) {
									google.maps.event.addListener(marker, 'click', function(){
										var data = $(this).data();
										map.setCenter(data.pos);
										map.setZoom(data.city === 'Budapest' ? 9 : 12);
									});
									bigMarkers.push(marker);
								}
								else {
									google.maps.event.addListener(marker, 'click', function(){
										var data = $(this).data();
										callAjax(false, data.pos.Pa, data.pos.Qa);
									});
									smallMarkers.push(marker);
								}
							}
							google.maps.event.addListener(map, 'zoom_changed', function() {
								var zoomLevel = map.getZoom();
								if (zoomLevel > 7) {
									for (var i in bigMarkers) {
										bigMarkers[i].setMap(null);
									}
									bigMarkers.length = 0;
									if (!zoomedMarkers.length) {
										for (var c in cities) {
											var allPosZoomed = cities[c];
											if (allPosZoomed.length>1) {
												for (var i=0, l=allPosZoomed.length; i<l; i++) {
													var zoomedMarker = new google.maps.Marker({
														map: map,
														position: allPosZoomed[i],
														icon: smallIcon
													});
													zoomedMarkers.push(zoomedMarker);
													$(zoomedMarker).data({
														pos: allPosZoomed[i]
													});
													google.maps.event.addListener(zoomedMarker, 'click', function(){
														var data = $(this).data();
														callAjax(false, data.pos.Pa, data.pos.Qa);
													});
												}
											}
										}
									}
								}
								if (zoomLevel < 8 && !bigMarkers.length) {
									for (var i in zoomedMarkers) {
										zoomedMarkers[i].setMap(null);
									}
									zoomedMarkers.length = 0;
									for (var c in cities) {
										var allPos = cities[c];
										if (allPos.length > 1) {
											var bigMarker = new google.maps.Marker({
												map: map,
												position: allPos[0],
												icon: bigIcon
											});
											$(bigMarker).data({
												pos: allPos[0],
												city: c
											});
											bigMarkers.push(bigMarker);
										}
										google.maps.event.addListener(bigMarker, 'click', function(){
											var data = $(this).data();
											map.setCenter(data.pos);
											map.setZoom(data.city === 'Budapest' ? 9 : 12);
										});
									}
								}
								if (zoomLevel < 13 && bottleMarker) {
									bottleMarker.setMap(null);
									bottleMarker = null;
								}
							});
						}
					}
				});
			}
			else {
				setTimeout(initMap, 100);
			}
		}

		function codeAddress(address) {
			if (address == '') return false;
			geocoder.geocode(
				{'address': address},
				function(results, status) {
					if (status == google.maps.GeocoderStatus.OK) {
						callAjax(results);
					} else {
						alert('Nincs találat! Próbáld más keresőszavakkal!');
					}
				}
			);
		}

		function callAjax(results, lat, lng) {
			$.ajax({
				url : '/ajax.php',
				data : {
					action			: 'getLocationsNear',
					lat				: results ? results[0].geometry.location.lat() : lat,
					lng				: results ? results[0].geometry.location.lng() : lng
				},
				dataType : 'json',
				type: 'POST',
				success: function (response) {
					var nearest_location,
						html = '';
					if (response.location_count == 1) {
						var city = cityIds[response.times[0].id];
						html += '<strong>' + city.name + '</strong><ul>';
						for (var i=0, l=response.times.length; i<l; i++)
							html += '<li> - ' +  response.times[i].time + '</li>';
						html += '</ul>';
						nearest_location = new google.maps.LatLng(city.lat, city.lng);
					}
					else {
						nearest_location = new google.maps.LatLng(cityIds[response.times[0].id].lat, cityIds[response.times[0].id].lng); 
						html += '<ul>';
						for (var j=0, k=response.location_count; j<k; j++) {
							var time = response.times[j];
							html += '<li>- ' + time.time + ' - <a href="#nogo" data-lat="' + cityIds[time.id].lat + '" data-lng="' + cityIds[time.id].lng + '">' + cityIds[time.id].name + '</a></li>';
						}
						html += '</ul>';
					}
					map.setCenter(nearest_location);
					map.setZoom(14);
					if (bottleMarker) {
						bottleMarker.setPosition(nearest_location);
					} else {
						bottleMarker = new google.maps.Marker({
							map: map,
							position: nearest_location,
							icon: new google.maps.MarkerImage(
								'/static/img/pic_marker.png',
								new google.maps.Size(28,66),
								new google.maps.Point(0,0),
								new google.maps.Point(14,33)
							)
						});
					}
					bottleMarker.setAnimation(google.maps.Animation.DROP);
					$('#hidden').show().find('#list').html(html).scrollTop(0);
				}
			});
		}

		initMap();
		$('form').submit(function() {
			var address = document.getElementById('field-location').value;
			if (address === 'Unicornia' || address === 'unicornia') {
				addCornify();
			}
			else {
				codeAddress(address, true);
			}
			
			return false;
		});

		$('#list').on('click', 'a', function(e){
			var data = $(this).data(),
				newLoc = new google.maps.LatLng(data.lat, data.lng);
			map.setCenter(newLoc);
			bottleMarker.setPosition(newLoc);
			bottleMarker.setAnimation(google.maps.Animation.DROP);
			e.preventDefault();
		});

	}
}

$('document').ready(function(){
	initPage();
});

var kkeys = [],
	konami = "38,38,40,40,37,39,37,39,66,65";
jQuery(document).keydown(function(e) {
	kkeys.push( e.keyCode );
	if ( kkeys.toString().indexOf( konami ) >= 0 ){
		jQuery(document).unbind('keydown',arguments.callee);
		addCornify();
	}
});

function addCornify() {
	jQuery.getScript('http://www.cornify.com/js/cornify.js',function(){
		cornify_add();
		for (var i=0; i<30; i++)
			setTimeout(cornify_add, i*1000);
	});
}


