/**
* Funkce v JavaScriptu
* By  Blondak
* (c) Blondak
* Posledni uprava: 30.07.2003
*Upravena fce OpenWindow aby centrovala lepe
*/

/* Zmeni  text daneho elementu. Element se urcu je podle id.
* @param elementId Id elementu
* @param elementText Novy text elementu
*/
function changeElementText(elementId, elementText) {
    element = document.getElementById(elementId);
	if (typeof(element) != 'undefined') 
	    element.innerHTML = elementText;
}

/* Zmeni  hodnotu daneho elementu. Element se urcu je podle id.
* @param elementId Id elementu
* @param newValue Novy hodnota
*/
function changeElementValue(elementId,newValue) {
    var element = document.getElementById(elementId);
	if (typeof(element) != 'undefined') {
      element.value = newValue;
	  return element;
	}  
}

/* Nastavi element readOnly podle druheho parametru readOnly. Pozor lze pouze u text, textarea a password elementu
* @param aElementId Id elementu
* @param isReadOnly Novy hodnota
*/
function setReadOnly(aElementId, isReadOnly, aColor) {
  var element = window.document.getElementById(aElementId);
  if (typeof(element) != 'undefined') {
  	element.readOnly = isReadOnly;
  	if (aColor == undefined)
    	if (isReadOnly)		
			aColor = 'silver';
		else
			aColor = 'white';
 	}		
	element.style.backgroundColor= aColor;
}

//vymaze policko formulare
function clearField(fieldName) {
    var fld = document.getElementById(fieldName);
	if (typeof(fld) != 'undefined') 
      fld.value = '';
}

//udela refresh (reload) rodicovskeho okna
function reloadOwner(strLocation){
    if(typeof(window.opener) == 'object') {
      if(strLocation == undefined) strLocation = window.opener.location;
	  window.opener.location =  strLocation;
	}  
}

//odstraneni nadframu
function removeFrames() {
   if (typeof(self.parent.frames) != 'undefined') 
     if (self.parent.frames.length != 0)
        self.parent.location=document.location;
}  

//fce na obnoveni leveho framu (menu)
function reloadMenu()
{
  parent.frames[0].location = parent.frames[0].location;
}

//otevreni okna
function OpenWin(wndName,wndPage, wndWidth, wndHeight, wndLeft, wndTop, isParent, showScrollBars) {
  wnd = window.open (wndPage, wndName, 'scrollbars=no,dependent='+isParent+',width='+wndWidth+',height='+wndHeight+',top=300,left=200,resizable=yes')
  wnd.focus();
}

//otevreni okna, pokud neni zadano wndLeft resp. wndTop, nezadana hodnota se centruje podle obrazovky
function OpenWindow(wndName,wndPage, wndWidth, wndHeight, wndLeft, wndTop, showScrollBars, isParent,isFullScreen) {
  var scWidth = screen.width;
  var scHeight = screen.height;
  if(wndName == undefined) wndName = 'Noname';
  if(wndPage == undefined) {
    alert('Nelze zobrazit nedefinovanou stránku!');
	return false;
  }
  if(wndWidth == undefined) wndWidth = '300';
  if(wndHeight == undefined) wndHeight = '300';
  if(isParent == undefined) isParent = 'yes';
  if(isFullScreen == undefined) isFullScreen = 'no';
  if(showScrollBars == undefined) showScrollBars = 'no';
 
  if((wndLeft == undefined) || (wndLeft == '')) {
     wndLeft = (scWidth - wndWidth)/2; 	
  } 
 
  if((wndTop == undefined) || (wndTop == '')) {
      wndTop = (scHeight - wndHeight)/2; 	
  }	

  wnd = window.open (wndPage, wndName, 'scrollbars='+showScrollBars+',resizable=yes,dependent='+isParent+',width='+wndWidth+',height='+wndHeight+',top='+wndTop+',left='+wndLeft+',fullscreen='+isFullScreen);
  wnd.focus();
}

//zobrazi chybovou stranku
function showError(msg) {
  var strana = 'errorDlg.php?msg='+ msg;
  OpenWindow('Chyba',strana,220,200);
}

