
var map;
var geocoder;
var marker;

function geocodePosition(pos) {

  geocoder.geocode({
    latLng: pos
  }, function(responses) {
    if (responses && responses.length > 0) {

		var responsesArr = new Array();
		$.each(responses, function(){
			$.each(this.address_components, function(){
				responsesArr[this.types.join(", ")] = this.long_name;
			});
		});
		
	if(responsesArr[""] && responsesArr["street_number"]){
		responsesArr["street_number"] = responsesArr[""]+"/"+responsesArr["street_number"];
	} else if(responsesArr[""] && !responsesArr["street_number"]){
		responsesArr["street_number"] = responsesArr[""];
	}
	
	if(responsesArr["route"] && !responsesArr["street_number"]){
	 $("#gAdress").val(responsesArr["route"]);
	 
	} else if(responsesArr["street_number"] && !responsesArr["route"]){
		
	 $("#gAdress").val(responsesArr["street_number"]);}

	else if(responsesArr["route"] && responsesArr["street_number"]){
	 $("#gAdress").val(responsesArr["route"]+" "+responsesArr["street_number"]);
	 
	}else{
	 $("#gAdress").val(""); 
	}
	
	if(responsesArr["sublocality, political"]){
		$("#gCity").val(responsesArr["sublocality, political"]);
	}else{
		$("#gCity").val(responsesArr["locality, political"]);
	}
	 
	
	$("#gPostal").val(responsesArr["postal_code"]);
	$("#gState").val(responsesArr["country, political"]);
	 
	 
    } else {
	 $("#adress").val('Není možné určit adresu.');
    }
  });
}

function updateMarkerPosition(latLng) {
  $("#lat").val(latLng.lat());
  $("#lng").val(latLng.lng());
  var latGps = convertDecDegGPS(latLng.lat());
  var lngGps = convertDecDegGPS(latLng.lng());
  $("#gGPS").val(latGps+"N, "+lngGps+"E");
}

function zoomMarker(zoom){
	var latLng = marker.getPosition();
	map.setCenter(latLng);
	map.setZoom(zoom);
}

function initializeMap(mapID,markers,myOptions) {

  map = new google.maps.Map(document.getElementById(mapID),myOptions);
  geocoder = new google.maps.Geocoder();
  if(markers.length>1){
	  
  google.maps.event.addListener(map, 'click', function() {
        infowindow.close();
        });
		
		
  	setMarkers(map, markers);
  
	  var LatLngList= new Array(markers.length);
	  for (var i = 0; i < markers.length; i++) {
			var markerList = markers[i];
			LatLngList[i] = new google.maps.LatLng(markerList[1],markerList[2]);
	  }
	
	//  Make an array of the LatLng's of the markers you want to show
	
	//  Create a new viewpoint bound
	var bounds = new google.maps.LatLngBounds ();
	//  Go through each...
	for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
	  //  And increase the bounds to take this point
	  bounds.extend (LatLngList[i]);
	}
	//  Fit these bounds to the map
	map.fitBounds (bounds);  
  }
  else {
	marker = new google.maps.Marker({
	position: new google.maps.LatLng(markers[0][1],markers[0][2]),
	draggable: markers[0][5],
	map: map
	  });
	marker.setMap(map);
	
	google.maps.event.addListener(marker, 'click', function() {
	infowindow.setContent(markers[0][4]); 
	infowindow.open(map,marker);
	});
	
  	google.maps.event.addListener(marker, 'drag', function() {
    updateMarkerPosition(marker.getPosition());
  });	
  
  google.maps.event.addListener(marker, 'dragend', function() {
    geocodePosition(marker.getPosition());
  });   
	    
  google.maps.event.addListener(map, 'click',function(me){
		marker.setPosition(me.latLng);
		map.setCenter(me.latLng);
		updateMarkerPosition(me.latLng);
		geocodePosition(me.latLng);
	});  
  }
}

 

var icons = new Array();

