function isObject(id){
	 if(document.getElementById(id)){
		 return true;
	 } else {
		return false;
	};
}

function initSmoothMenu(menuid,cls) {
	if (isObject(menuid) == true) {
		ddsmoothmenu.init({
			mainmenuid: menuid, //menu DIV id
			orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
			classname: cls, //class added to menu's outer DIV
			//customtheme: ["#1c5a80", "#18374a"],
			contentsource: "markup" //"markup" or ["container_id", "path_to_menu_file"]
		})
		
	};
}


function initAjaxForms(){
$(".ajaxForm").each(function (){

	var ajaxForm = $(this).attr('id');
	var targetObj = $(this).attr('target');
	
	$.validator.methods.equal = function(value, element, param) {
		return value == param;
	};	

	var validator = $("#"+ajaxForm).validate({
		success: function(form) {},	
		error: function(form) {},	
		invalidHandler: function() {
			$("#formErrors").html("Formulář není správně vyplněný.<br>Počet špatně vyplněných položek: " + validator.numberOfInvalids() + " ");
			$("#formErrors").addClass("info-ko");
		 },	
		submitHandler: function(form) {

		 var options = { 
				target: targetObj,  // target element(s) to be updated with server response 
				replaceTarget:	false,
				resetForm: true,
				timeout:   3000 
			}; 		

			$('#'+ ajaxForm).ajaxSubmit(options);

			
			width = $(targetObj).innerWidth();
			height = $(targetObj).innerHeight();
			
			$(targetObj).prepend('<div style=\"display:none;\" class="ajax-loader-fader" id="ajax-loader-fader'+targetObj+'"></div><div class="ajax-loader-info" id="ajax-loader-info'+targetObj+'"><div class="ajax-loader-img" id="ajax-loader-img'+targetObj+'"><img src="/system/img/ajax-horizontal.gif"></div><div class="ajax-loader-text" id="ajax-loader-text'+targetObj+'">Moment ...</div></div>');
			
			leftMargin = (width-$("#ajax-loader-info"+targetObj).innerWidth())/2;
			topMargin = (height-$("#ajax-loader-info"+targetObj).innerHeight())/2;
			$("#ajax-loader-info"+targetObj).css('margin-left',leftMargin);
			$("#ajax-loader-info"+targetObj).css('margin-top',topMargin);
			$("#ajax-loader-fader"+targetObj).css('height',height);
			$("#ajax-loader-fader"+targetObj).css('width',width);	
			$("#ajax-loader-fader"+targetObj).fadeIn(200);		
			
			$("#"+id+' input').attr("disabled", true);
			$("#"+id+' textarea').attr("disabled", true);
			$("#"+id+' input:submit').attr("disabled", true);
			$("#formErrors").html("Čekejte formulář se odesílá.");
			$("#formErrors").addClass("info-ok");
  	 	}	
	});
});
}

function initEditForm(id){
if (isObject(id) == true) {


	$.validator.methods.equal = function(value, element, param) {
		return value == param;
	};	

	var validator = $("#"+id).validate({
		  invalidHandler: function() {		  
			$("#formErrors").html("Formulář není správně vyplněný.<br>Počet špatně vyplněných položek: " + validator.numberOfInvalids() + " ");
			$("#formErrors").addClass("info-ko");	
		  },		
		submitHandler: function(form) {
		var $inputs = $('#myForm input, #myForm textarea');
			$inputs.each(function() {
				if ($(this).val() == $(this)[0].title)
				{
					$(this).removeClass("defaultTextActive");
					$(this).val("");
				}				
			});
		   form.submit();
			$("#formErrors").html("Čekejte formulář se odesílá.");
			$("#formErrors").addClass("info-ok");		   
		 },				
		rules: {
				math: {
				}
		},
		messages: {
			math: {
				equal: "Vložte správný výsledek"
			}
		}
	});

	
}
}


function initPriceRange(id,currConversion,highestPrice,selectedLow,selectedHigh){

$("#"+id).slider({
			range: true,
			min: 0,
			max: highestPrice,
			values: [selectedLow,selectedHigh],
			slide: function(event, ui) {
				$("#lowestPrice").val(Math.floor(ui.values[0]));
				$("#highestPrice").val(Math.ceil(ui.values[1]));
				$("#minValue").html(Math.floor(ui.values[0]*currConversion));
				$("#maxValue").html(Math.ceil(ui.values[1]*currConversion));				
			}
		});
		$("#lowestPrice").val(Math.floor($("#"+id).slider("values", 0)));
		$("#highestPrice").val(Math.ceil($("#"+id).slider("values", 1)));
		$("#minValue").html(Math.floor($("#"+id).slider("values", 0)*currConversion));
		$("#maxValue").html(Math.ceil($("#"+id).slider("values", 1)*currConversion));		
}


