var disableOnEnter = false
var sSpecialType
var sCurForm
var sCurSearchType
var sFlasher
var bFirstTimer = false;
var intervalAutoComplete;

function submitSearchForm(sFrm) {
	var m = '';
	if(document.getElementById('idDepartureAirport'+sFrm)) {
		if(!document.getElementById('idDepartureAirport'+sFrm).value || document.getElementById('idDepartureAirport'+sFrm).value=='-') {
			m+='Please confirm your departure airport\n';
		}
	}
	if(document.getElementById('idLocationto'+sFrm)) {
		if(!document.getElementById('idLocationto'+sFrm).value || document.getElementById('idLocationto'+sFrm).value=='-') {
			m+='Please confirm your destination\n';
		}
	}
	if(document.getElementById('idAirportto'+sFrm)) {
		if(!document.getElementById('idAirportto'+sFrm).value || document.getElementById('idAirportto'+sFrm).value=='-') {
			m+='Please select your destination airport\n';
		}
	}
	
	
	if(m) {
		alert(m);
		return false;
	}else{
		document.forms['frm'+sFrm].submit();
	}
}

function submitSearchFormAuto(sFrm) {
    var m = '';
    if (document.getElementById('idDepartureAirport' + sFrm)) {
        if (!document.getElementById('idDepartureAirport' + sFrm).value || document.getElementById('idDepartureAirport' + sFrm).value == '-') {
            m += 'Please confirm your departure airport\n';
        }
    }
    if (document.getElementById('idLocationto' + sFrm)) {
        if (!document.getElementById('idLocationto' + sFrm).value || document.getElementById('idLocationto' + sFrm).value == '-') {
            m += 'Please confirm your destination\n';
        }
    }
    if (document.getElementById('idAirportto' + sFrm)) {
        if (!document.getElementById('idAirportto' + sFrm).value || document.getElementById('idAirportto' + sFrm).value == '-') {
            m += 'Please select your destination airport\n';
        }
    }
    if (!m) {
        document.forms['frm' + sFrm].submit();
    }
}


function switchCarhireCoupon() {
    bShowCoupon = ((document.getElementById("btnSearchCar").style.display == 'none') ? false : true);
    document.getElementById("btnSearchCar").style.display = ((bShowCoupon) ? 'none' : 'block');
    document.getElementById("sectionCoupon").style.display = ((bShowCoupon) ? '' : 'none');
    
    if (!bShowCoupon)
    {
    
        document.getElementById('idCarCouponCompany').selectedIndex = 0;
        document.getElementById('idCarCouponCode').value = '- Coupon code -';
        
    }
    
}

function DisableOnEnter(bValue) {
	disableOnEnter = bValue;
}

function OpenSearch() {
	if(document.getElementById('DivLocations')) {
		showhidechangeoptions('show');
	}
}

function checkAndRemoveReturnDate(sFrm) {
    if (document.getElementById('oneway' + sFrm)) {
		var sShow = '';
		if (document.getElementById('oneway' + sFrm).checked != true) {
			sShow = 'none';
		}
		if(document.getElementById('idReturnDateText'+sFrm)) {
			document.getElementById('idReturnDateText'+sFrm).style.display = sShow;
		}
		if(document.getElementById('idReturnDateField'+sFrm)) {
			document.getElementById('idReturnDateField'+sFrm).style.display = sShow;
		}
	}
}

function changeCarInclude(sFrm, iType) {
	var iFound = 0;
	sList = sFrm.includecar;
	for(x=0;x<sList.length;x++) {
		if(sList(x).checked == true && sList(x).value == 'yes') {
			iFound = 1
			sFrm.flexibility.disabled = true;
			if(sFrm.flexibility.value != '0' && sFrm.flexibility.value != '') {
				alert('By including car hire, date flexibility has been disabled.');
			}
			if(iType==1){
				sFrm.flexibility.selectedIndex = 0;
			}else{
				sFrm.flexibility.selectedIndex = 1;
			}
		}else{
			if(iFound == 0) {
				sFrm.flexibility.disabled = '';
				if(iType==1){
					sFrm.flexibility.selectedIndex = 3;
				}else{
					sFrm.flexibility.selectedIndex = 4;
				}
			}
		}
	}
}

function onEnterSearch(sFrmName,sSearchType){
	//if(event.keyCode==13&&document.getElementById('doWhat'+sFrmName).value==1){
	//	getLocations(document.getElementById('idFreetext'+sFrmName).value,sFrmName,sSearchType,'contact');
	//}
}

function showFullSearch() {
	if(document.getElementById('DivShow')) {
		showhidechangeoptions('show');	
	}
}

function validateLocationForm(sDatePattern) {
	var startdate_d = '';
	var startdate_m = '';
	var startdate_y = '';
    sSubmitForm = document.getElementsByName('frm' + sCurForm);
    sLocationID = document.getElementById('idLocationto' + sCurForm);
    var e = sSubmitForm.elements, m = '';
    if (sLocationID && sLocationID.value == '-') { m += '- Please select a destination.\n'; }

    if (document.getElementById('startdate' + sCurForm)) {
        if (!DateValidator(document.getElementById('startdate' + sCurForm).value, sDatePattern)) {
            m += '- Departure date is not valid. Please enter a date in the ' + sDatePattern + ' format.\n';
        }
    }

    if (document.getElementById('enddate' + sCurForm)) {
        if (!DateValidator(document.getElementById('enddate' + sCurForm).value, sDatePattern) && IsReturnTrip(sCurForm)) {
            m += '- Return date is not valid. Please enter a date in the ' + sDatePattern + ' format.\n';
        }
    }

    //Only run this check if the dates have already been marked as valid
    if (!m && document.getElementById('enddate' + sCurForm)) {
        var oDate1 = DateSplitter(document.getElementById('startdate' + sCurForm).value, sDatePattern);
        var oDate2 = DateSplitter(document.getElementById('enddate' + sCurForm).value, sDatePattern);

        if (oDate1.bDateSplitted && oDate1.bDateSplitted) {
            var dDate1 = CreateDate(oDate1.sDay, oDate1.sMonth, oDate1.sYear);
            var dDate2 = CreateDate(oDate2.sDay, oDate2.sMonth, oDate2.sYear);

            if (DateCompare(dDate1, dDate2, sDatePattern) > 0)
                m += "- Departure date is after the return date. Please enter a valid date range.";
        }
    }

    if (document.getElementById('rooms' + sCurForm)) {
        if (document.getElementById('rooms' + sCurForm).value == '0') {
            m += '- Please select no. of rooms\n';
        }
    }

    if (m) {
        showFullSearch();
        switchLocationDivs('divLocation' + sCurForm);
        alert('The following errors occurred:\n\n' + m);
        return false;
    } else {
    var sCurFormLc = sCurForm.toLowerCase();
        if (sCurFormLc == "car" || sCurFormLc == "hotel" || sCurFormLc == "resort")
            sSubmitForm[0].submit();
    }

	return true;
}

