/*
Author: Vaclav Sedo - vaclav.sedo@volny.cz
Date made: 28.5.2006
Date modified: 28.5.2006
Function: Funkce v javaScriptu

Výpis funkcí:
-------------------------------------------------------------------------------------------
insAtCursor(myFieldId, myValue)               - Vloží znak "myValue" na aktuální pozici kurzoru v poli, které má "id=myFieldId"
addElement(tableID, r_pos, c_pos, e_type, e_id, e_name, e_value, e_size, e_read_only)
deleteLastRowOfTable(table_id)
-------------------------------------------------------------------------------------------

*/

/**
 * DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

function email_validate(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	
	var allowed_characters = "&'*%#$._-+/=?`~{|}^@0123456789abcdefghijklmnopqrstuvwxyz"

	 if (str.indexOf(at)==-1)	return false

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)	return false

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)	return false

	 if (str.indexOf(at,(lat+1))!=-1)	return false

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)	return false

	 if (str.indexOf(dot,(lat+2))==-1)	return false
	
	 if (str.indexOf(" ")!=-1)	return false
	 
	 for (a = 0; a < str.length; a++)	{
	 	chr = str.substring(a, a + 1)
	 	chr = chr.toLowerCase()
	 	if (allowed_characters.search(chr) < 0)	return false
	 }

	 return true					
}

// function to format a number with separators. returns formatted number.
// num - the number to be formatted
// decpoint - the decimal point character. if skipped, "." is used
// sep - the separator character. if skipped, "," is used
function FormatNumberBy3(num, decpoint, sep) {
  // check for missing parameters and use defaults if so
  if (arguments.length == 2) {
    sep = ",";
  }
  if (arguments.length == 1) {
    sep = ",";
    decpoint = ".";
  }
  // need a string for operations
  num = num.toString();
  // separate the whole number and the fraction if possible
  a = num.split(decpoint);
  x = a[0]; // decimal
  y = a[1]; // fraction
  z = "";


  if (typeof(x) != "undefined") {
    // reverse the digits. regexp works from left to right.
    for (i=x.length-1;i>=0;i--)
      z += x.charAt(i);
    // add seperators. but undo the trailing one, if there
    z = z.replace(/(\d{3})/g, "$1" + sep);
    if (z.slice(-sep.length) == sep)
      z = z.slice(0, -sep.length);
    x = "";
    // reverse again to get back the number
    for (i=z.length-1;i>=0;i--)
      x += z.charAt(i);
    // add the fraction back in, if it was there
    if (typeof(y) != "undefined" && y.length > 0)
      x += decpoint + y;
  }
  return x;
}


function zobraz_help(div_name)	{
	var pos = getMousePosition();
	var el_help_zvyhodneni = document.getElementById(div_name);

	el_help_zvyhodneni.style.display = 'block';
	var help_height = getHeight(div_name);
	var help_widht = getWidth(div_name);
	var max_y = getAbsoluteTop("div_content")+getHeight("div_content");

	var wind = getWindowSize();
	var max_x = wind.width;
	
	if ((getWidth(div_name) + pos.x) > max_x)	{
		pos.x = max_x - getWidth(div_name);
	}

	el_help_zvyhodneni.style.left = (pos.x-30)+'px';
	el_help_zvyhodneni.style.top = (pos.y - help_height - 25)+'px';
}

function skryj_help(div_name)	{
	document.getElementById(div_name).style.display = 'none';
}

function getWindowSize() {
	var width, height;
	var el_window = {width:0, height:0};

	if (window.innerWidth) {
		el_window.width = window.innerWidth;
		el_window.height = window.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientWidth) {
		el_window.width = document.documentElement.clientWidth;
		el_window.height = document.documentElement.clientHeight;
	}
	else if (document.body) {
		el_window.width = document.body.clientWidth;
		el_window.height = document.body.clientHeight;
	}
	el_window.width = el_window.width - 16;
	
	return el_window;
}

function system_get_mouse_XY(e) {
	if(!e) var e = window.event;
	x = (window.Event) ? e.pageX : event.clientX;
	y = (window.Event) ? e.pageY : event.clientY;

	var de = document.documentElement;
	var b = document.body;
	x = e.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
	y = e.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
	
	mouse_x = x;
	mouse_y = y;
	//document.ee.sd.value = mouse_x+":"+mouse_y;
}

function getMousePosition(e) {
    /*if(!e) var e = window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }*/
    var cursor = {x:0, y:0};
    cursor.x = mouse_x;
    cursor.y = mouse_y;
    return cursor;
}

