// set: var oStationSelect, object dropdown menu for stations
var oStationSelect;
function getWebroot(){
	return webroot + 'microtips'; // NSC-19

	// begin: select webroot url
/* 	var webroot = String(document.location);
	arrWebroot  = webroot.split("/");
	var lastWebroot = arrWebroot.last();
	
	if ( lastWebroot == "" || typeof( lastWebroot ) == "undefined" ) {
		arrWebroot.pop();
	}
	
	lastWebroot = arrWebroot.last();
	
	return webroot; */
	// end: select webroot url
}

function enableReductionCardListeners() {
	Event.observe('bahncard', 'click', function(e) {
		if ($('bahncard').checked) {
			$('bottomcolumnwrapper').style.height = '260px';
			$('bahncard_choice').show();	
		} else {
			if ($('thalysThePass').checked == false) {
				$('bottomcolumnwrapper').style.height = '140px';
			}
			
			$('bahncard_choice').hide();
			$('bahncard25').checked = false;
			$('bahncard50').checked = false;
			$('bahncard100').checked = false;
		}
	});
	Event.observe('thalysThePass', 'click', function(e) {
		if ($('thalysThePass').checked) {
			$('bottomcolumnwrapper').style.height = '260px';
			$('thalysThePass_choice').show();	
		} else {
			if ($('bahncard').checked == false) {
				$('bottomcolumnwrapper').style.height = '140px';
			}
			
			$('thePassWeekend').checked = false;
			$('thePassBusiness').checked = false;
			$('thalysThePass_choice').hide();
		}
		
	});

}

function getRoot(){
	var webroot = String(document.location);
	arrWebroot  = webroot.split("/");
	var lastWebroot = arrWebroot.first();
	
	if ( lastWebroot == "" || typeof( lastWebroot ) == "undefined" ) {
		arrWebroot.pop();
	}
	lastWebroot = arrWebroot.first();
	return webroot;
}

function jsLoadStations(t){
	var xml = t.responseXML;
	var stations = xml.getElementsByTagName('Station');
	
	// oStationSelect = $('stationlist');
	// clear all items but the first in select box 
	for (var i=oStationSelect.options.length-1;i>0;i--){
		oStationSelect.remove(i);
	}
	for (var i=0;i<stations.length;i++){
		var oOption = document.createElement('option');
		oOption.setAttribute('value', stations[i].getAttribute('id'));
		oOption.appendChild(document.createTextNode(stations[i].getAttribute('name')));
		oStationSelect.appendChild(oOption);
	}
	
	if(oStationSelect.options.length > 0){
		oStationSelect.disabled = false;
	}else{
		oStationSelect.disabled = true;
	}
	
}

function jsSearchStation( oInput ){
	$('stationsearchid').value = oInput.id;
	$('searchstations').style.display = 'block';
}

function jsLoadStationsByCountryCode( oSelect, objStation, sUrl ){
	oStationSelect = objStation;
	
	if(sUrl){
		new Ajax.Request(sUrl, {parameters:'country='+oSelect.value, onSuccess:jsLoadStations});
	}else{
		new Ajax.Request(getWebroot()+'/loadstations', {parameters:'country='+oSelect.value, onSuccess:jsLoadStations});
	}
}

function jsSelectLoadStation( oSelect ){
	for(i=0;i<oSelect.options.length;i++){
		if (oSelect.options[i].firstChild != null && oSelect.options[i].selected ){
			$($('stationsearchid').value).value = oSelect.options[i].firstChild.nodeValue;
			if( $('stationsearchid').value == 'autocompleteOrigin'){
				$('MicrotipsIOrigin').value = oSelect.options[i].value;
			}else if( $('stationsearchid').value == 'autocompleteDestination'){
				$('MicrotipsIDestination').value = oSelect.options[i].value;
			}
		}
	}
	$('searchstations').style.display = 'none';

	jsBookingWindow();
	jsFyraCheck();
}

function jsChangeClass( tacoId, comfortClass ){
	new Ajax.Updater(	'ajaxContent'
						,'changeclass/' + comfortClass + '/' + tacoId
						,{	asynchronous:true
							, evalScripts:true
							, onLoading :function(request){
								 if( jsGetCookie('COBS_LANG') == 'EN') {
								 	showbox('Your request is being processed.','progress');
								 } else{
								 	showbox('De gegevens worden geladen.', 'progress')
								 }
							}
						 	, onComplete :function(request){ closebox(); }  
							
						}
	);
}


function jsTamaraSelect( varDirection, varTariffChoiceSegment, varTamaraOptionId, varTamaraSelectedValue ) {
	var getVars = varDirection + '/' + varTariffChoiceSegment + '/' + varTamaraOptionId + '/' + varTamaraSelectedValue;
	new Ajax.Request('tamaraselect/' + getVars, { method: 'post' });
//	alert(varDirection + ' ' +  varTariffChoiceSegment + ' ' + varTamaraOptionId + ' ' +  varTamaraSelectedValue);
}

/**
 * Send information about reservation to server
 * @param int direction 0=outbound,1=inbound
 * @param int the selected travel option for this direction 
 * @param bool bUpdateTariffBlock if true update tariff selection.
 */
function jsConfirmReservation( direction, travelOptionIdx, bUpdateTariffBlock ){
	value = ($('tariefoptie4reserved_'+direction).checked) ? 1 : 0;
	new Ajax.Request('reservation/' + direction + '/' + value, {method:'post', onComplete:
					function(){
							if( bUpdateTariffBlock ){
								jsSelection( direction , travelOptionIdx);
							}else{
								$('hidden_tariffblock_'+direction).show();
								$('reservetripdialog_'+direction).hide();
							}
					}
	});
}

/**
 * Close/hides reservation dialog
 */
function jsCloseReservationDialog( senderId ){
	if($('reservationDlg_'+senderId)) {
			if($('reservationDlg_'+senderId).getAttribute('senderId') == senderId){
				$($('reservationDlg_'+senderId).getAttribute('senderId')).innerHTML = $('reservationDlg_'+senderId).innerHTML;
				document.body.removeChild($('reservationDlg_'+senderId));
			}
	}
}

/*
 * update tariff block
 */
function jsTariffSelect(event, varObject, varSelection){
	new Ajax.Updater(	'tariffblock'
							,'tariffselect/'+varObject+'/'+varSelection
							,{	asynchronous:true
								, evalScripts:true
								, onLoading:function(request){new Effect.Fade('tariffblock', { duration: 0.2, to: 0.1 });}
								, onComplete:function(request){new Effect.Appear('tariffblock', { duration: 0.3, queue: 'end' });}
							 }
						);
}

function jsSetTotalPrice(varPriceString){
	var priceSpans = document.getElementsByTagName('span');
	for(var i=0; i<priceSpans.length; i++){
		if(priceSpans[i].className == 'totalPriceLabel'){
			priceSpans[i].innerHTML = varPriceString;
		}
	}
}

function jsReorder(varDir,varColumn,varOrder){
	var dirStr = 'dep';
	if(varDir==1) dirStr = 'ret';
	new Ajax.Updater(	dirStr+'AdviceBlock'
						,'reorder/'+varDir+'/'+varColumn+'/'+varOrder
						,{	asynchronous:true
							, evalScripts:true
							, onLoading:function(request){new Effect.Fade(dirStr+'AdviceBlock', { duration: 0.2, to: 0.1 });}
							, onComplete:function(request){new Effect.Appear(dirStr+'AdviceBlock', { duration: 0.3, queue: 'end' });}
 						 }
						); 
	return false;
}

