window.onerror=function(desc,page,line,chr){
/* alert('JavaScript error occurred! \n'
  +'\nError description: \t'+desc
  +'\nPage address:      \t'+page
  +'\nLine number:       \t'+line
 );
 */
}

function loginFbUser(data){
	$.getJSON("/ajax/facebooklogin.php?id="+data[2][0]['session']['uid']+"",
			function(data){
			if (data == 1) {
			document.location.href="/";
			}else{
			alert('Nepodařilo se přihlásit přes účet na facebooku. Zkontrolujte zda jste registrován a pokud ano, tak zda  máte účet propojen s facebookem.')
			document.location.href = '/eshop/registrace/';
			}
			});


}
function ValidateNotEmpty( values){
	for(var i=0; i<values.length; i++){
		
		if(values[i] == ''){
			alert("Vyplňte prosím požadované údaje.");
			return false;
		}
	}
	return true;
}
function formatTitle(title, currentArray, currentIndex, currentOpts) {
    return '<div id="tip7-title"><span><a href="javascript:;" onclick="$.fancybox.close();"><img src="/data/closelabel.gif" /></a></span>' + (title && title.length ? '<b>' + title + '</b>' : '' ) + 'Obrázek ' + (currentIndex + 1) + ' z ' + currentArray.length + '</div>';
}


$(document).ready(function() 
{

$("#zobraz-obchodni-podminky").click(function(){
			if($("#obchodni-podminky-box").css("display") == 'block'){
				$("#obchodni-podminky-box").slideUp(300);
			}else{
				$("#obchodni-podminky-box").slideDown(300);
			}
			return false;
		});
	$('.hideme').click(function(){
			$(this).hide();
			$('.lastpart').fadeIn('slow');
	});
	$('.kompat').toggle(function(){
		$('div.compat').fadeIn('fast');
	},function(){
		$('div.compat').hide();

	});


	// vase nazory v pravo
	var $yourOpinion = $("div#yourOpinion");
	$yourOpinion.show(); //aby se zobrazoval jen pro zapnute JS
	$yourOpinion.hover(function() {
		$(this).css("cursor", "pointer");
		$(this).animate({left: '+=12'}, 300);
	}, function() {
	     $(this).animate({left: '-=12'}, 300);
	});

	$yourOpinion.colorbox({href:"/inc/opinionForm.php",width:"710px",height:"410px", close:"", opacity:0.7,onOpen: function() {
			
		var $heureka = $("body").children("div").eq(0);
		if ($heureka.css("z-index") == "2147483647") $heureka.css("z-index", 10);
			
	}});
	$("button#closeYourOpinion").live("click",(function() {
		$.colorbox.close();
	}));
	
	$("a.rastroPopup").fancybox({
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic',
		'speedIn'	:	600,
		'speedOut'	:	200,
		'width'		:	840,
		'height'	:	"99%",
		'overlayShow'	:	true,
		'autoScale'	:	false,
		//'titleShow'	:	false,
		'scrolling'	:	'no',
		'centerOnScroll':	true
	});
  
	$.ui.autocomplete.prototype._renderItem = function (ul, item) {

            var nazev = item.label.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(this.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
            return $("<li></li>")
                    .data("item.autocomplete", item)
                    .append("<a href='" + item.url +"' title='" + nazev + "'>" + nazev + "</a>")
                    .appendTo(ul);

        };

	$.ui.autocomplete.prototype._renderMenu = function (ul, items) {

			var self = this,
			currentCategory = "";
			$.each( items, function( index, item ) {

				if ( item.category != currentCategory ) {

					ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
					currentCategory = item.category;
				}

				self._renderItem( ul, item );
			});

	};

	// hledani
	$(function(){

		//attach autocomplete
		$("input.searchField").autocomplete({

			source: function(req, add){

				$.getJSON("/ajax/fullTextSearch.php?callback=?", req, function(data) {

					var suggestions = [];
					$.each(data, function(i, val){
						suggestions.push(eval(val));
					});

					add(suggestions);
				});
			},
			minLength: 2,
			delay: 300,
			position: { my: "right top", at: "right bottom"}
			,select: function(event, ui) {

			        var text = ui.item.label;
				
				$.getJSON("/ajax/saveFullText.php?text="+text+"&callback=?");
				window.open(ui.item.url,"_self");
				return false;
				
			}
			
		}).keydown(function(e){
		    if (e.keyCode === 13) {
			$(this).closest('form').trigger('submit');
		    }});
	});

        var tabbed = $(".tabbed");
	$(tabbed).not(":first").css("display","none");
	$(".nav2 li a").click(function() {

	        var selectorId = $(this).attr("rel");
		var elementSelected = $("#"+selectorId);
		var visibility = elementSelected.not(":visible");
		
		if (visibility.length != 0) {

			$(".nav2 li.selected").removeClass("selected");
			$(tabbed).not("id[="+selectorId+"]").stop(true, true).hide();
			$(this).parents("li").eq(0).addClass("selected");
			elementSelected.fadeIn(1200);
	
		}
	});
	
	try	
	{
		$("a[rel=product_images]").fancybox({
			'transitionIn'		: 'normal',
			'transitionOut'		: 'normal',
			'titlePosition' 	: 'over',
			'overlayColor'	    : '#000',
			'overlayOpacity' : '0.7',
			'padding'			: 0,
			'transitionIn'		: 'elastic',
			'transitionOut'		: 'elastic',
			'titlePosition' 	: 'over',
			'titleShow': true,
			'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
			    return '<span id="fancybox-title-over">Obrázek ' +  (currentIndex + 1) + ' / ' + currentArray.length + ' ' + title + '</span>';
			}
		});
	}
	catch (e)
	{
	
	}
});