function IsReturnTrip(sFrm)
{
    var bCheckReturnDate = true;
    if (document.forms['frm'+sFrm].oneway)
        bCheckReturnDate = document.forms['frm'+sFrm].oneway.checked;
        
    return bCheckReturnDate;
}

function locationGoBack(sForm) {
	var sLocationID = document.getElementById('idLocationto'+sForm);
	var sFreetext = document.getElementById('idFreetext'+sForm);
	clearLocationList(sLocationID);
	div_switch('divLocationLoad'+sForm, false, true);
	div_switch('divLocation'+sForm, false, true);
	div_switch('divFreetext'+sForm, true, true);
	//sFreetext.focus(); sFreetext.select();
	
	if(document.getElementById('idConfirmedDestination'+sForm)) {
		document.getElementById('idConfirmedDestination'+sForm).style.display = 'none';
	}
	if(document.getElementById('idConfirmDestinationDDL'+sForm)) {
		document.getElementById('idConfirmDestinationDDL'+sForm).style.display = '';
	}
	if(document.getElementById('idConfirmDepartureAirport'+sForm)) {
		document.getElementById('idConfirmDepartureAirport'+sForm).style.display = 'none';
	}
	if(document.getElementById('idConfirmDepartureAirportDDL'+sForm)) {
		document.getElementById('idConfirmDepartureAirportDDL'+sForm).style.display = '';
	}
	clearInterval(intervalAutoComplete);
}

function switchLocationDivs(sDiv) {
	div_switch('divFreetext'+sCurForm, false, true);
	div_switch('divLocationLoad'+sCurForm, false, true);
	div_switch('divLocation'+sCurForm, false, true);
	div_switch(sDiv, true, true);
}

//Clear List
function clearLocationList(listElem) {
	if(listElem!=0){
	    if(listElem && listElem.options){
		    while(listElem.options.length > 0) {
			    listElem.options[0] = null;
		    }
		    while(listElem.hasChildNodes()) {
			    listElem.removeChild(listElem.firstChild);
		    }
		}
	}
}

//On Change Event

function HideAutoCompleteDiv(id) {
	if(document.getElementById(id)) {
		document.getElementById(id).style.display = 'none';
		// gets rid of iframe in ie6
		if(document.getElementById('DivShim')) {
			document.getElementById('DivShim').style.display = 'none';
			document.getElementById("DivShim").parentNode.removeChild(document.getElementById("DivShim"));
		}
		clearInterval(intervalAutoComplete);
	}	
}

function countPassengers() {
	var iNumPas = 0
	sSubmitForm = document.forms['frm'+sCurForm];
	if(sCurForm.indexOf('Flight')>-1 || sCurForm.indexOf('Package')>-1) {
		if(sCurSearchType=='Hotel') {
			for(x=1;x<parseFloat(sSubmitForm.rooms.value)+1;x++) {
				if(sSubmitForm.elements['r'+x+'a']) {
					iNumPas += parseFloat(sSubmitForm.elements['r'+x+'a'].value);
					iNumPas += parseFloat(sSubmitForm.elements['r'+x+'c'].value);
					iNumPas += parseFloat(sSubmitForm.elements['r'+x+'i'].value);
				}
			}
		}else{
			if(sSubmitForm.elements['seats_adult']) {
				iNumPas += parseFloat(sSubmitForm.elements['seats_adult'].value);
				iNumPas += parseFloat(sSubmitForm.elements['seats_child'].value);
				iNumPas += parseFloat(sSubmitForm.elements['seats_infant'].value);
			}
		}
	}
	return iNumPas;
}

function countInfants() {
	var iNumPas = 0
	sSubmitForm = document.forms['frm'+sCurForm];
	if(sCurForm.indexOf('Flight')>-1 || sCurForm.indexOf('Package')>-1) {
		if(sCurSearchType=='Hotel') {
			for(x=1;x<parseFloat(sSubmitForm.rooms.value)+1;x++) {
				if(sSubmitForm.elements['r'+x+'c']) {
					if(sSubmitForm.elements['r'+x+'i']) {iNumPas += parseFloat(sSubmitForm.elements['r'+x+'i'].value);}
					var intChildren = parseFloat(sSubmitForm.elements['r'+x+'c'].value);
					if(intChildren > 0){
					    for(iC = 1;iC<=intChildren;iC++){
					        if(parseFloat(document.getElementById('r' + x + 'c_ages' + iC + sCurForm).options[document.getElementById('r' + x + 'c_ages' + iC + sCurForm).selectedIndex].value) < 2){
					            iNumPas++;
					        }
					    }
					}
				}
				
			}
		}else{
			if(sSubmitForm.elements['seats_infant']) {
				iNumPas += parseFloat(sSubmitForm.elements['seats_infant'].value);
			}
		}
	}
	return iNumPas;
}


