/**
* Javascript for the forms
*
* @author  Sebastian Beyer
* @version $Id: form.js 556 2010-08-04 09:24:15Z sb $
* @package hpm_formcreator
*/
// extension for PHP AJAX calls
var php_ext = '.php';
var formcreatorPath = '../../';

// the language of the form
var form_language = getFormLanguage();
// the related dropwdown and target array is build like this "actualdropdown;relateddropdown;relateddropdownoption"
var relatedDropdowns = new Array();
var relatedTargets = new Array();
// terms needed for multi language layout
var terms_form_de = new Array();
terms_form_de['submitted'] = 'Vielen dank f\xFCr deine Anfrage!';
terms_form_de['checkBoxLimit'] = 'Du darfst leider nicht mehr Haken setzen!';
terms_form_de['silverpopadded'] = ' F\xFCr Newsletter registriert.';
terms_form_de['captchafail'] = 'Sicherheitscode ist falsch!';
terms_form_de['day'] = 'Tag';
terms_form_de['month'] = 'Monat';
terms_form_de['year'] = 'Jahr';

var terms_form_en = new Array();
terms_form_en['submitted'] = 'Thank you for your submission!';
terms_form_en['checkBoxLimit'] = 'You\'re not allowed to check more boxes!';
terms_form_en['silverpopadded'] = ' You\'re registered for the newsletter.';
terms_form_en['captchafail'] = 'Security code wrong!';
terms_form_en['day'] = 'Day';
terms_form_en['month'] = 'Month';
terms_form_en['year'] = 'Year';

var terms_form_fr = new Array();
terms_form_fr['submitted'] = 'Les informations ont \xE9t\xE9 transmis';
terms_form_fr['checkBoxLimit'] = 'You\'re not allowed to check more boxes!';
terms_form_fr['silverpopadded'] = ' Inscrits la newsletter.';
terms_form_fr['captchafail'] = 'Sicherheitscode ist falsch!';
terms_form_fr['day'] = 'Jour';
terms_form_fr['month'] = 'Mois';
terms_form_fr['year'] = 'An';

// fixed values for days in a month and days in a year
var daysInMonth = 30;
var daysInYear = 360;
var dayInMilliseconds = 86400000;

var formterms = '';
/**
* finally submit the form
**/
function submitForm() {
	// check validation
	ret = document.getElementById('createdForm').onsubmit();
	// submit the form if all fields correct
	if(ret) {
		document.getElementById('createdForm').submit();
	}
}

/**
* switch the colors of the submit button onmouseover and -out
* SPECIAL FOR STA_WEB STYLE!!!!
* @TODO replace this 
*/
function switchButtonColors(change) {
	if(change) {
		document.getElementById('btn_left').src = '../images/sta_web_button_left_act.gif';
		document.getElementById('btn_right').src = '../images/sta_web_button_right_act.gif';
		document.getElementById('btn_middle').style.backgroundColor = '#00AEEF';
	}
	else {
		document.getElementById('btn_left').src = '../images/sta_web_button_left.gif';
		document.getElementById('btn_right').src = '../images/sta_web_button_right.gif';
		document.getElementById('btn_middle').style.backgroundColor = '#FF9800';
	}
}

/**
* OLD: check if a form has been submitted
* NEW: for older forms we need to call the right function
*/
function checksubmitted() {
	checkforwardedparams();
}