$(document).ready(function(){	

	$(".butt").button();

	
	$("input.inputClick").click(function (){
		window.location = $(this).attr("link");
	});
	
	$("input.inputClickConfirm").click(function (){

		var location = $(this).attr("link");	
											
		$( "#"+$(this).attr("dialog") ).dialog({
					modal: true,
					draggable: false,
					resizable: false,
					buttons: {
						Ok: function() {
							window.location = location;	
						},
						Zavřít: function() {
							$( this ).dialog( "close" );
						}
					}
				});			
		
	});	


	
	var multiselect = $("body").find(".multiselect");
	if(multiselect.length > 0){ $(".multiselect").multiselect(); };	
	
	$(".externalCbox").colorbox({iframe:true, innerWidth:800, innerHeight:550});
	$(".menuCbox").colorbox({inline:true, href: function(){return $(this).attr('href');}, initialWidth:0, initialHeight:0, innerWidth:200});
	$(".helpBox").colorbox({inline:true, href: function(){return $(this).attr('href');}, initialWidth:0, initialHeight:0, innerWidth:200});
	$(".itemCbox").colorbox({
							onClosed:function(){ document.documentElement.style.overflow = "auto"; }, 
							iframe:true, 
							preloading:true, 
							overlayClose:false, 
							initialWidth:0, 
							initialHeight:0, 
							innerWidth:150, 
							innerHeight:150, 
							maxHeight:"90%"});
	

	
	$(".fotoCbox").colorbox({photo:true, slideshow:true, transition:"elastic", maxHeight:"90%", maxWidth:"90%", speed:300});
	
	if($("#contentType").val()!="ajax"){
	
	/*$("#bcTarget").barcode("9934567890128", "ean13");  */ 
	
	$(".hover.row1").hover(function() {
		$(this).stop().animate({ backgroundColor: "#fff" }, 200);
		},function() {
		$(this).stop().animate({ backgroundColor: "#fbfbfb" }, 500);
	});	

	$(".hover.row2").hover(function() {
		$(this).stop().animate({ backgroundColor: "#fff" }, 200);
		},function() {
		$(this).stop().animate({ backgroundColor: "#f1f1f1" }, 500);
	});	
	
	$(".hoverRows.row1").hover(function() {
		$(this).stop().animate({ backgroundColor: "#fff" }, 200);
		},function() {
		$(this).stop().animate({ backgroundColor: "#fbfbfb" }, 500);
	});	

	$(".hoverRows.row2").hover(function() {
		$(this).stop().animate({ backgroundColor: "#fff" }, 200);
		},function() {
		$(this).stop().animate({ backgroundColor: "#f1f1f1" }, 500);
	});	
	
	$(".hover.row2, .hover.row1").click(function() {
		$(this).find(".hoverHref").each(function() {
			$(this).find("a").each(function() {
				redirectPage($(this).attr("href"));
			});
		});   
	});
	
	$(".hoverRows.row2, .hoverRows.row1").click(function() {
		$(this).find(".hoverHref").each(function() {
			$(this).find("a").each(function() {
				redirectPage($(this).attr("href"));
			});    
        });
	})
	
	$("ul.sf-menu").supersubs({ 
            minWidth:    	12,   		// minimum width of sub-menus in em units 
            maxWidth:    	27,   		// maximum width of sub-menus in em units 
            extraWidth:  	1     		// extra width can ensure lines don't sometimes turn over 
                               			// due to slight rounding differences and font-family 
        }).superfish({ 
            delay:       	1000, 
			animation:   {height:'show',easing:'easeInOutElastic'},		//animation:   {opacity:'show',height:'show'},   fade-in and slide-down animation 
            speed:       	'fast', 	// faster animation speed 
            autoArrows:  	true,		// disable generation of arrow mark-up 		
            dropShadows: 	true        // disable drop shadows 
        });  							// call supersubs first, then superfish, so that subs are 
                         				// not display:none when measuring. Call before initialising 
                         				// containing tabs for same reason. 	
	
		
		initEditForm("myForm");
		initAjaxForms();
		initSmoothMenu('smoothmenu1','ddsmoothmenu');
		initSmoothMenu('smoothmenu2','ddsmoothmenu2');		
		
		toggleMenu('.operationMenu','toggleElementOpened');	
		
		$(".signin").click(function() {
                $("div#signin_menu").slideToggle('fast');
				$(".topMenuLinkToggle").toggleClass("topmenu-open");
            });
			
			$("div#signin_menu").mouseup(function() {
				return false
			});
			$(document).mouseup(function(e) {
				if($(e.target).parent("a.signin").length==0) {
					$(".topMenuLinkToggle").removeClass("topmenu-open");
					$("div#signin_menu").hide();
				}
			});		
			
			$(".openExtendedFilter").click(function() {
                $("div#filterExtended").slideToggle('fast','easeOutSine');

            });	
			
			$('#colorpickerField').ColorPicker({
				onSubmit: function(hsb, hex, rgb, el) {
					$(el).val(hex);
					$(el).ColorPickerHide();
				},
				onBeforeShow: function () {
					$(this).ColorPickerSetColor(this.value);
				},
				onChange: function (hsb, hex, rgb) {
					$('#colorpickerField').val(hex);
				}
			})
			.bind('keyup', function(){
				$(this).ColorPickerSetColor(this.value);
			});	
			
			$(".defaultInputText").focus(function(srcc)
			{
				if ($(this).val() == $(this)[0].title)
				{
					$(this).removeClass("defaultTextActive");
					$(this).val("");
				}
			});
			
			$(".defaultInputText").blur(function()
			{
				if ($(this).val() == "")
				{
					$(this).addClass("defaultTextActive");
					$(this).val($(this)[0].title);
				}
			});
			
			$(".defaultInputText").blur(); 	
			
			$(document).bind('cbox_cleanup', function(){
					var changed = $('#cboxIframe').contents().find('#withOutSaveClose').val();
					
					if(changed!="changed"){
						$.fn.colorbox.close_flag=true; 
 						 document.documentElement.style.overflow = "auto";	
					} else {
						var question = $('#cboxIframe').contents().find('#withOutSaveCloseQuestion').val();
						var answer = confirm(question);
						if (answer){
							$.fn.colorbox.close_flag=true;
 						 document.documentElement.style.overflow = "auto";											
						}	
						else{
							$.fn.colorbox.close_flag=false; 
						}
					}
			});	
			
			
			$('#datum1, #timeDatum').change(function() {
				
				if($('#datum_end').val()==""){$('#datum_end').val($('#datum1').val());};
				var datum = $('#datum1').val().split(".");
				var datumEnd = $('#datum_end').val().split(".");
				var datumFormated = datum[1]+"."+datum[0]+"."+datum[2];
				var datumEndFormated = datumEnd[1]+"."+datumEnd[0]+"."+datumEnd[2];
				
				var SDate = new Date(datumFormated+" "+$('#timeDatum').val());
				var EDate = new Date(datumEndFormated+" "+$('#timeDatumEnd').val());
				
				if(SDate > EDate)
					{
						
					$('#datum_end').val($('#datum1').val());
					$('#timeDatumEnd').val($('#timeDatum').val());
				}
				
				$( "#datum_end" ).datepicker( "option", "minDate", new Date(datumFormated) );

			});
			
			$('#datum_end, #timeDatumEnd').change(function() {
				
				if($('#datum1').val()==""){$('#datum1').val($('#datum_end').val());};
				var datum = $('#datum1').val().split(".");
				var datumEnd = $('#datum_end').val().split(".");
				var datumFormated = datum[1]+"."+datum[0]+"."+datum[2];
				var datumEndFormated = datumEnd[1]+"."+datumEnd[0]+"."+datumEnd[2];
				
				var SDate = new Date(datumFormated+" "+$('#timeDatum').val());
				var EDate = new Date(datumEndFormated+" "+$('#timeDatumEnd').val());
				
				if(SDate > EDate)
					{
				$('#datum1').val($('#datum_end').val());
				$('#timeDatum').val($('#timeDatumEnd').val());
				}

			});			
			
			$('.showTipsy').tipsy({gravity: 'n',html: true});
			$('.topMenuLink a').tipsy({gravity: 'n',html: false});
			
			$(".tableRowx:odd").css("background-color", "#eee");
			$(".tableRowx").hover( function(){
				$(this).css("background-color", "#fff");
			},
			function(){
				$(".tableRowx:odd").css("background-color", "#eee");
				$(".tableRowx:even").css("background-color", "#f5f5f5");
			});
			
			var maskedPhone = $("body").find(".masked-phone");
			if(maskedPhone.length > 0){$.mask.definitions['~']='[+-]'; $(".masked-phone").mask("+(999) 999 999 999"); };
			
			var maskedRC = $("body").find(".masked-rc");
			if(maskedRC.length > 0){$.mask.definitions['~']='[+-]'; $(".masked-rc").mask("999999/999?9"); };
			
			var maskedPsc = $("body").find(".masked-psc");
			if(maskedPsc.length > 0){$.mask.definitions['~']='[+-]'; $(".masked-psc").mask("999 99"); };	
								

	};
	
});





	