//potvrzeni nejeke otzaky/ nebo odmitnuti akce
function confirmDialog(aText) {
  return confirm(aText);
}


//Potvrzeni smazani
function confirmDel() {
  return confirmDialog('Opravdu smazat?');
}

//***************** ZACATEK FCI k DropDownu (<SELECT>)  ******************

//pridani Option do selectu
function appendOption(aSelect,val,txt) {
  
  addOption(aSelect,val,txt, aSelect.length);
  
}

//vyhledani polozky v SELECTU vraci hodnotu indexu pri nalezeni
//pri nenalezeni vraci -1
function findByValue(aSelect, aValue) {
    for(i = 0; i < aSelect.length; i++) {
      if(aSelect.options[i].value == aValue) 
	    return i;
	}	
	return -1;
}

//vybere jednu polozku a ostatni odvybere
function selectOneByValue(sel,aValue) {
  for(i = 0; i < sel.length; i++) {
    if( sel.options[i].value != aValue) {
	  sel.options[i].selected = false;
	} else {
	  sel.options[i].selected = true;
	}  
  }
}

//pridani Option do selectu
function addOption(aSelect,aKey,aText, aIndex) {
  var tempIndex = 0;
  var tempKey = '';
  var tempText = '';
  var oldLen = aSelect.length;
  
  tempIndex = aIndex;
  
  for(tempIndex;tempIndex < oldLen; tempIndex++) {
    tempKey = aSelect.options[tempIndex].value;
	tempText = aSelect.options[tempIndex].text;
	
	aSelect.options[tempIndex].value = aKey;
	aSelect.options[tempIndex].text = aText;
	aKey = tempKey;
	aText = tempText;
	
  }
  
  var opt = new Option(aText,aKey);
  aSelect.options[oldLen] = opt;
}

//vrati hodnotu vybraneho selectu, jinak vrati false
function getValue(sel) {
	var Index = sel.selectedIndex;
	if (Index != -1) {
		return sel.options[Index].value;
	} else {
		return false;
	}
}

//vraci text vybraneho prvku v selectu, jinak vraci false
function getSelectedItemText(sel) {
	var Index = sel.selectedIndex;
	if (Index != -1) {
		return sel.options[Index].text;
	} else {
		return false;
	}
}

//funkce na vymaz polozky v SELECTu 1 polozka
function delOption(sel) {
  var Index = sel.selectedIndex;
  if(Index != -1) {  
    sel.options[Index]=null;
	if(Index == 0) {
	  if(sel.length > 0) {
	    sel.options[Index].selected = true;
	  }
	} else {
	  sel.options[Index-1].selected = true;
	}
  }	else {
    alert('Položka není vybrána!');
  }
}



//funkce na vybrani vsech v <SELECT>
function moveUpInList(sel) {
  var tempKey = '';
  var tempText = '';
  var index = 0;
  if ((sel.selectedIndex != null) && (sel.selectedIndex > 0)  && (sel.selectedIndex != -1)) {
    index = sel.selectedIndex;
	tempKey = sel.options[index].value;
	tempText = sel.options[index].text;
	delOption(sel);
	addOption(sel,tempKey,tempText,index-1);
	selectOnlyOne(sel,index - 1);
  }
}

//funkce na vybrani vsech v <SELECT>
function moveDownInList(sel) {
  var tempKey = '';
  var tempText = '';
  var index = 0;
  if ((sel.selectedIndex != null) && (sel.selectedIndex < sel.length - 1) && (sel.selectedIndex != -1)) {
    index = sel.selectedIndex;
	tempKey = sel.options[index].value;
	tempText = sel.options[index].text;
	delOption(sel);
	addOption(sel,tempKey,tempText,index+1);
	selectOnlyOne(sel,index + 1);
  }
  
}

//vybere jednu polozku a ostatni odvybere
function selectOnlyOne(sel,aIndex) {
  for(i = 0; i < sel.length; i++) {
    if( i != aIndex) {
	  sel.options[i].selected = false;
	} else {
	  sel.options[i].selected = true;
	}  
  }
}