/**
* check the params that a form gets submitted to do the actions for them
*/
function checkforwardedparams() {
	getArgs();
	
	if(passedArgs['lang']) {
		formterms = eval('terms_form_'+passedArgs['lang']);
	}
	
	// if we prefill a form we need to replace the target
	if(passedArgs['prefill']) {
		document.getElementById('createdForm').action = document.getElementById('createdForm').action.replace(/\/action\/mail.php\?/g, '/../form.php?operation=prefillCreate&');
		
		var inputs = document.getElementsByTagName('input');
		for(var i=0;i<inputs.length;i++) {
			inputs[i].removeAttribute('readonly');
		}
	}
	
	// load userprofile from silverpop
	if(passedArgs['Email']) {
		getUserInfoSilverpop();
	}
	
	for ( var key in passedArgs )
	{
		// we go through all passed arguments and check if we find a form element for it
		if(typeof(document.getElementsByName(key.toLowerCase())) != 'undefined'){
			var obj = document.getElementsByName(key.toLowerCase());
			
			// if there are more than one formelements with the same name it might be a dropdown and we check the visibility first 
			if(obj.length > 0) {
				for(var i = 0;i < obj.length;i++){
					if(obj[i].tagName == 'SELECT'){
						// if tr 3 levels above is is hidden we ignore it
						if(obj[i].parentNode.parentNode.parentNode.style.display != 'none'){
							// now check if element is a dropdown and set the value
							for(var y = 0;y < obj[i].options.length;y++){
								if(obj[i].options[y].value.toLowerCase() == passedArgs[key].toLowerCase()) {
									obj[i].options[y].selected = 'selected';
								}
							}
							// to check the relation to this element we call the function that is set on onchange
							if(typeof(obj[i].onchange) == 'function') {
								obj[i].onchange();
							}
						}					
					}
				}
			}
		}
	}
	
	// if form was submitted alert to user
	if(passedArgs['mail'] == 'submitted' && passedArgs['silverpop'] == 'true') {
		alert(formterms['submitted']); // + formterms['silverpopadded']);
	}
	else if (!passedArgs['silverpop'] && passedArgs['mail'] == 'submitted') {
		alert(formterms['submitted']);
	}
	
	// if a captcha failed, send text
	if(passedArgs['captcha'] == 'fail') {
		alert(formterms['captchafail']);
	}
}

/**
* FOR OLDER FORMS: check if a dropdown is related to another one 
* in older forms only relation to dropdowns were possible
* @param {Integer} dropdwn_id
* @param {Integer} selected_option
*/
function checkrelation(dropdwn_id, selected_option){
	
	for(var i=0;i<relatedDropdowns.length;i++){
		tmp_dropdwn = relatedDropdowns[i].split(';');
		// if we found a dropdown that is related to this one check if the selected option
		// is also related and display it
		if(dropdwn_id == tmp_dropdwn[1] && selected_option-1 == tmp_dropdwn[2]) {
			document.getElementById(tmp_dropdwn[0] + "_dropdown_tr").style.display = '';
		}	
		// if we found a dropdown that is related to this one and the selected option is different
		// we need to hide the dropdown and search for a dropdown that might be related to this one
		// if we find one hide them all
		if(dropdwn_id == tmp_dropdwn[1] && selected_option-1 != tmp_dropdwn[2]) {
			// hide the dropdown
			document.getElementById(tmp_dropdwn[0] + "_dropdown_tr").style.display = 'none';
			// set the selected index back to "0"
			if(document.getElementById(tmp_dropdwn[0] + "_dropdown")) {
				document.getElementById(tmp_dropdwn[0] + "_dropdown").firstChild.selectedIndex = '0';
			}
			// check if any dropdowns where related to any option of this one (0 should hide them all)
			checkrelation(tmp_dropdwn[0],0);
		}
	}
	
	
}

