// needed for resetting travelwith
var blnNoResult = false;


function resetTravelWith()
{
	objForm                   = document.getElementById( 'frmQuicksearch' );
	objForm.travelwith.value  = '';
	objForm.airportarea.value = '';
	//objForm.orderby.value     = '';
	return true;
}

function resetPage()
{
	objForm            = document.getElementById( 'frmQuicksearch' );
	objForm.page.value = '1';
	
	objForm.destination.value = strDestination;
	objForm.elements['duration'].options[objForm.elements['duration'].selectedIndex].value = strDuration;
	objForm.elements['price'].options[objForm.elements['price'].selectedIndex].value = strPrice;
	return true;
}


function resetFilters()
{
	resetPage();
	
	objForm                   = document.getElementById( 'frmQuicksearch' );
	objForm.orderby.value     = 'price ASC, travelduration ASC';
	objForm.travelwith.value  = '';
	objForm.airportarea.value = '';
	objForm.hotelcategory.value = '';
	objForm.traveltype.value = '';
	objForm.destinationID.value = '';
	objForm.catering.value = '';
	objForm.resetSearch.value = 'true';
	objForm.blnIgnoreAlternation.value = 'true';
	objForm.submit();
	
	return true;
}


function changeCriteria( strCrit, mixValue )
{
	objForm          = document.getElementById( 'frmQuicksearch' );
	objForm.elements[strCrit].value = mixValue;
	return true;
}

function searchWithDifferentCriteria( strCrit, mixValue )
{
	// reset page because of changing criterias
	resetPage();

	// change criteria
	changeCriteria( strCrit, mixValue );
	
	// submit form
	document.getElementById( 'frmQuicksearch' ).submit();

	return true;
}

function changeTravelWith( mixValue )
{
	changeCriteria( 'airportarea', "" );
	return searchWithDifferentCriteria( 'travelwith', mixValue );
}

function dateToString(objDate)
{
	if (typeof objDate != "object") return 'beliebig';

	var day 	= ""+objDate.getDate();
	var month 	= ""+(objDate.getMonth()+1);  // Javascript considers months in the range 0 - 11
	var year 	= ""+objDate.getFullYear();
	
	// set format to dd.mm.yyyy
	if (day.length == 1) day = "0"+day;
	if (month.length == 1) month = "0"+month;
	if (year.length == 2) year = "20"+year;
	
	return day + "." + month + "." + year;
}

/*
 checks format of given date (dd.mm.yyyy)
 returns Date object or false
*/
function checkDateFormat(strDate)
{
	// do not check empty value
	if ( (strDate == '') || (strDate == 'beliebig') ) return '';
	
	var pattern = new RegExp(/^[0-3]?[0-9]\.(0|1)?[0-9]\.(20)?[0-9]{2}$/);
	if(!strDate.match(pattern))
	{   
		return false;
	}
	
	var arrDate	= strDate.split(".");
	if (arrDate.length != 3) return false;
	
	var day 	= arrDate[0];
	var month 	= arrDate[1] - 1;  // Javascript considers months in the range 0 - 11
	var year 	= arrDate[2];
	
	if (day.length == 1) { day = "0"+day;	}
	if (month.length == 1) { month = "0"+month; }
	if (year.length == 2) { year = "20"+year;	}
	
	objDate = new Date(year,month,day);
	if ( (year != objDate.getFullYear()) 
	  || (month != objDate.getMonth())
  	  || (day != objDate.getDate()) )
	{
		return false;
	}
	
	return objDate;
}

/*
* shows error for startdate or enddate
*/
function errorOutput(strField, strMsg)
{
	if (strField == "startdate")
	{
		$('#error_startdate').text(strMsg);
		$('#error_startdate').fadeIn('fast');
		$('#error_duration').hide();
		$('#hotelcategory').hide();
		$('#qs_startdate').addClass('error');
	}
	else if (strField == "enddate")
	{
		$('#error_enddate').text(strMsg);
		$('#error_enddate').fadeIn('fast');
		$('#error_duration').hide();
		$('#catering').hide();
		$('#qs_enddate').addClass('error');
	}
	else if (strField == "destination")
	{
		$('#error_destination').text(strMsg);
		$('#error_destination').fadeIn('fast');
		$('#destinationInput').addClass('error');
	}
}