function jsSelection(varDir,varOption, blnShowDetailTable){
	if(varDir!=''&&varOption!=''){
		//unmark any selected rows
		for(i=0;i<30;i++){
			if(document.getElementById('row_'+varDir+'_'+i)){
				document.getElementById('row_'+varDir+'_'+i).className='normal';
			}
			// hide travelinformation
			if(document.getElementById('detailtable_'+varDir+'_'+i)){
				document.getElementById('detailtable_'+varDir+'_'+i).style.display = 'none';
			}
		}
		//mark newly selected row
		if(document.getElementById('row_'+varDir+'_'+varOption)){
			document.getElementById('row_'+varDir+'_'+varOption).className='selected';
		}
		//set the right radio button
		var dirStr = 'dep';
		if(varDir==1) dirStr = 'ret';
		
		// show travelinformation
		if(document.getElementById('detailtable_'+varDir+'_'+varOption)
				&& blnShowDetailTable == 1){
			document.getElementById('detailtable_'+varDir+'_'+varOption).style.display = 'block';
		}
		document.getElementById('sel_'+dirStr+'_'+varOption).checked = true;
	
		new Ajax.Updater(	'tariffblock'
							,'selection/'+varDir+'/'+varOption
							,{	asynchronous:true
								, evalScripts:true
								, onLoading:function(request){new Effect.Fade('tariffblock', { duration: 0.2, to: 0.1 });}
								, onComplete:function(request){new Effect.Appear('tariffblock', { duration: 0.3, queue: 'end' });}
	 						 }
							);
	}else{
		new Ajax.Updater(	'tariffblock'
							,'selection'
							,{	asynchronous:true
								, evalScripts:true
								, onLoading:function(request){new Effect.Fade('tariffblock', { duration: 0.2, to: 0.1 });}
								, onComplete:function(request){new Effect.Appear('tariffblock', { duration: 0.3, queue: 'end' });}
	 						 }
							);
	}
}

function jsShowDetails(varDir,varOption){
	var onButton	= document.getElementById('detailsOn_'+varDir+'_'+varOption);
	var offButton	= document.getElementById('detailsOff_'+varDir+'_'+varOption);
 	onButton.style.display='none';
 	offButton.style.display='none';
 	
 	var nonFunctionalA	= document.createElement('a');
	 	nonFunctionalA.href="#";
	 	nonFunctionalA.className="lessdetails";
	 	nonFunctionalA.appendChild(document.createTextNode(offButton.innerHTML));
	 	
 	onButton.parentNode.appendChild(nonFunctionalA);
 	document.getElementById('detailtable_'+ varDir + '_' + varOption).style.display='none';
 	
	new Effect.SlideDown('details_'+varDir+'_'+varOption, {duration:0.4, fps:15,
			afterFinish: function(element) {
			 	offButton.style.display='block';
			 	onButton.parentNode.removeChild(nonFunctionalA);
			}
		}
	);
 	return false;
}

function jsHideDetails(varDir,varOption){
	var onButton	= document.getElementById('detailsOn_'+varDir+'_'+varOption);
	var offButton	= document.getElementById('detailsOff_'+varDir+'_'+varOption);
 	onButton.style.display='none';
 	offButton.style.display='none';
 	
 	var nonFunctionalA	= document.createElement('a');
	 	nonFunctionalA.href="#";
	 	nonFunctionalA.className="details";
	 	nonFunctionalDiv = document.createElement('div');
	 	nonFunctionalDiv.innerHTML = onButton.innerHTML;
	 	nonFunctionalA.appendChild(nonFunctionalDiv);
 	
 	offButton.parentNode.appendChild(nonFunctionalA);
	new Effect.SlideUp('details_'+varDir+'_'+varOption, {duration:0.4, fps:15,
			afterFinish: function(element) {
			 	onButton.style.display='block';
			 	offButton.parentNode.removeChild(nonFunctionalA);
			 	strDirection = (varDir == 0) ? 'dep' : 'ret';
			 	objCheckbox = document.getElementById('sel_' + strDirection + '_' + varOption);
			 	if(objCheckbox.checked){
			 		document.getElementById('detailtable_'+ varDir + '_' + varOption).style.display='block';
			 	}
			}
		}
	);
 	return false;
}

function jsNavigate(varDir,varOffset,varLimit,varCount){
	var dirStr = 'dep';
	if(varDir==1) dirStr = 'ret';
	new Ajax.Updater(	dirStr+'AdviceBlock'
						,'navigate/'+varDir+'/'+varOffset+'/'+varLimit+'/'+varCount
						,{	asynchronous:true
							, evalScripts:true
							, onLoading:function(request){new Effect.Fade(dirStr+'AdviceBlock', { duration: 0.2, to: 0.1 });}
							, onComplete:function(request){new Effect.Appear(dirStr+'AdviceBlock', { queue: 'end' });}
						 }
						); 
	return false;
}

function jsUpdateCalendar(varDir,varMonth){
	var dirStr = 'dep';
	if(varDir==1) dirStr = 'ret';
	new Ajax.Updater(	dirStr+'calendar'
    					,'updatecalendar/'+varDir+'/'+varMonth
    					,{	asynchronous:true
    						, evalScripts:true
    						, onLoading:function(request){new Effect.Fade(dirStr+'calendar', { duration: 0.2, to: 0.1 });}
							, onComplete:function(request){new Effect.Appear(dirStr+'calendar', { queue: 'end' });}
    					 }
    					); 
    return false;
}	

function jsChangeDate(varDir,varDate){
	var dirStr = 'dep';
	if(varDir==1) dirStr = 'ret';
	new Ajax.Updater(	'ajaxContent'
						,'changedate/'+varDir+'/'+varDate
						,{	asynchronous:true
							, evalScripts:true
							, onLoading :function(request){
									 if( jsGetCookie('COBS_LANG') == 'EN') {
									 	showbox('Your request is being processed.','progress');
									 } else{
									 	showbox('De gegevens worden geladen.', 'progress')
									 }
							 }
						 	, onComplete :function(request){ closebox(); }  
						 }
						); 
	return false;
}

function jsCalendarSelect(varDir,calObj,varDate){
	
	//for(var i = 0; i <= 31; i++ ){
	//	if(document.getElementById('cal_'+varDir+'_'+i)){
	//		if(document.getElementById('cal_'+varDir+'_'+i).className=='calselected'){
	//			document.getElementById('cal_'+varDir+'_'+i).className='calselect';
	//		}
	//	}
	//}
	calObj.className='calselected';
	calObj.blur();
	jsChangeDate(varDir,varDate);
	return false;
}

function jsShowRateDetails(varIdstring){
	document.getElementById('detailsOn_'+varIdstring).style.display='none';
 	document.getElementById('detailsOff_'+varIdstring).style.display='block';
	new Effect.SlideDown('details_'+varIdstring,  {duration:0.2});
 	return false;
}

function jsHideRateDetails(varIdstring){
 	document.getElementById('detailsOff_'+varIdstring).style.display='none';
 	document.getElementById('detailsOn_'+varIdstring).style.display='block';
	new Effect.SlideUp('details_'+varIdstring,  {duration:0.2});
 	return false;
}

