var feld_arr, namen_arr, krit1_arr, formName;
//hier können die Dialoge an Sprache angepasst werden
// z.B. var dialog_1 = "<?php echo $lang["dialog_1"] ?>";
var dialog_1 = "Sie haben im Feld '{fieldname}' nichts eingetragen!";
var dialog_2 = "Ungültige Angabe im Feld '{fieldname}'!";
var dialog_3 = "Bitte {fieldname} auswählen!";
var dialog_4 = "Bitte im Feld '{fieldname}' nur Zahlen eintragen (Ziffern 0-9)!";
var password;
var errors = [];
document.onmousemove = updateHint;

/*-------------------------------GLOBAL VARIABLES------------------------------------*/

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

/*-----------------------------------------------------------------------------------------------*/

//Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/

function getBrowserInfo() {
	if (checkIt('konqueror')) {
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser 	= "Safari"
	else if (checkIt('omniweb')) browser 	= "OmniWeb"
	else if (checkIt('opera')) browser 		= "Opera"
	else if (checkIt('webtv')) browser 		= "WebTV";
	else if (checkIt('icab')) browser 		= "iCab"
	else if (checkIt('msie')) browser 		= "Internet Explorer"
	else if (!checkIt('compatible')) {
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";

	if (!version) version = detect.charAt(place + thestring.length);

	if (!OS) {
		if (checkIt('linux')) OS 		= "Linux";
		else if (checkIt('x11')) OS 	= "Unix";
		else if (checkIt('mac')) OS 	= "Mac"
		else if (checkIt('win')) OS 	= "Windows"
		else OS 								= "an unknown operating system";
	}
}

function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

/*-----------------------------------------------------------------------------------------------*/

function padding(laenge) {
  result = '';
  for (i = 0; i < laenge; i++)
    result = result + '___';
  return result;
}

function print_r(das_array, ebene) {
  var result = '';  
  for (var wert in das_array)
    if (typeof das_array[wert] == "object")
      result = result + ' ' + padding(ebene) + wert + "\n" + print_r(das_array[wert], ebene + 1);
    else
      result = result + ' ' + padding(ebene) + wert + ' = ' + das_array[wert] + "\n";

  return result;
}

function formCheck(formObj){
	 //return true;
	 if(typeof customFormCheckFunction != 'undefined'){
			//alert(customFormCheckFunction);
			return customFormCheckFunction();
	 }
	 if(typeof evalArray == 'undefined')return true;
	 wait = true;
	 errormessage = '';
	 firstErrorField = null;
	 for(key in evalArray){
		 if(typeof key != 'undefined' && $(prefix + '_' + key)){
			
			aktField = $(prefix + '_' + key);
			aktDiv = $(key);
			aktLabel = evalArray[key]['label'];
			if(typeof aktField.length!='undefined' || aktField.type=="checkbox" || aktField.type=="radio"){
				if(aktField.type=="checkbox")aktWert=aktField.checked;
				else aktWert=aktField.value;
			}
			else aktWert=trim(aktField.value);
			evalKrit = evalArray[key]['eval'];
			for(j=0;j<evalKrit.length;j++){
				krit = evalKrit[j];
				if(!in_array(krit,evalSkipFields) && krit !=''){
					if(!evalValue(aktWert,krit)){
						if(!firstErrorField)firstErrorField = aktField;
						if(!aktDiv){
							aktField.style.backgroundColor = 'yellow';
							aktField.style.border = '1px solid #900';
							if(aktField.type=="checkbox")aktField.style.padding = '5px';
						}
						else {
							aktDiv.style.border = '1px solid #900';
							aktDiv.style.color = '#900';
							aktDiv.style.marginTop = '4px';
						}
						if(aktLabel.toLowerCase().indexOf('agb')>-1)errormessage += "\n" + aktLabel + ':' + errorLabels['agb'];
						else if(aktField.type=="select-one")errormessage += "\n" + aktLabel + ':' + errorLabels['nothingSelected'];
						else errormessage += "\n" + aktLabel + ':' + errorLabels[krit];
					}
				}
			}
			if(in_array('password',evalKrit)){
				if(!in_array('twice',evalKrit))password = aktWert;
				else if(aktWert != password){
					if(!firstErrorField)firstErrorField = aktField;
					aktDiv.style.border = '1px solid #900';
					errormessage += "\n" + aktLabel + ':' + errorLabels['twice'];
				}
			}
		 }
		 //else alert(prefix + '_' + key);
	 }
	 
	 if(document.bookingForm.arrivalCond.selectedIndex == 1){
	 	if(document.bookingForm.tx_hotelportal_pi3_tx_hotelportal_hotels_creditcard.selectedIndex == ''){
	 		errormessage += "\n" + 'Kreditkarten-Typ:' + errorLabels[krit];
	 		document.bookingForm.tx_hotelportal_pi3_tx_hotelportal_hotels_creditcard.focus();
	 	}
	 	if(document.bookingForm.tx_hotelportal_pi3_tx_hotelportal_hotels_cardHolder.value == ''){
	 		errormessage += "\n" + 'Kreditkarten-Inhaber:' + errorLabels[krit];
	 		document.bookingForm.tx_hotelportal_pi3_tx_hotelportal_hotels_cardHolder.focus();
	 	}
	 	if(document.bookingForm.tx_hotelportal_pi3_tx_hotelportal_hotels_cardNumber.value == ''){
	 		errormessage += "\n" + 'Kreditkarten-Nummer:' + errorLabels[krit];
	 		document.bookingForm.tx_hotelportal_pi3_tx_hotelportal_hotels_cardNumber.focus();
	 	}
	 	if(document.bookingForm.tx_hotelportal_pi3_tx_hotelportal_hotels_ccyear.selectedIndex == '' || document.bookingForm.tx_hotelportal_pi3_tx_hotelportal_hotels_ccmonth.selectedIndex == ''){
	 		errormessage += "\n" + 'gültig bis:' + errorLabels[krit];
	 		document.bookingForm.tx_hotelportal_pi3_tx_hotelportal_hotels_ccmonth.focus();
	 		document.bookingForm.tx_hotelportal_pi3_tx_hotelportal_hotels_ccyear.focus();
	 	}
	 }
	 if(errormessage != ''){
		 alert("Bitte korrigieren Sie Ihre Eingaben: \n " + errormessage);
		 firstErrorField.focus();
		 window.scrollBy(0,-100);
		 return false;
	 }
	searchLightbox.activate();
	return true;

}

var userFunctions = {}


var wait = false;
var lastInputField = null;
var lastEvalStr = null;
var defaultBackgroundColor = null;
var evalSkipFields = ['trim','country'];

// called onfocus
function checkError(inputObj){
	if(typeof userFunctions[inputObj.id] == 'function'){
		userFunctions['formElement'] = inputObj;
		eval('userFunctions.' + inputObj.id + '();');
	}
	if(typeof errors[inputObj.id] == 'undefined' || errors[inputObj.id] == ''){
		if(typeof inputObj.currentStyle != 'undefined')defaultBackgroundColor = inputObj.currentStyle['backgroundColor'];
		else defaultBackgroundColor = inputObj.getStyle('background-color');
	}
	return;
	//alert('onchange');
	// IE < 7 alerts 2 times :-(
	//nav = navigator.appVersion;
	//if(navigator.appName =="Microsoft Internet Explorer" && parseInt(nav.substr(nav.indexOf('MSIE') +5,3)) < 7)return true;
	if(inputObj == lastInputField || wait)return true;
	if(lastInputField && lastEvalStr){
		if(lastInputField.type == 'text' || lastInputField.type == 'password' )v = lastInputField.value;
		if(lastInputField.type == 'select-one')v = lastInputField.options[lastInputField.selectedIndex].value;
		evalKrit = lastEvalStr.split(',');
		for(j=0;j<evalKrit.length;j++){
			krit = evalKrit[j];
			if(!in_array(krit,evalSkipFields)){
				if(!evalValue(v, krit)){
					wait = true;
					lastInputField.style.backgroundColor = 'yellow';
					//lastInputField.focus();
					if(krit == 'required' && lastInputField.type == 'select-one')krit = 'nothingSelected';
					//alert("Bitte korrigieren Sie Ihre Eingabe: " + errorLabels[krit]);
					//window.scrollBy(0,-100);
					//lastInputField.focus();
					wait = false;
					return false;
				}
			}
		}
	}
	lastEvalStr = null;
	return true;
}


// called onblur
function checkField(inputObj,evalStr){
		evalKrit = evalStr.split(',');
		if(inputObj.type == 'text' || inputObj.type == 'password' )v = inputObj.value;
		if(inputObj.type == 'select-one')v = inputObj.options[inputObj.selectedIndex].value;
		for(j=0;j<evalKrit.length;j++){
			krit = evalKrit[j];
			if(!in_array(krit,evalSkipFields)){
				if(!evalValue(v, krit)){
					wait = true;
					inputObj.style.backgroundColor = 'yellow';
					if(krit == 'required' && inputObj.type == 'select-one')krit = 'nothingSelected';
					errors[inputObj.id] = "Bitte korrigieren Sie Ihre Eingabe: " + errorLabels[krit];
					return false;
				}
			}
		}
		inputObj.style.backgroundColor = defaultBackgroundColor;
		errors[inputObj.id] = '';
		return true;
		if(wait)return true;
		if(lastInputField)lastInputField.style.backgroundColor = defaultBackgroundColor;
		lastInputField = inputObj;
		if(typeof inputObj.currentStyle != 'undefined')defaultBackgroundColor = inputObj.currentStyle['backgroundColor'];
		else defaultBackgroundColor = inputObj.getStyle('background-color');
		lastEvalStr = evalStr;
}

function displayError(inputObj){
	
	if(typeof errors[inputObj.id] != 'undefined' && errors[inputObj.id] != ''){
		showHint('flexform_hint',errors[inputObj.id]);
	}
}

function hideError(inputObj){
	hideHint();
}

var hint = null;
var x = 585;
var y = 0;

function updateHint(e) {
	//x = 585;
	//x = (document.all) ? window.event.x + document.body.scrollLeft : e.pageX;
	y = (document.all) ? window.event.y   + 150 : e.pageY;
	//alert("Scroll: " + document.body.scrollTop);
	if (hint != null) {
		hint.style.left = (x + 20) + "px";
		hint.style.top 	= (y - 70) + "px";
	}
}

function showHint(id,message) {
	if(!hint){
		d = document.createElement('div');
		idAttr = document.createAttribute('id');
		idAttr.nodeValue = id;
		d.setAttributeNode(idAttr);
		d.innerHTML = message;
		document.getElementsByTagName("body")[0].appendChild(d);
	}
	hint = document.getElementById(id);
	hint.style.position = 'absolute';
	hint.style.left = (x + 20) + "px";
	hint.style.top 	= (y - 70) + "px";
	hint.style.display = "block";
	d.innerHTML = message;
	//alert(" x: "  + x + " y: " + y + "Scroll: " + document.body.scrollTop);
}



function hideHint() {
	if(hint)hint.style.display = "none";
}


function in_array(item,arr){
	if(typeof arr == 'undefined')return false;
	for(var k=0;k<arr.length;k++){
		if(arr[k]==item)return true;
	}
	return false;
}




function trim(s){
	if(typeof s == 'undefined')return '';
	if(s.length>0){	
		while(s.indexOf(' ')==0){
			s = s.substring(1);
		}
		while(s.lastIndexOf(' ')==s.length-1){
			s = s.substring(0,s.length-1);
		}
	}

	return s;
}

var dialogArr = [];
			
function dialog(feldname, fehler){
    if(fehler=="leer"){
        d = dialog_1.split('{fieldname}');
    }
    if(fehler=="text"){
        d = dialog_2.split('{fieldname}');
    }
    if(fehler=="choice"){
       d = dialog_3.split('{fieldname}');
    }
	if(fehler=="noNr"){
       d = dialog_4.split('{fieldname}');
    }
	 return d[0] + feldname + d[1];
   // alert(d[0] + feldname + d[1]);
}	



function evalValue(aktWert, krit){
		if(typeof krit == 'undefined')return true;
		if(krit == 'required' && aktWert==""){
			return false;
		}
			
		//alert(name + " Krit: " + krit_arr[i] + " Wert: " + aktWert);
		if(krit=="num"){
			for (var j = 0; j < aktWert.length-1; j++){
				var ch = aktWert.substring(j, j + 1);
				if (isNaN(ch) && ch!="." && ch!="," && ch!=" "){
					return false;
				}
			}
		}
		if(krit=="double2"){
			for (var j = 0; j < aktWert.length-1; j++){
				var ch = aktWert.substring(j, j + 1);
				if (isNaN(ch) && ch!="." && ch!="," && ch!=" "){
					return false;
				}
			}
		}
		if(krit=="alphanum_x"){
			for(j=0;j<aktWert.length;j++){
                cv =aktWert.charCodeAt(j);
				if (cv == 45 || // Bindestrich 
				    cv == 46 || // Punkt
				    cv == 38 || // Apostroph
					cv == 32 || // Leerzeichen
				   (cv > 64 && cv < 91) || //Großbuchstaben
                   (cv > 96 && cv < 123) || //Kleinbuchstaben
                   (cv > 192 && cv < 255)){ //Umlaute etc.
                    // do nothing
				}
				else {
					return false;
				}
			}
		}
		if(krit=="phone"){
			if(aktWert.indexOf("-")>0){
				aktWert_arr = aktWert.split("-");
			}
			else if(aktWert.indexOf("/")>0){
				aktWert_arr = aktWert.split("/");
			}
			else if (aktWert.indexOf("+")==0){
				aktWert_arr = new Array(aktWert.substring(1));
			}
			else aktWert_arr = new Array(aktWert);
			for(z=0;z<aktWert_arr.length;z++){
				temp = trim(aktWert_arr[z]);
				if(isNaN(temp)){
						return false;
				}
			}
		}
		if(krit=="email" && aktWert!=""){ //falls eine E-mail-Adresse eingetragen ist, 
													//muss sie gültig sein
			return checkMail(aktWert);
			if(!aktWert.match(/^[a-zA-Z0-9_\.-]{2,}@[a-z0-9-]{3,}\.[a-z]{2,4}|museum$/)) {
				return false;
			}
		}
		if(krit.indexOf('selected_isNot')==0){
			var w = krit.split('_');
		    if(aktWert==w[2]){
		    	return false;
			   
			}		
		}
		if(krit=='checked'){
			isEmpty=true;
			for(z=0;z<aktField.length;z++){
				if(aktField[z].checked)isEmpty=false;
			}
			if(isEmpty){
			    return false;
			   
			}
		}
		if(krit=='zip'){
			if (isNaN(aktWert)||aktWert.length!='5'){
				return false;
			}
		}
		if(krit=='password' && passwordLength && aktWert!=''){
			if (aktWert.length < passwordLength){
				return false;
			}
		}
		if(krit=='twice' && lastInputField){
			// the id of the repeat password field is XXX_password_twice and the first password field has xxx_password_news
			if(lastInputField.id.indexOf('password')>-1 && $(lastInputField.id.substr(0,lastInputField.id.length - 5) + 'new').value != aktWert && aktWert !=''){
				return false;
			}
		}
		return true;
}

function checkMail(s){
  var a = false;
  var res = false;
  if(typeof(RegExp) == 'function'){
    var b = new RegExp('abc');
    if(b.test('abc') == true){a = true;}
  }

  if(a == true){
    reg = new RegExp('^([a-zA-Z0-9\\-\\.\\_]+)'+
                     '(\\@)([a-zA-Z0-9\\-\\.]+)'+
                     '(\\.)([a-zA-Z]{2,4})$');
    res = (reg.test(s));
   }
  else{
    res = (s.search('@') >= 1 &&
           s.lastIndexOf('.') > s.search('@') &&
           s.lastIndexOf('.') >= s.length-5)
    }
  return(res);
}