/*
* checks dates and duration input before submitting the ABE form
*/
function checkUserInput()
{
	var objForm      	= document.getElementById( 'frmQuicksearch' );
	var objDateStart 	= checkDateFormat(objForm.startdate.value);
	var objDateEnd 		= checkDateFormat(objForm.enddate.value);
	var now				= new Date();
	var blnStatus = true;
	var objDateStartMax	= checkDateFormat(strMaxStartdate);
	
	// if strMaxStartdate is not set, use today + 2 years as fallback
	if (objDateStartMax === false)
	{
		objDateStartMax = new Date(now.getFullYear()+2, now.getMonth(), now.getDate());
	}
	
	var objDateEndMax	= new Date(objDateStartMax.getFullYear(), objDateStartMax.getMonth(), objDateStartMax.getDate()+1);
	
	// unset error states
	$('#error_startdate').hide();
	$('#hotelcategory').show();
	$('#error_enddate').hide();
	$('#catering').show();
	$('#qs_startdate').removeClass('error');
	$('#qs_enddate').removeClass('error');
	$('#qs_duration').removeClass('error');
	$('#error_duration_select_wrap').removeClass('errorSelectWrap');
	
	
	// errors in startdate
	if (objDateStart === false)
	{
		errorOutput('startdate', 'Bitte geben Sie das Datum in diesem Format ein: tt.mm.jjjj');
		blnStatus = false;
	}
	else if ( (typeof(objDateStart) == 'object') && (objDateStart < now) )
	{
		errorOutput('startdate', 'Bitte geben Sie ein gültiges Datum ein.');
		blnStatus = false;
	}
	else if ( objDateStart > objDateStartMax )
	{
		errorOutput('startdate', 'Letztes mögliches Anreisedatum: '+dateToString(objDateStartMax));
		blnStatus = false;
	}
	else
	{
		objForm.startdate.value = dateToString(objDateStart);
	}
	
	// errors in enddate
	if (objDateEnd === false)
	{
		errorOutput('enddate', 'Bitte geben Sie das Datum in diesem Format ein: tt.mm.jjjj');
		blnStatus = false;
	}
	else if ( (typeof(objDateEnd) == 'object') && (objDateEnd < now) )
	{
		errorOutput('enddate', 'Bitte geben Sie ein gültiges Datum ein.');
		blnStatus = false;
	}
	else if ( objDateEnd > objDateEndMax )
	{
		errorOutput('enddate', 'Letztes mögliches Rückreisedatum: '+dateToString(objDateEndMax));
		blnStatus = false;
	}
	else
	{
		objForm.enddate.value = dateToString(objDateEnd);
	}
	
	// if we have an error now, at least one date is invalid => break here
	if (!blnStatus) return false;
	
	// create Date objects
	if (objDateStart == '')
	{	// no start day set => use today
		objDateStart = new Date();
	}
	if (objDateEnd == '')
	{	// no end day set => use start date plus 2 years
		objDateEnd = new Date(objDateStart.getFullYear()+2, objDateStart.getMonth(), objDateStart.getDate());
	}
	
	// check if startdate lies before enddate
	else if (objDateStart >= objDateEnd)
	{
		//$('#error_enddate').text('Bitte geben Sie ein gültiges Rückreisedatum ein.');
		//$('#error_enddate').fadeIn('fast');
		errorOutput('enddate', 'Bitte geben Sie ein gültiges Rückreisedatum ein.');
		return false;
	}
	
	// if destination has error, do not submit
	if ( ($('#checkDestination').val() == 'error') && ($('#destinationInput').val() != '') )
	{
		errorOutput('destination', 'Bitte geben Sie ein gültiges Reiseziel ein.');
		return false;
	}
	
	// get duration from user input (if set)
	// in case of interval, use shortest duration
	var duration = objForm.duration.value;
	if (duration.indexOf("-") != -1)
	{
		duration = duration.substring(0, duration.indexOf("-"));
	}
	if (duration == 'overmax') duration = 22;
	
	if (duration == '') return true;
	
	// check if duration is not too long for date range
	objDateStart.setDate( objDateStart.getDate() + Math.abs(duration) );
	if (objDateStart > objDateEnd)
	{
		$('#error_duration').text('Die Reisedauer passt nicht zu Ihren Reisedaten. Bitte ändern Sie Ihre Eingaben.');
		$('#error_duration').fadeIn('fast');
		$('#qs_duration').addClass('error');
		$('#error_duration_select_wrap').addClass('errorSelectWrap');
		return false;
	}
	
	$('#blnIgnoreAlternation').val('false');
	return blnStatus;
}



function goBack()
{
	// in error case remove subselect airportarea
	changeCriteria( 'airportarea', '' );
	changeCriteria( 'travelwith', '' );
	changeCriteria( 'traveltype', '' );
	changeCriteria( 'destinationID', '' );
	changeCriteria( 'hotelcategory', '' );
	changeCriteria( 'catering', '' );
	
	// submit form
	document.getElementById( 'frmQuicksearch' ).submit();
}

function handleOnClick(sInitValue){
	if( document.getElementById('destinationInput').value == sInitValue ){
		document.getElementById('destinationInput').value = '';
	}
}

