
function setCookie(cookieName, cookieValue, nDays) {
	var today = new Date();
	var expire = new Date();
	if (nDays == null || nDays == 0) {
		nDays=1;
	}
	expire.setTime(today.getTime() + 3600000 * 24 * nDays);
	document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString();
}


$(function() {

	$(document.body).addClass("js");
	
	// detect IE
	var ie = false;
	var ie6 = false;
	if ($.browser.msie) {ie = true;}
	if ($.browser.version == "6.0") {ie6 = true;}


	// show nav bubble on over
	if (ie) {
		$("nav li").hover(function() {
			$(this).find(".bubble").show().css({top: "34px"});
		}, function() {
			$(this).find(".bubble").hide().css({top: "-200px"});
		});
	} else {
		$("nav li").hover(function() {
			$(this).find(".bubble").filter(":not(:animated)").animate({opacity: "show", top: "34px"}, 200);
		}, function() {
			$(this).find(".bubble").animate({opacity: "hide", top: "50px"}, 50);
		});
	}


	// function for easy tabs
	$(".tabs", "#content").each(function() {

		var tab = this;
		$(".tab", tab).hide();

		if(window.location.hash) {
			var tabId = window.location.hash.split("#")[1];
			$("#" + tabId).show();
			$("#tab-" + tabId).addClass('active');
			Cufon.refresh();

			/*if (!$(tab).hasClass("filter")) {
				$(".tabsNavi li a[href$=#" + tabId + "]", tab).parent().addClass("active");
			}*/
		} else if ($(tab).hasClass("tabScroll")) {
			$(".tab:eq(1)", tab).show();
			$(".tabsNavi li:eq(1)", tab).addClass("active");
			bubbleLinksInit();
			Cufon.refresh();
		} else {

			/*if (!$(tab).hasClass("filter")) {
				$(".tab:first", tab).show();
			}*/
			//$(".tabsNavi li:first[id!='tab-viewAll']", tab).addClass("active");
			//$(".tabsNavi li:first", tab).addClass("active");
			// kvuli clankum
			if ($(".tabsNavi li:first", tab).attr('id') != 'tab-viewAll') {
				$(".tabsNavi li:first", tab).addClass("active");
			}

			$(".tab:first", tab).show();
			//$(".tab:eq(1)", tab).show();
			//$(".tabsNavi li:eq(1) a", tab).addClass("active");
			Cufon.refresh();
		}
		$(".tabsNavi li a", tab).click(function (event) {
			if(!$(tab).hasClass('filter')){
				event.preventDefault();
				$(".tabsNavi .active", tab).removeClass("active");
				$(this).parent().addClass("active");
				$(".tab", tab).hide();
				$($(this).attr("href")).show();

				if ($(tab).hasClass("tabScroll")) {
					bubbleLinksInit();
					productScroll();
				}
				Cufon.refresh();
			}
		});
	});



	if (document.body.id == "productLine") {
		$("#productList li", "body.js").hover(function() {
			if (ie) {
				$(this).filter(':not(#active)').find("span.bg").show();
				$(this).find("div.bubble").css({top: "210px"}).show();
			} else {
				$(this).filter(':not(#active)').find("span.bg").filter(':not(:animated)').fadeIn(300);
				$(this).find("div.bubble").filter(':not(:animated)').animate({opacity: "show", top: "210px"}, 300);
			}
		}, function() {
			if (ie) {
				$(this).filter(':not(#active)').find("span.bg").hide();
				$(this).find("div.bubble").hide();
			} else {
				$(this).filter(':not(#active)').find("span.bg").fadeOut(100);
				$(this).find("div.bubble").animate({opacity: "hide", top: "250px"}, 100);
			}
		});

		if ($("#productList")[0] && $("#productList").hasClass("mouseScroll")) {
			var div = $("#productList.mouseScroll"),
				ul = $("#productList > ul"),
				ulPadding = 0;

			var divWidth = div.width();

			var ulContentWidth = 80;
			$(">li", ul).each(function() {
				ulContentWidth += $(this).width();
			});
			ul.width(ulContentWidth);

			if (!ie6) {
				div.css({overflow: 'hidden'});
				mouseScrollInit(div, ulContentWidth);
			}
		}
	}



	// red box filter
	if ($("#redBoxBottomContent")[0]) {
		$("#redBoxBottomContent").mouseenter(function() {
			$(this).stop().animate({top: "-426px"}, 400);
		}).mouseleave(function() {
			$(this).delay(500).animate({top: "0"}, 200);
		});
	}

	if ($("#redBoxLeft")[0]) {
		$("#redBoxLeft").mouseenter(function() {
			$(this).stop().animate({left: "0px"}, 400);
		}).mouseleave(function() {
			$(this).delay(500).animate({left: "-187px"}, 200);
		});
	}


	// show related bubble on over
	if ($(".related > a", "#contentHorizontal")[0]) {
		$(".related > a", "#contentHorizontal").mouseenter(function() {
			$(this).next().show();
		});
		$(".related .bubbleBigger", "#contentHorizontal").mouseleave(function() {
			$(this).hide();
		});
	}



	// kids slider
	if ($.fn.selectToUISlider) {
		var loader = $(".loader", "#kidsSlider");
		$("select#kidYear").selectToUISlider({
			labels: 25,
			tooltip: false,
			sliderOptions: {
				/*range: "min",
				slide: function() {
					$(".ui-slider-range").width($(".ui-slider-handle")[0].style.left);
				},*/
				change: function(e, ui) {
					var value = ui.value + 1;

					$.ajax({
						type: "POST",
						url: "sweetie/fromSlidebar?months=" + value,
						beforeSend: function() {
							loader.show();
						},
						success: function(result) {
							loader.hide();

							$('#kidsList').html(result);

							page = 0;
							months = value;
							$('#kidsSlider p:first').html($('#sweeties_list_info').html());
							var count = $('#sweeties_selection_count').text() * 1;
							if ($('#kidsList li').length >= count) {
								$('#show_more_button').addClass('hidden');
							} else {
								$('#show_more_button').removeClass('hidden');
							}
						}
					});

				}
			}
		}).hide();

    if ($("select#kidYear").val() != 12) {
      //$("select#kidYear").val($("select#kidYear").val());
      $("select#kidYear").change();
    }
	}



	// jqtransform
	if($.fn.jqTransform) {
		$("fieldset", "#redBoxBottomContent").jqTransform();
		$("fieldset", "#redBoxLeftContent").jqTransform();
		$(".custom", "form").jqTransform();
		$(".blueCheck", "form").jqTransform();
		$(".greyCheck", "form").jqTransform();
		$(".radioCheck", "form").jqTransform();
		$(".anketa form, #anketaBanner form").jqTransform();
	}



	$("a[rel=showLoginForm]", "header").click(function(event) {
		event.preventDefault();
		$("#loginForm", "header").toggleClass("activeForm").find("#loginForm_username").focus();
		outClick();
	});



	$('#bottomSplash').submit(function() {
		//alert($('#bottomSplash').serialize());
		location.href = $('#bottomSplash').attr('action') + '?' + $('#bottomSplash').serialize();
		return false;
	});



	// product over
	if ($(".products")[0]) {
		if (!ie) {
			$(".products li a").hover(function() {
				$(this).find("span.bg").filter(':not(:animated)').fadeIn(150);
			}, function() {
				$(this).find("span.bg").fadeOut(150);
			});
		} else {
			$(".products li a").hover(function() {
				$(this).find("span.bg").show();
			}, function() {
				$(this).find("span.bg").hide();
			});
		}
	}


	// plus over
	if ($(".fotogallery")[0]) {
		plusOver();
	}



	// eyes over
	if ($("#colorInput")[0]) {
		$("#colorInput li").hover(function() {
			$(this).find("label").show();
		}, function() {
			$(this).find("label").hide();
		});
	}



	if ($.fn.colorbox) {
		photogalleryColorbox();

		$("a[rel=videoplayer]").colorbox({
			opacity: 0.8,
			close: "",
			rel: "nofollow",
			onOpen: function() {
				$("#cboxContent .h1div").remove();
			}
		});

		$("a[rel=lightbox]").bind("click", function(e) {
			e.preventDefault();
			var url = $(this).attr("href");
			$(this).colorbox({
				opacity: 0.8,
				transition: "none",
				close: "",
				rel: "nofollow",
				inline: true,
				href: url,
				onOpen: function() {
					colorBoxHead1($(this));
				},
				onComplete: function() {
					$(".custom", ".lightboxForm").jqTransform();
					inputState();
				}
			});
		});
	}

	$("a[rel=gPlayer]").click(function(e) {
		e.preventDefault();
		window.open(this.href, "_blank", "width=759,height=305,menubar=no,resizable=no,left=0,top=0");
	});

	$("a[rel=authorize], a[rel=delete]", "#dashboard .dashboardMessages").click(function(e) {
		e.preventDefault();
		var messElIn = $(this).closest(".c");

		var sendUrl, successClass, successText;

		if (e.currentTarget.rel == "delete") {
			sendUrl = "/?action=delete";
			successClass = "del";
			successText = "Vzkaz byl smazán.";
		} else {
			sendUrl = "/?action=authorize";
			successClass = "ok";
			successText = "Vzkaz byl přidán do deníčku.";
		}

		$.ajax({
			type: "POST",
			url: sendUrl,
			beforeSend: function() {
				messElIn.append('<img src="/images/loader2.gif">');
			},
			success: function(result) {
				messElIn.empty().addClass(successClass).append(successText);
			}
		});
	});



	if ($(".greenStrip").length > 0) {
		var moreTxt = $("a[rel=greenStripMoreTxt]");
		var lessTxt = $("a[rel=greenStripLessTxt]");
		var moreTxtEl = $(".moreTxt", ".greenStrip");

		moreTxt.click(function(e) {
			e.preventDefault();
			$(this).hide();
			lessTxt.show();
			moreTxtEl.slideDown(200);
		});
		lessTxt.click(function(e) {
			e.preventDefault();
			$(this).hide();
			moreTxt.show();
			moreTxtEl.slideUp(200);
		});
	}



	if ($("table").length > 0) {
		$("table tr").each(function() {
			$("td:last", $(this)).addClass("last");
		});
	}


	if ($(".tabScroll")[0]) {
		//bubbleLinksInit();
		window.setTimeout(productScroll, 1000);
	}


	/* show hide */
	$('#content #addNewThread').click(function(){
		$('.addThread').slideToggle(500);
	});

	$('.comment .panelRe a.re').click(function(){
		$(this).parent().parent().next('.commentReply').toggle(0);
		$(this).parent().parent().next('.commentReply').find('textarea').focus();
		$(this).parent().parent().hide();
	});

	$('.comment .commentReply a.reBig').click(function(){
		$(this).parent().parent().parent().parent().toggle(0);
		$(this).parent().parent().parent().parent().prev('.panelRe').show();
	});

	$('ul.comment li div.wrap a.re').click(function(event){
		event.preventDefault();
	});

	$('ul.comment li div.wrap a.reBig').click(function(event){
		event.preventDefault();
	});	

	/* media list */
	$('.mediaList ul.spots li a').hover(function(){
		$(this).find('.play').show();
	}, function(){
		$(this).find('.play').hide();
	});

	$('.mediaList ul.print li a').hover(function(){
		$(this).find('.show').show();
	}, function(){
		$(this).find('.show').hide();
	});

	$('ul.fotogallery li a').hover(function(){
		$(this).find('.show').show();
	}, function(){
		$(this).find('.show').hide();
	});

	/* Contest Swicth */

	$('#articles a#linkArticle1').click(function(event){
		event.preventDefault();
		$('#articles div#contentArticle1').show();
		$('#articles div#contentArticle2').hide();
		$('#articles div#contentArticle3').hide();
	});
	$('#articles a#linkArticle2').click(function(event){
		event.preventDefault();
		$('#articles div#contentArticle1').hide();
		$('#articles div#contentArticle2').show();
		$('#articles div#contentArticle3').hide();
	});
	$('#articles a#linkArticle3').click(function(event){
		event.preventDefault();
		$('#articles div#contentArticle1').hide();
		$('#articles div#contentArticle2').hide();
		$('#articles div#contentArticle3').show();
	});

	 if ($('#detailPerex').length > 0) {
		var detailPerex = $('#detailPerex').height();
		var setMinHeight = 530 - detailPerex;
		$('#heightDesc').css('min-height', setMinHeight);
	 }


	// Flying ballon
	if ($("#promoHp .promo11")[0]) {
		var ballon = $("#promoHp .promo11");
		var flyBallon = window.setTimeout(function() {
			ballon.animate({top: "-250px"}, {queue: false, duration: 1500, easing: "easeInOutSine"});
			window.setInterval(function() {
				ballon.animate({top: "-52px"}, {queue: false, duration: 1500, easing: "easeInOutSine", complete: function() {
					//ballon.animate({top: "-52px"}, {duration: 3000, complete: function() {
					setTimeout(function() {
						ballon.animate({top: "-250px"}, {queue: false, duration: 1500, easing: "easeInOutSine"});
					}, 3000);
					//}});
				}});
			}, 7500);
		}, 3500);
	}



  if ($('#loginForm').length > 0) {
    $('#loginForm, #loginForm2').submit(function () {
      //alert('sdfds');
      $.ogAjax({
        type: 'POST',
        url: $(this).attr('action'),
        dataType: "json",
        data: formQueryString($(this)),
        form: $(this),
        success: function(result) {
          //alert(result);
          window.location.reload();
        }
      });
      return false;
    });

    $('#resetPassword').submit(function () {
      //alert('sdfds');
      $.ogAjax({
        type: 'POST',
        url: $(this).attr('action'),
        dataType: "json",
        data: formQueryString($(this)),
        form: $(this),
        success: function(result) {
          ///alert(result.errors);
          $('#resetPassword .bubble').removeClass('hidden').hide().slideDown('fast');
          setTimeout(function() { $('#resetPassword .bubble').slideUp() }, 5000);
          //window.location.reload();
        }
      });
      return false;
    });
    
    $('#registration').submit(function () {
      $.ogAjax({
        type: 'POST',
        url: $(this).attr('action'),
        dataType: "json",
        data: formQueryString($(this)),
        form: $(this),
        success: function(result) {
          window.location = result.data.redirect;
        }
      });
      return false;
    });

  }


	inputState();
	centerContent();

	
	if($.browser.msie){
	  var redirect = window.setInterval(function() { $('#glow').toggle(); }, 2000);
   }else{
	  var redirect = window.setInterval(function() { $('#glow').animate({opacity: "show"}, 3000).animate({opacity: "hide" }, 3000); }, 2000);
   }
});