icons["red"] = new google.maps.MarkerImage("mapIcons/mm_20_3d_red.png",
      // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(12, 20),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(6, 20));

function getMarkerImage(iconColor) {
   if ((typeof(iconColor)=="undefined") || (iconColor==null)) { 
      iconColor = "red"; 



   }
   if (!icons[iconColor]) {
      // icons[iconColor].image = "http://labs.google.com/ridefinder/images/mm_20_"+ iconColor +".png",
      icons[iconColor] = new google.maps.MarkerImage("mapIcons/mm_20_3d_"+ iconColor +".png",
      // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(12, 20),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(6, 20));
   } 

   return icons[iconColor];



// new google.maps.MarkerImage("mapIcons/mm_20_3d_"+ beach[4] +".png"),

}
  // Marker sizes are expressed as a Size of X,Y
  // where the origin of the image (0,0) is located
  // in the top left of the image.

  // Origins, anchor positions and coordinates of the marker
  // increase in the X direction to the right and in

  // the Y direction down.

  var iconImage = new google.maps.MarkerImage('http://labs.google.com/ridefinder/images/mm_20_red.png',
      // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(12, 20),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(6, 20));
  	  var iconShadow = new google.maps.MarkerImage('http://labs.google.com/ridefinder/images/mm_20_shadow.png',
      // The shadow image is larger in the horizontal dimension
      // while the position and offset are the same as for the main image.
      new google.maps.Size(22, 20),
      new google.maps.Point(0,0),
      new google.maps.Point(6, 20));
      // Shapes define the clickable region of the icon.
      // The type defines an HTML &lt;area&gt; element 'poly' which
      // traces out a polygon as a series of X,Y points. The final
      // coordinate closes the poly by connecting to the first
      // coordinate.

  var iconShape = {
      coord: [4,0,0,4,0,7,3,11,4,19,7,19,8,11,11,7,11,4,7,0],
      type: 'poly'
  };



var infowindow = new google.maps.InfoWindow(
  { 
    size: new google.maps.Size(150,50)
  });


function geocode() {
	var address = "";
	if($("#gAdress").val()!=""){ address+=$("#gAdress").val(); }
	if($("#gCity").val()!=""){ 
	if(address!=""){ address+=", "; }
	address+=$("#gPostal").val()+ " "; 
	address+=$("#gCity").val(); 
	}

	geocoder.geocode({
	  'address': address,
	  'partialmatch': true}, geocodeResult);
}

 function geocodeResult(results, status) {
    if (status == 'OK' && results.length > 0) {
	  
      map.fitBounds(results[0].geometry.viewport);
	  marker.setPosition(map.getCenter());
	  updateMarkerPosition(map.getCenter());
	  /*addMarkerAtCenter();*/
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  }
  
function getAdressData(ulice,mesto,psc){
	if(ulice!=""){$("#gAdress").val($("#"+ulice).val())}
	if(mesto!=""){$("#gCity").val($("#"+mesto).val())}
	if(psc!=""){$("#gPostal").val($("#"+psc).val())}
}

function resetAdressData(){
	$("#gAdress").val("");
	$("#gCity").val("");
	$("#gPostal").val("");
	$("#gState").val("");
}

function setAdressData(ulice,mesto,psc){
	if(ulice!=""){$("#"+ulice).val($("#gAdress").val())}
	if(mesto!=""){$("#"+mesto).val($("#gCity").val())}
	if(psc!=""){$("#"+psc).val($("#gPostal").val().split(' ').join(''))}
}

function createMarker(map, latlng, label, html, color) {
    var contentString = html;
    marker = new google.maps.Marker({
       position: latlng,
        map: map,
        title: label
		//draggable: true
        });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString); 
        infowindow.open(map,marker);
        });
		
	  // Add dragging event listeners.
	  google.maps.event.addListener(marker, 'dragstart', function() {

	  });
	  
	  google.maps.event.addListener(marker, 'drag', function() {
		
	  });
	  
	  google.maps.event.addListener(marker, 'dragend', function() {
		geocodePosition(marker.getPosition());
	  });
	  

	  

}

  function addMarkerAtCenter() {
    var marker = new google.maps.Marker({
        position: map.getCenter(),
        map: map
    });
  }
 

function setMarkers(map, locations) {
  // Add markers to the map
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = createMarker(map,myLatLng,beach[0],beach[4],beach[3]);
  }

}