/*
*	posouva obrazky
*/
function slideImage(idGroup,idImg)
{
	imageGroup = $("[id^="+idGroup+"]");

	if (imageGroup.length > 0)
	{
		var lengthImageGroup = imageGroup.length;
		var activeId = getActive(imageGroup);

		if (idImg == 'left')
		{
			if (1 != activeId)
			{
				idImg = activeId-1;
				$("#"+idGroup+"_"+activeId).fadeOut('normal');
				$("#anchor_"+idGroup+"_"+activeId).removeClass('act');
			}
		}
		else if (idImg == 'right')
		{
			if (lengthImageGroup != activeId)
			{
				idImg = activeId+1;
				$("#"+idGroup+"_"+activeId).fadeOut('normal');
				$("#anchor_"+idGroup+"_"+activeId).removeClass('act');
			}
		}
		else if (IsNumeric(idImg))
		{
			if (idImg != activeId)
			{
				$("#"+idGroup+"_"+activeId).fadeOut('normal');
				$("#anchor_"+idGroup+"_"+activeId).removeClass('act');
			}
		}

		$("#"+idGroup+"_"+idImg).fadeIn('normal');
		$("#anchor_"+idGroup+"_"+idImg).addClass('act');
		
	}
}

function getActive (group)
{
	var id = false;
	group.each( function(index, Element)
	{
		if ($("#"+Element.id).css("display") == 'block')
		{
			id = index+1;
		}
	})
	return id;
}
/*
function _hideActive(idGroup)
{
	var imageGroup = $("[id^="+idGroup+"]");
	
	imageGroup.each( function(index, Element)
	{
		if (Element.style.display != 'none')
		{
			//$("#"+Element.id).css('display','none');
			$("#"+Element.id).fadeOut('normal');
		}

	})
}
*/
function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
}


function notSpaces (checkedVar )
{
	var i = 0;
	for (j=0; j < checkedVar.length; j++)
	{
		if (checkedVar.charCodeAt(j) == 32) i++;
	}
	
	if (i >= 3)
	{
		return new Array(false, "nesprávný formát");
	}
	else
	{
		return new Array(true, "");
	}
	
}
function isMinLength (checkedVar )
{
	var minLength = 2;
	if (checkedVar.length >= minLength)
	{
		return new Array(true, "");
	}
	else
	{
		return new Array(false, "příliš krátké");
	}

}

function isNotEmpty( checkedVar )
{
	if(checkedVar)
	{
	   return new Array(true, "");
	}
	else
	{
	  return new Array(false, "není vyplněno");
	}
}

function isPostalCode( checkedVar )
{
	if( (parseInt(checkedVar) || parseInt(checkedVar) == 0) && checkedVar.length == 5 )
	{
	   return new Array(true, "");
	}
	else
	{
	  return new Array(false, "není platné PSČ");
	}
}

