function kontrola_formulare(uzivatel)
{
if (((uzivatel.edit_login.value=="") || (uzivatel.edit_jmeno.value=="")) || (uzivatel.edit_email.value=="")) {
alert("Nezadali jste všechny povinné položky!");
return false;
}
if (uzivatel.edit_old_login.value=="") {
  if ((uzivatel.edit_heslo.value=="") || (uzivatel.edit_heslo_over.value=="")) {
    alert("Nezadali jste všechny povinné položky!");
    return false;
  }
}

RE_mail=/^[a-zA-Z0-9]+([\._-]?[a-zA-Z0-9])*@[a-zA-Z0-9]+([.-]?[a-zA-Z0-9])*\.[a-zA-Z]{2,4}$/
if (!RE_mail.test(uzivatel.edit_email.value)) {
alert("Email není ve správném formátu");
return false;
}

if (uzivatel.edit_heslo.value!=uzivatel.edit_heslo_over.value) {
alert("Ověření hesla se nepodařilo, hesla nejsou stejná!");
return false;

}

return true;
}

function kontrola_zmeny_hesla(formular) {
if (((formular.old_heslo.value=="") || (formular.new_heslo.value=="")) || (formular.new_heslo_2.value=="")) {
  alert("Nevyplnili jste všechny povinné položky");
  return false;
}
if (formular.new_heslo.value!=formular.new_heslo_2.value) {
  alert("Ověření hesla se nezdařilo, nové a ověřovací heslo jsou rozdílné");
  return false;
}

return true 
}

function kontrola_data(hodnota,prazdne,text) {
RE_mail=/^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{4}$/
if ((prazdne) && (hodnota=="")) return true;
if (!RE_mail.test(hodnota)) {
alert(text+" není ve správném formátu (dd.mm.rrrr)");
return false;
}
return true;
}

function kontrola_textu(hodnota,text) {
	if (hodnota=="") {
		alert(text+" nesmí být prázdný text.");
		return false;
	}
		return true;
}

function add_firma() {
  firma=document.getElementById('nazev_firmy_id').value;
  email=document.getElementById('email_firmy_id').value;
  if (firma!="") {
  RE_mail=/^([a-zA-Z0-9]+([\._-]?[a-zA-Z0-9])*@[a-zA-Z0-9]+([.-]?[a-zA-Z0-9])*\.[a-zA-Z]{2,4})?$/
  if (!RE_mail.test(email)) {
    alert("Email není ve správném formátu");
    return false;
  }
  var oScript = document.createElement('script');
  oScript.setAttribute('type','text/javascript');
  oScript.setAttribute('src','podobna_firma.php?new_firma='+firma);
  document.getElementById('js_loader').appendChild(oScript);
  }
  else alert('Nezadali jste název firmy.');
  return false;
}

function podobna_firma(text) {
firma=document.getElementById('nazev_firmy_id').value;
if (text!="") {
potvrd=confirm("V systému již existují firmy s podobným, či stejným názvem : \n\n"+text+"\nOpravdu chcete firmu "+firma+" přidat");
}
else potvrd=true;

if (potvrd) {
  email=document.getElementById('email_firmy_id').value;
  data="&new_kontakt="+document.getElementById('konakt_firmy_id').value;
  data+="&new_ulice="+document.getElementById('ulice_firmy_id').value;
  data+="&new_mesto="+document.getElementById('mesto_firmy_id').value;
  data+="&new_psc="+document.getElementById('psc_firmy_id').value;
  
  data+="&new_ico="+document.getElementById('ico_firmy_id').value;
  data+="&new_dic="+document.getElementById('dic_firmy_id').value;
  data+="&new_telefon="+document.getElementById('telefon_firmy_id').value;
  
  data+="&new_fax="+document.getElementById('fax_firmy_id').value;
 
  var oScript = document.createElement('script');
  oScript.setAttribute('type','text/javascript');
  oScript.setAttribute('src','edit_firma.php?new_firma='+firma+"&new_email="+email+data);
  document.getElementById('js_loader').appendChild(oScript);
}
else
  schovej('js_working');
}

