var oldVal = '';
var str = new Array();
var adresse = new Array();
var tarif = new Array();
var iTimeout = 250;
var timeout = 0;
var kunde = new Array();
var hinweis = 'Klicken Sie eine Adresse aus der Liste an.';
var lang = "DE";
var numMietwagen = 0;
var heute = new Date();
var clearAfteOrder = true; // Switch between clear or filled form after submit
var clearAfterSelect = false; // Switch between clear or filled adress select after onchange
var emptyCol = document.getElementById('emptyCol').value;
var nonEmptyCol = document.getElementById('nonEmptyCol').value;

if (!emptyCol) emptyCol = '#FFCF01';
if (!nonEmptyCol) nonEmptyCol = 'white';

function bookmark(url,title,comment){

  if (window.sidebar)
  {
    // firefox
    window.sidebar.addPanel(title,url,comment);
  }
  
  else if(window.opera && window.print)
  {
    // opera
    var elem = document.createElement('a');
    elem.setAttribute('href',url);
    elem.setAttribute('title',title);
    elem.setAttribute('rel','sidebar');
    elem.click();
  }
  
  else if(document.all)
  {
    // ie
    window.external.AddFavorite(url,title);
  }
}

////////////////////////////////////////////////////////////////////////////////
function Button(lbl,href) {
  return '<span class="art-button-wrapper">'+
         '<span class="l"> </span>'+
         '<span class="r"> </span>'+
         '<a class="art-button" href="'+href+'">'+lbl+'</a>'+
         '</span>';        
}

function colorFields() { 
  var inputs = document.getElementsByTagName('input');
  for(var k=0;k<inputs.length;k++) {
    var input = inputs[k]
    if (input.type != 'text' || input.id.match(/ID/) || input.id.match(/ExtRef/)) continue;
    
    if (input.readOnly) input.style.backgroundColor = nonEmptyCol;
    
    if (input.id == 'AdrStrId') {
      if (input.value == '') document.getElementById('sucheAdr').style.backgroundColor = emptyCol;
      else input.style.backgroundColor = nonEmptyCol;
    }
        
    if (input.id == 'AdrHnr') {
      if (document.getElementById('AdrStrId').value == '') input.style.backgroundColor = nonEmptyCol;
      else if (input.value == '') input.style.backgroundColor = nonEmptyCol;
    }   

    else {
      if (validField(input)) input.style.backgroundColor = nonEmptyCol;
      else input.style.backgroundColor = emptyCol;
    } 
  }
}

function resetFields() {
  tarif.length = 0;
  adresse.length = 0;  
  totalAmount.value = 0;
  
  getTotal();
  while (document.getElementById('preise').hasChildNodes()) {document.getElementById('preise').removeChild(document.getElementById('preise').lastChild);}
  while (document.getElementById('selectAdr').hasChildNodes()) {document.getElementById('selectAdr').removeChild(document.getElementById('selectAdr').lastChild);}                        
  document.getElementById('betrag').innerHTML = '<span class="sum">TOTAL 0,00 &euro;</span>';
  document.getElementById('sucheAdr').value = '';
  document.getElementById('AdrStrId').value = '';
  document.getElementById('AdrPOI').value = '';  
  document.getElementById('AdrStrName').value = '';
  document.getElementById('AdrStrName').readOnly = true;
  document.getElementById('AdrHnr').value = '';
  document.getElementById('AdrHnr').readOnly = true;
  document.getElementById('AdrPlz').value = '';  
  document.getElementById('AdrOrt').value = '';
  document.getElementById('kubem').value = '';
  colorFields();   
}                         

function resetAllFields() {
  document.getElementById('contactVname').value = '';
  document.getElementById('contactNname').value = '';
  document.getElementById('contactEmail').value = document.getElementById('loginEmail').value;  
  document.getElementById('contactTel').value = '';
  document.getElementById('contactExtRef').value = '';
  resetFields();    
}

function hideBesteller() {
  if (document.getElementById('BestellerDaten')) {
    var theDiv = document.getElementById('BestellerDaten');
    if (document.getElementById('entity').value == "KuAdmin") theDiv.style.display = "block";
    else theDiv.style.display = "none";
  }
}