$(window).resize(centerContent);



function colorBoxHead1(el) {
	var element = el;
	if (typeof(el) == "object") { element = el.attr("rev"); }
	$("#cboxContent .h1div").remove();
	$("<h1/>").html(element).appendTo($("#cboxContent", "#colorbox")).wrap('<div class="h1div">');
	Cufon.replace('#cboxContent h1', {fontFamily: 'DaxCE-Medium'});
}



function productScroll() {
	var sUl = $(".productsImages ul");
	var params = { scale: "noscale", allowScriptAccess: "always", wmode: "transparent" };

	sUl.each(function() {
		var list = $(this);
		var listWidth = 0;
		var listScrollbar = list.next().children()[0].id;

		$(">li:visible", list).each(function() {
			listWidth += $(this).width() + 28;
		});

		list.parent().css({overflow: "hidden"});
		if (listWidth > 405) {
			list.width(listWidth);

			var flashvars = {
				callback: "doScroll",
				id: this.id,
				contentWidth: listWidth,
				maskWidth: 385,
				height: 8,
				easing: 2
			};

			swfobject.embedSWF("/swf/scrollbar.swf", listScrollbar, "385px", "26px", "10.0.0", "/swf/expressInstall.swf", flashvars, params, {});
		}
	});
}



function doScroll(a, b) {
	$("#" + a).css({left: b + "px"});
}