function getLocations(sLocation,sForm,sSearchType,sType, sDatePattern) {
	if(!disableOnEnter) {
		sSpecialType = sType;
		sCurForm = sForm;
		sCurSearchType = sSearchType;
		var sFreetextID = document.getElementById('idFreetext'+sCurForm);
		var bPopularDestinationSelected = false;
		var bFreetextDeparturePoint = false;
		var bAutoSuggestSelection = false;
		//var sLocation = '';

		if (document.getElementById(popularDestination(sCurForm))) {
		    if(document.getElementById(popularDestination(sCurForm)).value != ''){
				var sLocationID = document.getElementById(popularDestination(sCurForm));
				sLocation = (sForm == 'Resort') ? document.getElementById(popularDestination(sCurForm)).options[document.getElementById(popularDestination(sCurForm)).selectedIndex].value : document.getElementById(popularDestination(sCurForm)).options[document.getElementById(popularDestination(sCurForm)).selectedIndex].text
				sLocation = sLocation.replace("-", "");
				sLocation = LTrim(sLocation);
				bPopularDestinationSelected=true;
			}else{
				var sLocationID = document.getElementById('idLocationto'+sCurForm);
			}
		}else{
			var sLocationID = document.getElementById('idLocationto'+sCurForm);
		}
		
		if(document.getElementById('idHdnLocationTo'+sCurForm)) {
			if(document.getElementById('idHdnLocationTo'+sCurForm).value != ''){
			    var sLocationID = document.getElementById('idHdnLocationTo'+sCurForm);
			    sLocation = document.getElementById('idFreetext'+sCurForm).value;
			    bAutoSuggestSelection=true;
			}
		}
		if (sCurSearchType == 'Airport' && document.getElementById('idFreetextDep' + sCurForm)) { //checks whether site has freetext departure point searching fields present
		    var sFreetextDepID = document.getElementById('idFreetextDep'+sCurForm);
		    var sDeparture = (document.getElementById('idHdnAirportFrom'+sCurForm).value != '') ? document.getElementById('idHdnAirportFrom'+sCurForm).value : document.getElementById('idFreetextDep'+sCurForm).value;
		    var sLocation = (document.getElementById('idHdnAirportTo'+sCurForm).value != '') ? document.getElementById('idHdnAirportTo'+sCurForm).value : document.getElementById('idFreetext'+sCurForm).value;
		    bFreetextDeparturePoint = true;
		} else if ((sForm == 'FlightHotel' || sForm == 'Resort') && document.getElementById('idFreetextDep' + sCurForm)) { //checks whether site has freetext departure point searching fields present
		    var sFreetextDepID = document.getElementById('idFreetextDep'+sCurForm);
		    var sDeparture = (document.getElementById('idHdnAirportFrom'+sCurForm).value != '') ? document.getElementById('idHdnAirportFrom'+sCurForm).value : document.getElementById('idFreetextDep'+sCurForm).value;
		    if (sLocation == '') { sLocation = (document.getElementById('idHdnLocationTo' + sCurForm).value != '') ? document.getElementById('idHdnLocationTo' + sCurForm).value : ((document.getElementById('idFreetext' + sCurForm)) ? document.getElementById('idFreetext' + sCurForm).value : ''); }
		    bFreetextDeparturePoint = true;
		    //if (sForm == 'Resort' && document.getElementById('includeflight' + sCurForm).checked == false) { bFreetextDeparturePoint = false; sDeparture = '';sFreetextDepID = ''; };
		    var sDepartureID = '';
		} else {
		    var sFreetextDepID = '';
		    var sDepartureID = '';
		    var sDeparture = '';
		}

		sLocation = sLocation.replace("'","");
		if(sCurForm.toLowerCase() == 'flight' && document.getElementById('deptime_'+sCurForm) && document.getElementById('rettime_'+sCurForm)) {
	        if(Date.parse(document.getElementById('startdate'+sCurForm).value) == Date.parse(document.getElementById('enddate'+sCurForm).value)) {
	            var oDepTime = document.getElementById('deptime_'+sCurForm);
	            var oRetTime = document.getElementById('rettime_'+sCurForm);
	            var sDepTime = oDepTime.options[oDepTime.selectedIndex].value;
	            var sRetTime = oRetTime.options[oRetTime.selectedIndex].value;
    	        
	            if(sDepTime == "" || sRetTime == "") {
	                alert('As you wish to depart and return on the same day, please choose both an arrival and a departure time e.g. Morning -> Afternoon, Afternoon -> Evening\n');
	                return false;
	            } else if(parseInt(sDepTime.split(':')[0]) >= parseInt(sRetTime.split(':')[0])) {
	                alert('Please ensure your return time is after your departure time. e.g. Morning -> Afternoon\n');
	                return false;
	            }
	        }
	    }
	     if (sCurForm.toLowerCase() == 'car')
	    {
	    
	        if (document.getElementById('idCarCouponCode'))
	        {
	            bCouponCodeEmpty = (document.getElementById('idCarCouponCode').value.length == 0 || document.getElementById('idCarCouponCode').value == '- Coupon code -');
    	    
                if(!bCouponCodeEmpty && document.getElementById('idCarCouponCompany').selectedIndex==0){
		                alert('Please select a company'); 
		                document.getElementById('idCarCouponCompany').focus();
		                return false; 
		            }
                if(bCouponCodeEmpty && document.getElementById('idCarCouponCompany').selectedIndex > 0){
		                alert('Please enter your coupon code!');
		                document.getElementById('idCarCouponCode').focus();
		                return false;
		            }
			 }   
		}
		
		 if (countInfants() > 0 && sCurForm.toLowerCase().indexOf('flight') > -1) {
            alert('Please note, all infant passengers will be seated upon an adult\'s lap as flight seats aren\'t allocated for infants');//this is a notice, not failure
        }
		
		if (countPassengers() > 9) {
			alert('You can only search for a maximum of 9 passengers when your search includes a flight');
			return false;
        } else if (bFreetextDeparturePoint && (sDeparture.length < 1 || sDeparture.toLowerCase() == "- type in your departure airport -")) {
            showFullSearch()
		    alert('Please enter your departure airport');
		    sFreetextDepID.focus(); //Without this check this code will break in IE7
		    return false;
		} else if (sFreetextID && (sFreetextID.value.length < 1 || sFreetextID.value == "- type in destination -") && !bPopularDestinationSelected) {
            showFullSearch()
			alert('Please enter your destination');
			if(sFreetextID.style.display != 'none'){sFreetextID.focus();} //Without this check this code will break in IE7
			return false;
        } else if (sLocationID.value == '' || (bFreetextDeparturePoint && sDepartureID.value == '') || (bPopularDestinationSelected && sCurForm != 'Hotel' && sCurForm != 'Resort') || (sCurForm == 'FlightHotel' || (sCurForm == 'Resort' && document.getElementById("includeflight" + sCurForm) && document.getElementById("includeflight" + sCurForm).checked == true))) {
			intervalAutoComplete = setInterval("HideAutoCompleteDiv('as_idFreetext"+sForm+"')", 500);
			sSpecialSearchType = '';
            var sIncludeCar = "";
			if(document.getElementById("includecar" + sCurForm) && document.getElementById("includecar" + sCurForm).checked == true){
			    sIncludeCar = "&includecar=true";
			}
    		// NE 28/05/2010 Add a car context to the locations search
			sCarContext = ''
			if (sCurForm.toLowerCase() == 'car' && document.getElementById("Car_SearchMethod")) sCarContext = "&carcontext=" + document.getElementById("Car_SearchMethod").options[document.getElementById("Car_SearchMethod").selectedIndex].value;
			sURL = "/includes/search/LookupXML.asp?searchtype="+sCurSearchType+"&location=" + sLocation + "&departure=" + sDeparture + "&hund=true" + sIncludeCar + sCarContext;
			if(sURL!='') {
				if(bDebug){
					if(confirm('Open '+ sURL)) {
						window.open(sURL);
					}
				}
				if (!bPopularDestinationSelected && !bAutoSuggestSelection) {clearLocationList(sLocationID);}
				setTimeout("loadLocationXMLDoc('"+sURL+"', '" + sDatePattern + "')", 100);
			}else{
				alert('No url defined');
            }
        } else {
            if (!validateLocationForm(sDatePattern)) {
                locationGoBack(sCurForm);
                return false;
            }
		}
	}
}

function LTrim(value) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

//XML Loader
function loadLocationXMLDoc(url, sDatePattern)
{
	// If global domain set and the URL doesn't contain the domain then append global domain to it
	url = (url.substring(0, 3).toLowerCase() != "http" && typeof(sProxyLocation) != "undefined") ? sProxyLocation + '?url=' + encodeURIComponent(url) : url;
	
	if (window.XMLHttpRequest)
        req = new XMLHttpRequest();
    else if (window.ActiveXObject)
        req = new ActiveXObject("Microsoft.XMLHTTP");
        
    if (req)
    {
        switchLocationDivs('divLocationLoad'+sCurForm);

        req.onreadystatechange = function() {
            if (req.readyState == 4)
            {
	            if (req.status == 200)
	                processLocationChange(sDatePattern, req.responseXML.documentElement);
	            else
	                alert("There was a problem retrieving the XML data:\n" + req.statusText);
	        }
        };
        
        req.open("GET", url, true);
        req.send(null);
    }
}