function hide_picture(path)	{
	document.getElementById("image_preview").style.display = "none";
}

function show_picture(path, id)	{
	document.getElementById("image_preview").style.display = "block";
	document.getElementById("image_preview").style.left = (getAbsoluteLeft(id)-255)+"px";
	document.getElementById("image_preview").style.top = getAbsoluteTop(id)+"px";
	document.getElementById("image_preview_img").src = path;
}

function sleep(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
		return;
	}
}	

function popupw(file_name, nr_foto)	{
	var a = file_name.indexOf('_')+1;
	var act_foto = parseInt(file_name.substr(a,1),10);

	var img_array = new Array();
	for (b = 0; b < nr_foto; b++)	{
		img_array[b] = file_name.substr(0,a)+(b+1)+file_name.substr(a+1);
	}
	win_name=window.open('about:blank','','top=10px, left=10px, width=200px, height=200px');
	with (win_name.document)	{
		writeln('<html><head><title>Načítám fotografie...</title><style>body{margin:0px;}</style>');
		writeln('<script language="javascript">');
		writeln('function set_navig(){');
		writeln('var act_foto = parseInt(document.getElementById(\"act_foto\").value,10);');
		writeln('var nr_foto = parseInt(document.getElementById(\"nr_foto\").value,10);');
		writeln('var tbl_pos = document.getElementById(\"big_foto_\"+act_foto).height;');
		//writeln('document.getElementById(\"tbl_navig\").style.top = tbl_pos+10;');
		writeln('if ((act_foto) == 1) {');
			writeln('document.getElementById(\"bt_prev\").style.border = \"window-inset\";');
			writeln('document.getElementById(\"bt_prev\").style.color = \"#AAAAAA\";');
			writeln('document.getElementById(\"bt_prev\").style.borderWidth = \"2px\";');
			writeln('}');
		writeln('else	{');
			writeln('document.getElementById(\"bt_prev\").style.border = \"outset\";');
			writeln('document.getElementById(\"bt_prev\").style.color = \"black\";');
			writeln('document.getElementById(\"bt_prev\").style.borderWidth = \"2px\";');
			writeln('}');
		writeln('if ((act_foto) == nr_foto)	{');
			writeln('document.getElementById(\"bt_next\").style.border = \"window-inset\";');
			writeln('document.getElementById(\"bt_next\").style.color = \"#AAAAAA\";');
			writeln('document.getElementById(\"bt_next\").style.borderWidth = \"2px\";');
			writeln('}');
		writeln('else	{');
			writeln('document.getElementById(\"bt_next\").style.border = \"outset\";');
			writeln('document.getElementById(\"bt_next\").style.color = \"black\";');
			writeln('document.getElementById(\"bt_next\").style.borderWidth = \"2px\";');
			writeln('}');
		writeln('}');
		writeln('function ch_image(smer){');
		writeln('var nr_foto = parseInt(document.getElementById(\"nr_foto\").value,10);');
		writeln('var old_img_nr = parseInt(document.getElementById(\"act_foto\").value,10);');
		writeln('var act_foto = parseInt(document.getElementById(\"act_foto\").value,10);');
		writeln('if (smer == \"next\")	{if (act_foto == nr_foto) var new_foto = 0; else var new_foto = 1;}');
		writeln('if (smer == \"prev\")	{if (act_foto == 1) var new_foto = 0; else var new_foto = -1;}');
		writeln('if ((new_foto == 1) || (new_foto == -1))	{');
			writeln('var new_img_nr = (old_img_nr+new_foto);');
			writeln('document.images[old_img_nr-1].style.visibility = \"hidden\";');
			writeln('document.images[new_img_nr-1].style.visibility = \"visible\";');
			writeln('document.getElementById(\"act_foto\").value = new_img_nr;');
			writeln('set_navig();');
			writeln('reSizeToImage();');
			writeln('}');
		writeln('}');
		writeln('function reSizeToImage(){');
		writeln('var act_foto = parseInt(document.getElementById(\"act_foto\").value,10)-1;');
		writeln('var NS = (navigator.appName==\"Netscape\")?true:false;');
		writeln('iWidth = (NS)?window.innerWidth:document.body.clientWidth; ');
	   writeln('iHeight = (NS)?window.innerHeight:document.body.clientHeight; ');
	   writeln('iWidth = document.images[act_foto].width - iWidth; ');
	   writeln('iHeight = document.images[act_foto].height - iHeight; ');
	   writeln('window.resizeBy(iWidth, iHeight);} ');
		writeln('function doTitle(){document.title=\"detail\"; document.getElementById(\"nacitam\").style.visibility=\"hidden\";}');writeln('</sc'+'ript>');
		writeln('</head><body bgcolor=#FFFFFF scroll=\"no\" onload=\"reSizeToImage();self.focus();doTitle();set_navig();\">');
		for (a = 1; a < (nr_foto+1); a++)	{
			writeln('<img name=\"big_foto_'+a+'\" id=\"big_foto_'+a+'\" src=\"'+img_array[a-1]+'\" onMouseUp=\"self.close()\" style=\"display:block; cursor:pointer; position:absolute; top:0px; visibility:hidden\" alt=\"zavřít okno\">');
		}
		writeln('<script language="javascript">document.getElementById(\"big_foto_'+act_foto+'\").style.visibility = \"visible\";');
		writeln('</script>');
		writeln('<br><table name=\"tbl_navig\" id=\"tbl_navig\" width=\"250px\" style=\"position:absolute;top:10px; left:10px;border:solid black 1px; background:white;\"><tr>');
		writeln('<td style=\"text-align:left; width:33%\"><input type=\"button\" id=\"bt_prev\" onMouseUp=\"ch_image(\'prev\')\" value=\"<< předchozí\"></td>');
		writeln('<td style=\"text-align:center; width:34%\">');
		writeln('<a href=\"\" onMouseUp=\"self.close()\">zavřít</a></td><td style=\"text-align:right; width:33%\">');
		writeln('<input type=\"button\" id=\"bt_next\" onMouseUp=\"ch_image(\'next\')\" value=\"daląí >>\"></td>');
		writeln('</tr></table>');
		writeln('<input type=\"text\" id=\"act_foto\" style=\"position:absolute; left:0px; top:0px; visibility:hidden\" value=\"'+act_foto+'\">');
		writeln('<input type=\"text\" id=\"nr_foto\" style=\"position:absolute; left:0px; top:30px; visibility:hidden\" value=\"'+nr_foto+'\">');
		writeln('<div id=\"nacitam\" style=\"background:#FFFFFF;z-index:1;position:absolute; top:0px; left:0px; width:250px; height:200px; padding:20px 0px 20px 20px\">Načítám fotografie.<br><br>Prosím, čekejte...</div>');
		writeln('</body></html>');
		close();		
	}
}