/*soundManager.url = '../soundmanager/';

soundManager.onload = function() {
// SM2 has loaded - now you can create and play sounds!
//soundManager.createSound('helloWorld','http://www.voltage.cz/cz/storage/markof/download/200912301119_02-From-Rino.mp3');
//soundManager.play('helloWorld');
}

function playSound(sound,name) {
	soundManager.createSound(name,sound);
	soundManager.play(name);  
}*/


 function refreshHs() {
 window.location = window.location.href;
 }

 
 function redirectPage(loc) {
 window.location = loc;
 }
 
  function redirectPageCSFD(loc) {
 var newLoc = loc+"&parseUrl="+document.getElementById('parseCsfdUrl').value;
 window.location = newLoc;
 } 
 
  function closeHs() {
	parent.$.fn.colorbox.close();	 	
 }
 
  function loadContent(where,what){

	target = "#"+where;
	width = $(target).innerWidth();
	height = $(target).innerHeight();
		
	//alert(where+"/"+what);
	
	$(target).prepend('<div style=\"display:none;\" class="ajax-loader-fader" id="ajax-loader-fader'+where+'"></div><div class="ajax-loader-info" id="ajax-loader-info'+where+'"><div class="ajax-loader-img" id="ajax-loader-img'+where+'"><img src="/system/img/ajax-horizontal.gif"></div><div class="ajax-loader-text" id="ajax-loader-text'+where+'">Moment ...</div></div>');
	leftMargin = (width-$("#ajax-loader-info"+where).innerWidth())/2;
	topMargin = (height-$("#ajax-loader-info"+where).innerHeight())/2;
	$("#ajax-loader-info"+where).css('margin-left',leftMargin);
	$("#ajax-loader-info"+where).css('margin-top',topMargin);
	$("#ajax-loader-fader"+where).css('height',height);
	$("#ajax-loader-fader"+where).css('width',width);	
	$("#ajax-loader-fader"+where).fadeIn(200);
	
	$(target).load(what, function() { 
		$(target).prepend('<div id="ajax-loader-fader"></div>');
		$("#ajax-loader-fader"+where).css('height',height);
		$("#ajax-loader-fader"+where).css('width',width);			
	 	$("#ajax-loader-fader"+where).fadeOut(200);
		$.getScript("/js.js");		
	 //$(target).hide("slide", { direction: "left" }, 1000);
	  });

 }
 
   function slideContent(where,what,direction,type,speed,easing,automatic){
	//alert(where+"/"+what);
	target = "#"+where;
	width = $(target).innerWidth();
	height = $(target).innerHeight();
	var duration = speed;
	var ease = easing;
	
	if(automatic==false){
		stopCount(target.substr(6));
	}
	
	$(target).html('<div style=\"display:none;\" id="ajax-loader-clickStopper'+where+'" class="ajax-loader-clickStopper"></div><div id="ajax-loader-info'+where+'" class="ajax-loader-info"><div id="ajax-loader-img'+where+'" class="ajax-loader-img"><img src="/system/img/ajax-horizontal.gif"></div><div id="ajax-loader-text'+where+'" class="ajax-loader-text">Nahrávám data ...</div></div><div id="content-old'+where+'" class="content-old">'+$(target).html()+'</div><div id="content-new'+where+'" class="content-new">&nbsp;</div>');

	
	leftMargin = (width-$("#ajax-loader-info"+where).innerWidth())/2;
	topMargin = (height-$("#ajax-loader-info"+where).innerHeight())/2;
	$("#ajax-loader-info"+where).css('margin-left',leftMargin);
	$("#ajax-loader-info"+where).css('margin-top',topMargin);
	$("#ajax-loader-info"+where).css('display','none');
	$("#ajax-loader-info"+where).fadeIn(300);
	
	$("#ajax-loader-clickStopper"+where).css('height',height);
	$("#ajax-loader-clickStopper"+where).css('width',width);	
	$("#ajax-loader-clickStopper"+where).fadeIn(200);
	
	$(target).css('width',width);
	$(target).css('height',height);
	
	$("#content-old"+where).css('width',width);
	$("#content-old"+where).css('height',height);
	
	$("#content-new"+where).css('width',width);
	
	$("#content-new"+where).load(what, function() { 
	$("#ajax-loader-info"+where).fadeOut(500);	
	$("#ajax-loader-clickStopper"+where).fadeOut(200);	

		if(type=="slideHorizontal"){
			
			if(direction=="next"){
				var oldBlock = "right";
				var newBlock = "left";
			}else{
				var oldBlock = "left";
				var newBlock = "right";		
			};
			
			$("#ajax-loader-info"+where).fadeOut('fast');

			$(target).animate({height: $("#content-new"+where).innerHeight()}, duration );
			$("#content-old"+where).hide("slide", { direction: oldBlock ,duration: duration, easing:ease});
			$("#content-new"+where).show("slide", { direction: newBlock, duration: duration, easing:ease},  function() { 
				
	  			$(target).html($("#content-new"+where).html());
				
				if(automatic==true){
				doTimer(target.substr(6));
				} else {
					$.getScript("/js.js");
				}
			  });
		  
		};
		
		if(type=="slideVertical"){
			
			if(direction=="previous"){
				var oldBlock = "up";
				var newBlock = "down";
			}else{
				var oldBlock = "down";
				var newBlock = "up";		
			};
			
			$("#ajax-loader-info"+where).fadeOut('fast');
			$(target).animate({height: $("#content-new"+where).innerHeight()}, duration );
			
			$("#content-old"+where).hide("slide", { direction: oldBlock ,duration: duration, easing:ease});
			$("#content-new"+where).show("slide", { direction: newBlock, duration: duration, easing:ease},  function() { 
				
	  			$(target).html($("#content-new"+where).html());
				
				if(automatic==true){
				doTimer(target.substr(6));
				} else {
					$.getScript("/js.js");
				}
				
			  });
		  
		};		
	
		if(type=="fade"){
		
			$("#ajax-loader-info"+where).fadeOut('fast');
			$("#content-old"+where).fadeOut(speed);
			$(target).animate({height: $("#content-new"+where).innerHeight()}, duration );
			$("#content-new"+where).fadeIn(speed,  function() { 
				
				$(target).html($("#content-new"+where).html());
				
				if(automatic==true){
				doTimer(target.substr(6));
				} else {
					$.getScript("/js.js");
				}
			  });
		};	
	
  	});
	
	
 }
 
   function loadContent2(where,what){
	target = "#"+where;
	//alert(where+" / "+what);
	width = $(target).innerWidth();
	height = $(target).innerHeight();
	leftMargin = (width-150)/2;
	topMargin = (height-40)/2;
	$(target).prepend('<div style=\"position:absolute; text-align:center; z-index:100; background-image: url(/system/img/lighten-80.png); top:0; right:0; height:' + height + 'px; width:' + width + 'px;\"><div style="text-align:center;"><img src="/system/img/ajax-horizontal.gif"></div></div>');

	$("#"+where).load(what);
 }
 

 
 function showButt(element) {
	 	  //alert(element);
          var div = document.getElementById(element);
          div.style.visibility = "visible";
          div.style.display = "block";
          div.top = "50";
          div.left = "50";
}

 
function closeButt(element) {
         var div = document.getElementById(element);
         div.style.visibility = "hidden";
         div.style.display = "none";
}