function ccmail() {
  if (document.getElementById('div_ccmail')) {
    var theDiv = document.getElementById('div_ccmail');     
    if (document.getElementById('contactEmail').value != document.getElementById('loginEmail').value) { 
      theDiv.style.display = "block";     
    }        
    else {
      theDiv.style.display = "none";
    }
  }
}

////////////////////////////////////////////////////////////////////////////////
function init() {
  var sel = document.getElementById('stellZt');
  
  if (document.getElementById('loginId')) {
    if (document.getElementById('loginId').value > 0) { 
      if (!isNaN(document.getElementById('loginId').value)) {
        saturnStrFav();
        document.getElementById('fav').style.display = "block"; 
        // getPaxdata(document.getElementById('loginId').value); 
      } 
      else document.getElementById('fav').style.display = "none"; 
    }
  }
        
  if (sel) {
    var elem;
    var selected = false;
    var cont;
    for (var h = 0; h < 24; h++) {
      for (var m = 0; m < 60; m = m + 15) {
        var hour = h + '';
        elem = document.createElement('option');  
        if (heute.getHours() < hour && heute.getMinutes() < min + 30 && !selected) {
            elem.selected = true;
            selected = true;
        }
        if (hour.length == 1) hour = '0' + hour;
        var min = m + '';
        if (min.length == 1) min = '0' + min;
        elem.value = hour + ':' + min;
        cont = document.createTextNode(elem.value);
        sel.appendChild(elem);
        elem.appendChild(cont);
        hideBesteller();
      }
    }
  }    
  if (document.getElementById('lang')) lang = document.getElementById('lang').value;
  iTimeout = document.getElementById('timeout');  
  getControls('InquiryForm.Buttons.Send', 'control');
  getTotal();
  
  document.getElementById('contactEmail').value = document.getElementById('loginEmail').value;  
  colorFields(); 
}

function clearConfirm() {if (document.getElementById('confirm')) document.getElementById('confirm').innerHTML = '';}

function resetForm() {
  clearConfirm;
  resetAllFields();
  getControls('InquiryForm.Buttons.Send', 'control');
}

////////////////////////////////////////////////////////////////////////////////
/// Currency class /////////////////////////////////////////////////////////////
function currency() {
  this.value = 0;  
  this.cSign = document.getElementById('currencySign').value;
  this.culture = document.getElementById('culture').value;
  
  this.convert = function() {
    num = this.value.toString().replace(/\$|\,/g,'');
    if(isNaN(num)) { return ''; }

    sign = (num == (num = Math.abs(num)));
    
    num = Math.floor(num*100+0.50000000001);    
    cents = num%100;
    
    num = Math.floor(num/100).toString();
    if(cents<10) {cents = "0" + cents;}
    
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
      num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));      
    }    
    var newVal = (((sign)?'':'-') + num + '.' + cents + ' ' + this.cSign )

    if (this.culture == 'european') {
      newVal = newVal.replace(/\./,"#");
      newVal = newVal.replace(/\,/,".");
      newVal = newVal.replace(/\#/,","); 
    }
    return newVal;
  }  
}

var totalAmount = new currency();

////////////////////////////////////////////////////////////////////////////////
function shMsg(txt) {
  document.getElementById("errors").innerHTML = 
  document.getElementById("errors").innerHTML + '<br />' + txt;
}

////////////////////////////////////////////////////////////////////////////////
function getTotal() {
  totalAmount.value = 0;
  for (var i = 0; i < tarif.length; i++) {
    totalAmount.value += Boolean(tarif[i][5]) ? parseFloat(tarif[i][3]) : 0;        
  }
  
  if (document.getElementById('contactCash').value == 'FALSE') getControls('InquiryForm.Zmwunsch.Debitor','zm');
  else getControls('InquiryForm.Zmwunsch.Customer','zm');
  
  if (document.getElementById('betrag')) document.getElementById('betrag').innerHTML = 'Total ' +  totalAmount.convert();
  validForm();
}

////////////////////////////////////////////////////////////////////////////////
// Trigger for radios, changes total amount 
function chngMandPrice(tarifId) {
  for (i = 0; i < tarif.length; i++) {
    if (tarif[i][2].toLowerCase() == 'mietwagen') {
      if (tarif[i][0] == tarifId) {tarif[i][5] = true;}
      else {tarif[i][5] = false;}
    }       
  }      
  getTotal();
}
////////////////////////////////////////////////////////////////////////////////
// Trigger for checkboxes, changes total amount 
function chngPrice(chkBoxId) {
  var chkBox = document.getElementById(chkBoxId);
  for (i = 0; i < tarif.length; i++) {
    if (tarif[i][0] == chkBox.value) {
      tarif[i][5] = chkBox.checked;
    }    
  }
  getTotal();
}