function convertDD(gps)
{
	var deg = document.inDDMMSS.form1_dd.value;
	var min = document.inDDMMSS.form1_mm.value;
	var sec = document.inDDMMSS.form1_ss.value;

	if (deg == "" || min == "" || sec == ""){
			alert("Enter a value for DD MM or SS.");
	}

	else if (deg > 180 || deg < 0){
			alert("Enter a value less than 180 or greater than 0.");
	}
	else if (min > 60 || min < 0){
			alert("Enter a value less than 60 or greater than 0 for minutes.");
	}
	else if (sec > 60 || sec < 0){
			alert("Enter a value less than 60 or greater than 0 for seconds.");
	}

	else {

		document.inDDMMSS.form1_gpsdeg.value = deg;

		var dec_min = (min*1.0 + (sec/60.0));
		document.inDDMMSS.form1_gpsmin.value = dec_min.toFixed(4);

		var answer1 = deg*1.0 + (dec_min/60.0);
		document.inDDMMSS.form1_dec.value=answer1.toFixed(4);
	}
}

function convertDecDeg(deg)
{

	if (deg == ""){
			alert("Enter a value for decimal degrees.");
		}
		else if (deg > 180 || deg < 0){
			alert("Enter a value less than 180 for deg or greater than 0");
		}
	else {
		var gpsdeg = parseInt(deg);
		var remainder = deg - (gpsdeg * 1.0);
		var gpsmin = remainder * 60.0;

		document.inDecDeg.form2_gpsdeg.value = gpsdeg;
		document.inDecDeg.form2_gpsmin.value = gpsmin.toFixed(4);

		document.inDecDeg.form2_dd.value = gpsdeg;
		document.inDecDeg.form2_mm.value= parseInt(gpsmin);
		var remainder2 = gpsmin - (parseInt(gpsmin)*1.0);
		document.inDecDeg.form2_ss.value = parseInt(remainder2*60.0);

	}
}

function convertDecDegGPS(deg)
{

	if (deg == ""){
			return "Enter a value for decimal degrees.";
		}
		else if (deg > 180 || deg < 0){
			return "Enter a value less than 180 for deg or greater than 0";
		}
	else {
		var gpsdeg = parseInt(deg);
		var remainder = deg - (gpsdeg * 1.0);
		var gpsmin = remainder * 60.0;


		var dd = gpsdeg;
		var mm = parseInt(gpsmin);
		var remainder2 = gpsmin - (parseInt(gpsmin)*1.0);
		var ss = parseInt(remainder2*60.0);
		

		return dd+"°"+mm+"'"+ss+'"';
	}
}