function pridej_firmu(firma, id) {
  arr_tit2[arr_tit2.length]=firma;
  arr_val2[arr_val2.length]=id;
  schovej('js_working');
}

function zobraz(co) {
//alert("jede");
  var okno = document.createElement('div');
//  okno.setAttribute('class','hlaska')
  okno.setAttribute('id','hlaska_1')
  okno.className="hlaska";
  okno.innerHTML="";
  okno.innerHTML+="<div style='width:250px;margin:0px'><table class='edit' cellpadding=5 style='border-collapse:collapse;border:0px;' cellspacing=0><tr><th colspan=2> Vložení firmy</th></tr><tr> <td></td></tr><tr> <td> <b>Název</b></td> <td> <input type=text name=nazev_firmy id=nazev_firmy_id maxlength=50></td></tr><tr> <td> Kontaktní&nbsp;osoba</td> <td> <input type=text name=kontakt_firmy id=konakt_firmy_id maxlength=60></td></tr><tr> <td> Ulice</td> <td> <input type=text name=ulice_firmy id=ulice_firmy_id maxlength=60></td></tr><tr> <td> Město</td> <td> <input type=text name=mesto_firmy id=mesto_firmy_id maxlength=60></td></tr><tr> <td> PSČ</td> <td> <input type=text name=psc_firmy id=psc_firmy_id size=6 maxlength=6></td></tr><tr> <td> IČO</td> <td> <input type=text name=ico_firmy id=ico_firmy_id size=15 maxlength=15></td></tr><tr> <td> DIČ</td> <td> <input type=text name=dic_firmy id=dic_firmy_id size=18 maxlength=18></td></tr><tr> <td> Telefon</td> <td><input type=text name=telefon_firmy id=telefon_firmy_id size=20 maxlength=20></td></tr><tr> <td> FAX</td> <td> <input type=text name=fax_firmy id=fax_firmy_id size=20 maxlength=20></td></tr><tr> <td> E-mail</td> <td> <input type=text name=email_firmy id=email_firmy_id maxlength=50></td></tr><tr> <td></td> <td><button onclick='add_firma()'> Uložit</button> &nbsp;<button onclick='schovej(\""+co+"\")'> Zrušit</button></td></tr></table> &nbsp;* tučně označené položky je třeba vyplnit</div>";
  okno.style.width="250px";
  okno.style.height="370px";
  okno.style.top=(document.body.scrollTop+(document.body.clientHeight-370)/2) + "px";
  okno.style.left=(document.body.clientWidth-200)/2 + "px";
  //okno.style.background="red";
  comba=document.getElementsByTagName('select');
  for (var n = 0; n < comba.length; n++)
    comba[n].style.visibility="hidden";
  var okno2=document.createElement('div');
  okno2.className="vyskakovaci_div";
  
  okno2.style.width=document.body.clientWidth;
  okno2.style.height=document.body.scrollHeight;
  okno2.style.display="block";
  
  okno3=document.getElementById(co);
  okno3.style.display="block";
  okno3.style.zIndex="200";

  okno3.appendChild(okno2);
  okno3.appendChild(okno);
  return false;
}

function schovej(co) {
  document.getElementById(co).style.display="none";
  comba=document.getElementsByTagName('select');
  for (var n = 0; n < comba.length; n++)
    comba[n].style.visibility="visible";
  document.getElementById(co).removeChild(document.getElementById("hlaska_1"));
return false;
}

function del_file(id) {
  if (id!=0) {
    td = document.createElement("td");
    td.style.border="none";
    td.colSpan=4;
    neco = document.createTextNode(" ");
    td.appendChild(neco);
    element=document.getElementById("divfile_"+id);
    while (element.firstChild) {
     element.removeChild(element.firstChild);
    }
    element.appendChild(td);
    
    //document.getElementById("divfile_"+id).innerHTML="<td colspan=4 style=\"border:none;\">&nbsp;</td>";
    element.style.background="url('./images/progress.gif')";
    element.style.height="20px";
    var oScript = document.createElement('script');
    oScript.setAttribute('type','text/javascript');
    oScript.setAttribute('src','smaz_file.php?id='+id);
    document.getElementById('js_loader').appendChild(oScript);

  }
}