/*function popupw(file_name, win_name, img_width, img_height, pos_top, pos_left)	{

	$win_name = window.open(file_name, win_name, "width="+img_width+", height="+img_height+",toolbar=no, status=no")

	$win_name.document.write("<HTML>\n<HEAD>\n");
	$win_name.document.write("<BODY style='margin:0 0 0 0'>\n");
	$win_name.document.write("<img src="+file_name+" onClick='self.close()' style='cursor:pointer;' ALT='zavřít okno'>");
	$win_name.document.write("</BODY>\n");
	$win_name.document.write("</HTML>");
	$win_name.document.close();
}*/

//Ověří, zda řetězec obsahuje desetinné číslo
function isFloat(input)	{
	maxBefore = 100
	maxAfter = 100
  eval("var RE = /^\\d{0," + maxBefore + "}(\\.\\d{0," + maxAfter + "})?$/");
  
  //  regexp used is /^\d{0,maxBefore}(\.\d{0,maxAfter})?$/

  input = input.replace(/,/g, '.')
  if(!RE.test(input))	{    
    return false
    input = input.slice(0, -1);
  }
  else return true
}

//Ověří, zda řetězec obsahuje pouze celá čísla
function isInteger(str) {
	var i;
  for (i = 0; i < str.length; i++){   
    var c = str.charAt(i);
    if (((c < "0") || (c > "9"))) return false;
  }
  return true;
}