function processLocationChange(sDatePattern, xmldoc)
{
	var sFreetext = document.getElementById('idFreetext'+sCurForm);
	if(document.getElementById('idAirportto'+sCurForm)) {
		sLocationList = document.getElementById('idAirportto'+sCurForm);
		sLocationList.disabled='true';	
	}
	var sLocationID = document.getElementById('idLocationto'+sCurForm);
	
	if(document.getElementById('idDepartureAirport'+sCurForm)){
	    var bFreetextDeparturePoint = true
	    var sDepartureID = document.getElementById('idDepartureAirport'+sCurForm);
	}else{
	    var sDepartureID = ""
	}

	//section which populates the locations
	nodes = xmldoc.getElementsByTagName('Location');
	nodesDeparturePoints = xmldoc.getElementsByTagName('DepartureAirport');
	nodesArrivalPoints = xmldoc.getElementsByTagName('ArrivalAirport');

	sLocationID.options[0] = new Option('- Select a destination -','-');
	for(var i = 0; i < nodes.length; i++) {
		if (nodes.length != 0) {
			var GroupName = nodes.item(i).attributes.getNamedItem("title").nodeValue
			if(PreGroupName!=GroupName){
				var RegionName = document.createElement('optgroup');
				RegionName.label = GroupName;
				if(GroupName!='zzz') {
					sLocationID.appendChild(RegionName);
				}else if(i>0) {
					RegionName.label = 'Others';
					sLocationID.appendChild(RegionName);
				}
			}
			var PreGroupName = GroupName
			sCode = nodes.item(i).attributes.getNamedItem("code").nodeValue;
			sName = nodes.item(i).childNodes.item(0).nodeValue;
			sLocationID.options[sLocationID.options.length] = new Option(sName, sCode);
			
		}
    }

    if (nodes.length == 1 && sSpecialType != 'contact') {

		if(document.getElementById('idConfirmDestinationDDL'+sCurForm)) {
			document.getElementById('idConfirmDestinationDDL'+sCurForm).style.display = 'none';
		}
		if(document.getElementById('idConfirmedDestination'+sCurForm)) {
			document.getElementById('idConfirmedDestination'+sCurForm).style.display = '';
			document.getElementById('idConfirmedDestinationText'+sCurForm).innerHTML = sLocationID.options[1].innerHTML
		}
		sLocationID.options[1].selected = true;

		findDestAirport(sCurForm, sLocationID.options[1].value, nodesArrivalPoints);

		bFirstTimer = true

		if ((sCurForm != 'Resort' || (sCurForm == 'Resort' && nodesArrivalPoints.length == 1)) && !validateLocationForm(sDatePattern)) {
		        locationGoBack(sCurForm);
	        return false;
	    }
	} else if (nodes.length < 1) {
		showFullSearch();
		var bOkCancel = true;
		var sConfirmText = 'No destinations found.\n\nClick OK to open the destination guide or cancel to go back and refine your search!';
		switch(sCurForm){
			case 'FlightHotel':
			    sConfirmText = 'No destinations found for your flight and hotel search.\nWe may only be able to provide you with a flight to this destination.\nPlease try and refine your search.';
			    bOkCancel = false;
			    break;
			case 'Hotel':
			    sConfirmText = 'No destinations found for your hotel search.\n\nClick OK to open the destination guide or cancel to go back and refine your search!';
			    //bOkCancel = false;
			    break;
			case 'Flight':
			    sConfirmText = 'No destinations found for your flight search.\n\nClick OK to open the destination guide or cancel to go back and refine your search!';
			    break;
		}
		if(bOkCancel && confirm(sConfirmText)) {
			locationGoBack(sCurForm);
			openDestinationHelp(sCurSearchType.toLowerCase(), 'frm'+sCurForm);
		}else{
		    if(!bOkCancel) alert(sConfirmText);
			locationGoBack(sCurForm);
			sFreetext.focus();
			sFreetext.select();
			return false;
		}							
		//alert('No destinations found.\n\nPlease refine your search.');
	}else{
		showFullSearch();
		switchLocationDivs('divLocation'+sCurForm);
		sFlasher = setInterval('selectFlash();',600);
	}

	//Section to display list of possible departure airports
	if (bFreetextDeparturePoint && (sCurForm.toLowerCase().indexOf('flight') != -1 || sCurForm.toLowerCase().indexOf('resort') != -1)) {
	    clearLocationList(sDepartureID);
	    sDepartureID.options[0] = new Option('- Select a departure airport -','-');
	    for(var i = 0; i < nodesDeparturePoints.length; i++) {
		    if (nodesDeparturePoints.length != 0) {
			    var GroupName = nodesDeparturePoints.item(i).attributes.getNamedItem("title").nodeValue
			    if(PreGroupName!=GroupName){
				    var RegionName = document.createElement('optgroup');
				    RegionName.label = GroupName;
				    if(GroupName!='zzz') {
					    sDepartureID.appendChild(RegionName);
				    }else if(i>0) {
					    RegionName.label = 'Others';
					    sDepartureID.appendChild(RegionName);
				    }
			    }
			    var PreGroupName = GroupName
			    sCode = nodesDeparturePoints.item(i).attributes.getNamedItem("code").nodeValue;
			    sName = nodesDeparturePoints.item(i).childNodes.item(0).nodeValue;
			    sDepartureID.options[sDepartureID.options.length] = new Option(sName, sCode);
				
		    }
		}
	    if(nodesDeparturePoints.length==1&&sSpecialType!='contact') {
		    if(document.getElementById('idConfirmDepartureAirportDDL'+sCurForm)) {
		    	document.getElementById('idConfirmDepartureAirportDDL'+sCurForm).style.display = 'none';
		    }
		    if(document.getElementById('idConfirmDepartureAirport'+sCurForm)) {
		    	document.getElementById('idConfirmDepartureAirport'+sCurForm).style.display = '';
		    	document.getElementById('idConfirmedDepartureAirportText'+sCurForm).innerHTML = sDepartureID.options[1].innerHTML
		    }
		    sDepartureID.options[1].selected = true;
		    // If destination airport node length is also 1 then post off automatically
		   
		    if(nodes.length == 1 && nodesArrivalPoints.length <= 1)
		        document.getElementsByName('frm'+sCurForm)[0].submit();
		    
	    }else if(nodesDeparturePoints.length<1){
		    showFullSearch();
		    var sConfirmText = 'No departure airports found.';
		    switch(sCurForm){
			    case 'FlightHotel':
			    sConfirmText = 'No departure airports found for your flight and hotel search.';
			    break;
			    case 'Flight':
			    sConfirmText = 'No departure airports found for your flight search.';
			    break;
		    }
		    if(confirm(sConfirmText)) {
			    locationGoBack(sCurForm);
			    openDestinationHelp('departureairport', 'frm'+sCurForm);
		    }else{
		        var sDepartureFreetext = document.getElementById('idFreetextDep'+sCurForm);
			    locationGoBack(sCurForm);
			    //switchLocationDivs('divFreetext'+sCurrentFormID);
			    sDepartureFreetext.focus();sDepartureFreetext.select();
		    }				
		    //alert('No destinations found.\n\nPlease refine your search.');
	    }else{
		    showFullSearch();
		    switchLocationDivs('divLocation'+sCurForm);
		    sFlasher = setInterval('selectFlash();',600);
	    }
	}
}