////////////////////////////////////////////////////////////////////////////////
// Request a list of tariffs based on a match from the input field (async)
function saturnTarifSuche() {
  var xhr;
  var url = 'checktarif';
  var params = 'kat=' + escape(document.getElementById('kat').value) + 
               '&str=' + escape(document.getElementById('AdrStrId').value) + 
               '&pax=' + escape(document.getElementById('pax').value) +
               '&richtung=' + escape(document.getElementById('richtung').value) +
               '&first=NO';

  // create async call - if you can
  try {
      xhr = new ActiveXObject("MSxml2.XMLHTTP");
  }
  catch (e) {
      try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
      catch (e2) {
          try { xhr = new XMLHttpRequest(); }
          catch (e3) { xhr = false; }
      }
  }
    
  xhr.onreadystatechange = function() { 
    if(xhr.readyState == 4)	{
  		if(xhr.status == 200) {
  		  tarif = new Array();
  		  newTariff(xhr.responseText);  		  
  	  }
  	}
  }
  
  if (xhr) {
    xhr.open('POST', url, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", params.length);
    xhr.setRequestHeader("Connection", "close");
    xhr.send(params);
  }
}

////////////////////////////////////////////////////////////////////////////////
// Fill the tariff array   
function newTariff(xhrResponse) {
  var xhr;
  var tab = document.getElementById('preise');
  var preisliste = document.getElementById('preisliste');
  var str = new Array();
  var betrag = new currency();  
  str = xhrResponse.split('$');
  
  if (str[0] == 'ERROR') {
    alert(str[1]);
    resetFields();
    tarif.length = 0;    
    getTotal();                                                   
  }
  
  else {       
    var isFirst = true;
    var mandatory;
    var values = new Array();
    var recs = new Array();    
    numMietwagen = 0;
    
    recs = xhrResponse.split('$');
     
    if (recs.length > 0) {
  	  
  	  // for each returned tariff create an array entry
      for (var r = 0; r < recs.length; r++ ) {
      
        values = recs[r].split('|');
                         
        tarif[r] = new Array(values.length);
        tarif[r] = values;                

        if (tarif[r][2].toLowerCase() == 'mietwagen') {numMietwagen++}

        betrag.value = tarif[r][3];
        tarif[r][6] = betrag.convert();                 
      }      
      
      // Display
      if (tarif) {
        
        while (tab.hasChildNodes()) {tab.removeChild(tab.lastChild);}  
        
        var row = new Array();
        var cell = new Array();  
        
        var row_num = tarif.length; 
        var cell_num = tarif[0].length + 1; 
        var tbo = document.createElement('tbody');
        
        for(c = 0; c < row_num; c++){
          row[c] = document.createElement('tr');
            
          // Checkbox-Cell           
          cell[0] = document.createElement('td');
          cell[0].id = tarif[c][0];
          cell[0].width = '4%'; 
          cell[0].align = 'left';
          cell[0].setAttribute('style','text-align: left');
          var checkbox = document.createElement('input');
                                        
          // mandatory services
          if (tarif[c][2].toLowerCase() == 'mietwagen')  {
            checkbox.type = 'radio';    
            checkbox.id = 'radio_mietwagen';   
            checkbox.name = 'radio_mietwagen';
            checkbox.value = tarif[c][0];                    

            // check if first service
            tarif[c][5] = isFirst;
            checkbox.checked = Boolean(tarif[c][5]);                                            
            isFirst = false;                       
            checkbox.onclick = function(){chngMandPrice(this.value);}
          }
          // optional services
          if (tarif[c][2].toLowerCase() == 'zusatzleistung')  {
            checkbox.type = 'checkbox';    
            checkbox.name = tarif[c][2];            
            checkbox.id = 'checkbox_' + tarif[c][0];
            checkbox.value = tarif[c][0];                              
            tarif[c][5] = false;            
            checkbox.onclick = function(){chngPrice(this.id);}             
          }
          cell[0].appendChild(checkbox);
          checkbox.checked = tarif[c][5];  // for IE checkboxes must set 'checked' after they've been realized (appended to a parent)
      
          // Description    
          cell[1] = document.createElement('td');
          cell[1].width = '80%';
          cell[1].align = 'left';
          cont = document.createTextNode(getTariff(c,1));
          cell[1].appendChild(cont);
      
          // Price
          cell[2] = document.createElement('td');
          cell[2].width = '16%';
          cell[2].align = 'right';
          cont = document.createTextNode(getTariff(c,6));
          cell[2].appendChild(cont);      

          //               
          for(var k = 0; k < cell.length; k++) {
            row[c].appendChild(cell[k]);      
          }      
          tbo.appendChild(row[c]);
        }
        tab.appendChild(tbo);
        preisliste.appendChild(tab);
      }
    }
    getTotal();
  }  
} 

////////////////////////////////////////////////////////////////////////////////
// Returns a tariff from the array
function getTariff(rowid,colid) {
  if (tarif[rowid] != null) {
    if (colid == 3) {
      var myCurrency = new currency();
      myCurrency.culture = 'german';
      myCurrency.value = tarif[rowid][3];
      return myCurrency.convert();
    }
    else {return tarif[rowid][colid];}
  }
}

////////////////////////////////////////////////////////////////////////////////
// Fill the address array, and the target html-object    
function newStrAdr(responseTxt) {
  var tempString;
  var tempHnr;
  var choice;
  var allRecords = new Array();
  var txtLine = new Array();

  // Reset vars
  cBox = document.getElementById('selectAdr');
  cBox.length = 0;
  
  adresse = new Array();  
  
  // read recs into array
  allRecords = responseTxt.split('$');
  
  for (var iStr = 0; iStr < allRecords.length; iStr++) {
      
    if (allRecords[iStr] > '')
    {    
      // read fields into array       
      txtLine = allRecords[iStr].split('|');
           
      if (txtLine.length > 0) {  
        choice = document.createElement('option');      
        
        // assign fields to sub-array [from rec]            
        adresse[iStr] = txtLine;        
        
        choice.value = adresse[iStr][0];
        
        if (adresse[iStr][1] != '') {
          tempName = adresse[iStr][1] + ' - '; 
        } else { tempName = '' };
    
        if (adresse[iStr][3] != '') {
          tempHnr = ' ' + adresse[iStr][3] + ', '; 
        } else { tempHnr = ', ' };
        
        // Fill selection    
        choice.appendChild(document.createTextNode(
            tempName +
            adresse[iStr][2] +
            tempHnr + 
            adresse[iStr][4] + ' ' +
            adresse[iStr][5]));
        
        cBox.appendChild(choice);
      }
    }
  }  
  if (adresse.length > 0) document.getElementById('listeHinweis').innerHTML = hinweis; 
  else document.getElementById('listeHinweis').innerHTML = '';
}

////////////////////////////////////////////////////////////////////////////////
// input search addr. 
function lookupStr() {       
  var searchValue = document.getElementById('sucheAdr').value + (document.getElementById('sucheOrt').value ? ',' + document.getElementById('sucheOrt').value : '');
  if ( oldVal + searchValue != oldVal ) {   
    oldVal = searchValue;
    saturnStrassenSuche(oldVal);                             
  }      
}

////////////////////////////////////////////////////////////////////////////////
// Request a list of addresses based on a match from the input field (async)
function saturnStrassenSuche(sVal) {
  var xhr;
  var url = "lookupStr";
  var params = "strName=" + escape(sVal); 
  
  // async call
  try { xhr = new ActiveXObject("MSxml2.XMLHTTP"); }
    catch (e) { try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } 
      catch (e2) { try { xhr = new XMLHttpRequest(); }
        catch (e3) { xhr = false; } 
      }
    }
    
  xhr.onreadystatechange = function() { 
    if(xhr.readyState == 4)	{    
  		if(xhr.status == 200) {        
        if (xhr.responseText != null) { newStrAdr(xhr.responseText); }          		  
  	  }
  	}
  }
  
  if (xhr) {
    xhr.open('POST', url, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", params.length);
    xhr.setRequestHeader("Connection", "close");
    xhr.send(params);
  }
}

function disableInput(how) {
    var x, i, t, tags = ['input', 'select', 'textarea', 'radio', 'checkbox'];
    for (t = 0; t < tags.length; t++) {        
        x = document.getElementsByTagName(tags[t]);
        for (i = 0; i < x.length; i++) {
            alert(x[i].name+'\n'+x[i].type);
            x[i].disabled = how;
            x[i].readOnly = how;
        }
    }
    colorFields();
}

////////////////////////////////////////////////////////////////////////////////
// Request a list of addresses based on a match from the input field (async)
function saturnStrFav() {
    var xhr;
    var url = 'lookupStrfav';
    var params = 'email=' + escape(document.getElementById('contactEmail').value);

    // async call
    try { xhr = new ActiveXObject("MSxml2.XMLHTTP"); }
    catch (e) {
        try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
        catch (e2) {
            try { xhr = new XMLHttpRequest(); }
            catch (e3) { xhr = false; }
        }
    }

    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                if (xhr.responseText != null) { newStrAdr(xhr.responseText); }
            }
        }
    }
    if (xhr) {
        xhr.open('POST', url, true);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.setRequestHeader("Content-length", params.length);
        xhr.setRequestHeader("Connection", "close");
        xhr.send(params);
    }
}