function outClick() {
	$(document.body).click(function(event) {
		var parents = $(event.target).parents();
		if (!parents.is("#userBox")) {
			$("#loginForm", "header").removeClass("activeForm");
		}

		if (!parents.is("li" , ".bubbleLine")) {
			$(".bubbleLine:visible").hide().parent().css({zIndex: 20});
		}
	});
}



function bubbleLinksInit() {
	var bubbleLinks = $(".products > ul > li > a");
	if(bubbleLinks[0]) {
		bubbleLinks.each(function(a, b) {
			var bubbleDiv = $(".bubbleLine", $(b).parent());
			var newleft = ($(b).outerWidth() + b.offsetLeft) - 138;

			if ($("ul", bubbleDiv).children().length == 2) { bubbleDiv.addClass("oneItem"); }
			if ($("ul", bubbleDiv).children().length == 3) { bubbleDiv.addClass("twoItems"); }

			if (($("footer")[0].offsetTop - 505) < bubbleDiv.closest(".row")[0].offsetTop) {
				bubbleDiv.addClass("rev");
			}

			bubbleDiv.css({left: newleft});

			$(b).click(function(event) {
				event.preventDefault();
				$(".bubbleLine:visible").hide().parent().css({zIndex: 20});
				bubbleDiv.show().parent().css({zIndex: 100});
				outClick();
			});

			$("a", bubbleDiv).click(function(event) {
				$(this).blur();
				event.preventDefault();
				var product2hide = bubbleDiv.prev();

				var prIm2show = $(this).attr("rel");

				var prIm2hideLi = bubbleDiv.closest(".products").next();
				prIm2hideLi.find("li[rel=" + product2hide.attr("rel") + "]").addClass("hidden");
				prIm2hideLi.find("li[rel=" + prIm2show + "]").removeClass("hidden");

				var productTextOld = $(this).text();
				var productTextNew = product2hide.text();
				var productTextNewRel = product2hide.attr("rel");

				product2hide.html($(this).text()).attr("rel", $(this).attr("rel"));
				$(this).text(productTextNew);
				$(this).attr("rel", productTextNewRel);
				$("li.first strong", bubbleDiv).html(productTextOld);
				bubbleDiv.hide().parent().css({zIndex: 20});
			});
		});


	}
}