function querySt(ji) {
    var q = window.location.search.substring(1).split("&");
    for (i=0;i<q.length;i++){
        ft = q[i].split("=");
        if (ft[0] == ji){return ft[1];}
    }
    return "";
}

/* START GET SERVED AIRPORT SCRIPT BY Casper Thun August 2007 */
	var sCurrentFormID = '';
	var sCurrentForm = '';
	function findDestAirport(sFormID, sLocation, arrivals) {
	    sCurrentForm = document.getElementsByName('frm'+sFormID);
		sCurrentFormID = sFormID;
		if (arrivals && arrivals.length != 0) {

		    sLocationList = document.getElementById('idAirportto'+sFormID);
		    clearLocationList(sLocationList);
			sLocationList.disabled='true';
			sLocationList.options[0] = new Option('- Select destination airport -','');
			

			for(var i = 0; i < arrivals.length; i++) {
		        if (arrivals.length != 0) {
			        sCode = arrivals.item(i).attributes.getNamedItem("code").nodeValue;
			        sName = arrivals.item(i).childNodes.item(0).nodeValue;
			        sLocationList.options[sLocationList.options.length] = new Option(sName, sCode);
			    }
            }
            sLocationList.disabled='';
            if(arrivals.length == 1){
                sLocationList.selectedIndex = 1;
                sCurrentForm[0].submit();
            }else{
				switchLocationDivs('divLocation'+sFormID);
            }

        } else if (document.getElementById('idAirportto' + sFormID)) {
			sLocationList = document.getElementById('idAirportto'+sFormID);
			sLocationList.disabled='true';
			if(sLocation.length>0 && sLocation!='-') {
			    sType = "";
			    if(document.getElementById("includecar" + sFormID) && document.getElementById("includecar" + sFormID).value == "yes"){
			        sType = "&includecar=true";
			    }
				sURL = "/includes/search/LookupXML.asp?searchtype=findairports&location=" + sLocation + "&c=t" + sType;
				if(sURL!='') {
					if(bDebug){
						if(confirm('Open '+ sURL)) {
							window.open(sURL);
						}
					}
					clearLocationList(sLocationList);
					sLocationList.options[0] = new Option('Loading... Please wait','');
					setTimeout("loadServedAirportXMLDoc('" + sURL + "')",100);
				}else{
					alert('No url defined');	
				}
			}else{
				sLocationList.options[0] = new Option('- Select destination airport -','');
				sLocationList.selectedIndex = 0;
				sLocationList.disabled='true';
			}
        } else {
            if(!document.getElementById('idDepartureAirport'+sFormID)){
			    sCurrentForm[0].submit();	
			}else{switchLocationDivs('divLocation'+sFormID);}
		}
	}
	
	//XML Loader
	function loadServedAirportXMLDoc(url) {
		// branch for native XMLHttpRequest object
		if (window.XMLHttpRequest) {
			req = new XMLHttpRequest();
			req.onreadystatechange = processServedAirportChange;
			req.open("GET", url, true);
			req.send(null);
		// branch for IE/Windows ActiveX version
		} else if (window.ActiveXObject) {
			req = new ActiveXObject("Microsoft.XMLHTTP");
			if (req) {
				req.onreadystatechange = processServedAirportChange;
				req.open("GET", url, true);
				req.send();
			}
		}
	}
	
	function processServedAirportChange() {
		if (req.readyState == 4){
			if (req.status == 200){
			    
				sLocationList = document.getElementById('idAirportto'+sCurrentFormID);
				xmldoc = req.responseXML.documentElement;
				nodes = xmldoc.getElementsByTagName('Location');
				sLocationList.options[0] = new Option('- Select destination airport -','');
				for(var i = 0; i < nodes.length; i++) {
					if (nodes.length != 0) {
						sCode = nodes.item(i).attributes.getNamedItem("code").nodeValue;
						sName = nodes.item(i).childNodes.item(0).nodeValue;
						sLocationList.options[sLocationList.options.length] = new Option(sName, sCode);
					}
				}
				sLocationList.disabled='';
				if(nodes.length==1) {
					sLocationList.selectedIndex = 1;
					if(!document.getElementById('idDepartureAirport'+sCurrentFormID)){
					    sCurrentForm[0].submit();
					}else{switchLocationDivs('divLocation'+sCurrentFormID);}
				}else if(nodes.length==0 && bFirstTimer==true){
					alert('No airports found for this destination');
					locationGoBack(sCurrentFormID);
				}else{
					switchLocationDivs('divLocation'+sCurrentFormID);
				}
			}
		}
	}
	


/* START GET SERVED AIRPORT SCRIPT BY Casper Thun August 2007 */

function addDurationBYO(sform)
{
	var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
	
		oSelect = document.getElementById('startdate_d'+sform);
		iDay = oSelect.options[oSelect.selectedIndex].value;
		oSelect = document.getElementById('startdate_m'+sform);
		iMonth = oSelect.options[oSelect.selectedIndex].value;
		oSelect = document.getElementById('startdate_y'+sform);
		iYear = oSelect.options[oSelect.selectedIndex].value;
	
	cindate = new Date(iYear, iMonth - 1, iDay, 0, 0, 0);
	
	oSelect = document.getElementById('duration'+sform);
	//alert('duration'+sform);
	if (oSelect.options[oSelect.selectedIndex].value == 'other')
	{
		tmpDuration = prompt("Please enter the number of nights","")
		if ( (tmpDuration==' ') || (tmpDuration==null) || (tmpDuration == ''))
		{
			iDuration = 7
			oSelect.options[0].selected = 'selected';
		}
		else
		{
			var stemp = tmpDuration
			if (stemp < 10)
			{
				stemp = "0" + stemp
			}
			for (loop=0; loop < oSelect.options.length; loop++)
			{
				if (oSelect.options[loop].value == stemp)
				{
					oSelect.options[loop].selected = 'selected';
					iDuration = stemp
				}
			}

			if (isNumeric(tmpDuration) == true)
			{	
				var opt = new Option(tmpDuration + ' days', tmpDuration);
				insertOptionAt (oSelect, opt, oSelect.options.length);
				iDuration = oSelect.options[oSelect.options.length-1].value;
				oSelect.selectIndex = oSelect.options.length;
				oSelect.options[oSelect.options.length-1].selected = 'selected';
			}
			else
			{
				iDuration = 7
				oSelect.options[0].selected = 'selected';
			}
		}
	}
	else
	{
		iDuration = oSelect.options[oSelect.selectedIndex].value;
	}

	// Amend the end date
	days = 1000 * 60 * 60 * 24 * iDuration;
	newdate = new Date(cindate.valueOf() + days);
	if ((newdate.getHours() != 0) || (newdate.getMinutes() != 0) || (newdate.getSeconds() != 0)) {
		// Workaround to JavaScript bug: sometimes when adding days represented as milliseconds it would onhly add 23 hrs
		// Work out time in milliseconds
		time = newdate.getHours() * 60 * 60 * 1000;
		time += newdate.getMinutes() * 60 * 1000;
		time += newdate.getSeconds() * 1000;
		newdate = new Date(newdate.getTime() + time);
		//alert(newdate);
	}
	
	if(newdate.getDate()+'' != "NaN") {
		sArrDate = newdate.getDate() + ' ' + months[newdate.getMonth()] + ' ' + newdate.getFullYear();
	 } else {
		 sArrDate = 'Please select a departure date.';
	 }
	
	//alert(sArrDate);
	document.getElementById("arrdate"+sform).innerHTML = '<b>' + sArrDate + '</b>'
	//document.getElementById("arrdate"+sform).value = sArrDate	
}

