var themePictures = new Array();
var themeUrls = new Array();
//var themePictures = window.MyPictures;
var themePath = ""; //path to the picture
var picThemePosition = 1; //first picture to show in slideshow
var picThemePositionNext; // nextPicture
var picThemeRotator = null;
var picThemeRotatorSpeed = 5000; //speed of slideshow (in ms)
var picThemeRotatorFadeOutSpeed = 500; //speed of fadeOut effect in slideshow (in ms)

function getPictures() {
	var pictures = new Array();
	$("#intro img").each(function(i) {
		pictures.push(this.src);
	});
	return pictures;
}

function getUrls() {
	var URLs = new Array();
	$("#intro a").each(function(i) {
		URLs.push(this.href);
	});
	return URLs;
}

function setTab(tab) {
	if (typeof tab == "undefined") tab = getCookie_("detailTab" + numForm) ? getCookie_("detailTab" + numForm) : 1;
	setCookie_("detailTab" + numForm, tab);
	var ul = document.getElementById('tabnavul');
	var li = ul.getElementsByTagName('LI');
	var formPref = "tabContent";
	var tabs = document.getElementById('tabs');
	tabs.className = "stab" + tab;
	
	for (var i = 0; i < li.length; i++) {
		if (i + 1 == tab) {
			document.getElementById(formPref + (i+1)).style.display = "block";
		} else {
			document.getElementById(formPref + (i+1)).style.display = "none";
		}
		//alert(li[i]);
	}
}

function setCookie_(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
      //alert(curCookie);
  document.cookie = curCookie;
}