function skryj_file(id) {
  //alert("mazu2");
  document.getElementById(id).style.display="none";
  document.getElementById(id).parentNode.removeChild(document.getElementById(id));
  document.getElementById("files_title").rowSpan-=1;
  //alert(document.getElementById("files_titl e").rowSpan);
  multi_selector.max++;
  
}

function validuj_datum(id_termin,id_zahajeni) {
//alert('Testuji datum...');
termin=document.getElementById(id_termin).value
zahajeni=document.getElementById(id_zahajeni).value
if ((termin!="") && (zahajeni!="")) {
  term=termin.split(".");
  zah=zahajeni.split(".");
  var termDate=new Date();
  termDate.setFullYear(term[2]);
  termDate.setMonth(term[1]-1);
  termDate.setDate(term[0]);
  var zahDate=new Date();
  zahDate.setFullYear(zah[2]);
  zahDate.setMonth(zah[1]-1);
  zahDate.setDate(zah[0]);
  if (termDate<zahDate) {
  alert('Termín ukončení je starší než datum zadání. Nastavuji datum zahájení');
  document.getElementById(id_termin).value=zahajeni;
  }
  //alert("Zatim nefungujici kontrola datumu : "+term[2]+term[1]+term[0]);
  return false;
}
return true;
}

function zak_over(titulek,text) {
if (titulek=="") {
  alert("Titulek je nutné vyplnit.");
  return false;
}
if (text=="") {
  alert("Text je nutné vyplnit.");
  return false;
}
return true;
}

function chces_smazat() {
  return confirm("Opravdu chce danou položku smazat ?");
}

function zmena_opakovani(form) {
  //alert(form.opakovani.value);
  if (form.opakovani.value==0) {
    form.den_navstevy.disabled=true;
    form.cas_hod.disabled=true;
    form.cas_min.disabled=true;
    form.zacatek.disabled=true;
    //form.kalendar.disabled=true;
    return true;
  }
  if (form.opakovani.value==2) {
    //form.zacatek.
    for (i=0;form.zacatek.options.length>0;i++) {
      form.zacatek.options[0] = null;
    }
    form.zacatek.options[0]= new Option('Sudé týdny','100');
    form.zacatek.options[1]= new Option('Liché týdny','101');
    form.den_navstevy.disabled=false;
    form.cas_hod.disabled=false;
    form.cas_min.disabled=false;
    form.zacatek.disabled=false;
    
  return true;
  }
    for (i=0;form.zacatek.options.length>0;i++) {
      form.zacatek.options[0] = null;
    }
    form.zacatek.options[0]= new Option('1. týden v měsíci','1');
    form.zacatek.options[1]= new Option('2. týden v měsíci','2');
    form.zacatek.options[2]= new Option('3. týden v měsíci','3');
    form.zacatek.options[3]= new Option('4. týden v měsíci','4');
  
    form.den_navstevy.disabled=false;
    form.cas_hod.disabled=false;
    form.cas_min.disabled=false;
    form.zacatek.disabled=false;
    //form.kalendar.disabled=false;
  
  
}

// nacteni hodnot o firme do formulare dle jejiho ID
function ajax_get_firma(firma_id, form_id)
{ 
 var http_request = false;
 var data = "id=" + encodeURIComponent(firma_id) + '&';
 
 // vytvoreni XMLHttpRequest pro FF a IE
 if (window.XMLHttpRequest) 
 {
   http_request = new XMLHttpRequest();
 } 
 else if (window.ActiveXObject) 
 {
   try 
   {
     http_request = new ActiveXObject("Msxml2.XMLHTTP");
   } 
   catch (eror) 
   {
     http_request = new ActiveXObject("Microsoft.XMLHTTP");
   }
 }

 // odchyceni vysledku
 http_request.onreadystatechange = function() 
 { 
   if (http_request.readyState == 4) 
   {
     if (http_request.status == 200) 
     {
       // naplneni formulare prijatymi daty
       hodnoty=http_request.responseText.split(";;;");
       form_id.edit_firma_nazev.value=hodnoty[0];
       form_id.edit_jmeno.value=hodnoty[1];
       form_id.edit_telefon.value=hodnoty[2];
       form_id.edit_email.value=hodnoty[3];
       form_id.adresa.value=hodnoty[4];
       form_id.edit_ICO.value=hodnoty[5];
       form_id.edit_DIC.value=hodnoty[6];
     } 
     else if(http_request.status == 0)
     {
       alert('Váš prohlížeč bohužel tuto operaci nedokáže provést.');
     }
     else
     {
       alert(http_request.status+' - Operaci se nepovedlo úspěšně dokončit.');
     }
   }
 };
 // odeslani formulare na zadanou url
 http_request.open("POST", "./get_firma.php", true); 
 http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
 http_request.send(data);
  
}  // ajax_get_firma();