function hideSlide(element) {
          $("#"+element).slideUp(500);
}



function formCallback(result, form) {
	window.status = "valiation callback for form '" + form.id + "': result = " + result; }
	

 function hideScrollbar() {
 parent.document.documentElement.style.overflow = "hidden";
 document.documentElement.style.overflow = "hidden";
 }
 
 function showScrollbar() {
 parent.document.documentElement.style.overflow = "auto";
 document.documentElement.style.overflow = "auto";
 } 


function Smazat(url) {
if (confirm('Opravdu smazat?')) {location.href=url;return true;
}else{return false;}
}

function objGet(x) {
   if (typeof x != 'string') return x;
   else if (Boolean(document.getElementById))
      return document.getElementById(x);
   else if (Boolean(document.all))
      return eval('document.all.'+x);
   else if (Boolean(document.ids))
      return eval('document.ids.'+x);
   else
      return null;
}



function checkTree(){
  if(document.getElementById("mainTree")){
	treeObj = new DHTMLSuite.JSDragDropTree();
	treeObj.setTreeId('mainTree');
	treeObj.init();
	};
}

function setActiveZone(){
	
	var old = document.getElementById("itemZone").value;
	
	if(old!=''){
 	if(document.getElementById(old)){
		oldItem = document.getElementById(old);
		oldItem.style.backgroundImage = 'url(system/img/ok.png)';
		oldItem.style.backgroundRepeat = 'no-repeat';
		oldItem.style.backgroundPosition = 'center center';
	};		
	};		
}