function isEmail( email )
{
	var regStr = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if( !regStr.test(email)){
		return new Array(false, "nemá platný formát");
	}
	return new Array(true, "");
}

	
function odeslatConfirm(){
	$("#orderOk").val("yes");
	return true;//confirm('Opravdu odeslat?');
}


// uprava 23.02.2010 - odstraneni voleb
function validateUserData(sFormId, aExceptions)
{
		if(aExceptions == undefined) aExceptions = new Array();
  		var minPwdLength = 5;
		var maxResultInfoRows = 4;
		var minFieldLength = 2;
		var form = document.getElementById(sFormId);
		var errorFields = new Array();

		var requiredFieldsIds = new Array
		(
				new Array('name', 'jméno', 'isNotEmpty;isMinLength;notSpaces'),
				new Array('sname', 'příjmení', 'isNotEmpty;isMinLength;notSpaces'),
				new Array('street', 'ulice, č.p.', 'isNotEmpty;isMinLength;notSpaces'),
				new Array('city', 'město', 'isNotEmpty;isMinLength;notSpaces'),
				new Array('psc', 'PSČ', 'isNotEmpty;isPostalCode'),
				new Array('email', 'e-mail', 'isNotEmpty;isEmail'),
				new Array('tel', 'telefon', 'isNotEmpty')
		);
  
		// delivery enabled
  		var deliveryDisabled = document.getElementById('delivery_address');
  		if(!deliveryDisabled.checked)
  		{
    			deliveryDiffers = false;
		}
		else
		{
	  			deliveryDiffers = true;
	  			requiredFieldsIds.push
	  			(
						new Array('dname', 'jméno (dodací adresa)', 'isNotEmpty'),
						new Array('dsname', 'příjmení (dodací adresa)', 'isNotEmpty'),
						new Array('dstreet', 'ulice, č.p. (dodací adresa)', 'isNotEmpty'),
						new Array('dcity', 'město (dodací adresa)', 'isNotEmpty'),
						new Array('dpsc', 'PSČ (dodací adresa)', 'isNotEmpty;isPostalCode')
				);
		}

		// kontrola poli
		var result = true;
		var resultInfo = new Array();
		for(i = 0; i < requiredFieldsIds.length; i ++)
		{
	  			var fieldId = requiredFieldsIds[i][0];
	  			var fieldName = requiredFieldsIds[i][1];
	  			var fieldRef = document.getElementById(fieldId);
	  			var fieldValue = fieldRef.value;
	  			var fieldChecks = (requiredFieldsIds[i][2].indexOf(";") != -1) ? requiredFieldsIds[i][2].split(";") : new Array(requiredFieldsIds[i][2]);

    			fieldRef.className = 'tdinput'; // reset border color na default

	  			for(j = 0; j < fieldChecks.length; j ++) // projede vsechny typy kontrol pro kazde pole
	  			{
						aCheckResults	= eval(fieldChecks[j] + "(fieldValue);");
						checkResult		= aCheckResults[0];
						checkInfo		= 	aCheckResults[1];
	    				if( !checkResult )// nalezena chyba pri jedne z def. kontrol pole
						{
								result = false;
								//resultInfo.push('Pole <strong>' + fieldName + '</strong> ' + checkInfo + '.');
								resultInfo.push('Pole ' + fieldName + ' ' + checkInfo + '.\n');
								errorFields.push(fieldRef);
								fieldRef.className = 'incorrectlyFilled tdinput';
								fieldRef.value = "";
								break;
						}
				}
		}
	/*
	// EXCEPTIONS
	for(i = 0; i < aExceptions.length; i ++)
	{
    sException = aExceptions[i];
    
    switch(sException)
    {
      case 'regPwd':
        var pwd = document.getElementById('regPwd');
        var pwdConfirmation = document.getElementById('regPwdConfirmation');
        pwd.className = 'rqd';
        pwdConfirmation.className = 'rqd';
        // equal pwds
        if( pwd.value != pwdConfirmation.value )
        {
          result = false;
          resultInfo.push( "<strong>Hesla</strong> nejsou shodná." );
          pwdConfirmation.className = 'rqd incorrectlyFilled';
          pwdConfirmation.value = "";
        }
        // min length
        if( pwd.value.length < minPwdLength )
        {
          result = false;
          pwd.className = 'rqd incorrectlyFilled';
          pwdConfirmation.className = 'rqd incorrectlyFilled';
          resultInfo.push( "<strong>Heslo</strong> musí být minimálně " + minPwdLength + " znaků dlouhé." );
          pwd.value = "";
          pwdConfirmation.value = "";
        }
      break;
      case 'legalAgreement':
        var legalAgreement = document.getElementById('legalAgreement');
        if( !legalAgreement.checked )
        {
          result = false;
          resultInfo.push( "<strong>Souhlas s obchodními podmínkami</strong> je vyžadován." );
        }
      break;
    	}
  	}
	*/
  		// RESULT
		if(!result)
		{
	 			/*if(resultInfo.length > 4)// oseknuti na max 4 prvky pole
	  			{
	    				resultInfo = resultInfo.slice(0, maxResultInfoRows);
	    				//resultInfo.push("<em>... počet chyb je větší než dovoluje zobrazení ...</em>");
				}*/
				alert(resultInfo.join(""));
				if (errorFields.length > 0) errorFields[0].focus();
				//resultInfo.push("<strong>Chybně vyplněná pole byla pro přehlednost zvýrazněna.</strong>");
	  			//changeErrContent('warning', 'Dopustil/a jste se chyb !', resultInfo);
	  			//switchErr("show");
	  			return false;
		}
		else
		{
	  		return odeslatConfirm() ? true : false;
		}

}
// validace kontatkniho formu
function validateContactForm(sFormId, aExceptions)
{

		if(aExceptions == undefined) aExceptions = new Array();
  		var minPwdLength = 5;
		var maxResultInfoRows = 4;
		var minFieldLength = 2;
		var form = document.getElementById(sFormId);
		var errorFields = new Array();

		var requiredFieldsIds = new Array
		(
				new Array('name', 'Vaše jméno', 'isNotEmpty;isMinLength;notSpaces'),
				new Array('email', 'Váš e-mail', 'isNotEmpty;isEmail'),
				new Array('text', 'Text zprávy', 'isNotEmpty'),
				new Array('spamblock', 'Spam', 'isNotEmpty')
		);
  
		// kontrola poli
		var result = true;
		var resultInfo = new Array();
		for(i = 0; i < requiredFieldsIds.length; i ++)
		{
	  			var fieldId = requiredFieldsIds[i][0];
	  			var fieldName = requiredFieldsIds[i][1];
	  			var fieldRef = document.getElementById(fieldId);
	  			var fieldValue = fieldRef.value;
	  			var fieldChecks = (requiredFieldsIds[i][2].indexOf(";") != -1) ? requiredFieldsIds[i][2].split(";") : new Array(requiredFieldsIds[i][2]);

    			fieldRef.className = ''; // reset border color na default

	  			for(j = 0; j < fieldChecks.length; j ++) // projede vsechny typy kontrol pro kazde pole
	  			{
						aCheckResults	= eval(fieldChecks[j] + "(fieldValue);");
						checkResult		= aCheckResults[0];
						checkInfo		= 	aCheckResults[1];
	    				if( !checkResult )// nalezena chyba pri jedne z def. kontrol pole
						{
								result = false;
								//resultInfo.push('Pole <strong>' + fieldName + '</strong> ' + checkInfo + '.');
								resultInfo.push('Pole ' + fieldName + ' ' + checkInfo + '.\n');
								errorFields.push(fieldRef);
								fieldRef.className = 'incorrectlyFilled';
								fieldRef.value = "";
								break;
						}
				}
		}
  		// RESULT
		if(!result)
		{
	 			/*if(resultInfo.length > 4)// oseknuti na max 4 prvky pole
	  			{
	    				resultInfo = resultInfo.slice(0, maxResultInfoRows);
	    				//resultInfo.push("<em>... počet chyb je větší než dovoluje zobrazení ...</em>");
				}*/
				alert(resultInfo.join(""));
				if (errorFields.length > 0) errorFields[0].focus();
				//resultInfo.push("<strong>Chybně vyplněná pole byla pro přehlednost zvýrazněna.</strong>");
	  			//changeErrContent('warning', 'Dopustil/a jste se chyb !', resultInfo);
	  			//switchErr("show");
	  			return false;
		}
		else
		{
	  		return odeslatConfirm() ? true : false;
		}

}
  