/**
* check if a element of the form is related to another one
* @param {Integer} dropdwn_id
* @param {Integer} selected_option
*/
function checkAllRelation(dropdwn_id, selected_option){
	// check all fields related to dropdowns
	for(var i=0;i<relatedDropdowns.length;i++){
		tmp_dropdwn = relatedDropdowns[i].split(';');
		// if we found a field that is related to this dropdown check if the selected option
		// is the one it is related to and display the element
		if(dropdwn_id == tmp_dropdwn[1] && selected_option-1 == tmp_dropdwn[2]) {
			document.getElementById(tmp_dropdwn[0] + "_related_tr").style.display = '';
			
			// we need to check if it is a text element that is hidden and substract the "NOT" from it so the text appears in the email
			if(document.getElementById(tmp_dropdwn[0] + "_related_tr").firstChild.lastChild && document.getElementById(tmp_dropdwn[0] + "_related_tr").firstChild.lastChild.name) {
				if(document.getElementById(tmp_dropdwn[0] + "_related_tr").firstChild.lastChild.name.match(/textinEmail/)&& document.getElementById(tmp_dropdwn[0] + "_related_tr").firstChild.lastChild.name.match(/not/)){
					document.getElementById(tmp_dropdwn[0] + "_related_tr").firstChild.lastChild.name = document.getElementById(tmp_dropdwn[0] + "_related_tr").firstChild.lastChild.name.substr(0,document.getElementById(tmp_dropdwn[0] + "_related_tr").firstChild.lastChild.name.length-4);
				}
			}
			// if this is a mobile form we need to do perform special actions
			if(document.getElementById(tmp_dropdwn[0] + "_related_tr2")) {
				document.getElementById(tmp_dropdwn[0] + "_related_tr2").style.display = '';
			}
		}	
		// if we find elements that are related to this dropdown and the selected option is different
		// we need to hide the elements 
		if(dropdwn_id == tmp_dropdwn[1] && selected_option-1 != tmp_dropdwn[2]) {
			// hide the element
			document.getElementById(tmp_dropdwn[0] + "_related_tr").style.display = 'none';
			// set the selected index back to "0"
			if(document.getElementById(tmp_dropdwn[0] + "_dropdown")) {
				document.getElementById(tmp_dropdwn[0] + "_dropdown").firstChild.selectedIndex = '0';
			}
			// if it is a text element and it is hidden, it also must be hidden from the email. So we add a "NOT" to the name so we can decide in the mail
			if(document.getElementById(tmp_dropdwn[0] + "_related_tr").firstChild.lastChild && document.getElementById(tmp_dropdwn[0] + "_related_tr").firstChild.lastChild.name) {
				if(document.getElementById(tmp_dropdwn[0] + "_related_tr").firstChild.lastChild.name.match(/textinEmail/) && !document.getElementById(tmp_dropdwn[0] + "_related_tr").firstChild.lastChild.name.match(/not/)){
					document.getElementById(tmp_dropdwn[0] + "_related_tr").firstChild.lastChild.name = document.getElementById(tmp_dropdwn[0] + "_related_tr").firstChild.lastChild.name + "_not";
				}
			}
			
			// if this is a mobile form we need to do perform special actions
			if(document.getElementById(tmp_dropdwn[0] + "_related_tr2")) {
				document.getElementById(tmp_dropdwn[0] + "_related_tr2").style.display = 'none';
			}
			
			// check if any dropdowns where related to any option of this one (0 should hide them all)
			checkAllRelation(tmp_dropdwn[0],0);
		}
	}
	
	// check all hidden fields that contain different targets
    for(var i=0;i<relatedTargets.length;i++){
        tmp_target = relatedTargets[i].split(';');
        var possblTrgt = document.getElementById(tmp_target[0]);	
        // if we found a hidden field that is related to this dropdown check if the selected option
        // is the one it is related to and if the name of the hidden field starts with 'target' or 'mail'
        if(dropdwn_id == tmp_target[1] && selected_option-1 == tmp_target[2] && (possblTrgt.name.substr(0,6) == 'target' || possblTrgt.name.substr(0,4) == 'mail')) {
            // get the hidden target & the default target
            // add the value to the target
            document.getElementById('extraTarget').value = possblTrgt.value;
        }
        // if we found a hidden field that is related to this dropdown and the selected option is different
        /*if(dropdwn_id == tmp_target[1] && selected_option-1 != tmp_target[2]) {
            document.getElementById('extraTarget').value = '';	
        }*/
    }
}

/**
 * getCalendarMaxDate
 * @param {String} timerelated The dropdown with the time included that sets the timespan
 * @param {Date} startDate The startdate that we need to calculate from
 */