function changeZone(id,sablona,zona) {
	
for (var i=0;i<document.katForm.zona.options.length;i++) {
    if (document.katForm.zona.options[i].value == zona)
        document.katForm.zona.options[i].selected = true;
		
	}
	
for (var i=0;i<document.katForm.sablona.options.length;i++) {
    if (document.katForm.sablona.options[i].value == sablona)
        document.katForm.sablona.options[i].selected = true;
		
	}
	
	var old = document.getElementById("itemZone").value;
	
	if(old!=''){
 	if(document.getElementById(old)){
		oldItem = document.getElementById(old);
		oldItem.style.backgroundImage = 'none';
		oldItem.style.backgroundRepeat = 'no-repeat';
		oldItem.style.backgroundPosition = 'bottom right';
	};		
	};	
	
	document.katForm.itemZone.value = id;
	
 	if(document.getElementById(id)){
		selectedItem = document.getElementById(id);
		selectedItem.style.backgroundImage = 'url(system/img/ok.png)';
		selectedItem.style.backgroundRepeat = 'no-repeat';
		selectedItem.style.backgroundPosition = 'center center';

	};	
	
	
}

function moveHtml(from,to){
	
	var content = document.getElementById(from).innerHTML;

	document.getElementById(to).innerHTML = content;
	document.getElementById(from).innerHTML = '';
	document.getElementById(from).style.display = 'none';

}

function updateValue(id,value){
	var currValues = $("#preRelativeIDs"+id).val();
	if(currValues!=""){
		$("#preRelativeIDs"+id).val(currValues+","+value);
	}else{
		$("#preRelativeIDs"+id).val(value);
	}
	var values = $("#preRelativeIDs"+id).val();
	updateRelItems(id);
}

function updateRelItems(id){
	var currValues = $("#preRelativeIDs"+id).val();
	loadContent('preRelativeItems'+id,'/actions.php?akce=showItemsByIDs&formItemID='+id+'&items='+currValues);
}

function getSelBoxTitle(id,setInput){
		//alert($("#"+id+' option:selected').attr("title"));
		$("#"+setInput+'').val($("#"+id+' option:selected').attr("title"))
}

function fillDiv(divId,content){
	document.getElementById(divId).innerHTML = content;
}

function changeBox(cbox) {
	box =	document.getElementById(cbox);
	box.checked = !box.checked;
}