function disableInput(how) {
    var x, i, t, tags = ['input', 'select', 'textarea', 'radio', 'checkbox'];
    for (t = 0; t < tags.length; t++) {
        x = document.getElementsByTagName(tags[t]);
        for (i = 0; i < x.length; i++) {
            if (x[i].type != 'hidden') x[i].disabled = how;
        }
    }
}


////////////////////////////////////////////////////////////////////////////////
// Requested save data
function saveIt(lang) {
  var xhr;
  var url = 'save';
  var params = '';

  if (validForm()) {
      document.getElementById('control').innerHTML = '';
      disableInput(true);

      for (var p = 0; p < document.buchung.elements.length; p++) {
          if (document.buchung.elements[p].id != undefined && document.buchung.elements[p].value != undefined) {
            if (document.buchung.elements[p].id == "ccmail") params += '&ccmail='+document.buchung.elements[p].checked;   
            else params += (p > 0 ? '&' : '') + document.buchung.elements[p].id +'='+ escape(document.buchung.elements[p].value);
          }
      }
      
      for (var i = 0; i < tarif.length; i++) {
          if (tarif[i][5] == true) {
              params += '&tarif_' + i + '=' + tarif[i][0] + '|' + tarif[i][3].replace(/\./g, ',') + '|' + tarif[i][7].replace(/\./g, ',');
          }
      }
      
      // create async call
      try { xhr = new ActiveXObject("MSxml2.XMLHTTP"); }
      catch (e) {
          try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
          catch (e2) {
              try { xhr = new XMLHttpRequest(); }
              catch (e3) { xhr = false; }
          }
      }

      xhr.onreadystatechange = function() {
          if (xhr.readyState == 4) {
              if (xhr.status == 200) {
                  if (xhr.responseText != null) document.getElementById('confirm').innerHTML = xhr.responseText;
                  else disableInput(false); 
              }
          }
      }
      if (xhr) {
          xhr.open('POST', url, true);
          xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
          xhr.setRequestHeader("Content-length", params.length);
          xhr.setRequestHeader("Connection", "close");
          xhr.send(params);
      }
  }
  else {
      alert(document.getElementById('emptyMsg').value);
  }
}