//=========================================================================================
//Vloží znak "myValue" na aktuální pozici kurzoru v poli, které má "id=myFieldId"
function insAtCursor(myFieldId, myValue) {
  if (document.selection) {
    document.getElementById(myFieldId).focus();
    sel = document.selection.createRange();
    sel.text = myValue;
  }
}
//=========================================================================================

//=========================================================================================
//Vloží element (INPUT) do tabulky (tableID), r_pos (řádek - počítá se od nuly), c_pos (sloupec), e_type (typ elementu - 'checkbox'...) 
function addElement(tableID, r_pos, c_pos, e_type, e_id, e_name, e_value, e_size, e_read_only){
	var theTable = document.getElementById(tableID);

	if (document.getElementById) {
    var input = document.createElement('INPUT');
    input.type = e_type;
    input.id = e_id;
    input.name = e_name;
    input.value = e_value;
    input.size= e_size;
    input.readOnly=e_read_only;
    //input.onblur=new_instr_row;
  }
  theTable.rows[r_pos].cells[c_pos].appendChild(input);
}
//=========================================================================================

//=========================================================================================
//Odstraní poslední řádek v tabulce (id=tableID)
function deleteLastRowOfTable(tableID)  {
  var row = document.getElementById(tableID).deleteRow(-1);
}
//=========================================================================================


function getHeight(objectId) {
	return document.getElementById(objectId).clientHeight;
}

function getWidth(objectId) {
	return document.getElementById(objectId).clientWidth;
}

//Vrátí absolutní pozici (left) elementu
function getAbsoluteLeft(objectId) {
	// Get an object left position from the upper left viewport corner
	// Tested with relative and nested objects
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	// Return left postion
	return oLeft
}

//Vrátí absolutní pozici (top) elementu
function getAbsoluteTop(objectId) {
	// Get an object top position from the upper left viewport corner
	// Tested with relative and nested objects
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	// Return top position
	return oTop
}

//Hlídá zadávání času hh:mm
function guardInputTime(obj)	{
 with (event)  {
   if (keyCode == 58 || keyCode == 46 || keyCode == 44)  {
     insAtCursor(obj, ":");
     returnValue = false;
   }
   if ((keyCode < 48 || keyCode > 57) && (keyCode != 13)) {		// != 13 - povolí stisknutí enteru
     returnValue = false;
   }
 }
}

//Zkontroluje správný formát času hh:mm
function checkTime(el_id)  {
   el_date = document.getElementById(el_id);
   my_time = el_date.value;
   
   if (my_time)   {
      var pos1 = my_time.indexOf(':');
      var my_hours = my_time.substring(0,pos1);
      var my_minutes = my_time.substring(pos1+1);
      
      ch_result = true
      if (my_hours.length > 2 || my_hours.length < 1) {
         alert('Prosím, zadejte čas ve správném formátu hh:mm!')
         ch_result = false
      }
      if ((my_minutes.length > 2 || my_minutes.length < 1) && (ch_result))   {
         alert('Prosím, zadejte čas ve správném formátu hh:mm!')
         ch_result = false
      }
      
      if (ch_result) {
         hr = parseInt(my_hours, 10);
         min = parseInt(my_minutes, 10);
         if (hr > 23 || hr < 0)  {
            alert('Prosím, zadejte správně hodiny!')
            ch_result = false
         }
         if (min > 59 || min < 0)  {
            alert('Prosím, zadejte správně minuty!')
            ch_result = false
         }
      }
      if (ch_result) {
         ch_result = (hr < 10?'0'+hr:hr)+':'+(min < 10?'0'+min:min)
      }   
      switch (ch_result)  {
         case false : document.getElementById(el_id).focus(); break;
         case "-1"  : break;
         default    : el_date.value = ch_result;
      }
   }
}