function datePicker(id){

	
		$('#'+id).datepicker({
			showAnim: 'slideDown',
			changeMonth: true,
			changeYear: true,
			closeText: 'Zavřít',
			prevText: '&#x3c;Dříve',
			nextText: 'Později&#x3e;',
			currentText: 'Nyní',
			monthNames: ['leden','únor','březen','duben','květen','červen',
        	'červenec','srpen','září','říjen','listopad','prosinec'],
			monthNamesShort: ['leden','únor','březen','duben','květen','červen',
        	'červenec','srpen','září','říjen','listopad','prosinec'],
			dayNames: ['neděle', 'pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek', 'sobota'],
			dayNamesShort: ['ne', 'po', 'út', 'st', 'čt', 'pá', 'so'],
			dayNamesMin: ['ne','po','út','st','čt','pá','so'],
			weekHeader: 'Týd',
			dateFormat: 'dd.mm.yy',
			firstDay: 1,
			isRTL: false,
			showMonthAfterYear: false,
			dateFormat: 'dd.mm.yy',
			showButtonPanel: true,
			showOtherMonths: true, 
			selectOtherMonths: true,
			showWeek: true
		});
}

function datePicker2(id,min_date,max_date){

		$('#'+id).datepicker({
			showAnim: 'slideDown',
			changeMonth: true,
			changeYear: true,
			closeText: 'Zavřít',
			prevText: '&#x3c;Dříve',
			nextText: 'Později&#x3e;',
			currentText: 'Nyní',
			monthNames: ['leden','únor','březen','duben','květen','červen',
        	'červenec','srpen','září','říjen','listopad','prosinec'],
			monthNamesShort: ['leden','únor','březen','duben','květen','červen',
        	'červenec','srpen','září','říjen','listopad','prosinec'],
			dayNames: ['neděle', 'pondělí', 'úterý', 'středa', 'čtvrtek', 'pátek', 'sobota'],
			dayNamesShort: ['ne', 'po', 'út', 'st', 'čt', 'pá', 'so'],
			dayNamesMin: ['ne','po','út','st','čt','pá','so'],
			weekHeader: 'Týd',
			dateFormat: 'dd.mm.yy',
			firstDay: 1,
			isRTL: false,
			showMonthAfterYear: false,
			dateFormat: 'dd.mm.yy',
			showButtonPanel: true,
			showOtherMonths: true, 
			selectOtherMonths: true,
			showWeek: true,
			showOn: "both",
			buttonImage: "/system/img/calendar_sm.png",
			buttonImageOnly: false,
			minDate: min_date,
			maxDate: max_date,
			yearRange: '-100:+1',
			showWeek: false
		});
}

function countPricesFromDop(){

	var changedInput = changed.name;
	var doporucena = $("#priceDop").val();
	var procento = $("#procento").val();
	var marze = $("#marze").val();
	var sleva = $("#sleva").val();
	var price = $("#price").val();
	var priceNak = $("#priceNak").val();
	var priceNakNoVat = $("#priceNakNoVat").val();
	var priceExt = $("#priceExt").val();
	var vyslednaCena = $("#vyslednaCena").val();
	
	if(priceExt!=""){
		priceExt = parseFloat(priceExt);
	}else{
		priceExt = 0;
	}	
	
	if(price!=""){
		price = parseFloat(price);
	}else{
		price = 0;
	}	
	
	if(changedInput=='priceDop'){
		
		if(marze!=""){
			var priceNak = Math.round(doporucena / ((marze /100)+1));
			$("#priceNak").val(priceNak);
			$("#priceNakNoVat").val(Math.round(priceNak/1.2));
		}
		
		if(procento!=''){
			
			var price = Math.round(doporucena*(( 100- procento )/100));
			
			$("#price").val(price);		
		}		
	}	
	
	if(changedInput=='priceNakNoVat'){
		var priceNak = Math.round(priceNakNoVat*1.2);
		$("#priceNak").val(priceNak);
	}
	
	if(changedInput=='priceNak'){
		var priceNakNoVat = Math.round(priceNak/1.2);
		$("#priceNakNoVat").val(priceNakNoVat);
	}
	
	if(changedInput=='priceExt'){

	}
	
	if(changedInput=='procento'){
		var price = Math.round(doporucena*(( 100- procento )/100));
		$("#price").val(price);		
		createCookie('procento',procento,365);	
	}
	
	if(changedInput=='marze'){
		var priceNak = Math.round(doporucena / ((marze /100)+1));
		$("#priceNak").val(priceNak);
		$("#priceNakNoVat").val(Math.round(priceNak/1.2));
		createCookie('marze',marze,365);
	}	
	

	var zisk = price-priceNak;
	var maxSleva = 100-(Math.round(priceNak/doporucena*1000)/10);
	
	$("#vynos").val(zisk);
	$("#maxSleva").val(maxSleva);

	if(sleva!="" && sleva!=undefined && changedInput!='vyslednaCena'){
		var cenaPoSleve = Math.round(doporucena/100*(100-sleva))+priceExt;
		$("#vyslednaCena").val(cenaPoSleve);
		$("#vynosPoSleve").val(Math.round(cenaPoSleve-priceNak));
	}else if(changedInput!='vyslednaCena'){
		var vyslednaCena = (price+priceExt);
		$("#vyslednaCena").val(vyslednaCena);
		$("#vynosPoSleve").val(zisk);
	}else if(changedInput=='vyslednaCena'){
		if(price!="" && priceExt==""){
			var priceExt = vyslednaCena-price;
			$("#priceExt").val(priceExt);
		} else if (priceExt!="" && price==""){
			var price = vyslednaCena-priceExt;
			$("#price").val(price);
		} else {
			var price = vyslednaCena-priceExt;
			$("#price").val(price);			
		};
		var zisk = price-priceNak;
		$("#vynosPoSleve").val(zisk);

	}
	
	if(zisk<=0){
		colorRed('vynosPoSleve');
	}else if(zisk>0){
		colorGreen('vynosPoSleve');
		
	}
}