//funkce na vybrani vsech v <SELECT>
function selectAllInList(sel) {
  var i = 0;
  while( i < sel.length) {
	sel.options[i].selected = true;
	i++;
  }	
}

//funkce na vyprazdneni SELECTu
function clearlist(sel)
{
  do
  {
    sel.options[0]=null;
  }	
  while(sel.length >0);	
}

//funkce na vyprazdneni, naplneni selectu
function populate(ParentSelect,ChildSelect,FromArray)
{   
  var x = 0;
  clearlist(ChildSelect);
  
  for(i=0;i<FromArray.length;i++)
  {
	if(FromArray[i][0] == ParentSelect.options[ParentSelect.selectedIndex].value)
	{ 
	  eval('var option'+x+' = new Option(FromArray[i][2],FromArray[i][1])');
	  x = x+1;
	}  
  }
  for (var i=0; i < x; i++) 
    eval('ChildSelect.options[i]=option' + i);
}


//********************* KONEC Fci k <SELECT> ***************************************************


//funkce na naplneni 2x pole Nx3
function PullToArray(arr,a,b,c) {
   var tempArray = new Array(a,b,c);
   arr[arr.length] = tempArray;
}

// zjisteni zda pole neni prazdny
function isblank(s)
{
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}

//validace formulare *************
function verify(f)
{
    var msg;
    var empty_fields = "";
    var errors = "";

    
    for(var i = 0; i < f.length; i++) {
        var e = f.elements[i];
        
		if ((e.type == "select-one") && (!e.optional) && (f.validateSelect == 1)) {
			if (e.selectedIndex < 1){
                empty_fields += "\n          " + e.name;
                }
			}
		
		if (((e.type == "text") || (e.type == "textarea")) && !e.optional) {
            // first check if the field is empty
            if ((e.value == null) || (e.value == "") || isblank(e.value)) {
                empty_fields += "\n          " + e.name;
                continue;
            }

            // Now check for fields that are supposed to be numeric.
            if (e.numeric || (e.min != null) || (e.max != null)) { 
                var v = parseFloat(e.value);
                if (isNaN(v) || 
                    ((e.min != null) && (v < e.min)) || 
                    ((e.max != null) && (v > e.max))) {
                    errors += "- The field " + e.name + " must be a number";
                    if (e.min != null) 
                        errors += " that is greater than " + e.min;
                    if (e.max != null && e.min != null) 
                        errors += " and less than " + e.max;
                    else if (e.max != null)
                        errors += " that is less than " + e.max;
                    errors += ".\n";
                
				}
            }
        			
		}
	}
	
    
	
    if (!empty_fields && !errors) return true;

	    if(f.jazyk == 'CZ'){
		msg  = "______________________________________________________\n\n"
	    msg += "Formulář nebyl odeslán díky následujícím chybám.\n";
    	msg += "Prosím opravte tyto chyby a odešlete formulář znovu.\n";
	    msg += "______________________________________________________\n\n"
		}
		else{
		msg  = "______________________________________________________\n\n"
	    msg += "The form was not submitted because of the following error(s).\n";
    	msg += "Please correct these error(s) and re-submit.\n";
	    msg += "______________________________________________________\n\n"
		}
    
	if (empty_fields) {
        if(f.jazyk == 'CZ'){
		msg += "- Následující povinné položky jsou prázdné:" 
                + empty_fields + "\n";
		}
		else{
		msg += "- The following required field(s) are empty:" 
                + empty_fields + "\n";
		}
        if (errors) msg += "\n";
    }
    msg += errors;
    alert(msg);
    return false;
}

//validace prihl formulare
function Validator(theForm)
{

  if (theForm.logname.value == "")
  {
    alert("Uživatelské jméno je nutné zadat");
    theForm.logname.focus();
    return (false);
  }

  if (theForm.logname.value.length > 12)
  {
    alert("Jméno nad 12 písmen");
    theForm.logname.focus();
    return (false);
  }

  if (theForm.pwd.value == "")
  {
    alert("Heslo je nutné zadat");
    theForm.pwd.focus();
    return (false);
  }

  if (theForm.pwd.value.length > 12)
  {
    alert("Heslo nad 12 písmen");
    theForm.pwd.focus();
    return (false);
  }
  return (true);
}