//Hlídá zadávání datumu
function guardInputDate()  {
	var src_obj_name = event.srcElement.name
 	with (event)  {
	   if (keyCode == 44 || keyCode == 46)  {
	     insAtCursor(src_obj_name, ".");
	     returnValue = false;
	   }
	   if (keyCode < 48 || keyCode > 57) {
	     returnValue = false;
		}
 	}
}

//Ověří, zda byl vybrán soubor *.jpg
function checkJPG(src_obj_name)  {
	val = document.getElementById(src_obj_name).value;
	if (!val)	return true
	if (val)	{
		var my_split = val.split(".");
		if ((my_split[1] == undefined) || !((my_split[my_split.length-1].toLowerCase() == "jpg") || (my_split[my_split.length-1].toLowerCase() == "jpeg")))	{
			return false
		}
		else return true
	}
}

//=========================================================================================
//Při ztrátě focusu ověří, zda byl správně zadán datum
function checkDate(src_obj_name)  {
	el_date = document.getElementById(src_obj_name);
	if (!el_date.value)	return true
	ch_result = isDateReport(el_date.value,0);
	switch (ch_result)  {
	   case false : document.getElementById(src_obj_name).focus(); break;
	   case "-1"  : break;
	   default    : {
	   	el_date.value = ch_result;
	   	return true
	   }
	}
}

//Zkontroluje, zda je datum ve formátu dd.mm.yyyy ; dále doplní počáteční nuly a století;
function isDate(dtStr){
   return isDateReport(dtStr,1)
}

//Zkontroluje, zda je datum ve formátu dd.mm.yyyy ; dále doplní počáteční nuly a století; kdyľ se nastaví report=0, tak nevyskočí okno s hláąkou
function isDateReport(dtStr, report){

   // Deklarace oddělovače dne, měsíce a roku. Minimální a max. rok
  var dtCh= ".";
  var minYear=1900;
  var maxYear=9999;

  if (dtStr == "")  { //Pokud je "dtStr" prázdná proměnná, vrátí (-1)
    return "-1";
  }
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strDay=dtStr.substring(0,pos1);
	var strMonth=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	
	if (strDay.length == 1) strDay = "0"+strDay;
	if (strMonth.length == 1) strMonth = "0"+strMonth;
	if (strYear.length == 2) { //pokud je rok dvoučíselný, doplní "20" nebo "19" (století)
	  if (strYear < 80) strYear = "20" + strYear;
	  else strYear = "19" + strYear;
	}
	
	strYr=strYear
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth,10)
	day=parseInt(strDay,10)

	year=parseInt(strYr,10)
	if (pos1==-1 || pos2==-1){
		if (report)  alert("Zadejte datum ve formátu: dd.mm.rrrr")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		if (report)  alert("Prosím, zadejte správný měsíc!")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		if (report)  alert("Prosím, zadejte správný den!")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		if (report)  alert("Prosím, zadejte rok mezi "+minYear+" a "+maxYear+"!")
		return false
	}
	correct_date = strDay + "." + strMonth + "." +year;
return correct_date; //Vrátí datum ve formátu "dd.mm.yyyy"
}

//Pomocná funkce pro funkci isDate(dtStr)
function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

//Pomocná funkce pro funkci isDate(dtStr)
//vrati pocet dni v unoru pro dany letopocet
function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