/**
 * Update the hidden fields for the corresponding
 * autocompletion fields.
 */
function jsUpdateHidden( txt, li ) {
	var hiddenName = txt.name.replace("_","");
	var id = li.id.replace("auto_", "");
	txt.form[hiddenName].value = id;
	
	jsBookingWindow();
	jsFyraCheck();
}

/**
 * Callback for the autocompletion fields 
 * We always send the values of both
 * the origin and destination fields to 
 * the server through Ajax.
 * We add an extra flag to the querystring to know
 * which field is the sender
 */
function jsAutoCompletionCallback( txt, queryString ) {
	
	var txt2 = null;
	if ( txt.id == 'autocompleteOrigin' ) {
		txt2 = document.getElementById('autocompleteDestination');
		
	} else if ( txt.id == 'autocompleteDestination' ) {
		txt2 = document.getElementById('autocompleteOrigin');
	}
	
	// the default encoding is not correct, so we add the value here again
	queryString = queryString + '&' + txt.name + '=' + txt.value
	
	if ( txt2 != null && txt2.value != '' ) {
		// add value of other field
		queryString = queryString + '&' + txt2.name + '=' + txt2.value
		
		// add valudId of other field
		var hiddenName = txt2.name.replace("_","");
		queryString = queryString + '&' + hiddenName + '=' + txt.form[hiddenName].value; 
	}
	
	queryString = queryString + '&sender=' + txt.name; 
	
	var partner = jsGetGET('partner');
	if(partner != '') {
		queryString += '&partner=' + partner;
	}
	
	return queryString;	
}

/**
 * execute javascript
 * @param string
 * @return
 */
function executeJavaScript(string) {
 	startString='<script type="text/javascript">';
 	var endPos = 0;
 	while(string.indexOf(startString, endPos) > -1) {
	 	startPos=string.indexOf(startString,endPos)+startString.length;
	 	endPos=string.indexOf('</script>',startPos);

	 	if (startPos>0 && endPos>startPos) {
	 		eval(string.substring(startPos,endPos));
	 		return true;
	 	} else {
	 		return false;
	 	}
 	}
}

/**
 * Succesfull ajax response
 * check if form was validated as OK
 * then submit form
 */
function jsValidateSuccess(t, bEvalJs) {
	// if form is validated as correct by server
	// then send form
	var retVal = t.responseText.replace(/\n/g,"");

	if(typeof bEvalJs != "undefined"
		&& bEvalJs == true){
		if(executeJavaScript(t.responseText)){
			if ( jsGetCookie('COBS_LANG') == 'EN') {
				showbox('Your request is being processed.','progress');
			}else{
				showbox('De gegevens worden verwerkt.','progress');
			}
			return; // execute javascript, but don't show dialog
		}
	}
	
	//if ( retVal.substring(0,2) == 'OK' ) {
	if ( retVal.indexOf('OK') > -1 && retVal.indexOf('NOTOK') == -1) {		
		document.getElementById('form1').submit();
		if ( jsGetCookie('COBS_LANG') == 'EN') {
			showbox('Your request is being processed.','progress');
		}else{
			showbox('De gegevens worden verwerkt.','progress');
		}
		
	} else if ( retVal.indexOf('NOTOK') > -1 ) {
		showbox('De gegevens worden verwerkt.','progress');
		eval(t.responseText.replace('NOTOK', ''));
	} else {
		showbox(t.responseText);
	}
}


/**
 * Sending validatoin request failed.
 */
function jsValidateFailure(t) {

}

/**
 * setCookie
 * @param string name 
 * @param string value 
 * @param dateobject expire date
 * @param string path
 * @param string domain
 * @param bool secure
 */
function jsSetCookie( sName, sValue, oExpires, sPath, sDomain, bSecure ){
	var sCookie = sName + "=" + encodeURIComponent(sValue);
	
	if (oExpires){
		sCookie += "; expires=" + oExpires.toGMTString();
	}
	if (sPath){
		sCookie += "; path=" + sPath;
	}
	if (sDomain){
		sCookie += "; domain=" + sDomain;
	}
	if (bSecure){
		sCookie += "; secure";
	}
	document.cookie = sCookie;
}

/**
 * getCookie
 * @param string name
 * 
 * @return cookie, or null if not found
 */
function jsGetCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}