function GetElementWidth(sObject) {
	var elem;
	if(typeof(sObject) == "object") {
		elem = sObject;
	} else {
		elem = document.getElementById(sObject);
	}
	return parseInt(elem.offsetWidth);
}
function clearFlash() {
	try{
		var sLocationID = document.getElementById('idLocationto'+sCurForm);
		clearInterval(sFlasher);
		sLocationID.className = 'redSelectBox';
	}catch(err){}
}
function selectFlash() {
    var sLocationID = document.getElementById('idLocationto' + sCurForm);
    sLocationID.className = (sLocationID.className == 'redSelectBox') ? 'redSelectBox_Switch' : 'redSelectBox';
}




// Start functions relating to MultipleRoomTypes
function updateRooms(control, maxRooms, idForm) {
	if (idForm == null) {
		formid = '';
	}else{
		formid = idForm;
	}
	if (control) {
		var iRooms = parseInt(control.options[control.selectedIndex].value);
		if (!iRooms == 0) {
			
			for (var iRoom=1;iRoom<=maxRooms;iRoom++) {
				var obj = document.getElementById('trRoom'+iRoom+'Values'+formid)
				var obj2 = document.getElementById('trRoom'+iRoom+'Ages'+formid)
				vAgeControl = parseFloat(document.getElementById('ageControl'+iRoom+formid).value);
				if (obj) {
					if (iRoom > iRooms) {
						obj.style.display = 'none';
					} else {
						obj.style.display = '';
					}
				}			
				if (obj2) {
					if (iRoom > iRooms) {
						obj2.style.display = 'none';
					} else {
						if (!vAgeControl == 0) {
							obj2.style.display = '';
						}
					}
				}				
			}		
		}	
	}
}


function updatePax(maxPax, maxAdults, maxChild, maxInfant) {
	var oRooms = document.getElementById('rooms');
	var iPax = 0, iAdults = 0, iChildren = 0, iInfants = 0, iTotalAdults = 0, iTotalChildren = 0, iTotalInfants = 0;
	var paxOkay =  false;

	if (oRooms) {
		paxOkay = true;
		var iRooms = parseInt(oRooms.options[oRooms.selectedIndex].value);
		for (var iRoom=1;iRoom<=iRooms;iRoom++) {
			iAdults = 0;
			iChildren = 0;
			iInfants = 0;
			
			var objAdult = document.getElementById('r'+iRoom+'a');
			if (objAdult) { iAdults = parseInt(objAdult.options[objAdult.selectedIndex].value); }

			var objChild = document.getElementById('r'+iRoom+'c');
			if (objChild) { iChildren = parseInt(objChild.options[objChild.selectedIndex].value); }	

			var objInfant = document.getElementById('r'+iRoom+'i');
			if (objInfant) { iInfants = parseInt(objInfant.options[objInfant.selectedIndex].value); }
			
			iPax += iAdults + iChildren + iInfants;

			if (maxPax != -1) {
				if (iPax > maxPax) { alert('The maximum number of people allowed across all rooms is ' + maxPax); paxOkay = false;}
			}

			if (paxOkay && maxAdults != -1) {
				if (iAdults > maxAdults) { alert('The maximum number of adults allowed in room ' + iRoom + ' is ' + maxAdults); paxOkay = false; }
			}

			if (paxOkay && maxChild != -1) {
				if (iChildren > maxChild) { alert('The maximum number of children allowed in room ' + iRoom + ' is ' + maxChild); paxOkay = false; }
			} 

			if (paxOkay && maxInfant != -1) {
				if (iInfants > maxInfant) { alert('The maximum number of infants allowed in room ' + iRoom + ' is ' + maxInfant); paxOkay = false; }
			}
			
			if (iChildren > 0 || iInfants > 0) {
				//var obj = document.getElementById('trRoom'+iRoom+'Ages');	
				//if (obj) { 
				//	obj.style.display = 'block'; 
					for (var iChild=1;iChild<=maxChild;iChild++) {
						obj = document.getElementById('r'+iRoom+'c_ages'+iChild);
						if (obj) {
							if (iChild <= iChildren) { obj.style.display = 'block'; } else { obj.style.display = 'none'; }
						}
					}	

					obj = document.getElementById('sCAges'+iRoom);
					if (obj) {
						if (iChildren < 1) { obj.style.display = 'none'; } else { obj.style.display = 'block'; }
					}
					
					for (var iInfant=1;iInfant<=maxInfant;iInfant++) {
						obj = document.getElementById('r'+iRoom+'i_ages'+iInfant);
						if (obj) {
							if (iInfant <= iInfants) { obj.style.display = 'block'; } else { obj.style.display = 'none'; }
						}
					}			
					
					obj = document.getElementById('sIAges'+iRoom);
					if (obj) {
						if (iInfants < 1) { obj.style.display = 'none'; } else { obj.style.display = 'block'; }
					}
				//}
			/*} else {
				var obj = document.getElementById('trRoom'+iRoom+'Ages');
				if (obj) { obj.style.display = 'none'; }*/
			}
			
			if (iChildren < 1) {
				// Hide children
				for (var iChild=1;iChild<=maxChild;iChild++) {
					obj = document.getElementById('r'+iRoom+'c_ages'+iChild);
					if (obj) { obj.style.display = 'none'; }
				}	

				obj = document.getElementById('sCAges'+iRoom);
				if (obj) { obj.style.display = 'none'; }		
			}

			if (iInfants < 1) {
				// Hide infants
				for (var iInfant=1;iInfant<=maxInfant;iInfant++) {
					obj = document.getElementById('r'+iRoom+'i_ages'+iInfant);
					if (obj) { obj.style.display = 'none'; }
				}	

				obj = document.getElementById('sIAges'+iRoom);
				if (obj) { obj.style.display = 'none'; }		
			}
			
			iTotalAdults += iAdults
			iTotalChildren += iChildren
			iTotalInfants += iInfants
		}

		var objSeats = document.getElementById('seats_adult')
		if (objSeats && iAdults <= objSeats.options.length) { objSeats.options[iTotalAdults].selected = true; }
		var objSeats = document.getElementById('seats_child')
		if (objSeats && iChildren <= objSeats.options.length) { objSeats.options[iTotalChildren].selected = true; }
		var objSeats = document.getElementById('seats_infant')
		if (objSeats && iInfants <= objSeats.options.length) { objSeats.options[iTotalInfants].selected = true; }
	}
	
	return paxOkay;
}