//Pomocná funkce pro funkci isDate(dtStr)
//kdyz se zada "n=12", tak vrati pole s poctem dni v kazdem mesici (pozor! Unor vrati vzdy jako 29 dni, i kdyz je vetsinou 28 dni)
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}
//=========================================================================================

//Při ztrátě focusu ověří, zda bylo zadáno číslo (např. pro "5.556.6" - zahlásí chybu)
function checkNumber()  {
	var src_obj_name = event.srcElement.name
	element = document.getElementById(src_obj_name);
	ch_result = isNaN(element.value);
	switch (ch_result)  {
	   case true : {
	      alert('Nebylo zadáno číslo!');
	      document.getElementById(src_obj_name).focus(); break;
	   }
	}
}

//Při ztrátě focusu ověří, zda byl zadán rok (např. "06" - změní na "2006", "55" - změní na "1955")
function checkYear(src_obj_name)  {
	if (document.getElementById(src_obj_name).value == '')	return true;
	el_value = parseInt(document.getElementById(src_obj_name).value, 10);
	switch (true) {
		case (el_value < 1400)	:	{
			el_value = -1; break;
		}
		case (el_value > 2500)	:	{
			el_value = -1; break;
		}
		case (isNaN(el_value))	:	{
			el_value = -1; break;
		}
	}
	if (el_value == -1)	{
      return false
	}
	else	{
		document.getElementById(src_obj_name).value = el_value;		
		return true
	}
}

//Hlídá zadávání desetinného čísla
function guardInputFloat(src_obj_name, e)	{
	   if (e.charCode == 44 || e.charCode == 46)  {
	     //insAtCursor(src_obj_name, ".");	//Čárku nahradí tečkou
	     return false;
	   }
	   if ((e.charCode < 48 || e.charCode > 57) && (e.charCode != 13)) {		// != 13 - povolí stisknutí enteru
	   	//alert('charCode')
	   	return false;
	   }
}

//Hlídá zadávání celého čísla
function guardInputNumber()	{
 with (event)  {
   if ((keyCode < 48 || keyCode > 57) && (keyCode != 13)) {		// != 13 - povolí stisknutí enteru
     returnValue = false;
   }
 }
}

//Vyžádá si potvrzení pro smazání záznamu
function areYouSureDelete()	{
	with (event)	{
		if (confirm('Are You sure to delete the record?')==false)	returnValue=false;
		else returnValue=true;
	}
}