////////////////////////////////////////////////////////////////////////////////
// onchange Event from an address seletion /////////////////////////////////////
function selectDir(evt) {
  
  if (evt) {
    if (document.getElementById('richtung').value == 'vomAP') {
      document.getElementById('flNrLabel').style.visibility = "visible";
      document.getElementById('flNr').style.visibility = "visible";    
    }      
      
    else {
      document.getElementById('flNrLabel').style.visibility = "hidden";
      document.getElementById('flNr').style.visibility = "hidden";
    }    
    if (tarif.length > 0) {
      saturnTarifSuche(
      document.getElementById('AdrStrId').value,
      document.getElementById('pax').value,
      document.getElementById('kat').value,
      document.getElementById('richtung').value,
      document.getElementById('preisliste'));      
      validForm();
    }
    colorFields();
  } 
}

////////////////////////////////////////////////////////////////////////////////
// onchange Event from an address seletion /////////////////////////////////////
function selectStr(evt) {
  if (evt && adresse.length > 0) 
  {
    var idx = document.getElementById('selectAdr').selectedIndex;    
    // Street ID
    document.getElementById('AdrStrId').value = adresse[idx][0];
    if (document.getElementById('AdrStrName') && adresse[idx][2] > '') document.getElementById('AdrStrName').value = adresse[idx][2];   
    if (document.getElementById('AdrHnr') && adresse[idx][3] > '') document.getElementById('AdrHnr').value = adresse[idx][3];
    if (adresse[idx][1].length > 0) {document.getElementById('AdrPOI').value = adresse[idx][1];}
    else {document.getElementById('AdrPOI').value = '';}
    if (adresse[idx][2].length > 0) document.getElementById('AdrStrName').value = adresse[idx][2];
    else {
      document.getElementById('AdrStrName').value = ''; 
      document.getElementById('AdrStrName').readOnly = false;
    }
    if (adresse[idx][3].length > 0) document.getElementById('AdrHnr').value = adresse[idx][3];
    else {                              
      document.getElementById('AdrHnr').value = '';
      document.getElementById('AdrHnr').readOnly = false;
    }
    document.getElementById('AdrPlz').value = adresse[idx][4];
    document.getElementById('AdrOrt').value = adresse[idx][5];
    if (clearAfterSelect) {
      document.getElementById('selectAdr').length = 0;
      adresse = new Array(); 
      document.getElementById('sucheAdr').value = '';
      oldVal = '';    
      document.getElementById('listeHinweis').innerHTML = '';
    }
    saturnTarifSuche(
      document.getElementById('AdrStrId').value,
      document.getElementById('pax').value,
      document.getElementById('kat').value,
      document.getElementById('richtung').value,
      document.getElementById('preisliste')
    );
    validForm();
  }
} 