function changeIFrame(striFrameName, strPage, strIdVar, strIdValue,pageName) {
  var frameSrc = strPage + '?' + strIdVar + '='+strIdValue+'&showMenu=false&pageName='+pageName;
  parent.frames[striFrameName].document.location.replace(frameSrc);//myiFrame.window.location.replace(frameSrc);
}

function paintRow(theRow,bgColor,colNumber) {

    if (typeof(document.getElementsByTagName) != 'undefined') {
      theCells = theRow.getElementsByTagName('td');
	}	
    else {
	  if (typeof(theRow.cells) != 'undefined') 
        theCells = theRow.cells;
      else 
        return false;
    }  
//	alert(colNumber);
    for (c = 0; c < theCells.length; c++){
       if((colNumber == 'undefined') || (colNumber != c))
		theCells[c].style.backgroundColor = bgColor;
		//else alert("ok");
	}
   return true;	   
}

var selectedRow = null;

function rowAction(rowHandle,rowId) {
 // var myiFram = window.parent.document.getElementById('vypis');
 // myiFram.src = 'najemci_vypis.php' + '?id_hrob='+rowId;
  
   
}
//fce obarvuje radky a muze pustit nejakou dalsi fci 
function getRow(rowHandle, rowId, action, actionColor,secColor,defColor,colNumber)
{
  var theCells = null;

  if (typeof(rowHandle.style) == 'undefined') //pokud nejde urcit radek tak exit
    return false;

  if(action == 'click') {
    if((selectedRow == null) || (selectedRow != rowHandle)) {
      paintRow(rowHandle,actionColor,colNumber);
	
	  if (selectedRow != null) 
	    paintRow(selectedRow,defColor,colNumber);
	  selectedRow = rowHandle;
	}  
	else {
	  paintRow(rowHandle,secColor,colNumber);
	  if (selectedRow != null) 
	    selectedRow = null;
	}  
  }	
  if( (action != 'click') && ((selectedRow == null) || (selectedRow != rowHandle)) )
    paintRow(rowHandle,actionColor,colNumber);
  
   if( (action == 'click') && (selectedRow == rowHandle))
     rowAction(rowHandle,rowId);
  if( (action == 'click') && (selectedRow == null))
     rowAction(rowHandle,0);	 
    
}

//FCE - commaToDot; autor - Blondak; 18.12.2002
// Prevadi carky na tecky v nejakem prvku formulare 
//vstupni parametr je retezec k prevodu
function commaToDot(aString) {
  return aString.replace(/,/gi,".");
}  

//FCE - isEmailAlias
//vraci true pokud retezec muze byt email  
//jinak vraci false
//vstupni parametr je retezec, ktery by mel byt emailem
function isEmailAlias(email, required) {
    if (required==undefined) {   // if not specified, assume it's required
        required=false;
    }
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
    if (email.length==0) {  
        if (required) {
            return false;
        }
        return true;
    }
    if (! allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        return false;
    } else if (email.indexOf("..") >=0) { // two periods in a row is not valid
	return false;
    } else if (email.indexOf(".") == email.length) {  // . must not be the last character
	return false;
    }
    return true;
}

// pomocna funkce, ktera overuje zda jsou v mailu pouze povolene znaky
function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}

//pozor neni dodelano
function isDate(aDatum, aTyp) { 
  if(aTyp == undefined) aTyp = 'DATE_CZ';
  reg  = new RegExp("[^A-Za-z0-9._-]");
  return (!reg.test(aAlias)) && (aAlias.length > 0);
  
}

/* Nastaveni focusu na dany element, dobry pro formulare
* Pozor Pro Mozzilu a Netsacape nutne Id
*/
function focusElement(aElementId) {
   elem = document.getElementById(aElementId);
   if (typeof(elem) != "undefined") {
     elem.focus();
	 return elem;
   }
   return null;
}

 /*  Odstrani zakrtnuti u radiobuttonu nebo checkboxu
  * @access public
  * @param aBoxId Id checkboxu nebo radiobuttonu k odskrtnuti
  * @return void
  */
  function uncheckBox(aBoxId){
    var box = document.getElementById(aBoxId);
	if (box != null) {
	  box.checked = false;
	}
  }