// nacteni hodnot o firme do formulare dle jejiho ID
function ajax_get_firma_fakt(firma_id, div_id)
{ 
 var http_request = false;
 var data = "edit_firma=" + encodeURIComponent(firma_id) + '&';
 
 // vytvoreni XMLHttpRequest pro FF a IE
 if (window.XMLHttpRequest) 
 {
   http_request = new XMLHttpRequest();
 } 
 else if (window.ActiveXObject) 
 {
   try 
   {
     http_request = new ActiveXObject("Msxml2.XMLHTTP");
   } 
   catch (eror) 
   {
     http_request = new ActiveXObject("Microsoft.XMLHTTP");
   }
 }

 // odchyceni vysledku
 http_request.onreadystatechange = function() 
 { 
   if (http_request.readyState == 4) 
   {
     if (http_request.status == 200) 
     {
       // naplneni formulare prijatymi daty
       document.getElementById(div_id).innerHTML=http_request.responseText;
     } 
     else if(http_request.status == 0)
     {
       alert('Váš prohlížeč bohužel tuto operaci nedokáže provést.');
     }
     else
     {
       alert(http_request.status+' - Operaci se nepovedlo úspěšně dokončit.');
     }
   }
 };
 // odeslani formulare na zadanou url
 http_request.open("POST", "./get_firma_fakt.php", true); 
 http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
 http_request.send(data);
  
}  // ajax_get_firma_fakt();

function check_add_firm(form) {
  var undefined;
  //if (form.odeslano.value!=undefined) form.kontrola.value="odeslano";
  //if (form.odeslano2.value!=undefined) form.kontrola.value="odeslano2";
  //alert("spoustim fci pri odeslani");
  //if (form.kontrola.value=="ano") return true;
  if (form.edit_nazev.value=="") {
    alert("Název firmy je nutné vyplnit.");
    return false;
  }
  if (form.edit_ico.value!="") {
    if (isNaN(form.edit_ico.value)) {
      alert("IČO se může skládat pouze z číslic.");
      return false;
    }
  }
  if (form.edit_email.value!="") {
  RE_mail=/^([a-zA-Z0-9]+([\._-]?[a-zA-Z0-9])*@[a-zA-Z0-9]+([.-]?[a-zA-Z0-9])*\.[a-zA-Z]{2,4})?$/
  if (!RE_mail.test(form.edit_email.value)) {
    alert("Email není ve správném formátu");
    return false;
  }
  }
  // tady je kontrola na existenci podobne firmy v systemu
  if (form.id.value==0) {
  //alert("pozadam o kontrolu");
  var oScript = document.createElement('script');
  oScript.setAttribute('type','text/javascript');
  oScript.setAttribute('src','podobna_firma.php?verze=odeslat&new_firma='+form.edit_nazev.value);
  document.getElementById('js_loader').appendChild(oScript);
  return false;
  }
  return true;
}

function podobna_firma_odeslat(text) {
firma=document.getElementById('nazev_firmy_id').value;
potvrd=true;
if (text!="") {
potvrd=confirm("V systému již existují firmy s podobným, či stejným názvem : \n\n"+text+"\nOpravdu chcete firmu "+firma+" přidat");
}
if (potvrd) {
//alert("odesilam formular")
var odesl=document.createElement('input');
odesl.type = 'hidden';
odesl.name = 'odeslano';
odesl.value= 'ano'
document.forms['formular'].appendChild(odesl);
//document.getElementById('frm').submit();

document.forms['formular'].submit();
//alert("po odeslani");
}
}