function openUrlInCbox(object,url){
	if(object.value!=""){
		$.fn.colorbox({iframe:true, 
							preloading:true, 
							overlayClose:false, 
							initialWidth:0, 
							initialHeight:0, 
							innerWidth:150, 
							innerHeight:150, 
							maxHeight:"90%", href:url+object.value});
	}
}
function openElementInCbox(id){

		$.fn.colorbox({inline:true, 
							preloading:true, 
							overlayClose:false, 
							initialWidth:0, 
							initialHeight:0, 
							innerWidth:"90%", 
							innerHeight:"90%", 
							maxHeight:"100%",
							fixed:true,
							scrolling:false,
							href:"#"+id});

	$(document).bind('cbox_complete', function(){
    google.maps.event.trigger(map, 'resize');
	});			

}
function openElementInCbox2(id,width,height){

		$.fn.colorbox({inline:true, 
							preloading:true, 
							overlayClose:false, 
							initialWidth:0, 
							initialHeight:0, 
							innerWidth:width, 
							innerHeight:height, 
							maxHeight:"100%",
							fixed:true,
							scrolling:false,
							href:"#"+id});

	$(document).bind('cbox_complete', function(){
    google.maps.event.trigger(map, 'resize');
	});			

}

function moveCategory(moveWhat,curentcat,name,width,height){
	$("#moveWhat").val(moveWhat);
	$("#moveWhere").val(curentcat);
	$("#moveWhatName").html(name);
	$("#moveWhere option").each(function () { $(this).attr("disabled", false); });
	$("#moveWhere option[value*='#"+moveWhat+"#']").each(function () { $(this).attr("disabled", true); });
	
	openElementInCbox2('moveCatConfirm',width,height);
}

function joinCategory(moveWhat,curentcat,name,width,height){
	$("#joinWhat").val(moveWhat);
	$("#moveWhere").val(curentcat);
	$("#joinWhatName").html(name);
	$("#moveWhere option").each(function () { $(this).attr("disabled", false); });
	$("#moveWhere option[value*='#"+moveWhat+"#']").each(function () { $(this).attr("disabled", true); });	
	openElementInCbox2('joinCatConfirm',width,height);
}

function openUrlInCbox2(id,url){
	var idVal = $("#"+id).val();
	var itemHref = url+idVal;
	if(idVal!=""){
		$.fn.colorbox({iframe:true, 
							preloading:true, 
							overlayClose:false, 
							initialWidth:0, 
							initialHeight:0, 
							innerWidth:150, 
							innerHeight:150, 
							maxHeight:"90%", 
							href:itemHref});
	} else {
		alert("Nejdříve vyber položku!");
	}
}

var sekunda = new Array();
var timer = new Array();

function doTimer(blockID)
{
sekunda[blockID] = 0;
timedCount(blockID);
}


function timedCount(blockID)
{

	sekunda[blockID]=sekunda[blockID]+1;
	
	if(sekunda[blockID]==$("#autoNextBlock"+blockID+"Interval").val()) {
		sekunda[blockID] = 0;
		clearTimeout(timer[blockID]);
		$("#countDown"+blockID).val(sekunda[blockID]);
		if($("#autoNextBlock"+blockID+"Type").val()=="") {
			slideContent('block'+blockID,$("#autoNextBlock"+blockID+"Link").val());
		}
		
		if($("#autoNextBlock"+blockID+"Type").val()!="") {
		slideContent('block'+blockID,$("#autoNextBlock"+blockID+"Link").val(),'previous',$("#autoNextBlock"+blockID+"Type").val(),$("#autoNextBlock"+blockID+"Speed").val(),$("#autoNextBlock"+blockID+"Easing").val(),true);
		}
	
	}else{
		$("#countDown"+blockID).val(sekunda[blockID]);
		timer[blockID]=setTimeout("timedCount("+blockID+")",1000);
		
	};
	
	
}

function stopCount(blockID)
{
clearTimeout(timer[blockID]);
sekunda[blockID] = 0;
$("#countDown"+blockID).val(0);
}

function loadItemXML(xmlFile,onSuccess,object){
	var varList = [];
    var i = 0;
        // Get data and parse it into an array
	$("#content-inside").prepend("<div id='loading' style='position:absolute; top:70px; color:white; right:30%; background-color:red; padding:3px;'>Nahrávám ceny</div>");
    $.ajax({
    	type: "GET",
        url: xmlFile+object.value,
        dataType: "xml",
		cache: false,
        success: function(xml) {
           $(xml).find('record').each(function() {
                $(this).children().each(function(){
					varList[$(this)[0].tagName] = $(this).text();
		
				});
            }); //close each
			$("#content-inside").find("#loading").remove();
			updatePrices(varList);
        },
		error:  function(xml) {alert("Chyba načtení dat!");
		}
    });

}