////////////////////////////////////////////////////////////////////////////////
// Validate Field
function validField(obj) {
  if (!obj) return true;
  if (obj.id == 'contactExtRef') return true;
  if (obj.readOnly) return true;

  var isValid = false;
  
  if (obj.id.match(/mail/)) {
    var a = false;
    var s = obj.value;    
    // check valid email
    if(typeof(RegExp) == 'function') {
      var b = new RegExp('abc');
      if(b.test('abc') == true){a = true;}
    }
    
    if(a == true) {
      reg = new RegExp('^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*@([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$');
      isValid = (reg.test(s));
    }
    
    else {
      isValid = (s.search('@') >= 1 &&
                 s.lastIndexOf('.') > s.search('@') &&
                 s.lastIndexOf('.') >= s.length-5)    
    }
  }   
  else isValid = (obj.value == '') ? false : true;

  obj.style.backgroundColor = (isValid) ? nonEmptyCol : emptyCol;
  return isValid;              
}

////////////////////////////////////////////////////////////////////////////////
// Validate input 
function validForm() {
  var isValid = true;
  
  if (document.getElementById('richtung').value == 'vomAP') {
    if (!validField(document.getElementById('FlNr'))) isValid = false;
  }

  if (document.getElementById('AdrStrId').value == '') {
      document.getElementById('sucheAdr').style.backgroundColor = emptyCol;
      document.getElementById('sucheOrt').style.backgroundColor = emptyCol;
      isValid = false;
  }
  else {
      document.getElementById('sucheAdr').style.backgroundColor = nonEmptyCol;
      document.getElementById('sucheOrt').style.backgroundColor = nonEmptyCol;
  }
                                
  if (!validField(document.getElementById('AdrStrName'))) isValid = false;
  if (!validField(document.getElementById('AdrHnr'))) isValid = false;
  if (!validField(document.getElementById('contactVname'))) isValid = false;
  if (!validField(document.getElementById('contactNname'))) isValid = false;
  if (!validField(document.getElementById('contactTel'))) isValid = false;
  if (!validField(document.getElementById('contactEmail'))) isValid = false;
  
  if (totalAmount.value == 0 || totalAmount.value == null) isValid = false;  
  return isValid; 
} 