function menu_rozbal(co,zahlavi) {
var dnu = 7;
var datum= new Date(); // získá aktuální datum v milisekundách
datum.setTime(datum.getTime() + 1000 * 60 * 60 * 24 * dnu); // k datu přidá počet dnů

if ((document.getElementById(co).style.display=="none")) 
{
  document.getElementById(co).style.display="block";
  zahlavi.setAttribute("class", "zahlavi open"); 
  zahlavi.setAttribute("className", "zahlavi open"); 
  document.cookie = "easytask_"+ co + "=block;expires=" + datum.toGMTString(); 
}
else 
{
  document.getElementById(co).style.display="none";
  zahlavi.setAttribute("class", "zahlavi close"); 
  zahlavi.setAttribute("className", "zahlavi close"); 
  document.cookie = "easytask_"+ co + "=none;expires=" + datum.toGMTString(); 
}
}

function toggle(co) {
	
	akt=document.getElementById(co).className;
	if (akt=="hide")
		document.getElementById(co).className="unhide";	
	else		
		document.getElementById(co).className="hide";
}	


/*******************************
            FIRMA
*******************************/

function checkFirmaValue(hidden_id){
/*
check if hidden value firma is set
*/
  if (!getElem(hidden_id).value || getElem(hidden_id).value < 0){
    alert('Zadejte prosím firmu.');
    return false;
  }  
  return true;
}

function setHiddenVal(arr_tit, arr_val, input_id, hidden_id){
/*
function sets value of hidden variable if value is in array
*/
  var input_val = getElem(input_id).value;
  //try to find 
  for (var i=0; i < arr_tit.length; i++){
    if (arr_tit[i].match(input_val)){
      getElem(hidden_id).value = arr_val[i];
      return true;
    }
  }
  
  alert('Zadaná firma neodpovídá žádné existující.');
  return false;
}


/*******************************
            SUGGEST - naseptavac
*******************************/
function getElem(id){
  return document.getElementById(id);
}

function getTag(id){
  return document.getElementByTagName(id);
}
function getKeycode(e) {
/*
return last keycode
*/
  if (window.event) { 
    return window.event.keyCode;
  }
  else if (e) {
    return e.which;
  }
  else {
    return false;
  }
}
//array of suggest resutls
var arr_result = new Array();

//active suggest result LI tag (index in array of results)
var active_li = -1;

function initSuggestInput(id){
  getElem(id).setAttribute('autocomplete','off');
}

function createSuggest(e, arr_tit, input_id, suggest_id, onselect_action){
/*
check titles array with query string and create suggest block nodes for corresponding 
titles (corresponing titles are pushed into arr_result)
*/
 //create new suggest exept following keys (arrows and enter)
 var key = getKeycode(e);
 if (key != 40 && key != 38 && key != 13){
  //prepare values
  var query = getElem(input_id);
  var suggest = getElem(suggest_id);
  while (suggest.childNodes.length > 0)
    suggest.removeChild(suggest.childNodes[0]);
  var found = false;

  //init global variables
  arr_result = new Array();
  active_li = -1;
  
  //get results
  var query_lower = query.value.toLowerCase();
  var displayed = 0;
  var max_display = 10;
  for (var i=0; i < arr_tit.length; i++){
    if (displayed <= max_display && arr_tit[i].toLowerCase().match(query_lower)){
      //init values
      displayed++;
      found = true;
      arr_result.push(arr_tit[i]);
      //display results
      var li = document.createElement("LI");
      li.innerHTML = arr_tit[i];
      //hide if limit is over or title doesn't match
/*      if (displayed > max_display || !arr_tit[i].toLowerCase().match(query_lower)){
        li.style.display = 'none';
      }
      else{
        displayed++;
      }*/
      suggest.appendChild(li);
      //OnMouseOver background function
      li.onmouseover = function(){
        if (active_li > -1){  //unset values set with arrow keys  
          getElem(suggest_id).childNodes[active_li].className = 'suggest_li';
          active_li = -1;
        }
        this.className = 'suggest_li_hover';
      }
      //OnMouseOut background function
      li.onmouseout = function(){
        this.className = 'suggest_li';
      }
      //OnClick function -> set input field value
      li.onclick = function(){
        //set input field value
        getElem(input_id).value = this.firstChild.nodeValue;
        //onselect action
        suggestOnSelect(arr_tit, input_id, suggest_id, onselect_action);
      }
    }
  }

  //display suggest if result found
  if (found) {
    if (getElem(suggest_id).style.visibility=="visible") getElem(suggest_id).style.visibility = "hidden";
    else displaySuggest(1, suggest_id);
  } else {
    getElem(suggest_id).style.visibility = "hidden";
  }
 }
}