function updatePrices(array) {
    // this code runs when the ajax call is complete
	var delka = 0;
	for (var object in array) {
	delka++;
	}

	var prices = [];
	var specstring=array["specPromText"];
	var specstringarr=specstring.split("#");
	var specPrices = false;
	
	for (keyVar in specstringarr) {
		var specString = specstringarr[keyVar];
		var specStringArr = specString.split("=>");
		
		if(specStringArr[0]=="specialPrices"){
			var specPrices = specStringArr[1];
		}
	}
	
	if(specPrices!=false){
	var specpricesarr=specPrices.split("|");	
	
		for (keyVar in specpricesarr) {
			var valueString = specpricesarr[keyVar];
			var valueStringArr = valueString.split("=");
			var itemOblast=array["forLocality"];
			var itemCategoryArr=itemOblast.split(",");
	
			var s = valueStringArr[0];
			var r = s.match(/[\d\.]+/g);
			
			if(r!=null){
				var promNameNew = valueStringArr[0].substr(0,valueStringArr[0].length-r[0].length);
				if(inArray(r[0], itemCategoryArr)){
					if(prices[promNameNew]==null){
					prices[promNameNew] = valueStringArr[1];
					
					}
				}
			}
		}
	}
	
	var delkaPrice = 0;
	for (var object in prices) {
	delkaPrice++;
	}	
	
	if(delkaPrice == 0){
		var info = "nejsou data";
		
		$("#price").val(info);
		$("#priceDop").val(info);
		$("#priceNak").val(info);
		$("#priceExt").val(info);
		$("#vynosPoSleve").val(info);
		$("#vyslednaCena").val(info);
		$("#maxSleva").val(info);
			
	} else {
	$("#price").val("");
	$("#priceDop").val(prices["price"]);
	countPricesFromDop(document.getElementById("priceDop"));
	$("#priceNak").val(prices["priceMin"]);
	countPricesFromDop(document.getElementById("priceNak"));
	$("#priceExt").val(prices["priceDopr"]);
	countPricesFromDop(document.getElementById("priceExt"));
	
	}
};

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

function toggleMenu(toggleFrame,toggleClss){

			$(toggleFrame+" .toggleElement").click(function() {
                $(toggleFrame+" .toggleContent").slideToggle('fast');
				$(toggleFrame+" .toggleElement").toggleClass(toggleClss);
            });
			
			$("div"+toggleFrame).mouseup(function() {
				return false
			});
			
			$(document).mouseup(function(e) {
				if($(e.target).parent("a"+toggleFrame).length==0) {
					$(toggleFrame+" .toggleElement").removeClass(toggleClss);
					$(toggleFrame+" .toggleContent").hide();
				
				}
			});
}
function toggleItemMenu(){
			var menus="";
			var toggleClss = "contextualMenuOn";
			 $(document).find('.contextMenu').each(function() {
				var menuID = $(this).attr('id');
				
				var containerPos = $("#" + menuID).offset();
				menus+="<div id='content"+menuID+"' class='contextualMenu'><div id='content"+menuID+"inside' class='contextualMenuInside'>"+$("#" + menuID + " .toggleContent").html()+ "</div></div>";
				
			$("#" + menuID + " .toggleElement").click(function() {	
				$("#content" + menuID).toggle();
				
				var containerPos = $("#" + menuID).offset();
				var left = containerPos.left-($("#content" + menuID).innerWidth()-$("#" + menuID + " .toggleElement").innerWidth());
				$("#content" + menuID).css('margin-top',containerPos.top+'px');
				$("#content" + menuID).css('margin-left',left+'px');
				$("#" + menuID + " .toggleElement").addClass(toggleClss);

			 });
			 
/*			 $("#" + menuID).mouseup(function() {
				return false
			});*/
			
			$(document).mouseup(function(e) {
				if($(e.target).parent("a#content" + menuID).length==0) {
					$("#" + menuID + " .toggleElement").removeClass(toggleClss);
					$("#content" + menuID).hide();

				}
			});				
	

            });	
						
			$("#back").prepend(menus);

}

function roundNumber(number,decimal_points) {
	if(!decimal_points) return Math.round(number);
	if(number == 0) {
		var decimals = "";
		for(var i=0;i<decimal_points;i++) decimals += "0";
		return "0."+decimals;
	}

	var exponent = Math.pow(10,decimal_points);
	var num = Math.round((number * exponent)).toString();
	return num.slice(0,-1*decimal_points) + "." + num.slice(-1*decimal_points)
}

function showDialog(id,sirka) {
$( "#"+id ).dialog({
			modal: true,
			width:sirka,
			buttons: {
				Ok: function() {
					$( this ).dialog( "close" );
				}
			}
		});
}
function password(length, special) {
  var iteration = 0;
  var password = "";
  var randomNumber;
  if(special == undefined){
      var special = false;
  }
  while(iteration < length){
    randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
    if(!special){
      if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
      if ((randomNumber >=58) && (randomNumber <=64)) { continue; }
      if ((randomNumber >=91) && (randomNumber <=96)) { continue; }
      if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
    }
    iteration++;
    password += String.fromCharCode(randomNumber);
  }
  return password;
}

function showPassword(where){
	$(where).html(password(8,false));
}