function getCookie_(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

function handleInputClicked(inputObj, hideInputFakeText) {
	if(hideInputFakeText)
		inputObj.className = 'search middle';
	else 
		if (inputObj.value == "") inputObj.className = 'search middle faketextSearch';
	} 

try {
	document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}

//obladani polozek v kosiku
function baskedAdd(basket) {
	var curVal = $("#p" + basket).attr("value");
	curVal = parseInt(curVal);
	curVal++;
	$("#p" + basket).attr("value", curVal);
}

function baskedRemove(basket) {
	var curVal = $("#p" + basket).attr("value");
	curVal = parseInt(curVal);
	curVal--;
	if (curVal < 1) {
		alert("Počet kusů daného zboží musí být aspoň jeden!\nPro odstranění zboží z kosmetického kufříku klikněte na tlačítko ODSTRANIT.");
		curVal = 1;
	}
	$("#p" + basket).attr("value", curVal);
}


function setThemePic(position, pic, clicked) {
	if (typeof position == "undefined") position = 1;
	if (typeof pic == "undefined") pic = themePictures[0];
	if (typeof clicked == "undefined") clicked = false;
	
	picThemePosition = position;
	picThemePositionNext = ((position + 1) > themePictures.length) ? 1 : position + 1;
	picNext = themePictures[picThemePositionNext - 1];
	position = position - 1;
	
	if ($("#stripImageSrc").css("display") == "none") {
		$("#stripImageSrc").attr("src", $("#stripImageSrc2nd").attr("src"));
		$("#stripImageSrc").show();
	}
		
	$("#stripImageSrc2nd").attr("src", themePath + pic);
	$("#stripImageSrc").fadeOut(picThemeRotatorFadeOutSpeed);
	
	for (var y = 1; y <= themePictures.length; y++) {
		if (picThemePosition != y) $("#stripLinksImage" + y).text("").attr("class", "stripLinkOff");
		if (picThemePosition == y) $("#stripLinksImage" + y).text(y + ".").attr("class", "stripLinkOn stripLinkActive");
	}
	
	
}

jQuery.preloadImages = function() {
  for(var i = 0; i < arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

function firmFormData() {
	if ($("#customer_type").attr("value") != 2) {
		$("#ico").attr("value", "");		
		$("#dic").attr("value", "");
		$("#only_firm_data").hide();
	} else {
		$("#only_firm_data").show();
	}
}

function setTransferText() {
	/*
	if (typeof transfer != "undefined")
		$("#transferText").html(transfer[$("#transfer").attr("value")]['text']);
	*/	
}	

function setFinalPrice(_price) {
	if (typeof transfer != "undefined") {
		$("#packingPrice").html(formatNumber(balne, 2, 1, ".", ",", "", "", ",-", ""));
		$("#transferPrice").html(formatNumber(transfer[$("#transfer").attr("value")]['price'][_price], 2, 1, ".", ",", "", "", ",-", ""));
		$("#transferPriceDisctount").html(transfer[$("#transfer").attr("value")]['disctount']);
		$("#totalPrice").html(formatNumber(transfer[$("#transfer").attr("value")]['price'][_price] + _cenaCelkem, 2, 1, ".", ",", "", "", ",-", ""));
	}
	
}

/*
myNum - formatovane cislo
dec - pocet desetin
hideDec - 1/0 - zobrazuj/nezobrazuj desetiny, pokud jsou nulove
thouSep - oddelovac tisicu
decSep - oddelovac desetiny
prefA - 1. prefix (treba $ se pise pred castkou)
prefB - 2. prefix (urcen pro zaporne cislo) - pro "minus" pokud se ma znamenko zobrazovat
postA - 1. postfix (treba pro Kc za castkou)
postB - 2. postfix (urcetn pro zaporne cislo) - napr. v ucetnictvi se mam dojem nekde muzou 
pasiva oznacovat misto "minusem" pred cislem zkratkou za cislem
*/
function formatNumber(myNum,dec,hideDec,thouSep,decSep,prefA,prefB,postA,postB) {    
    if (isNaN(parseInt(myNum))) 
        return "NaN";
    var numst = myNum.toString();
    myNum = (numst.indexOf(",") >= 0) ? myNum.replace(",",".") : myNum;
    var x = Math.round(myNum * Math.pow(10,dec));
    if (x >= 0) prefB=postB='';
    var y = (''+Math.abs(x)).split('');
    var z = y.length - dec;
    if (y[z+1] == 0 && y[z] == 0 && hideDec) {
        y.splice(z, 2);
    } else {
    	if (x == 0) {
    		y.splice(z, 0);
    	} else {
        y.splice(z, 0, decSep);
      }
    }
        while (z > 3) {
            z-=3; y.splice(z,0,thouSep);
        }
    var r = prefA+prefB+y.join('')+postA+postB;
    return r;
}

//page onload ...

$(document).ready(function() {
	
	themePictures = getPictures(); // array of themepics
	themeUrls = getUrls();
	
	$("#logo").append('<img src="/images/page/logo.gif" height="98" width="237" alt="Heaven4Skin" class="logo-print" />');
	
	$("#logo-flash")
	.flash({
			swf: '/flash/logo.swf',
			width: 237,
			height: 98,
			wmode: 'transparent',
			flashvars: {
				clickthru: '/'
			}
		});
		
		$("#logo").css('background-image', 'none');
	
	//$("div.container").dropShadow({left: -1, top: -1, opacity: 0.3, blur: 2, color: '#000'});
	
	/*
	$("#loginLink").add(".loginLink").click(function() {
		if ($(".registerFormFly").css("display") == "block") {
		 	$(".registerFormFly").hide();
		 	$(".kosik").show();
		} else {
			$(".registerFormFly").show();
			$(".kosik").hide();
			$("#username").focus();
			window.scrollTo(0,0);
		}
		return false;
	});
	*/
	
	$("#loginLink")
		.add(".loginLink")
			.attr("href", $("#loginLink").attr("href") + "?iframe=true&width=450&height=220&lars:nolayout=1&layoutId=2254")
			.attr("rel", "loginbox");
	$("a[rel^='loginbox']").prettyPhoto({padding: 40, theme: 'light_square', language_: 'cs'});
	
	if(document.getElementById('username')) $("#username").focus();
	
	
	$("#podminky")
		.attr("href", $("#podminky").attr("href") + "?iframe=true&width=600&height=400&lars:nolayout=1&layoutId=2254&solo=1")
		.attr("rel", "podmbox")
		.click(function() {return false;});
	
	$("a[rel^='podmbox']").prettyPhoto({padding: 40, theme: 'light_square', language_: 'cs'});
	
	//&lars:nolayout=1&layoutId=2254
	
	
	//search input
	$("#search").mouseover(function() {
		//alert($.trim($(this).attr("value")));
	});
	$("#search")
		.attr("class", "search middle")
		.focus(function() {handleInputClicked(this, true);})
		.blur(function() {handleInputClicked(this, false);})
	;
	
	if ($.trim($("#search").attr("value")) == "") $("#search").addClass("faketextSearch");
	
	//fade efekt nad obrazkem
	/*
	$(".produktPict")
		.hover(
       function(){
           $(this).find("img").stop().fadeTo(400, 0.1);
       },
       function(){
           $(this).find("img").stop().fadeTo(400, 1.0	);
       }
   );
  */
	
	/*
	var i = 0;
	
	$(".produkt").hover(function() {
	++i;	
	$("#search").attr("value", i);
	
	$(this).find(".productPictFlip").stop().flip({
											direction: 'tb',
											color: '#B34212',
											speed: 0,
											content: "<div>test2</div>",
											onBefore: function(){$(this).find(".productPictFlip").stop()},
											onEnd: function(){$(this).find(".productPictFlip").stop();}
										})
									},
									
	function() {
	$(this).find(".productPictFlip").stop().flip({
											direction: 'bt',
											color: '#B34212',
											speed: 0,
											content: "<div>test</div>",
											onBefore: function(){$(this).find(".productPictFlip").stop()},
											onEnd: function(){$(this).find(".productPictFlip").stop()	}
										});
									
									i = -1;
									}								
									
								);
	*/
	
	//pocet komentaru v zalozce
	numComments = (typeof numComments == 'undefined') ? 0 : numComments;
	$(".tab2 a span").html(numComments);
	
	//tlacitka pridat a uprat pocet polozek v kosiku

	$(".addListener").each(function(i) {
		var inp = $(this).find(".changeCount");
		inp.attr("id", "p" + i);
		$(this).find(".countAdd")
			.show()
			.click(function() {
				baskedAdd(i);
				return false;
			});
		
		$(this).find(".countRemove")
			.show()
			.click(function() {
				baskedRemove(i);
				return false;
			});
		
		//alert(val.attr("value"));
	});
	
	$(".detailDescriptionCont").each(function(i) {
		var inp = $(this).find(".inpCount");
		inp.attr("id", "p" + i);
		$(this).find(".countAdd")
			.show()
			.click(function() {
				baskedAdd(i);
				return false;
			});
	});
	
	
	//emaily do fora
	$(".discussionMessageContent").each(function(i) {
		var username = $(this).find(".username").html();
		var email1 = $(this).find(".e1").html();
		var email2 = $(this).find(".e2").html();
		if (email1 && email2) {
			$(this).find(".username").html("<a href='mailto:" + email1 + "@" + email2 + "'>" + username + "</a>");
		}
	});
	
	//kosik url v zahlavi
	var kosikUrl = $(".kosik").find("a").attr("href");
	if (typeof kosikUrl != 'undefined') {
		 $(".kosik")
		 	.attr("class", "kosik pointer")
		 	.click(function() {
		 		location.href = kosikUrl;
		 	});
		 	//.attr("title", "Zobrazit košík");
	} else {
		$(".kosik")
			.attr("class", "kosik pointer")
			.click(function() {
				alert("Váš kosmetický kufřík je prázdný.");
			});
	}
	
	$("#addVoucher").click(function() {
		var voucher = $("#voucher").attr("value");
		if (voucher == "") {
			alert("Musíte vložit slevový voucher!");
			return false;
		}
	});
	
	//is HP
	if (document.getElementById("hp")) {
		
		//themePictures navigation and mouseovers
		var pictIndex = 0;
		jQuery.each(themePictures, function(i, pic){
			i++;
			$("#introLinks").append(
				$(document.createElement("a"))
				.attr("class",  (picThemePosition == i) ? "stripLinkOn stripLinkActive" : "stripLinkOff")
				.attr("href", "javascript:void(0);")
				.attr("id", "stripLinksImage" + i)
				//.text(i)
				.mouseover(function() {
						$(this)
							.text(i + ".")
							.attr("class", (picThemePosition == i) ? "stripLinkOn stripLinkActive" : "stripLinkOn");
				})
				.mouseout(function() {
						$(this)
							.text((picThemePosition == i) ? i + "." : "")
							.attr("class", (picThemePosition == i) ? "stripLinkOn stripLinkActive" : "stripLinkOff");
				})
				.click(function() {
						setThemePic(i, pic, true);
						clearInterval(picThemeRotator);
				})	
					);	
		});
		
		//second themePicture
		$("#intro").append(
				$(document.createElement("img"))
					.attr("id", "stripImageSrc2nd")
					.attr("src", themePath + themePictures[picThemePositionNext - 1])
					.attr("width", "731")
					.attr("height", "312")
					.click(function() {
						var newUrl = themeUrls[picThemePosition - 1];
						if (newUrl != "") {
							document.location = newUrl;
						}
					})
				);
		//init theme
		setThemePic();
		//show theme navigation only if js enabled
		$("#introLinks").show();
		
		//thenePicture auto rotation ...
		picThemeRotator = setInterval(function() {
      var picThemeLoaded = true;

      for (var i = 0; i < themePictures.length; i++) {
         var img = themePath + themePictures[i];
         if (img.complete == false)
            picThemeLoaded = false;
      }

      if (picThemeLoaded) {
         setThemePic(picThemePositionNext, themePictures[picThemePositionNext - 1]);
         //clearInterval(picThemeRotator);
      }
   	}, picThemeRotatorSpeed);
		
		
	}
	
	//lightbox pro detail produktu
	if (typeof gallery_images != 'undefined') {
		var prodAlt = $("#detailProductPhoto").find("img").attr("alt");
		for (var i = 0; i < gallery_images.length; i++) {
			if (gallery_images[i] != main_image) $("#detailProductPhoto").append("<a href=\"/script/productImage?id=" + gallery_images[i] +"\" rel=\"lightbox[gal]\" class=\"hide\"><img alt= \"" + prodAlt + "\" /></a> ");
		}
		//call lightbox		
		$("a[rel^='lightbox']").prettyPhoto({padding: 40, theme: 'light_square', language_: 'cs'});
	}
	
	//stripped table
	$("tr:even").addClass("even");
	
	//registerForm
	$("#customer_type")
		.change(function() {
			firmFormData();
		})
		.keyup(function() {
			firmFormData();
		})
		;
	
	if ($("#customer_type")) firmFormData();
	
	$("#autofillAddress").show();
	$("#autofillAddress a").click(function(event) {
		event.preventDefault();
		$("#sendStreet").attr("value", $("#contactStreet").attr("value"));
		$("#sendCity").attr("value", $("#contactCity").attr("value"));
		$("#sendCountry").attr("value", $("#contactCountry").attr("value"));
		//$("#sendState").attr("value", $("#contactState").attr("value"));
		$("#sendZip").attr("value", $("#contactZip").attr("value"));
	});
	
	//cena dopravy
	
	if ($("#payMethod")) {
		setTransferText();
		setFinalPrice($("#payMethod").val());
	}
	
	//dokoncit nakup
	$("#dokoncitNakup").submit(function() {
		if ($("#confirmOrder").attr("checked") == false) {
			alert("Musíte souhlasit s obchodními podmínkami!");
			$("#confirmOrder").focus();
			return false;
		}
		/*
		if (confirm("Přejete si dokončit nákup?")) {
			return true;
		}
		return false;
		*/
		return true;
	});
	
	//karty
		
	$("#payMethodLine").hide();
	if ($("#transfer").attr("value") != 0) {
		$("#payMethodLine").show();
	}
	
	var payMethodClone = $("#payMethod").clone();
	
	if (typeof $("#transfer").attr("value") != "undefined") {
		if ($("#transfer").attr("value") != 0) {
			var _trVal = $("#transfer").val();
			$("#payMethodLine").show();
			$("#payMethod").html(payMethodClone.html());
			$("#payMethod").find("option").each(function(i, val) {
				var _val = $(this).val().split(":");
				if (_val[0] != _trVal && _val != 0) {
					$(this).remove();
				} else {
					var payMethodText = $(this).text().split(":");
					$(this).text(payMethodText[1]);
				} 
			});
		} else {
			$("#payMethod").attr("value", 0);
			$("#cardType").hide();
			$("input[name='cardType']").each(function() {
				$(this).attr("checked", false);
			});
		}
	}
	
	$("#transfer").change(function() {
		
		$("#_transfer").val($(this).val());
		$("#_payMethod").val("");
		$("#_cardType").val("");
		
		$("#payMethod").val(0);
		$("#cardType").hide(1000);
		$("input[name='cardType']").each(function() {
				$(this).attr("checked", false);
			});
		
		if ($(this).val() != 0) {
			var _trVal = $(this).val();
			$("#payMethodLine").show(1000);
			
			$("#payMethod").html(payMethodClone.html());
			
			$("#payMethod").find("option").each(function(i, val) {
				//alert(val);
				//$(this).hide();
				var _val = $(this).val().split(":");
				if (_val[0] != _trVal && _val != 0) {
					
					$(this).remove();
				} else {
					$(this).removeAttr("selected");
					var payMethodText = $(this).text().split(":");
					$(this).text(payMethodText[1]);
				} 
			});
			
		} else {
			$("#payMethod").attr("value", 0);
			$("#cardType").hide(1000);
			$("#payMethodLine").hide(1000);
			$("input[name='cardType']").each(function() {
				$(this).attr("checked", false);
			});
		}
		setFinalPrice($("#payMethod").val());
	});
	
	$("#cardType").hide();
	if (typeof $("#payMethod").attr("value") != "undefined") {
		var payMethod = $("#payMethod").attr("value").split(":");
		if (payMethod[1] == 3) {
			$("#cardType").show();
		}
	}
	$("#payMethod").change(function() {
		
		var payMethod = $(this).attr("value").split(":");
		
		$("#_payMethod").val(payMethod[1]);
		$("#_cardType").val("");
		
		
		$("input[name='cardType']").each(function() {
				$(this).attr("checked", false);
			});
		if (payMethod[1] == 3) {
			$("#cardType").show(1000);
		} else {
			$("#cardType").hide(1000);
		}
		setFinalPrice($(this).val());
	});	
	
	$("input[name='cardType']").click(function() {
		$("#_cardType").val($(this).val());
	});
	
	//odeslat kosik 
	$("#submitBasket").submit(function() {
		var payMethod = $("#payMethod").attr("value").split(":");
		if (payMethod[1] == 3) {
			var cardTypeChecked = false;
			$("input[name='cardType']").each(function() {
				if ($(this).attr("checked") == true)
					cardTypeChecked = true;
			});
			if (!cardTypeChecked) {
				alert("Zvolte typ karty!");
				return false;
			}
		}
	});
	
	//doporucit
	$("#doporucit").click(function() {
		var produkt = $(".detailDescriptionContTop h1").html();
		var body = bezdiak(produkt) + "%0D%0A"+location.href;
		parent.location = "mailto:&Subject=Odkaz na produkt z webu www.heaven4skin.cz&Body=" + body;
	});
	
	//presunuti produktu
	$("#productBreadNav").html($("#productBreadNavTemp").html());
	$("#productBreadNavTemp").remove();
	
	//detailIcons
	$(".detailIcons").find("img").each(function() {
		//alert($(this).attr("alt"));
		$(this).wrap("<div class='detailImgDescrC'></div>").after("<div class='detailImgDescr'>"+$(this).attr("alt")+"</div>");
		$(this).attr("alt", "");
		$(this).attr("title", "");
	});
	$(".detailIcons .detailImgDescrC")
	.mouseover(function() {
		$(this).find("div").show();
	})
	.mouseout(function() {
		$(this).find("div").hide();
	});
	
	//cardtype select
	$(".cardType").find("input[name='cardType']").each(function() {
		if ($(this).attr("value") == cardType) {
			$(this).attr("checked", "checked");
		}
	});
	
	$("#showAll").click(function() {
		//document.forms.list['counts'].value = "1000";
		//document.forms.list.submit();
		//document.location.href = document.location.href + "?showAll="
	});
	
	$("#showParts").click(function() {
		//document.forms.list['counts'].value = "9";
		//document.forms.list.submit();¨
		//var custurl = document.location.href.split("?");
		//document.location.href = custurl[0];
	});
	
	
});

sdiak = "áäčďéěíĺľňóô öŕšťúů üýřžÁÄČĎÉĚÍĹĽŇÓÔ ÖŔŠŤÚŮ ÜÝŘŽ";
bdiak = "aacdeeillnoo orstuu uyrzAACDEEILLNOO ORSTUU UYRZ";

function bezdiak(txt)
{
  tx = "";
  for(p = 0; p < txt.length; p++)
  {
    if (sdiak.indexOf(txt.charAt(p)) != -1)
    {
      tx += bdiak.charAt(sdiak.indexOf(txt.charAt(p)));
    }
    else tx += txt.charAt(p);
  }
  return tx;
} 

//GA
	try {
		var pageTracker = _gat._getTracker("UA-10061630-1");
		pageTracker._trackPageview();

	} catch(err) {}