function displaySuggest(st, suggest_id) {
/*
hide or dispaly suggest array
*/
  self.act = st;
  var ul = getElem(suggest_id);
  if (st){
    clearTimeout(self.timer);
    ul.style.visibility = "visible";
  } else {
    var f = function(){ul.style.visibility = "hidden";}
    self.timer = setTimeout(f, 500);
  }
}

function moveSuggestCursor(e, arr_tit, input_id, suggest_id, onselect_action){
/*
move highlighted cursor and activity of LI tag in Suggest box
*/
  var key = getKeycode(e);

  if (key == '38'){       //arrow up
    if (active_li > 0){
      if (active_li > -1){  //unset values set with arrow keys  
        getElem(suggest_id).childNodes[active_li].className = 'suggest_li';
      }
      active_li--;
      getElem(suggest_id).childNodes[active_li].className = 'suggest_li_hover'; 
    }
  }  
  else if (key == '40'){  //arrow down
    if (active_li < arr_result.length-1){
      if (active_li > -1){  //unset values set with arrow keys  
        getElem(suggest_id).childNodes[active_li].className = 'suggest_li';
      }
      active_li++;
      getElem(suggest_id).childNodes[active_li].className = 'suggest_li_hover';
    }
  }
  else if ((key == '13') || ((key == '9'))){  //enter
    //set input field value
    if(arr_result[active_li]!=undefined)
    getElem(input_id).value = arr_result[active_li];
    else getElem(input_id).value = "";
    //onselect action
    suggestOnSelect(arr_tit, input_id, suggest_id, onselect_action);
    //hide suggest
    getElem(suggest_id).style.visibility = "hidden";
  }
}

function checkInputVariable(arr_tit, input_id, suggest_id){
/*
function check if variable in query input exists in array of values
if not, clear input and set it focus
*/
  var query = getElem(input_id);
  var found = false;
  //try to find 
  for (var i=0; i < arr_tit.length; i++){
    if (arr_tit[i] == query.value){
      found = true;
    }
  }
  //not found
  if (!found){
    alert('Vložená hodnota nebyla nalezena v seznamu');
    getElem(input_id).value='';
    getElem(input_id).focus();
  }
}

/***** ON SUGGEST SELECT FUNCTIONS *****/

function suggestOnSelect(arr_tit, input_id, suggest_id, onselect_action){
/*
function do onselect actions specified in 'onselect_action' parametter 
*/
  /* specialities */
  //menu link -> automaticly reload to current link  
  if (onselect_action == 'menu'){
    var idx = getSelectedIndex(arr_tit, input_id, suggest_id);
    window.open(link_root + '/' + arr_link[idx] + menu_code, "_self", "");
  }
  else if (onselect_action == 'edit_firma'){
    var idx = getSelectedIndex(arr_tit, input_id, suggest_id);
    getElem('frm').edit_firma.value = arr_val2[idx];
  }
}