function getControls(name, target) {
  var xhr;
  var url = 'getelement';
  var params = 'name=' + escape(name);  
  
  // create async call
  try { xhr = new ActiveXObject("MSxml2.XMLHTTP"); }  
  catch (e) { try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } 
    catch (e2) { try { xhr = new XMLHttpRequest(); }
      catch (e3) { xhr = false; } 
    }
  }
    
  xhr.onreadystatechange = function() { 
    if(xhr.readyState == 4)	{    
  		if(xhr.status == 200) {
        if (xhr.responseText != null) {
          document.getElementById(target).innerHTML = xhr.responseText;
        }
      }  		  
  	}
  }
  
  if (xhr) {
    xhr.open('POST', url, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", params.length);
    xhr.setRequestHeader("Connection", "close");
    xhr.send(params);
  }  
}
         
////////////////////////////////////////////////////////////////////////////////
// Confirm Inquiry
function confirm(task,resTarget) {
  var textElement = document.getElementById(resTarget);
  var email = escape(document.getElementById('c').value);
  if (email == null) email = escape(document.getElementById('contactEmail').value); 
  var xhr;
  
  var url = 'confirm';
  var params = 'task=' + escape(task) +
               '&inquiry=' + escape(document.getElementById('ia#').value) + 
               '&c=' + email +
               '&contactEmail='+escape(document.getElementById('contactEmail').value);
  if (document.getElementById('esuap')) {
    params = params + '&esuap='+escape(document.getElementById('esuap').value);
  }  
  
  // create async call
  try { xhr = new ActiveXObject("MSxml2.XMLHTTP"); }  
  catch (e) { try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } 
    catch (e2) { try { xhr = new XMLHttpRequest(); }
      catch (e3) { xhr = false; } 
    }
  }

  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        if (xhr.responseText != null) {

          if (task == 'confirm') 
          {
            textElement.innerHTML = xhr.responseText;
          }
          else textElement.innerHTML = '';

          if (task == 'cancel') {
            getControls('InquiryForm.Buttons.Send','control');
            disableInput(false);
          }                              
          else getControls('InquiryForm.Buttons.Continue','control');
        }
        else disableInput(false);              
      }
    }
  }

  if (xhr) {
    textElement.innerHTML = '';
    xhr.open('POST', url, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", params.length);
    xhr.setRequestHeader("Connection", "close");
    xhr.send(params);
  }
}

////////////////////////////////////////////////////////////////////////////////
function getPaxdata(id) {
  var xhr;
  var kuApId = (id) ? id : document.getElementById('kuAp').value;
  if (kuApId.length > 0) {
    var url = 'getkuap';
    var params = 'kuApId=' + escape(kuApId);  
    
    // create async call
    try { xhr = new ActiveXObject("MSxml2.XMLHTTP"); }  
    catch (e) { try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } 
      catch (e2) { try { xhr = new XMLHttpRequest(); }
        catch (e3) { xhr = false; } 
      }
    }
      
    xhr.onreadystatechange = function() { 
      if(xhr.readyState == 4)	{    
    		if(xhr.status == 200) {
          if (xhr.responseText != null) {   
            kuap = xhr.responseText.split('|');
            document.getElementById('contactAnr').value = kuap[3];
            document.getElementById('contactVname').value = kuap[1];
            document.getElementById('contactNname').value = kuap[2];            
            document.getElementById('contactEmail').value = kuap[5];            
            document.getElementById('contactTel').value = kuap[4];             
            // document.getElementById('contactCash').value = kuap[6];

            if (document.getElementById('contactCash').value == 'FALSE') getControls('InquiryForm.Zmwunsch.Debitor','zm');
            else getControls('InquiryForm.Zmwunsch.Customer','zm');
            validForm();
            ccmail();
          }  		  
    	  }
    	}
    }
        
    if (xhr) {
      xhr.open('POST', url, true);
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xhr.setRequestHeader("Content-length", params.length);
      xhr.setRequestHeader("Connection", "close");
      xhr.send(params);
    }
  }
}  

////////////////////////////////////////////////////////////////////////////////
// check valid keystroke ///////////////////////////////////////////////////////
function evtCheckInput(evt,obj) {
    if (evt) {
        validForm();
    }
}               

function asto(func) {
  try {clearTimeout(timeout);}
  catch(e) {}
  timeout = setTimeout(func+'()',iTimeout.value);        
}