function inputState() {
	// focus, blur inputs
	var textInputs = $("input[type=text],input[type=password], textarea");
	textInputs.focus(function(){
		$(this).parent().addClass("focus");
	}).blur(function(){
		$(this).parent().removeClass("focus");
	}).filter(":not(.noHide)").focus(function(){
		if ($(this).val() == '') {
			$("label[for=" + $(this).attr("id") + "]").addClass("hide");
		}
	}).blur(function(){
		if ($(this).val() == '') {
			$("label[for=" + $(this).attr("id") + "]").removeClass("hide");
		}
	}).each(function() {
		if ($(this).val() != "") {
			$("label[for=" + $(this).attr("id") + "]").addClass("hide");
		}
	});
}



function mouseScrollInit(el, ulW) {
	var elWidth = el.width();
	$(document.body).unbind("mousemove").mousemove(function(event) {
		var posleft2 = (event.pageX - el.offset().left) * (ulW-elWidth) / elWidth;
		el.scrollLeft(posleft2);
	});
}



function deb(arg) {
	console.log(arg);
}




function initPhotogallery() {
	$("a[rel=photogallery]").colorbox({
		opacity: 0.8,
		transition: "none",
		close: "",
		current: "{current} / {total}",
		onOpen: function() {
			$("#cboxLoadedContent").css({margin:"75px 0 40px"});
			colorBoxHead1($(this));
		},
		onLoad: function() {
			colorBoxHead1($(this));
		}
	});
}