function getSelectedIndex(arr_tit, input_id, suggest_id){
/*
function return index of selected value in suggest (return -1 if not found)
*/
  var query = getElem(input_id);
  //try to find 
  var query_lower = query.value.toLowerCase();
  for (var i=0; i < arr_tit.length; i++){
    if (arr_tit[i].toLowerCase().match(query_lower)){
      return i;
    }
  }
  return -1;
}
/**
 * Convert a single file-input element into a 'multiple' input list
 *
 * Usage:
 *
 *   1. Create a file input element (no name)
 *      eg. <input type="file" id="first_file_element">
 *
 *   2. Create a DIV for the output to be written to
 *      eg. <div id="files_list"></div>
 *
 *   3. Instantiate a MultiSelector object, passing in the DIV and an (optional) maximum number of files
 *      eg. var multi_selector = new MultiSelector( document.getElementById( 'files_list' ), 3 );
 *
 *   4. Add the first element
 *      eg. multi_selector.addElement( document.getElementById( 'first_file_element' ) );
 *
 *   5. That's it.
 *
 *   You might (will) want to play around with the addListRow() method to make the output prettier.
 *
 *   You might also want to change the line 
 *       element.name = 'file_' + this.count;
 *   ...to a naming convention that makes more sense to you.
 * 
 * Licence:
 *   Use this however/wherever you like, just don't blame me if it breaks anything.
 *
 * Credit:
 *   If you're nice, you'll leave this bit:
 *  
 *   Class by Stickman -- http://www.the-stickman.com
 *      with thanks to:
 *      [for Safari fixes]
 *         Luis Torrefranca -- http://www.law.pitt.edu
 *         and
 *         Shawn Parker & John Pennypacker -- http://www.fuzzycoconut.com
 *      [for duplicate name bug]
 *         'neal'
 */
 
function MultiSelector( list_target, max ){

	// Where to write the list
	this.list_target = list_target;
	// How many elements?
	this.count = 0;
	// How many elements?
	this.id = 0;
	// Is there a maximum?
	if( max ){
		this.max = max;
	} else {
		this.max = -1;
	};
	
	/**
	 * Add a new file input element
	 */
	this.addElement = function( element ){

		// Make sure it's a file input element
		if( element.tagName == 'INPUT' && element.type == 'file' ){

			// Element name -- what number am I?
			element.name = 'edit_soubor[' + this.id++ +']';

			// Add reference to this object
			element.multi_selector = this;

			// What to do when a file is selected
			element.onchange = function(){

				// New file input
				var new_element = document.createElement( 'input' );
				new_element.type = 'file';
				new_element.size = 50;

				// Add new element
				this.parentNode.insertBefore( new_element, this );

				// Apply 'update' to element
				this.multi_selector.addElement( new_element );

				// Update list
				this.multi_selector.addListRow( this );

				// Hide this: we can't use display:none because Safari doesn't like it
				this.style.position = 'absolute';
				this.style.left = '-1000px';

			};
			// If we've reached maximum number, disable input element
			if( this.max != -1 && this.count >= this.max ){
				element.disabled = true;
			};

			// File element counter
			this.count++;
			// Most recent element
			this.current_element = element;
			
		} else {
			// This can only be applied to file input elements!
			alert( 'Error: not a file input element' );
		};

	};

	/**
	 * Add a new row to the list of files
	 */
	this.addListRow = function( element ){

		// Row tr
		var new_row = document.createElement( 'div' );
    
		// Delete button
		var new_row_button = document.createElement( 'input' );
		new_row_button.type = 'button';
		new_row_button.value = 'Nepřikládat';
		new_row_button.className='button';

		// References
		new_row.element = element;

		// Delete function
		new_row_button.onclick= function(){

			// Remove element from form
			this.parentNode.element.parentNode.removeChild( this.parentNode.element );

			// Remove this row from the list
			this.parentNode.parentNode.removeChild( this.parentNode );

			// Decrement counter
			this.parentNode.element.multi_selector.count--;

			// Re-enable input element (if it's disabled)
			this.parentNode.element.multi_selector.current_element.disabled = false;

			// Appease Safari
			//    without it Safari wants to reload the browser window
			//    which nixes your already queued uploads
			return false;
		};
  

		// Set row value
    new_row.innerHTML = "&raquo; "+element.value+" ";

		// Add button
		new_row.appendChild( new_row_button );

		// Add it to the list
		this.list_target.appendChild( new_row );
		
	};

};