function normString(str){
	// replace special chars
	str = str.replace(/[áàâã]/g, 'a');
	str = str.replace(/[ÀÁÃÂ]/g, 'A');
	str = str.replace(/[éèê]/g, 'e');
	str = str.replace(/[ÉÈÊ]/g, 'E');
	str = str.replace(/[íìî]/g, 'i');
	str = str.replace(/[ÍÌÎ]/g, 'I');
	str = str.replace(/[óòô]/g, 'o');
	str = str.replace(/[ÒÓÔ]/g, 'O');
	str = str.replace(/[úùû]/g, 'u');
	str = str.replace(/[ÚÙÛ]/g, 'U');
	str = str.replace(/[ñ]/g, 'n');
	
	return str.toLowerCase();
}

YAHOO.namespace('Travel'); 
YAHOO.Travel.QuickSearchFunction = function(){
	var oACDS;
	var oAutoComp;
	var aResults;
	var sInitValue;
	
	return {
		init: function( sInitValue ) {
			
			// Instantiate JS Function DataSource
			oACDS = new YAHOO.widget.DS_JSFunction(searchDestination);
			oACDS.maxCacheEntries = 0;

			// Instantiate AutoComplete
			oAutoComp = new YAHOO.widget.AutoComplete("destinationInput","destinationContainer", oACDS);
			oAutoComp.queryDelay = 0.5;
			oAutoComp.minQueryLength = 2;
			oAutoComp.maxResultsDisplayed = 100;
			//oAutoComp.forceSelection = true; 
			oAutoComp.animVert = false;
			oAutoComp.animHoriz = false;
			//oAutoComp.alwaysShowContainer = true;
			 
			// format options: make search string bold, indent locations
			oAutoComp.resultTypeList = false; 
			oAutoComp.formatResult = function(oResultData, sQuery, sResultMatch)
			{
				sResult = oResultData[0];
				sNormed = normString(sResult);
				
				// set <b> around serach string
				regexp = new RegExp("^"+sQuery, "i");
				res = sNormed.match(regexp);
				if (res)
				{
					resBold = sResult.substring(0, sQuery.length);
					resNormal = sResult.substring(sQuery.length, sResult.length);
					sResult = "<b>"+resBold+"</b>"+resNormal;
				}
				
				// indent, if entry is a location
				if (oResultData.type == 'location')
				{
					sResult = '<div style="padding-left: 8px; width:100px; line-height: 11px;">-&nbsp;'+sResult+'</div>';
				}
				
				return sResult;
			};
			
			// Subscribe to Custom Events
			oAutoComp.textboxKeyEvent.subscribe(this.myOnKeyEvent);
			oAutoComp.dataReturnEvent.subscribe(this.myOnDataReturn);
			oAutoComp.containerExpandEvent.subscribe(this.myOnContainerExpand);
			oAutoComp.containerCollapseEvent.subscribe(this.myOnContainerCollapse);
			
			document.getElementById('destinationInput').value = sInitValue;
		},
		
		// Define function to hide/show input fileds under elContainer
		changeSelectBox: function (status) {
			document.getElementById('qs_startdate').style.visibility=status;
			document.getElementById('qs_enddate').style.visibility=status;
			document.getElementById('qs_duration').style.visibility=status;
			//document.getElementById('qs_price').style.visibility=status;
			document.getElementById('error_duration_select_wrap').style.visibility=status;
		},
		
		// Define Custom Event handlers
		myOnKeyEvent: function( oSelf , nKeycode ) {
			if(document.getElementById('destinationInput').value.length >= oAutoComp.minQueryLength){
				// show the animation
				document.getElementById('qs_destinationlistIcon').style.display='none';
				document.getElementById('advice_city_ani').style.display='block';
			} else {
				document.getElementById('advice_city_ani').style.display='none';
				document.getElementById('qs_destinationlistIcon').style.display='block';
			}
		},
		
		myOnDataReturn: function(sType, aArgs) {
			var oAutoComp = aArgs[0];
			var sQuery = aArgs[1];
			aResults = aArgs[2];
			
			$('#error_destination').hide();
			$('#hotelcategory').show();
			$('#destinationInput').removeClass('error');
			$('#checkDestination').val('ok');
			
			if(aResults.length == 0) {
				/* Layer on left
				$('#error_destination').fadeIn('fast');
				$('#hotelcategory').hide();
				$('#destinationInput').addClass('error');
				*/
				$('#checkDestination').val('error');
				oAutoComp._toggleContainer(true);
				oAutoComp.setBody("<div id=\"destinationContainerError\">Leider kein Ergebnis. Bitte &auml;ndern Sie Ihre Eingabe.</div>");
			}
			// hide the animation
			document.getElementById('advice_city_ani').style.display='none';
			document.getElementById('qs_destinationlistIcon').style.display='block';
		},
		
		myOnContainerCollapse: function(sType, aArgs) {
			YAHOO.Travel.QuickSearchFunction.changeSelectBox('visible');
		},
		
		myOnContainerExpand: function(sType, aArgs) {
			YAHOO.Travel.QuickSearchFunction.changeSelectBox('hidden');
		}

	}
}();