function jsInitCalendars() {
	
	cal1 = new YAHOO.widget.Calendar('cal1','cal1Container', { close:true } );
	cal2 = new YAHOO.widget.Calendar('cal2','cal2Container', { close:true } );
	
	var maxdate = new Date();

	maxdate.setMonth( maxdate.getMonth() + 6 );
	cal1.cfg.setProperty("mindate", new Date(),false);
	cal1.cfg.setProperty("maxdate",maxdate,false);
	cal2.cfg.setProperty("mindate", new Date(),false);
	cal2.cfg.setProperty("maxdate",maxdate,false);
	
	var handleSelectDep = function (type,args,obj){
	
		var dates = args[0];
		var date = dates[0];
		var year = date[0];var month = date[1];
		var day = date[2];

		var selMonth = $('MicrotipsDepartureDateMonth');
		for (var x = 0; x < selMonth.length; x++) {
				if (selMonth.options[x].value==month) {
					selMonth.selectedIndex 	= x;
				}
		}
		
		$('MicrotipsDepartureDateDay').selectedIndex = day-1;
		obj.hide();
		jsAutochangeInputDates('d');
	}
	
	var handleSelectRet = function (type,args,obj){
		var dates = args[0];
		var date = dates[0];
		var year = date[0];var month = date[1];var day = date[2];
		
		
		var selMonth = $('MicrotipsReturnDateMonth');
		for (var x = 0; x < selMonth.length; x++) {
				if (selMonth.options[x].value==month) {
					selMonth.selectedIndex 	= x;
				}
		}
		
		$('MicrotipsReturnDateDay').selectedIndex = day-1;
		obj.hide();
		jsAutochangeInputDates('r');
	}
	
	var setStartDates = function(){
		
		var dM = parseInt($('MicrotipsDepartureDateMonth').value);
		var rM = false;
		if($('MicrotipsReturnDateMonth')){
			var rM = parseInt($('MicrotipsReturnDateMonth').value);
		}
		var tmpDate = new Date();
		var currentMonth = tmpDate.getMonth();
		var dOffsetYear = tmpDate.getFullYear();
		var rOffsetYear = tmpDate.getFullYear();
		
		if ( parseInt(dM) < parseInt(currentMonth) ) {
			dOffsetYear = parseInt(tmpDate.getFullYear()) + 1;
		}

		if(rM){
			if ( parseInt(rM) < parseInt(currentMonth) ) {
				rOffsetYear = parseInt(tmpDate.getFullYear()) + 1;
			}
		}
		
		
		var selectedDateDep = new Date();
		selectedDateDep.setMonth( dM - 1 );
		selectedDateDep.setDate( parseInt($('MicrotipsDepartureDateDay').value) );
		selectedDateDep.setYear( dOffsetYear );
		
		if(rM){
			var selectedDateRet = new Date();
			selectedDateRet.setMonth( rM - 1 );
			selectedDateRet.setDate( parseInt($('MicrotipsReturnDateDay').value) );
			selectedDateRet.setYear( rOffsetYear );
		}
		
		cal1.cfg.setProperty("selected", ""+(selectedDateDep.getMonth()+1)+"/"+selectedDateDep.getDate()+"/"+selectedDateDep.getFullYear()+"",false);
		cal1.cfg.setProperty("pagedate", ""+(selectedDateDep.getMonth()+1)+"/"+selectedDateDep.getFullYear()+"",false);
		cal1.render();
		
		if(rM){
			cal2.cfg.setProperty("selected", ""+(selectedDateRet.getMonth()+1)+"/"+selectedDateRet.getDate()+"/"+selectedDateRet.getFullYear()+"",false);
			cal2.cfg.setProperty("pagedate", ""+(selectedDateRet.getMonth()+1)+"/"+selectedDateRet.getFullYear()+"",false);
			cal2.render();
		}
	}


	// Listener to show the page Calendar
	YAHOO.util.Event.addListener("departureCal", "click", cal1.show, cal1, true);
	YAHOO.util.Event.addListener("departureCal", "click", cal2.hide, cal2, true);
	YAHOO.util.Event.addListener("departureCal", "click", setStartDates, cal1, true);
	
	YAHOO.util.Event.addListener("returnCal", "click", cal2.show, cal2, true);
	YAHOO.util.Event.addListener("returnCal", "click", cal1.hide, cal1, true);
	YAHOO.util.Event.addListener("returnCal", "click", setStartDates, cal2, true);
	
	cal1.selectEvent.subscribe(handleSelectDep, cal1, true);  
	cal2.selectEvent.subscribe(handleSelectRet, cal2, true);
	
	cal1.render();
	cal2.render();
	
	cal1.hide();
	cal2.hide();
	
	
	var changeDateFields = function( dayField, monthField, dayValue, monthValue ) {
		dayField.selectedIndex = dayValue-1;
		
		monthValue+=1;
		for (var x = 0; x < monthField.length; x++) {
			if (monthField.options[x].value==monthValue) {
				monthField.selectedIndex = x;
			}
		}
	}
	
	function jsUpdateYahooCal1() {
	
		function updateCal1( t ) {
			cal1.cfg.setProperty("mindate", t.responseText ,false);
			
			var selectedDateDep = new Date();
			selectedDateDep.setMonth( parseInt($('MicrotipsDepartureDateMonth').value)-1 );
			selectedDateDep.setDate( parseInt($('MicrotipsDepartureDateDay').value) );
	
			var tmpDate = new Date(t.responseText);
			
			if ( tmpDate > selectedDateDep ) {
				changeDateFields( 	$('MicrotipsDepartureDateDay'),
									$('MicrotipsDepartureDateMonth'),
									tmpDate.getDate(), tmpDate.getMonth());
				jsAutochangeInputDates('d');									
			}
			
			cal1.render();
		}
	
		if( $('MicrotipsIOrigin').value != '') {
			new Ajax.Request(getWebroot()+'/getbookinghorizon/' + $('MicrotipsIOrigin').value + '/' + $('MicrotipsIDestination').value, { method: 'post', onSuccess:updateCal1 } );
		}
	}
	
	var jsChangeCalToDutch = function ( cal ) {
		cal.cfg.setProperty("MONTHS_LONG", ["Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"]);
		cal.cfg.setProperty("WEEKDAYS_SHORT", ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za"]); 
		cal.render();
	}
	

	// set locales
	var sLang = jsGetCookie('COBS_LANG');
	if (sLang == 'NL' || sLang == null) {
		jsChangeCalToDutch(cal1);
		jsChangeCalToDutch(cal2);
	} 	
	 
}


function jsInitCalendarsStep1_2() {
	
	cal1 = new YAHOO.widget.Calendar('cal1','cal1Container', { close:true } );
	cal2 = new YAHOO.widget.Calendar('cal2','cal2Container', { close:true } );
	
	var maxdate = new Date();

	maxdate.setMonth( maxdate.getMonth() + 6 );
	cal1.cfg.setProperty("mindate", new Date(),false);
	cal1.cfg.setProperty("maxdate",maxdate,false);
	cal2.cfg.setProperty("mindate", new Date(),false);
	cal2.cfg.setProperty("maxdate",maxdate,false);
	
	var handleSelectDep = function (type,args,obj){
	
		var dates = args[0];
		var date = dates[0];
		var year = date[0];var month = date[1];
		var day = date[2];

		var selMonth = $('MicrotipsDepartureDateMonth');
		for (var x = 0; x < selMonth.length; x++) {
				if (selMonth.options[x].value==month) {
					selMonth.selectedIndex 	= x;
				}
		}
		setOutboundOptions(month);
//		$('MicrotipsDepartureDateDay').selectedIndex = day-1;
		var selDay = $('MicrotipsDepartureDateDay');
		for (var x = 0; x < selDay.length; x++) {
			if (selDay.options[x].value==day) {
				selDay.selectedIndex 	= x;
			}
		}
		
		obj.hide();
		jsAutochangeInputDates('d');
	}
	
	var handleSelectRet = function (type,args,obj){
		var dates = args[0];
		var date = dates[0];
		var year = date[0];var month = date[1];var day = date[2];
		
		
		var selMonth = $('MicrotipsReturnDateMonth');
		for (var x = 0; x < selMonth.length; x++) {
				if (selMonth.options[x].value==month) {
					selMonth.selectedIndex 	= x;
				}
		}
		setInboundOptions(month);
//		$('MicrotipsReturnDateDay').selectedIndex = day-1;
		var selDay = $('MicrotipsReturnDateDay');
		for (var x = 0; x < selDay.length; x++) {
			if (selDay.options[x].value==day) {
				selDay.selectedIndex 	= x;
			}
		}		
		obj.hide();
		jsAutochangeInputDates('r');
	}
	
	var setStartDates = function(){
		
		var dM = parseInt($('MicrotipsDepartureDateMonth').value);
		var rM = false;
		if($('MicrotipsReturnDateMonth')){
			var rM = parseInt($('MicrotipsReturnDateMonth').value);
		}
		var tmpDate = new Date();
		var currentMonth = tmpDate.getMonth();
		var dOffsetYear = tmpDate.getFullYear();
		var rOffsetYear = tmpDate.getFullYear();
		
		if ( parseInt(dM) < parseInt(currentMonth) ) {
			dOffsetYear = parseInt(tmpDate.getFullYear()) + 1;
		}

		if(rM){
			if ( parseInt(rM) < parseInt(currentMonth) ) {
				rOffsetYear = parseInt(tmpDate.getFullYear()) + 1;
			}
		}
		
		
		var selectedDateDep = new Date();
		selectedDateDep.setMonth( dM - 1 );
		selectedDateDep.setDate( parseInt($('MicrotipsDepartureDateDay').value) );
		selectedDateDep.setYear( dOffsetYear );
		
		if(rM){
			var selectedDateRet = new Date();
			selectedDateRet.setMonth( rM - 1 );
			selectedDateRet.setDate( parseInt($('MicrotipsReturnDateDay').value) );
			selectedDateRet.setYear( rOffsetYear );
		}
		
		cal1.cfg.setProperty("selected", ""+(selectedDateDep.getMonth()+1)+"/"+selectedDateDep.getDate()+"/"+selectedDateDep.getFullYear()+"",false);
		cal1.cfg.setProperty("pagedate", ""+(selectedDateDep.getMonth()+1)+"/"+selectedDateDep.getFullYear()+"",false);
		cal1.render();
		
		if(rM){
			cal2.cfg.setProperty("selected", ""+(selectedDateRet.getMonth()+1)+"/"+selectedDateRet.getDate()+"/"+selectedDateRet.getFullYear()+"",false);
			cal2.cfg.setProperty("pagedate", ""+(selectedDateRet.getMonth()+1)+"/"+selectedDateRet.getFullYear()+"",false);
			cal2.render();
		}
	}


	// Listener to show the page Calendar
	YAHOO.util.Event.addListener("departureCal", "click", cal1.show, cal1, true);
	YAHOO.util.Event.addListener("departureCal", "click", cal2.hide, cal2, true);
	YAHOO.util.Event.addListener("departureCal", "click", setStartDates, cal1, true);
	
	YAHOO.util.Event.addListener("returnCal", "click", cal2.show, cal2, true);
	YAHOO.util.Event.addListener("returnCal", "click", cal1.hide, cal1, true);
	YAHOO.util.Event.addListener("returnCal", "click", setStartDates, cal2, true);
	
	cal1.selectEvent.subscribe(handleSelectDep, cal1, true);  
	cal2.selectEvent.subscribe(handleSelectRet, cal2, true);
	
	cal1.render();
	cal2.render();
	
	cal1.hide();
	cal2.hide();
	
	
	var changeDateFields = function( dayField, monthField, dayValue, monthValue ) {
		dayField.selectedIndex = dayValue-1;
		
		monthValue+=1;
		for (var x = 0; x < monthField.length; x++) {
			if (monthField.options[x].value==monthValue) {
				monthField.selectedIndex = x;
			}
		}
	}
	
	function jsUpdateYahooCal1() {
	
		function updateCal1( t ) {
			cal1.cfg.setProperty("mindate", t.responseText ,false);
			
			var selectedDateDep = new Date();
			selectedDateDep.setMonth( parseInt($('MicrotipsDepartureDateMonth').value)-1 );
			selectedDateDep.setDate( parseInt($('MicrotipsDepartureDateDay').value) );
	
			var tmpDate = new Date(t.responseText);
			
			if ( tmpDate > selectedDateDep ) {
				changeDateFields( 	$('MicrotipsDepartureDateDay'),
									$('MicrotipsDepartureDateMonth'),
									tmpDate.getDate(), tmpDate.getMonth());
				jsAutochangeInputDates('d');									
			}
			
			cal1.render();
		}
	
		if( $('MicrotipsIOrigin').value != '') {
			new Ajax.Request(getWebroot()+'/getbookinghorizon/' + $('MicrotipsIOrigin').value + '/' + $('MicrotipsIDestination').value, { method: 'post', onSuccess:updateCal1 } );
		}
	}
	
	var jsChangeCalToDutch = function ( cal ) {
		cal.cfg.setProperty("MONTHS_LONG", ["Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"]);
		cal.cfg.setProperty("WEEKDAYS_SHORT", ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za"]); 
		cal.render();
	}
	

	// set locales
	var sLang = jsGetCookie('COBS_LANG');
	if (sLang == 'NL' || sLang == null) {
		jsChangeCalToDutch(cal1);
		jsChangeCalToDutch(cal2);
	} 	
	 
}

// minBookHorizonCheck is a copy of jsUpdateYahooCal1 function which can manually be set with "onChange" to any object etc.
// this because jsUpdateYahooCal1 seems not to work in case getBookingWindo is also fired
// separation with timeout and "Fire" function is needed to correct the problem that autocompleter has not yet updated MicrotipsIOrigin field
function minBookHorizonCheck(){
	setTimeout("minBookHorizonFire();",500);
}
function minBookHorizonFire(){
	if( $('MicrotipsIOrigin').value != '') {
		new Ajax.Request(getWebroot()+'/getbookinghorizon/' + $('MicrotipsIOrigin').value + '/' + $('MicrotipsIDestination').value, { method: 'post', onSuccess:minBookHorizonCheckResult } );
	}
}
// minBookHorizonCheckResult is the response processor of minBookHorizonCheck, and is a blind copy of the 
// updateCal1 function within jsUpdateYahooCal1
function minBookHorizonCheckResult(t){
	cal1.cfg.setProperty("mindate", t.responseText ,false);
	var selectedDateDep = new Date();
	selectedDateDep.setMonth( parseInt($('MicrotipsDepartureDateMonth').value)-1 );
	selectedDateDep.setDate( parseInt($('MicrotipsDepartureDateDay').value) );
	var tmpDate = new Date(t.responseText);
	
	if ( tmpDate > selectedDateDep ) {
		//NSID-246: don't update selected date
		//$('MicrotipsDepartureDateDay').selectedIndex = tmpDate.getDate()-1;
		var monthValue = tmpDate.getMonth()+1;
		for (var x = 0; x < $('MicrotipsDepartureDateMonth').length; x++) {
			if ($('MicrotipsDepartureDateMonth').options[x].value==monthValue) {
				//NSID-246: don't update selected date
				//$('MicrotipsDepartureDateMonth').selectedIndex = x;
			}
		}
		jsAutochangeInputDates('d');	
	}
	cal1.render();
}

function minBookHorizonCheckResultWithUpdate(t){
	//cal1.cfg.setProperty("mindate", t.responseText ,false);
	var selectedDateDep = new Date();
	selectedDateDep.setMonth( parseInt($('MicrotipsDepartureDateMonth').value)-1 );
	selectedDateDep.setDate( parseInt($('MicrotipsDepartureDateDay').value) );
	var tmpDate = new Date(t.responseText);
	
	if ( tmpDate > selectedDateDep ) {
		$('MicrotipsDepartureDateDay').selectedIndex = tmpDate.getDate()-1;
		var monthValue = tmpDate.getMonth()+1;
		for (var x = 0; x < $('MicrotipsDepartureDateMonth').length; x++) {
			if ($('MicrotipsDepartureDateMonth').options[x].value==monthValue) {
				$('MicrotipsDepartureDateMonth').selectedIndex = x;
			}
		}
		jsAutochangeInputDates('d');	
	}
	cal1.render();
}

/**
 * Basic form validation
 */
function jsValidateForm (formname, form)  {
	if(form){
		new Ajax.Request(form.action, { method: 'post', evalScripts:true, postBody:Form.serialize(form.name), onSuccess:jsValidateSuccess, onFailure:jsValidateFailure });
	}else{
		new Ajax.Request(getWebroot() + '/validateform', { method: 'post', evalScripts:true, postBody:Form.serialize(formname), onSuccess:jsValidateSuccess, onFailure:jsValidateFailure });
	}
}

/**
 * check form 1.2
 * @param string formname
 * @param element form
 * @return void
 */
function jsValidateForm1_2 (form)  {
	new Ajax.Request(form.action, { method: 'post', evalScripts:true, postBody:Form.serialize(form.name), onSuccess: function(t){jsValidateSuccess(t, true)}, onFailure:jsValidateFailure });
}


function jsSelfserviceSubmit(){
	new Ajax.Updater('selfservicesubmit'
						,'selfservicesubmit'
						,{	asynchronous:true
							, evalScripts:true
							, onLoading :function(request){new Effect.Fade('selfservicesubmit', { duration: 0.5, to: 0.1 }); 									 
									if( jsGetCookie('COBS_LANG') == 'EN') {
									 	showbox('Your request is being processed.','progress');
									 } else{
									 	showbox('De gegevens worden geladen.', 'progress')
									 }
							
							}
							, onComplete:function(request){ ns_onclick(this,'','nl.COstap2.button.toon_beschikbaarheid','clickout'); new Effect.Appear('selfservicesubmit', { queue: 'end' }); }
	 						 }
						);
						
	return false;
}

bValidDeparture = true;
bValidReturn = true;
function jsSetSubmitbutton(enabled){
	if(document.getElementById('selfserviceSubmitButton')){
		$('selfserviceSubmitButton').style.visibility='hidden';
		if(enabled==1 && bValidDeparture == true && bValidReturn == true){
			$('selfserviceSubmitButton').style.visibility='visible';
		}else{
			$('selfserviceSubmitButton').style.visibility='hidden';
		}
	}
}

function jsInitTabs() {
	
	var tab1 = document.getElementById('tab1');
	var tab2 = document.getElementById('tab2');
	
	var showTab2FormElements = function () {

		$('step1subnav').style.display = 'block';
		$('horizontaldivider').className = 'horizontaldividersubnav';
					
	}
	
	var hideTab2FormElements = function () {
		
		$('step1subnav').style.display = 'none';
	}
	
	var showTab1FormElements = function () {
		
		$('youngerchildren').style.display = 'block';		
		$('OV').style.display = 'block';
		$('RP').style.display = 'block';
		$('horizontaldivider').className = 'horizontaldivider';
	//	document.getElementById('OV').style.visibility = 'visible';
	}
	
	var hideTab1FormElements = function () {
		
		$('youngerchildren').style.display = 'none';
		$('OV').style.display = 'none';
		$('RP').style.display = 'none';
		//document.getElementById('OV').style.visibility = 'hidden';
	}

	var tab1Click = function ( e ) {
		tab1.className = 'selected';
		tab2.className = '';
		
		showTab1FormElements();
		hideTab2FormElements();
	}

	var tab2Click = function ( e ) {
		tab2.className = 'selected';
		tab1.className = '';
		hideTab1FormElements();
		showTab2FormElements();
		// show tab2 specific form elements
		
		// and hide tab1 specific form elements
	}

	
	Event.observe('tab1', 'click', tab1Click );
	Event.observe('tab2', 'click', tab2Click );
	
}

function jsChangeLanguage( lang ) {
	if(lang == 'EN'){
		showbox('Bezig met nieuwe informatie laden', 'progress');
	}else{
		showbox('Your request is being processed.', 'progress');
	}	
	jsSetCookie('COBS_LANG', lang);
	new Ajax.Updater('content', webroot+'microtips/lang/' + lang, { method: 'post', evalScripts: true, insertion:Insertion.Before } );
}

function jsChangeSocusLanguage( lang ) {
	if(lang == 'EN'){
		showbox('Bezig met nieuwe informatie laden', 'progress');
	}else{
		showbox('Your request is being processed.', 'progress');
	}	
	jsSetCookie('COBS_LANG', lang);
	new Ajax.Updater('content', 'socus/lang/' + lang, { method: 'post', evalScripts: true, insertion:Insertion.Before } );
}


function jsToggleTravelType( travelType ){
	if(travelType=='e'){
		if(document.getElementById('datereturnon')){
			document.getElementById('datereturnon').style.display='none';
		}
	}
	if(travelType=='r'){
		if(document.getElementById('datereturnon')){
			document.getElementById('datereturnon').style.display='block';
		}
	}
}

function jsAutochangeInputDates( directionStr ){
	
	// current month
	var tmpDate = new Date();
	var currentMonth = tmpDate.getMonth();
	var dOffSetMonth = 0;
	var rOffSetMonth = 0;
	
	var dD = $('MicrotipsDepartureDateDay');
	var dM = $('MicrotipsDepartureDateMonth');
	var rD = $('MicrotipsReturnDateDay');
	var rM = $('MicrotipsReturnDateMonth');
	
	if( parseInt(dM.value) < parseInt(currentMonth) ) { // next year 
		dOffSetMonth = parseInt(dM.value) + 11;
			
	}

	if(!rM) return;
	
	if ( parseInt(rM.value) < parseInt(currentMonth) ) { // next year
		rOffSetMonth = parseInt(rM.value) + 11;
	}
	
	if(directionStr=='d'){
		if( ( (parseInt(dM.value)+ parseInt(dOffSetMonth)) ) > (parseInt(rM.value)+parseInt(rOffSetMonth)) ){
			rM.value = dM.value;
			rD.value = dD.value;
		}
		if( ( (parseInt(dM.value)+ parseInt(dOffSetMonth)) ) == (parseInt(rM.value)+parseInt(rOffSetMonth)) ){
			if(parseInt(dD.value+dOffSetMonth)>parseInt(rD.value+rOffSetMonth)){
				rD.value = dD.value;
			}
		}
	}
	if(directionStr=='r'){
		
		if( ( (parseInt(dM.value)+ parseInt(dOffSetMonth)) ) > (parseInt(rM.value)+parseInt(rOffSetMonth)) ){
			dM.value = rM.value;
			dD.value = rD.value;
		}
		if( ( (parseInt(dM.value)+ parseInt(dOffSetMonth)) ) == (parseInt(rM.value)+parseInt(rOffSetMonth)) ){
			if(parseInt(dD.value+dOffSetMonth)>parseInt(rD.value+rOffSetMonth)){
				dD.value = rD.value;
			}
		}
	}
}


function jsGetGET (sName) {

 	// the question string without the ? mark
 	var questionString = location.search.substring(1);

	// the variable/value pairs are in the
	// form of &variable=value
	// first we split up on & to get array of pairs
	var pairs = questionString.split("&");
	
	// now we walk through all pairs
	// and check if value is same as sName
	
	for ( var i=0; i < pairs.length; i++ ) {
		
		var tmpAry = pairs[i].split("=");
		
		if ( tmpAry[0] == sName ) {
			// found value	
			return tmpAry[1];
		}
	}
	
	// not found
	return null;
 }
 
 function jsRedirectOldTIP( url ) {
 	new Ajax.Updater(	'redirectOldTIP'
						,'tip'
						,{	asynchronous:true
							, evalScripts:true
							, onLoading :function(request){new Effect.Fade('redirectOldTIP', { duration: 0.5, to: 0.1 }); showbox('De gegevens worden geladen.', 'progress');}
							, onComplete:function(request){new Effect.Appear('redirectOldTIP', { queue: 'end' }); }
	 						 }
						);
	return false;
 }
 
 
 /* creer/verwijder iFrame - for internet explorer 6 only */
function jsAddIFrame(div) {
    var laag = document.createElement('iframe');
    laag.className = 'tooltipiframe';
    laag.tabIndex = '-1';
 //   laag.src = 'javascript:false;';
	div.insertBefore(laag,div.firstChild);
	
	return laag;
}

function jsRemoveIFrame(div) {
	var lagen = div.getElementsByTagName('iframe');
	while (lagen.length > 0) {
		lagen[0].parentNode.removeChild(lagen[0]);
	}
}


/* browser check */
function jsIsIE6() {
	//return false;
	var ie6 = false;
	var os = navigator.platform.toLowerCase();
	var agt = navigator.userAgent.toLowerCase();
	if ((os.indexOf('win') != -1) && (agt.indexOf('msie 6') != -1)) {
		var ie6 = true;
	}
	return ie6;
}

/* get booking horizon */
function jsBookingWindow(){
	originStationId = document.getElementById('MicrotipsIOrigin').value;
	destinationStationId = document.getElementById('MicrotipsIDestination').value;
	if(document.getElementById('type_r').checked == true) {
		travelType = 'r';
	} else {
		travelType = 'e';
	}
	new Ajax.Request(getWebroot()+'/getBookingWindow', { method:'post', onSuccess:jsUpdateBookingWindow, parameters:'originStationId='+originStationId+'&destinationStationId='+destinationStationId+'&travelType='+travelType});
}


/* update booking window based on XML data from server */
function jsUpdateBookingWindow(t){
	var xml = t.responseXML;
	var bookingWindow = xml.getElementsByTagName('BookingWindow');
	maxdate = new Date(bookingWindow[0].getAttribute('max_booking_date'));

	
	var InboundExceptions = xml.getElementsByTagName('inbound');
	for(j=0;j<InboundExceptions.length;j++){
		strDates = InboundExceptions[j].getAttribute('exclude');
		arrDates = strDates.split(',');
		for(i=0;i<arrDates.length;i++) {
			cal2.addRenderer(arrDates[i], cal2.renderOutOfBoundsDate);
		}
	}
	
	var OutboundExceptions = xml.getElementsByTagName('outbound');
	for(j=0;j<OutboundExceptions.length;j++){
		strDates = OutboundExceptions[j].getAttribute('exclude');
		arrDates = strDates.split(',');
		for(i=0;i<arrDates.length;i++) {
			cal1.addRenderer(arrDates[i], cal1.renderOutOfBoundsDate);
		}
	}
	
	var curdate = new Date();
	if ( maxdate < curdate ) {
		var maxdatestr = maxdate.getDate()+'-'+maxdate.getMonth()+'-'+maxdate.getFullYear();
		
		if( jsGetCookie('COBS_LANG') == 'EN') {
			showbox('It isn\'t possible to book this journey since '+maxdatestr);
		}
		else {
			showbox('Deze reis is sinds '+maxdatestr+' niet meer te boeken.');
		}
	}
	

	
	cal1.cfg.setProperty("maxdate",maxdate,false);
	cal2.cfg.setProperty("maxdate",maxdate,false);
	cal1.render();
	cal2.render();
	jsUpdateCalendarDropDowns(maxdate);
}

/* Dynamic form check (D-Cobs Fyra) */
function jsFyraCheck(){
	originStationId = document.getElementById('MicrotipsIOrigin').value;
	destinationStationId = document.getElementById('MicrotipsIDestination').value;
	if(document.getElementById('type_r').checked == true) {
		travelType = 'r';
	} else {
		travelType = 'e';
	}
	new Ajax.Request(getWebroot()+'/getFyraCheck', { method:'post', onSuccess:jsUpdateFyraForm, parameters:'originStationId='+originStationId+'&destinationStationId='+destinationStationId+'&travelType='+travelType});
}

function jsUpdateFyraForm(t){
	var result = t.responseText;
	if (result=='true') {
		
		$('bookMultipleDaysInput').show();
		jsSwitchMultipleDays();
		
		$('departureTimeHour').disabled=false;
		$('departureTimeMinute').disabled=false;		
		$('departureTimeSelectTime').disabled=true;
		$('departureTimeInput').show();
		$('departureTimeSelect').hide();

		$('returnTimeHour').disabled=false;
		$('returnTimeMinute').disabled=false;		
		$('returnTimeSelectTime').disabled=true;
		$('returnTimeInput').show();
		$('returnTimeSelect').hide();

		$('_help_person').hide();
		$('_help_person_fyra').show();
		$('MicrotipsPassType1').value='A';
		$('MicrotipsPassType1').disabled=true;
		$('MicrotipsPassType1Fixed').disabled=false;

		
		disableFields(document.getElementById('recoCobs'),true);
		disableFields(document.getElementById('recoFyra'),false);
		
		$('recoCobs').hide();
		$('recoFyra').show();
		
		document.getElementById('MicrotipsPax2').options.length = 4; // set childs dropdown to max 3
		
		$('olderchildren').hide();
		$('label4-5').hide();
		$('label4-11').show();
		disableFields(document.getElementById('olderchildren'),true);
	} else {
		$('bookMultipleDaysInput').hide();
		$('bookMultipleDays').checked=false;
		
		disableFields(document.getElementById('departureTimeType'),false)
		disableFields(document.getElementById('departureTimeInput'),false)
		disableFields(document.getElementById('returnTimeType'),false)
		disableFields(document.getElementById('returnTimeInput'),false)
		
		$('departureTimeHour').disabled=true;
		$('departureTimeMinute').disabled=true;
		$('departureTimeSelectTime').disabled=false;
		$('departureTimeInput').hide();
		$('departureTimeSelect').show();

		$('returnTimeHour').disabled=true;
		$('returnTimeMinute').disabled=true;
		$('returnTimeSelectTime').disabled=false;		
		$('returnTimeInput').hide();
		$('returnTimeSelect').show();
		
		$('_help_person').show();
		$('_help_person_fyra').hide();		
		$('MicrotipsPassType1').disabled=false;
		$('MicrotipsPassType1Fixed').disabled=true;
		
		disableFields(document.getElementById('recoCobs'),false);
		disableFields(document.getElementById('recoFyra'),true);
		
		$('recoCobs').show();
		$('recoFyra').hide();
		
		if ( document.getElementById('MicrotipsPax2').options.length == 4 ) {
			// set options back to 5
			document.getElementById('MicrotipsPax2').options[4]=new Option(4, 4, false, false);
			document.getElementById('MicrotipsPax2').options[5]=new Option(5, 5, false, false);
		}
		
		disableFields(document.getElementById('olderchildren'),false);
		$('olderchildren').show();
		$('label4-5').show();
		$('label4-11').hide();
	}
}

function jsSwitchMultipleDays(){
		disableFields(document.getElementById('departureTimeType'),document.getElementById('bookMultipleDays').checked)
		disableFields(document.getElementById('departureTimeInput'),document.getElementById('bookMultipleDays').checked)
		disableFields(document.getElementById('returnTimeType'),document.getElementById('bookMultipleDays').checked)
		disableFields(document.getElementById('returnTimeInput'),document.getElementById('bookMultipleDays').checked)
}

function disableFields(parentElement,disable) {
	for(var i=0; i<parentElement.children.length; i++) {
		if(parentElement.children[i].type=="checkbox" || parentElement.children[i].type=="text" || parentElement.children[i].type=="radio") {
			parentElement.children[i].disabled=(disable?"disabled":"");
			if (disable) {
				$(parentElement.children[i]).addClassName('disabled');
			} else {
				$(parentElement.children[i]).removeClassName('disabled');
			}
		} else if(parentElement.children[i].children.length>0) {
			disableFields(parentElement.children[i],disable)
		}
	}
}

/* End dynamic form check */

function jsUpdateCalendarDropDowns(maxdate){
	var dM = $('MicrotipsDepartureDateMonth');
	var rM = $('MicrotipsReturnDateMonth');
	
	var now = new Date();
	var dMselectedValue = jsClearSelect(dM);
	var rMselectedValue = jsClearSelect(rM);
	
	if ( now.getFullYear() < maxdate.getFullYear() ){
		maxMonth  = 11 + maxdate.getMonth()+1;
	} else {
		maxMonth  = maxdate.getMonth();
	}

	for(j=0;j<2;j++){
		for(var i=now.getMonth()+1; i <= maxMonth+1;i++){
			oOption = document.createElement('option');
			
			monthValue = ( i <= 12 ) ?  i : i-12; 
			
			oOption.setAttribute('value',monthValue);
			monthDesc = jsGetMonthDescription(i);
			oOption.appendChild(document.createTextNode(monthDesc));
			if( j==0 ) 	{
				dM.appendChild(oOption);
				if ( dMselectedValue != null && oOption.value == dMselectedValue ){
					oOption.selected = true;
				}
				
			}
			else{
				rM.appendChild(oOption);
				if ( rMselectedValue != null && oOption.value == rMselectedValue ){
					oOption.selected = true;
				}
			}
		}
	}
	jsAutochangeInputDates('d');	
}

function jsGetMonthDescription(maxMonth){
	now = new Date();
	if(maxMonth > 12) {
		year = now.getFullYear()+1;
		maxMonth-=12;
	}else{
		year = now.getFullYear();
	}
	switch (maxMonth){
		case 1:
			monthDesc = (jsGetCookie('COBS_LANG')=='EN') ? 'Jan' : 'jan';				
			break;
		case 2:
			monthDesc =  (jsGetCookie('COBS_LANG')=='EN') ? 'Feb' : 'feb';
			break;
		case 3:
			monthDesc =  (jsGetCookie('COBS_LANG')=='EN') ? 'Mar' : 'mrt'; 
			break;
		case 4:
			monthDesc =  (jsGetCookie('COBS_LANG')=='EN') ? 'Apr' : 'apr';
			break;
		case 5:
			monthDesc =  (jsGetCookie('COBS_LANG')=='EN') ? 'May' : 'mei';
			break;
		case 6:
			monthDesc =  (jsGetCookie('COBS_LANG')=='EN') ? 'Jun' : 'jun';
			break;
		case 7:
			monthDesc =  (jsGetCookie('COBS_LANG')=='EN') ? 'Jul' : 'jul';
			break;
		case 8:
			monthDesc =  (jsGetCookie('COBS_LANG')=='EN') ? 'Aug' : 'aug';
			break;
		case 9:
			monthDesc =  (jsGetCookie('COBS_LANG')=='EN') ? 'Sep' : 'sep';
			break;
		case 10:
			monthDesc =  (jsGetCookie('COBS_LANG')=='EN') ? 'Okt' : 'okt';
			break;
		case 11:
			monthDesc =  (jsGetCookie('COBS_LANG')=='EN') ? 'Nov' : 'nov';
			break;
		case 12:
			monthDesc =  (jsGetCookie('COBS_LANG')=='EN') ? 'Dec' : 'dec';
			break;
	}
	
	return monthDesc + ' ' + year;
}

function jsClearSelect(s){
	var selectedValue = null;
	for(var i = (s.options.length-1); i >=0; i--){
		if ( s.options[i].selected && selectedValue == null ) {
			selectedValue = s.options[i].value;
		}
		s.remove(i);
	}
	return selectedValue;
}

// NSID-246: Set default dates 
function setDefaultDates() {
	new Ajax.Request(getWebroot()+'/getbookinghorizon/0/0', { method: 'post', onSuccess:minBookHorizonCheckResultWithUpdate } );
}

// Check if enkele reis is selected, hide returndate if so
function checkEnkelereis() {
	if(document.getElementById('datereturnon')){
		if(document.getElementById('type_e').checked == true){
			document.getElementById('datereturnon').style.display='none';
		}
	}
}

//Simple Form submit via Javascript
function submitloginForm(formId)	{

	var curlang = jsGetCookie('COBS_LANG');	
	if (curlang == null) curlang = 'nl';	
	curlang = curlang.toLowerCase();
	
	eval('var lang = langs.'+curlang);
	
	if($('loginbox-username').value==''){
		showbox(lang.socus.nousername);
	}
	else if($('loginbox-password').value=='')	{
		showbox(lang.socus.nopassword);
		return false; 
	}
	else {
	
		var params = Form.serialize($(formId));		
		new Ajax.Request(webroot+'socus/login',{parameters: params, method: 'post', onSuccess:function(response){
			if (response.responseText == 'ok')	{
				if ($('refUrl').value!='/microtips') {
					window.location.href = $('refUrl').value;	
				} else {
					window.location.href = document.location.toString().replace('/socus','/microtips');
				}
			} 
			else {
				showbox(lang.socus.wronglogin);
				return false; 		
			}
		}
	
	});
	
	
	}
}

function addFavorite(){
	new Ajax.Request(	'bookmark/'
						,{  asynchronous:true
							, evalScripts:true
							, onLoading :function(request){
									 if( jsGetCookie('COBS_LANG') == 'EN') {
									 	showbox('Your request is being processed.','progress');
									 } else{
									 	showbox('De gegevens worden geladen.', 'progress')
									 }
							 }
						 	, onComplete :function(request){ closebox(); }  
						 }
						); 
	return false;
}

/*
 * Sophie ajax handler for microtips
 */
function askQuestion(frmId){
	/* NSID-473 GA code */
	if (typeof pageTracker != "undefined") {
		pageTracker._setCustomVar(3,"ServiceGebruiker", "Sophiegebruiker", 2);
		pageTracker._trackPageview("Sophiestart:" + document.location.pathname);
	}
	
	
	var params = Form.serialize($(frmId));
	var responseDiv = document.getElementById('et_aiseResponseDiv');
	var structDiv = document.getElementById('et_home_bgmid');
	var containerDiv = document.getElementById('status2div');
	var closeDiv = document.getElementById('status1div');
	var askSophie = document.getElementById('askSophie');
	new Ajax.Request(webroot+'sophie/askQuestionSophie/', {
							parameters: params,
							method: 'post',
							asynchronous:true,
							evalScripts:true,
							onLoading :function(request){
									askSophie.style.display='none';
									containerDiv.style.display='block';
									closeDiv.style.display='block';
									responseDiv.innerHTML = '<img src="'+webroot+'/app/webroot/img/nshispeed/loaders/loading_autocomplete.gif" />';
							},
							onComplete :function(request){ 
								structDiv.innerHTML = request.responseText;
						 	}  
						 }
						); 
	return false;
}

/*
 * Close Sophie popup 
 */
function closeQuestion(){
	var containerDiv = document.getElementById('status2div');
	var closeDiv = document.getElementById('status1div');
	var askSophie = document.getElementById('askSophie');
	containerDiv.style.display='none';
	closeDiv.style.display='none';
	askSophie.style.display='block';
	
}
function jsBzdSelection(objectId)
{
	var bzdId = $(objectId).value; 
	
	new Ajax.Updater( 'tariffblock',
					  'bzdselect/' + bzdId, 
					  { asynchronous: true,
					    evalScripts: true,
					    onLoading: function (request) {
					    	if (jsGetCookie('COBS_LANG') == 'EN') {
					    		showbox('Your request is being processed.', 'progress');
					    	}else {
					    		showbox('De gegevens worden geladen.', 'progress')
					    	}
					    },
					    onComplete: function (request) {
					    	closebox();
					    }}
					 );	
}

function gaLinkPost(obj) {
	if (typeof pageTracker != "undefined") {
		pageTracker._linkByPost(obj);
	}
}

function gaLink(href) {
	if (typeof pageTracker != "undefined") {
		pageTracker._link(href);
	}
}