function updatePax2(id, type, idForm) {
	if (idForm == null) {
		formid = '';
	}else{
		formid = idForm;
	}
	vPerson = parseFloat(document.getElementById('r'+id+type+formid).value);
	vAgeControl = parseFloat(document.getElementById('ageControl'+id+formid).value);
	var objAges = document.getElementById('trRoom'+id+'Ages'+formid);
	for(i=1;i<15;i++) {
		
		if(i>vPerson) {
			div_switch('r'+id+type+'_ages'+i+formid,false,true);
		}else{
			var personFound = 'yes'
			div_switch('r'+id+type+'_ages'+i+formid,true,true);
		}
	}
	if (personFound == 'yes') {
		if (document.getElementById('s'+type.toUpperCase()+'Ages'+id+formid).style.display == "none") {
			vAgeControl = vAgeControl + 1
		}
		div_switch('s'+type.toUpperCase()+'Ages'+id+formid,true,true);
	}else{
		if (document.getElementById('s'+type.toUpperCase()+'Ages'+id+formid).style.display == "block") {
			vAgeControl = vAgeControl - 1
		}
		div_switch('s'+type.toUpperCase()+'Ages'+id+formid,false,true);
	}
	if ((vAgeControl == 0) && (objAges)) {		
		div_switch('trRoom'+id+'Ages'+formid,false,true);	
	} else {
		if (objAges) {
			div_switch('trRoom'+id+'Ages'+formid,true,true);		
		}
	}
	document.getElementById('ageControl'+id+formid).value = vAgeControl;
		
}
// End functions relating to MultipleRoomTypes
function popularDestination(sForm) {
    if (document.getElementById('idPopularDestinationsAll' + sForm) && document.getElementById('idPopularDestinationsAll' + sForm).disabled == false && document.getElementById('idPopularDestinations' + sForm).disabled == true) {
        return 'idPopularDestinationsAll' + sForm
    } else {
        return 'idPopularDestinations' + sForm
    }
}
function switchPopularFreetextSearch(sFormID){
	if(document.getElementById('idPopularSearch' + sFormID).style.display == ''){
		document.getElementById('idPopularSearch' + sFormID).style.display = 'none';
		document.getElementById('idFreetextSearch' + sFormID).style.display = '';
		document.getElementById('idSearchSwitchLink' + sFormID).innerHTML = 'View our popular destinations';
		document.getElementById('idPopularDestinations' + sFormID).selectedIndex = 0;
	}else{
		document.getElementById('idPopularSearch' + sFormID).style.display = '';
		document.getElementById('idFreetextSearch' + sFormID).style.display = 'none';
		document.getElementById('idSearchSwitchLink' + sFormID).innerHTML = 'Type in your destination';
		document.getElementById('idHdnLocationTo' + sFormID).value = '';
		document.getElementById('idFreetext' + sFormID).value = '- type your destination -';
	}
}

function changeSearchRad(){
    var oAutoPop = new Array('idFreetextDepFlight','idFreetextFlight','idFreetextHotel','idFreetextCar');
    var sSearchType = '';
    for(iAr = 0; iAr < oAutoPop.length;iAr++){
        var oDiv = document.getElementById(oAutoPop[iAr]);
        if(oDiv){ var objAS = document.getElementById('as_' + oAutoPop[iAr]); if(objAS){document.body.removeChild(objAS);iAr=oAutoPop[iAr].length}} 
    }
    for(intR=0;intR<document.forms['frmSeachRadios'].searchRad.length;intR++){
        objRad = document.forms['frmSeachRadios'].searchRad[intR];
        if(objRad.checked==true){
            
            document.getElementById('includeAir').style.display = 'none';
            document.getElementById('includeCar').style.display = 'none';
            document.getElementById('includeHotel').style.display = 'none';
            switch(objRad.value){
                case "h":
                     for(intI=0;intI<document.forms['frmSeachRadios'].includeRadHotel.length;intI++){
                        objRadI = document.forms['frmSeachRadios'].includeRadHotel[intI];
                        if(objRadI.checked==true){
                           sSearchType = objRadI.value;
                           document.getElementById('includeHotel').style.display = '';
                           break;
                        }
                    }
                    break;
                case "f":
                    for(intI=0;intI<document.forms['frmSeachRadios'].includeRadAir.length;intI++){
                        objRadI = document.forms['frmSeachRadios'].includeRadAir[intI];
                        if(objRadI.checked==true){
                           sSearchType = objRadI.value;
                           document.getElementById('includeAir').style.display = '';
                           break;
                        }
                    }
                    break;
                case "c":
                    for(intI=0;intI<document.forms['frmSeachRadios'].includeRadCar.length;intI++){
                        objRadI = document.forms['frmSeachRadios'].includeRadCar[intI];
                        if(objRadI.checked==true){
                           sSearchType = objRadI.value;
                           document.getElementById('includeCar').style.display = '';
                           break;
                        }
                    }
                    break;
                case "cruise": sSearchType = "cruise"; break;
                case "resort": sSearchType = "resort"; break;
            }
            if(sSearchType!=''){break;}
        }
    }
    if(sSearchType != ''){
        switch(sSearchType.toLowerCase()){
            case "flight": case "flight_car":
                SwitchSearch("search_tab2");
                document.getElementById("includecarFlight").value = (sSearchType.toLowerCase().indexOf("car") > -1) ? "yes" : "no";
                
                if(sSearchType.toLowerCase().indexOf("car") > -1){
                    changeSearchContext(sSearchType,'car',as_xml4);
                }else{
                    changeSearchContext(sSearchType,'airport',as_xml4);
                }

                break;
            case "flight_hotel": case "flight_car_hotel":
                SwitchSearch("search_tab1");
                document.getElementById("includecarFlightHotel").value =  (sSearchType.toLowerCase().indexOf("car") > -1) ? "yes" : "no" ;
                break;
            case "hotel": SwitchSearch("search_tab3"); break;
            case "car": SwitchSearch("search_tab5"); break;
            case "cruise": SwitchSearch("search_tab8"); break;
            case "resort": SwitchSearch("search_tab9"); break;
        }
    }
}

function changeCarType(sel,objXML){
    if(objXML && objXML.oP && objXML.oP.script && objXML.oP.varname)
    {
        objXML.oP.script = (sel.options[sel.selectedIndex].value == 'airport') ? "/includes/autocomplete/getairportsXML.asp?type=car&": "/includes/autocomplete/getgeolocationsXML.asp?type=car&";
        objXML.oP.varname = (sel.options[sel.selectedIndex].value == 'airport') ? "airname":"destination";
    }
    document.getElementById('idFreetextCar').value = '';
    document.getElementById('idHdnLocationToCar').value = '';
    clearField(document.getElementById('idFreetextCar'),'','- Type your pick-up location -');
    clearAllAutoSuggests();
}