function getCalendarMaxDate(timerelated, startDate) {
 	var tmpTimeRelValues = timerelated.split(";");
 	var relatedDropdown = tmpTimeRelValues[0];
 	var relatedTimeunit = tmpTimeRelValues[1].toLowerCase();
 	// get the dropdown the timespan is related to and and it's value
 	var dropdown = document.getElementById(relatedDropdown+"_dropdown").firstChild;
 	// get the value from the text
 	var integerValues = dropdown[dropdown.selectedIndex].value.match(/\d+/g);
 	// create the dates
 	var today = new Date(startDate);
 	var maxdate = new Date();
 	// get the text for the language
 	var formterms = eval('terms_form_'+form_language);
	
 	
 	// only if a digit was found we add the dates
 	if(integerValues && parseInt(integerValues[0]) != 0) {
 		var dropdownvalue = parseInt(integerValues[0]);
 		
 		if(relatedTimeunit == 'dropdown') {
 			var day = new RegExp(formterms['day'],"gi");
 			var month = new RegExp(formterms['month'],"gi");
 			var year = new RegExp(formterms['year'],"gi");
	 		relatedTimeunit = dropdown[dropdown.selectedIndex].value.toLowerCase().match(day) ? 'tage' : relatedTimeunit;
			relatedTimeunit = dropdown[dropdown.selectedIndex].value.toLowerCase().match(month) ? 'monate' : relatedTimeunit;
			relatedTimeunit = dropdown[dropdown.selectedIndex].value.toLowerCase().match(year) ? 'jahre' : relatedTimeunit;
 		}
	 		
	 	switch(relatedTimeunit) {
	 		case 'tage':
	 			var thisDay = today.getTime();
	 			maxdate.setTime(thisDay + (dropdownvalue * dayInMilliseconds));
	 		
	 			break;
	 		case 'monate':
	 			var thisDay = today.getTime();
	 			var newDay = thisDay + (daysInMonth * dropdownvalue * dayInMilliseconds);
	 			maxdate.setTime(newDay);
	 			
	 			break;
	 		case 'jahre':
	 			var thisDay = today.getTime();
	 			var newDay = thisDay + (daysInYear * dropdownvalue * dayInMilliseconds);
	 			maxdate.setTime(newDay);
	 		
	 			break;
	 		default:
	 			break;
	 	}
 	}
 	else {
 		return false;
 	}
 	maxdate.setHours(0);
	maxdate.setMinutes(0);
	maxdate.setSeconds(0);
	maxdate.setMilliseconds(0);
 	
 	return maxdate;
 	
 }

/**
 * getCalendarStartDate
 * @param {String} relatedStart 
 */
 function getCalendarStartDate(relatedStart) {
 	var startdate = new Date();
 	if(relatedStart) {
	 	var otherCalendarTable = document.getElementById(relatedStart +'_related_tr').lastChild.childNodes;
		var otherCalendar = null;
		for(var i=0;i<otherCalendarTable.length;i++){
			if(otherCalendarTable[i].nodeName.toLowerCase() == 'input'){
				otherCalendar = otherCalendarTable[i].value;
			}
		}
		if(otherCalendar) {
			var startDates = otherCalendar.split('.');
			startdate.setDate(parseInt(startDates[0]));
			startdate.setMonth(parseInt(startDates[1])-1);
			startdate.setFullYear(parseInt(startDates[2]));
		}
 	}
	
	
	startdate.setHours(0);
	startdate.setMinutes(0);
	startdate.setSeconds(0);
	startdate.setMilliseconds(0);
 	
 	return startdate;
 }

/**
 * extract the language of the form from the filename
 * format is always formnumber plus 2 character language definition
 * Example: 67_fr.htm (german is always without _de)
 */
function getFormLanguage() {
	var address = self.location.href;
	var addressPos = address.search(/\.htm/);
	address = address.substr(0,addressPos);
	var parts = address.split("/");
	
	var lastpart = parts[parts.length-1].split("\_");
	var language = lastpart[1];
	
	if(language)
		return language
	else
		return 'de';
}