/*  Zobrazi napovedu pro danou akci - jeji popis (pouziti v changePermisions.tpl v Admin)
* @access public
* @param sel - objekt SELECT z ktereho jsou vybirany akce.
* @param aElementId - ID prvku do ktereho se bude vypisovat, default='napoveda'
* @return void
*/
function setSelectedHelp(sel, aElementId) {
	if ((sel.selectedIndex != null) && (sel.selectedIndex > -1)) {
		index = sel.selectedIndex;
		
		tempText = sel.options[index].text;
		title = sel.options[index].title;
		if (aElementId.length == 0){
			aElementId = 'napoveda';
		}
		changeElementText(aElementId, title);
	}
}

/*==========================================================================#
# * Function for adding a Filter to an Input Field                          #
# * @param  : [filterType  ] Type of filter 0=>Alpha, 1=>Num, 2=>AlphaNum   #
# * @param  : [evt         ] The Event Object                               #
# * @param  : [allowDecimal] To allow Decimal Point set this to true        #
# * @param  : [allowCustom ] Custom Characters that are to be allowed       #
#==========================================================================*/
function filterInput(filterType, evt, allowDecimal, allowCustom){
    var keyCode, Char, inputField, filter = '';
    var alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var num   = '0123456789';
    // Get the Key Code of the Key pressed if possible else - allow
    if(window.event) {
        keyCode = window.event.keyCode;
        evt = window.event;
    } else if (evt) {
    	keyCode = evt.which;
    }
    else {
    	return true;
    }
    // Setup the allowed Character Set
    if(filterType == 0) filter = alpha;
    else if(filterType == 1) filter = num;
    else if(filterType == 2) filter = alpha + num;
    if(allowCustom)filter += allowCustom;
    if(filter == '')return true;
    // Get the Element that triggered the Event
    inputField = evt.srcElement ? evt.srcElement : evt.target || evt.currentTarget;
    // If the Key Pressed is a CTRL key like Esc, Enter etc - allow
    if((keyCode==null) || (keyCode==0) || (keyCode==8) || (keyCode==9) || (keyCode==13) || (keyCode==27) )return true;
    // Get the Pressed Character
    Char = String.fromCharCode(keyCode);
    
    // If the Character is a number - allow
    if((filter.indexOf(Char) > -1)) return true;
    // Else if Decimal Point is allowed and the Character is '.' - allow
    else if(filterType == 1 && allowDecimal && (Char == '.') && inputField.value.indexOf('.') == -1)return true;
    else return false;
}

/*  aparat pro tvorbu dvojice zavislych selectu (napr. okres/mesto)
 *	Priklad uziti:
 *	
 *	//vytvoreni objektu
 *	var f1 = new MeFilter( "f1", "Region", "filteredField" )
 *	
 *	//vlozeni kategorii
 *	f1.AddFlag( 'ovoce' , '1' )
 *	f1.AddFlag( 'zelenina' , '2' )
 *	f1.AddFlag( 'ryby', '3' )
 *	
 *	//vlozeni itemu
 *	f1.Add( 100, 'Jablko' , '1' )
 *	f1.Add( 101, 'Hruška' , '1' )
 *	f1.Add( 105, 'Květák' , '2' )
 *	f1.Add( 106, 'Kapr' , '3' )
 *	
 *	//polozky s jakym ID maji byt selected
 *	f1.iSelMain = 2
 *	f1.iSelFiltered = 0
 *		
 *	//vykresleni obou selectu
 *	f1.WriteTable()
 *				     	
 *	//aby doslo k filtrovani hned pri nacteni stranky
 *	elementA = document.getElementsByName('Region')
 *	elementB = document.getElementsByName('filteredField')
 *	f1.FilterIt(elementA[0], elementB[0])   
*/