function formQueryString(form) {
  var qs = '';
  $.each(form.serializeArray(), function(i, field) {
      qs += '&' + field.name + '=' + encodeURIComponent(field.value);
  });
  return qs.substring(1);
}


function centerContent() {
	if ((document.body.id == "hp" || document.body.id == "productLine") && $(".productContent").length == 0) {
		if ($(document.body).height() > 640) {
			$("#contentHorizontal").addClass("centerContent");
		} else {
			$("#contentHorizontal").removeClass("centerContent");
		}
	}

	if ($(document.body).height() < 530) {
		$('#promoHp').hide();
	} else {
		$('#promoHp').show();
	}
}


function plusOver() {
	if (!$.browser.msie) {
		$(".fotogallery a").hover(function() {
			$(this).find("span.show").filter(':not(:animated)').fadeIn(100);
		}, function() {
			$(this).find("span.show").fadeOut(100);
		});
	}
}


function photogalleryColorbox() {
	$("a[rel=photogallery]").colorbox({
		opacity: 0.8,
		transition: "none",
		close: "",
		current: "{current} / {total}",
		maxWidth: "700px",
		onOpen: function() {
			$("#cboxLoadedContent").css({margin:"75px 0 40px"});
			colorBoxHead1($(this));
		},
		onLoad: function() {
			colorBoxHead1($(this));
		}
	});
}


/* GA TRACKING EVENT*/
function trackGA(category, action, label) {
	if(category && action && label) {
		_gaq.push(['_trackEvent', category, action, label]);
	} 
}