var elementIdGlob = null;
/**
 * @param {Integer} capLength 
 * @param {Integer} elementId 
 */
function getFormCaptcha(capLength, elementId){
	elementIdGlob = elementId;
    var dateNow = new Date();
    //var obj = new Ajax.Request('../../form' + php_ext, {
    var obj = new Ajax.Request('../action/captcha' + php_ext, {
        asynchronous:false,
        method:'get',
        onSuccess: formCaptchaSuccess,
        onFailure: function(){ alert('AJAX not possible')},
        parameters: {
            operation : 'createCapture',
            capLength : capLength,
            cacheOverwrite : dateNow.getTime()
        }
    });
}

/**
 * @param {Object} obj 
 */
function formCaptchaSuccess(obj) {
	var response = obj.responseText;
    
    $(elementIdGlob+'_captcha_img').src = "../action/botcheck" + php_ext + "?cap="+response;
    $(elementIdGlob+'_captcha_hidden').value = response;
}

/**
 * get the arguments passed by a link in GET param style and provide an array
 * passedArgs that contains them
 */
function getArgs() {
  passedArgs = new Array();
  search = self.location.href;
  search = search.split('?');
  if(search.length>1)
  {
    argList = search[1];
    argList = argList.split('&');

    for(var i=0; i<argList.length; i++)
    {
      newArg = argList[i];
      newArg = argList[i].split('=');
      passedArgs[unescape(newArg[0])] = unescape(newArg[1]);
    }
  }
  else
    passedArgs = false;
}

/**
 * function to set the breadcrumb if form is called by STA form proxy on www3.statravel.de
 * @param {String} breadCrumb value of the breadcrumb to set
 * @param {String} breadCrumbName name of the BreadCrumb link
 */
function setBreadCrumb(breadCrumb, breadCrumbName) {
	if(document.getElementById('breadcrumbUl')) {
		var homeItem = document.getElementById('breadcrumbUl').firstChild;
		var newItem = document.createElement('li');
		
		
		var newLink = document.createElement('a');
		newLink.href = decodeURIComponent(breadCrumb);
		
		// if name is set
		if(breadCrumbName && breadCrumbName != '') {
			var breadName = new String(breadCrumbName);
			breadName = decodeURIComponent(breadName);
			newLink.innerHTML = breadName.replace(/\+/g,' ');
		}
		else {
			newLink.innerHTML = 'Back';
		}
		// append the 
		newItem.appendChild(newLink);
		homeItem.parentNode.appendChild(newItem);
	}
}

/**
 * check if a limit for checkboxes is reached
 * 
 * @var {Object} obj The HTML object to check
 * @var {Integer} count The amount of allowed checked boxes
 */
function checkBoxLimit(obj, count) {
	// get the text for the language
 	var formterms = eval('terms_form_'+form_language);
	// get all checkboxes
	var checkboxes = document.getElementsByName(obj.name);
	var checked = 0;
	
	// search all checked boxes
	for(var i = 0;i < checkboxes.length;i++){
		if(checkboxes[i].checked) {
			checked++;
		}
	}
	
	if(checked > count) {
		obj.checked = false;
		alert(formterms['checkBoxLimit']);	
	}
}

/**
 * function to set the value for silverpopexport to a given server
 * 
 * @param {Obj} checkbox
 * @return void
 */
function checkSilverPopExport(checkbox) {
	var oldCheck = true;
	// if a silverpopexport is target check if it is related to this checkbox
	if(document.getElementById('silverpopexport')) {
		if(document.getElementById('silverrelchkbx')){
			if(document.getElementById('silverrelchkbx').value != '' ) {
				var checkid = document.getElementById('silverrelchkbx').value.substr(5);
				var regEx = new RegExp(checkid);
				if(checkbox.parentNode.id.match(regEx) && checkbox.checked)  {
					document.getElementById('silverpopexport').value = true;
				}
			}
			if(!checkbox.checked) {
				document.getElementById('silverpopexport').value = false;
			}
			oldCheck = false;
		}
		else if(checkbox.checked && oldCheck) {
			document.getElementById('silverpopexport').value = true;
		}
	}
}