function MeFilter( iName , mainSelectName, secondarySelectName) {

    this.instanceName = iName
    this.firstName = mainSelectName
    this.secondName = secondarySelectName

    this.iLength = 0
    this.arrIDs = new Array()
    this.arrNames = new Array()
    this.arrFlags = new Array()

    this.iLengthF = 0
    this.arrIDsF = new Array()
    this.arrNamesF = new Array()

    this.iSelMain = 0
    this.iSelFiltered = 0

    this.Add = function( ID, name, flags ) {
        this.iLength++;
        this.arrNames[this.iLength] = name
        this.arrIDs[this.iLength] = ID
        this.arrFlags[this.iLength] = flags
    }

    this.AddFlag = function( flagName, flagID ) {
        this.iLengthF++;
        this.arrNamesF[this.iLengthF] = flagName
        this.arrIDsF[this.iLengthF] = flagID
    }
    
    this.WriteTable = function( ) {
        document.write('<select name="' + this.firstName + '" onChange="' + this.instanceName + '.FilterIt(this,this.form.' + this.secondName + ')">')
        for(var i=1; i<=this.iLengthF; i++ ) {
        	select = ""
        	if (this.arrIDsF[i] == this.iSelMain) {
        		select = "selected"
        	}
            document.write('<option value="' + this.arrIDsF[i] + '" ' + select + '>' + this.arrNamesF[i] + '</option>' )             
        }
        document.write('</select>')
        document.write('<select name="' + this.secondName + '">')
        document.write('</select>')
    }    

    this.FilterIt = function( sField, fField ) {
        filterStr = sField.options[sField.selectedIndex].value
        this.DeleteSelect( fField )
        for(var i=1; i<=this.iLength; i++ ) {
            if( (this.arrFlags[i]==filterStr) || this.arrFlags[i]=="" ||
            (filterStr=="") ) {
                fField.options[fField.options.length] = new Option(this.arrNames[i]);
                fField.options[fField.options.length-1].value = this.arrIDs[i]
                if (this.arrIDs[i]==this.iSelFiltered) {
                fField.options[fField.options.length-1].selected = true
                }
            }
        }
    }
    
        this.DeleteSelect = function( selectfield ) {
        while(selectfield.length > 0 ) {
        selectfield.options[0] = null;
        }
    }    
}			

/**
 * funkce s kterou pracuje smarty netdogs_mailto slouzici k ochrane 
 * e-mailovych adres zobrazovanych na webu
 */
function MailTo(id, title, style, styleClass, js, box, domain, text) {

	if(typeof(id)!="undefined") {
		id = ' id="'+id+'"'; 
	} else id = '';

	if(typeof(title)!="undefined") {
		title = ' title="'+title+'"'; 
	} else title = '';

	if(typeof(style)!="undefined") {
		style = ' '+style; 
	} else style = '';

	if(typeof(styleClass)!="undefined") {
		styleClass = ' '+styleClass; 
	} else styleClass = '';

	if(typeof(js)!="undefined") {
		js = ' '+js; 
	} else js = '';

	mail = GenMail(box, domain);

	if(typeof(text)=="undefined") {
		text = mail;
	}

	document.write('<a'+id+' href="mailto:'+mail+'" '+title+''+style+''+styleClass+''+js+'>'+text+'</a>');
}

function GenMail(box, domain) {
	if(typeof(domain)=="undefined") {
		domain = mainDomain;
	}
	mail = box+String.fromCharCode(64)+domain;
	return mail;
}

/**
 * funkce zajistujici kompatibilni pridani stranky do oblibenych
 */
function AddFavorite(linkObj,addUrl,addTitle,alert) {
  if (document.all && !window.opera) {
    window.external.AddFavorite(addUrl,addTitle);
    return false;
  } else if (window.opera && window.print) {
    linkObj.title = addTitle;
    return true;
  } else if ((typeof window.sidebar == 'object') && (typeof window.sidebar.addPanel == 'function')) {
      window.sidebar.addPanel(addTitle,addUrl,'');
      return false;
  }
  if (alert != null) {
  	window.alert(alert);
  }
  return false;
}