function convertGps()
{
	var deg = 0;
	var min = 0;
	
	deg = document.inGPScoord.form3_gpsdeg.value;
	min = document.inGPScoord.form3_gpsmin.value;

	if (deg == "" || min == ""){
			alert("Enter a value for GPS degrees or GPS min.");
	}
	else if (deg > 180 || deg < 0){
			alert("Degrees should be greater than 0 and less than 180.");
	}
	else if (min > 60 || min < 0){
			alert("Minutes should be greater than 0 and less than 60.");
	}
	else {
		var decdeg = (deg*1.0) + min/60.0;
		document.inGPScoord.form3_dec.value = decdeg.toFixed(4);

		document.inGPScoord.form3_dd.value = deg;
		document.inGPScoord.form3_mm.value= parseInt(min);
		var remainder2 = min - (parseInt(min)*1.0);
		document.inGPScoord.form3_ss.value = parseInt(remainder2*60.0);
	}
}	//-->

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 initFileButt(id) {

if (isObject(id) == true) {
      $("input."+id).filestyle({ 
          image: "../jquery/choose-file.gif",
          imageheight : 22,
          imagewidth : 82,
          width : 50
      });  
	  
}
	  

}

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

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

	var validator = $("#"+id).validate({
		success: function(form) {

			},	
		error: function(form) {

			},					
		rules: {
				math: {
				}
		},
		messages: {
			math: {
				equal: "Vložte správný výsledek"
			}
		},
		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: $(ajaxForm).attr('target'),  // target element(s) to be updated with server response 
				replaceTarget:	true,
				resetForm: false
				// other available options: 
				//url:       url         // override for form's 'action' attribute 
				//type:      type        // 'get' or 'post', override for form's 'method' attribute 
				//dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
				//clearForm: true        // clear all form fields after successful submit 
				//resetForm: true        // reset the form after successful submit 
		 
				// $.ajax options can be used here too, for example: 
				//timeout:   3000 
			}; 		
			
			// pre-submit callback 
			function showRequest(formData, jqForm, options) { 
				var queryString = $.param(formData); 
				alert('About to submit: \n\n' + queryString); 
				return true; 
			} 
			 
			// post-submit callback 
			function showResponse(responseText, statusText, xhr, $form)  { 
				alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
					'\n\nThe output div should have already been updated with the responseText.'); 
				
			}
   			$('#ajaxForm').ajaxSubmit(options);
			
			$(target).html('<div style="text-align:center; padding:3px; position:relative; margin:1px 5px 0px 0px; float:right;  font-size:9px; color:red;"><img src="/system/img/ajax-horizontal.gif"> Čekejte zpracovávám data</div>'+$(target).html());
			
			$("#"+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(){	
  
	$('.ajaxify').ajaxify();
	$('.ajaxify').click(function(){
	target = $(this).attr('target');
	width = $(target).innerWidth();
	height = $(target).innerHeight();
	leftMargin = (width/2)-100;
	topMargin = (height/2)-16;
	$(target).prepend('<div style=\"position:absolute; z-index:100; background-image: url(/system/img/lighten-90.png); top:0; right:0; height:' + height + 'px; width:' + width + 'px;\"><div style=" text-align:center; margin-top:' +topMargin + 'px;"><img src="/system/img/ajax-horizontal.gif"><br>Čekejte zpracovávám data ...</div></div>');
	}
	);
	//$("select, input:checkbox, input:radio, input:file").uniform();				   
	initSmoothMenu('smoothmenu1','ddsmoothmenu');
	initSmoothMenu('smoothmenu2','ddsmoothmenu2');
	$(".butt").button();

	initEditForm("myForm");
	
	initAjaxForm("ajaxForm");
	$(".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});
	
	/*$("#bcTarget").barcode("9934567890128", "ean13");  */ 
	
	
		$( "#draggable" ).draggable({ revert: "invalid" });
		$( "#draggable2" ).draggable({ revert: "invalid" });

		$( "#droppable" ).droppable({
			activeClass: "ui-state-hover",
			hoverClass: "ui-state-active",
			drop: function( event, ui ) {
				$( this )
					.addClass( "ui-state-highlight" )
					.find( "p" )
						.html( "Dropped!" );
			}
		});
		
		$(".signin").click(function() {
                $("div#signin_menu").slideToggle('fast');
				$(".signin").toggleClass("topmenu-open");
            });
			
			$("div#signin_menu").mouseup(function() {
				return false
			});
			$(document).mouseup(function(e) {
				if($(e.target).parent("a.signin").length==0) {
					$(".signin").removeClass("topmenu-open");
					$("div#signin_menu").hide();
				}
			});		
			
			$(".filterExtendedToggle").click(function() {
                $("div#filterExtended").slideToggle('fast','easeOutSine');
				$(".filterExtendedToggle").toggleClass("filterExtendedToggleOpen");
            });	
			
			$('#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());
				}

			});			
			
			$('.tipsy').tipsy({gravity: $.fn.tipsy.autoNS,html: true});
			
});





	

/*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 showSaving(content) {
	 //hs.htmlExpand(null, {maincontentText: content, dimmingOpacity:1, dimmingDuration:0, outlineType:null } );

 }
 
 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;
	//alert(where+" / "+what);
	width = $(target).innerWidth();
	height = $(target).innerHeight();
	leftMargin = (width-170)/2;
	topMargin = (height-40)/2;
	$(target).prepend('<div style=\"position:absolute; text-align:center; z-index:100; background-image: url(/system/img/lighten-50.png); top:0; right:0; height:' + height + 'px; width:' + width + 'px;\"><div style="padding:10px;border:1px solid #ddd; width:150px; background-color:white; text-align:center; margin-left:' +leftMargin + 'px; margin-top:' +topMargin + 'px;"><img src="/system/img/ajax-horizontal.gif"><br>Čekejte zpracovávám data ...</div></div>');

	$("#"+where).load(what);
 }
 
   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 showButtAnim(element) {
	 	  var n = $("#"+element).queue("fx");
		  if (n<1) {
          $("#"+element).fadeIn(200);
		  };
}

function closeButtAnim(element) {
          $("#"+element).fadeOut(200);
}

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(changed){
	
	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();


	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=='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!=""){
		var cenaPoSleve = Math.round(doporucena/100*(100-sleva));
		$("#vyslednaCena").val(cenaPoSleve);
		$("#vynosPoSleve").val(Math.round(cenaPoSleve-priceNak));
	}else{
		$("#vyslednaCena").val(price);
		$("#vynosPoSleve").val(zisk);
	}
}

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 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!");
	}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