//Vratí n znaků z řetězce str z levé strany
function strLeft(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

//Vratí n znaků z řetězce str z pravé strany
function strRight(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

//Zaokrouhlí number na "dec" desetinných míst
function round(number, dec)	{
	return Math.round(number*Math.pow(10,dec))/Math.pow(10,dec);
}


//Vrátí dnešní datum ve formátu dd.mm.yyyy
function getTodayDate() {
	var today=new Date();
	var den;
	var mesic;
	if (today.getDate() < 10) den = "0" + today.getDate(); else den = today.getDate();
	if (today.getDate() < 10) mesic = "0" + today.getMonth(); else mesic = today.getMonth();
	return den +"."+(today.getMonth()+1)+"."+(today.getYear());
}

//Vrátí datum o jeden den větší
function datePlus(myDate){ //myDate - datum ve formátu dd.mm.yyyy
	if (myDate)	{
		newDate = new Date();
		newDatePlus = new Date();
	
		myDay = parseInt(String(myDate).substring(0,2),10);
		myMonth = parseInt(String(myDate).substring(3,5),10);
		myYear = parseInt(String(myDate).substring(6,10),10);
	
		newDate.setTime(0);
		newDate.setHours(0);
		newDate.setMinutes(0);
		newDate.setSeconds(0);
		newDate.setDate(myDay);
		newDate.setMonth(myMonth-1);
		newDate.setFullYear(myYear);
		newDatePlus.setTime(newDate.getTime() + 1000*60*60*24 + 1000*60*60*12); //Je nutné přičíst 24 + 12 hodin (1,5 dne)
		var a = parseInt(newDatePlus.getDate(),10);
		myDay = a > 9? a:"0"+a;
		a = parseInt(newDatePlus.getMonth(),10) + 1;
		myMonth = a > 9? (a):"0"+(a);
		myYear = newDatePlus.getFullYear();
		
		return myDay+"."+myMonth+"."+myYear;
	}
	else return '';
}

//Vrátí datum o X dní větší
function datePlusXDays(myDate, nr_days){ //myDate - datum ve formátu dd.mm.yyyy
	if (myDate)	{
		newDate = new Date();
		newDatePlus = new Date();
	
		myDay = parseInt(String(myDate).substring(0,2),10);
		myMonth = parseInt(String(myDate).substring(3,5),10);
		myYear = parseInt(String(myDate).substring(6,10),10);
	
		newDate.setTime(0);
		newDate.setHours(0);
		newDate.setMinutes(0);
		newDate.setSeconds(0);
		newDate.setDate(myDay);
		newDate.setMonth(myMonth-1);
		newDate.setFullYear(myYear);
		newDatePlus.setTime(newDate.getTime() + nr_days*1000*60*60*24 + 1000*60*60*12); //Je nutné přičíst 24 + 12 hodin (1,5 dne)
		var a = parseInt(newDatePlus.getDate(),10);
		myDay = a > 9? a:"0"+a;
		a = parseInt(newDatePlus.getMonth(),10) + 1;
		myMonth = a > 9? (a):"0"+(a);
		myYear = newDatePlus.getFullYear();
		
		return myDay+"."+myMonth+"."+myYear;
	}
	else return '';
}

//Vrátí datum o X měsíců větší
function datePlusXMonths(myDate, nr_months){ //myDate - datum ve formátu dd.mm.yyyy
   var minus = 0

   if (myDate)	{
		var myDay     = parseInt(String(myDate).substring(0,2),10);
		var myMonth   = parseInt(String(myDate).substring(3,5),10);
		var myYear    = parseInt(String(myDate).substring(6,10),10);

      if ((myMonth+nr_months) % 12 == 0) minus = 1

      var yearPlus = Math.floor((myMonth + nr_months) / 12)  - minus
      var newYear  = myYear + yearPlus
      var newMonth = (myMonth + nr_months) % 12
      if (newMonth == 0) newMonth = 12
      
		var newDay = myDay > 9? myDay:"0"+myDay;
		newMonth = newMonth > 9? newMonth:"0"+newMonth;
		
		final_date = newDay+"."+newMonth+"."+newYear;
		if (isDateReport(final_date,0))  {
		   return final_date
		}
		else {
		   do {
   		   myDay -= 1
   		   if (myDay < 20) {alert('Doąlo k chybě při kontrole datumu!'); break;}
   		   newDay = myDay > 9? myDay:"0"+myDay;
   		   final_date = newDay+"."+newMonth+"."+newYear;
         } while (isDateReport(final_date,0) == false)
		   return final_date
		}
	}
	else return '';
}

//Vrátí datum o X měsíců menąí
function dateMinusXMonths(myDate, nr_months){ //myDate - datum ve formátu dd.mm.yyyy
   var minus = 0

   if (myDate)	{
		var myDay     = parseInt(String(myDate).substring(0,2),10);
		var myMonth   = parseInt(String(myDate).substring(3,5),10);
		var myYear    = parseInt(String(myDate).substring(6,10),10);

      if ((myMonth-nr_months) % 12 == 0) minus = 1

      var yearPlus = Math.floor((myMonth - nr_months) / 12)  - minus
      var newYear  = myYear + yearPlus
      var newMonth = (myMonth - nr_months) % 12
      if (newMonth <= 0) newMonth += 12
      
		var newDay = myDay > 9? myDay:"0"+myDay;
		newMonth = newMonth > 9? newMonth:"0"+newMonth;
		
		final_date = newDay+"."+newMonth+"."+newYear;
		if (isDateReport(final_date,0))  {
		   return final_date
		}
		else {
		   do {
   		   myDay -= 1
   		   if (myDay < 20) {alert('Doąlo k chybě při kontrole datumu!'); break;}
   		   newDay = myDay > 9? myDay:"0"+myDay;
   		   final_date = newDay+"."+newMonth+"."+newYear;
         } while (isDateReport(final_date,0) == false)
		   return final_date
		}
	}
	else return '';
}

//Vrátí datum o jeden den menší
function dateMinus(myDate){ //myDate - datum ve formátu dd.mm.yyyy
	if (myDate)	{
		newDate = new Date();
		newDatePlus = new Date();
	
		myDay = parseInt(String(myDate).substring(0,2),10);
		myMonth = parseInt(String(myDate).substring(3,5),10);
		myYear = parseInt(String(myDate).substring(6,10),10);
	
		newDate.setTime(0);
		newDate.setHours(0);
		newDate.setMinutes(0);
		newDate.setSeconds(0);
		newDate.setDate(myDay);
		newDate.setMonth(myMonth-1);
		newDate.setFullYear(myYear);
		newDatePlus.setTime(newDate.getTime() - 1000*60*60*12);	//Je nutné odečíst jen 12 hodin (0,5 dne)
		var a = parseInt(newDatePlus.getDate(),10);
		myDay = a > 9? a:"0"+a;
		a = parseInt(newDatePlus.getMonth(),10) + 1;
		myMonth = a > 9? (a):"0"+(a);
		myYear = newDatePlus.getFullYear();
		
		return myDay+"."+myMonth+"."+myYear;
	}
	else return '';
}

//Vrátí datum o Y dni menší
function dateMinusXDays(myDate, nr_days){ //myDate - datum ve formátu dd.mm.yyyy
	if (myDate)	{
		newDate = new Date();
		newDatePlus = new Date();
	
		myDay = parseInt(String(myDate).substring(0,2),10);
		myMonth = parseInt(String(myDate).substring(3,5),10);
		myYear = parseInt(String(myDate).substring(6,10),10);
	
		newDate.setTime(0);
		newDate.setHours(0);
		newDate.setMinutes(0);
		newDate.setSeconds(0);
		newDate.setDate(myDay);
		newDate.setMonth(myMonth-1);
		newDate.setFullYear(myYear);
		newDatePlus.setTime(newDate.getTime() - 1000*60*60*12 - 1000*60*60*24*(nr_days-1));	//Je nutné odečíst jen 12 hodin (0,5 dne)
		var a = parseInt(newDatePlus.getDate(),10);
		myDay = a > 9? a:"0"+a;
		a = parseInt(newDatePlus.getMonth(),10) + 1;
		myMonth = a > 9? (a):"0"+(a);
		myYear = newDatePlus.getFullYear();
		
		return myDay+"."+myMonth+"."+myYear;
	}
	else return '';
}

//Uloží hodnotu zvolenou v JavaScriptovém selektu a skryje tento select
function selectClick(sel_name, hidden_name, hidden_val, data_name, data_val)	{
	document.getElementById(sel_name).style.display = 'none';
	document.getElementById(hidden_name).value = hidden_val;
	document.getElementById(data_name).value = data_val;
}

//Uloží hodnotu zvolenou v JavaScriptovém selektu Workers a skryje tento select
function selectClickWorker(sel_name, surname, name, hidden_val, data_val)	{
	if (document.getElementById(sel_name))	document.getElementById(sel_name).style.display = 'none';
	if (document.frm_main.in_worker_id.length == undefined)	{
		document.frm_main.in_worker_id.value = hidden_val;
		document.frm_main.tx_worker.value = data_val;
		document.frm_main.tx_surname.value= surname;
		document.frm_main.tx_name.value= name;
	}
	else	{
		var id = getCookie("worker_row");
		document.frm_main.in_worker_id[id].value = hidden_val;
		document.frm_main.tx_worker[id].value = data_val;
		document.frm_main.tx_surname[id].value= surname;
		document.frm_main.tx_name[id].value= name;
	}
}

 /* Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
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));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}