/**
 * get the userinformation from silverpop
 * @return void
 */
function getUserInfoSilverpop() {
	$('form_11_inputfield').value = passedArgs['Email'];
	$('usermail').value = passedArgs['Email'];
	
	// get profiledata
	var silverpoplist = $('silverpoplist').value;
	
	// In the live system we need to load a remote profile php to be able
	// to do cross server javascript AJAX calls (Workaround)
	var obj = new Ajax.Request('../profile/loadRemoteProfile' + php_ext, {   // LIVE
	//var obj = new Ajax.Request('../action/loadProfile' + php_ext, {			// TEST			 
	  	asynchronous:true, 
	  	method: 'post', 
	  	onSuccess: loadUserInfo, 
	  	onFailure:onError, 
	  	parameters: {
	  		Email :  passedArgs['Email'],
	  		silverpoplist : silverpoplist,
	  		hash : passedArgs['hash']
	  	} 
	});
}

/**
 * 
 * @return
 */
function loadUserInfo(obj) {
	if(obj.responseText != 'false') {
		obj = obj.responseText.evalJSON();
		// convert the saved properties back to a object
		// vorname
		$('form_3_inputfield').value = obj.vorname;
		// nachname
		$('form_4_inputfield').value = obj.nachname;
		// strasse hausnummer
		$('form_5_inputfield').value = obj.strassehsnr;
		// plz
		$('form_6_inputfield').value = obj.plz;
		// ort
		$('form_7_inputfield').value = obj.ort;
		// geburtsdtm
		var geburtsdtm = obj.geburtsdtm.split('/');
		$('form_8_calendar_input_day').value = geburtsdtm[1];
		$('form_8_calendar_input_month').value = geburtsdtm[0];
		$('form_8_calendar_input_year').value = geburtsdtm[2];
		// dest1
		if(obj.dest1 == 'true') {
			$('form_12_checkbox').firstChild.checked = true;
		}
		// dest2
		if(obj.dest2 == 'true') {
			$('form_13_checkbox').firstChild.checked = true;
		}
		// dest3
		if(obj.dest3 == 'true') {
			$('form_14_checkbox').firstChild.checked = true;
		}
		// dest4
		if(obj.dest4 == 'true') {
			$('form_15_checkbox').firstChild.checked = true;
		}
		// dest5
		if(obj.dest5 == 'true') {
			$('form_16_checkbox').firstChild.checked = true;
		}
		// dest6
		if(obj.dest6 == 'true') {
			$('form_17_checkbox').firstChild.checked = true;
		}
		// hash value
		$('hiddenfieldhash').value = obj.hash;
	}
}

/**
 * Error handling if AJAX Request didn't work
 * @param {Object} obj The AJAX response object
 */
function onError(obj)
{
    alert('Error ' + obj.status + ' -- ' + obj.statusText);
}

var staTrkId = '';
// @TODO Find a better way to generate view stats for formcreator 
if(self.location.href.match(/prefill/)) {
	document.writeln ('<sc' + 'ript src="formhandler/view' + php_ext + '" type="text/javascript"></sc'+'ript>');
}
else if(self.location.href.match('projects.hpm-kommunikation.de')) {
	//getformref.php calls the view.php in formhandler/view.php to generate views for the forms (ugly, ugly, ugly)
	document.writeln ('<sc' + 'ript src="https://tracking.statravel.de/getformref.php" type="text/javascript"></sc'+'ript>');
}
else {
	document.writeln ('<sc' + 'ript src="' + formcreatorPath + 'formhandler/view' + php_ext + '" type="text/javascript"></sc'+'ript>');	
}