function changeSearchContext(sCurForm, sContext,objXML){
    if(objXML && objXML.oP && objXML.oP.script && objXML.oP.varname)
    {
        switch(sCurForm.toLowerCase()){
            case "car":
                objXML.oP.script = (sContext == 'airport') ? "/includes/autocomplete/getairportsXML.asp?": "/includes/autocomplete/getgeolocationsXML.asp?type=car&";
                objXML.oP.varname = (sContext == 'airport') ? "airname":"destination";
                break;
            case "flight_hotel": case "flight": case "flight_car_hotel": case "flight_car":
                objXML.oP.script = (sContext == 'car') ? "/includes/autocomplete/getairportsXML.asp?type=car&": "/includes/autocomplete/getairportsXML.asp?";
                break;
        }
    }
}

function updateAvailCal(sForm,val) {
    d = new Date(); m = d.getMonth() + 1; y = d.getFullYear();
    for (i = 1; i < 13; i++) { $("#" + sForm + "_" + m + "_" + y).addClass("unavail"); if (m < 12) { m++ } else { m = 1; y++ }; }
    $.ajax({
    url: "/includes/resorts/ajaxCal.asp?locationto=" + val,
        cache: true,
        timeout: 10000,
        success: function(xml) {
            $(xml).find('avail[staycount!=0]').each(function() {
                $("#" + sForm + "_" + $(this).attr('month') + "_" + $(this).attr('year')).removeClass("unavail");
            });
        },
        error: function(rq, status, err) { }
    });
}

function switchResortList(lnk) {
    $('#idPopularDestinationsAllResort')[0].selectedIndex = 0;
    $('#idPopularDestinationsResort')[0].selectedIndex = 0;
    lnk.innerHTML = (lnk.innerHTML == 'See more destinations') ? 'See preferred destinations' : 'See more destinations'
    
    if(document.getElementById('idPopularSearchResort').style.display == ''){
        document.getElementById('idPopularSearchResort').style.display = 'none';
        document.getElementById('idFreetextSearchResort').style.display = '';
        document.getElementById('idPopularDestinationsResort').disabled = true;
        document.getElementById('idPopularDestinationsAllResort').disabled = false;
    }else{
        document.getElementById('idPopularSearchResort').style.display = '';
        document.getElementById('idFreetextSearchResort').style.display = 'none';
        document.getElementById('idPopularDestinationsResort').disabled = false;
        document.getElementById('idPopularDestinationsAllResort').disabled = true;
    }
    
}

//START - DATE FUNCTIONS

function DateValidator(sDate, sDatePattern)
{
    var bDateValid = false;	
	var oReturnedDate = DateSplitter(sDate, sDatePattern);
	
	if (oReturnedDate.bDateSplitted)
        bDateValid = isValidDate(oReturnedDate.sDay, oReturnedDate.sMonth, oReturnedDate.sYear);
    
    return bDateValid;
}

function getMonthFromRealName(sMonthName)
{
    var iMonthNo = 1;
    switch (sMonthName)
    {
        case "January": case "Jan": iMonthNo = 1; break;
        case "February": case "Feb": iMonthNo = 2; break;
        case "March": case "Mar": iMonthNo = 3; break;
        case "April":case "Apr":iMonthNo = 4;break;
        case "May": iMonthNo = 5; break;
        case "June":case "Jun":iMonthNo = 6;break;
        case "July":case "Jul":iMonthNo = 7;break;
        case "August":case "Aug":iMonthNo = 8;break;
        case "September":case "Sep":iMonthNo = 9;break;
        case "October":case "Oct":iMonthNo = 10;break;
        case "November": case "Nov": iMonthNo = 11; break;
        case "December": case "Dec": iMonthNo = 12; break;
    }
    return iMonthNo;
}

function StringToInt(sValue)
{
    //Convert to float then int as straight to int results in a 
    //value of 0 when converting 08 and 09 due to the browser
    //thinking the number is a base 8 (octal)
    return parseInt(parseFloat(sValue));
}

function isValidDate(sDay, sMonth, sYear)
{
    var dtDate = CreateDate(sDay, sMonth, sYear);
    
    var iDay = StringToInt(sDay);
    var iMonth = StringToInt(sMonth) - 1;
    var iYear = StringToInt(sYear);
    
    if (dtDate.getFullYear() != iYear || dtDate.getMonth() != iMonth || dtDate.getDate() != iDay)    //.getDate() actually returns the day of the month
        return false;
    else
        return true;
}

//Return values
// -1:  dDate1 is earlier then dDate2
//  0:  dDate1 == dDate2
//  1:  dDate1 is later then dDate2
function DateCompare(dDate1, dDate2, sDatePattern)
{
    if (dDate1 < dDate2)
        return -1;
    else if (dDate1 === dDate2)
        return 0;
    else
        return 1;
}

function DateSplitter(sDate, sDatePattern)
{
    var sDay = '';
    var sMonth = '';
    var sYear = '';
    
    var i;
	var aSplitDate;
	var aSplitDatePattern;
	var bDateSplitted = false;
	
	//Ignore characters
	sDatePattern = sDatePattern.replace(",", "");
	sDate = sDate.replace(",", "");
	
	//Attempt to seperate date
    var aSeperators = new Array(".", "/", " ");
    for (i in aSeperators)
    {
        aSplitDate = sDate.split(aSeperators[i]);
        aSplitDatePattern = sDatePattern.split(aSeperators[i]);
        
        if (aSplitDate.length == 3)
        {
            bDateSplitted = true;
            break;
        }
    }
    
    if (bDateSplitted)
    {
	    //Using the pattern attempt to match the date parts to the correct variables
	    for (i in aSplitDatePattern)
	    {
	        switch (aSplitDatePattern[i])
	        {
	            case "yyyy":
	            case "y":
	                sYear = aSplitDate[i];
	                break;
	            
	            case "MMM":
	            case "NNN":
	                sMonth = getMonthFromRealName(aSplitDate[i]);
	                break;
	            
	            case "MM":
	                sMonth = aSplitDate[i];
	                break;
	            
	            case "d":
	            case "dd":
	                sDay = aSplitDate[i];
	                break;
	        }
	    }
    }
    
    //First param indicates that we have a potential date. The date will still need validating through
    return {bDateSplitted : bDateSplitted, sDay : sDay, sMonth : sMonth, sYear : sYear};
}

function CreateDate(sDay, sMonth, sYear)
{
    var iDay = StringToInt(sDay);
    var iMonth = StringToInt(sMonth) - 1;
    var iYear = StringToInt(sYear);

    var dtDate = new Date();
    dtDate.setFullYear(iYear, iMonth, iDay);
    
    return dtDate;
}

//END - DATE FUNCTIONS
