	var gullTab; //used to move county / town title when auto complete is not visible 
	gullTab ='Tab';

    /* -------------------- JQuery functions -------------------- */
    /*  Notes:
        http://www.sloppycode.net/articles/using-jquery-with-aspnet-web-services.aspx
        http://codeleacher.wordpress.com/2008/12/09/how-to-addremove-items-from-a-dropdownlist-using-jquery/
        http://www.isolutionteam.co.uk/how-to-use-jquery-ajax-with-aspnet-dropdown-list-onchange-event/
    */
       
    function GetTowns()
    {
        // clear the current options in the list
        $('#County_TownDropDownList >option').remove();
        // add the default 'any town'
        $('#County_TownDropDownList').append($('<option></option>').val('').html('Any Town'));
        
        // get the selected value from the county drop down
        var prefix=$("#County_CountyDropDownList").val();
        
        // if the prefix is not empty(please select) 
        if(prefix != '')
        {
            var AffiliateID=$("#hdnAffiliateID").val();
            var ProviderID=$("#hdnProviderID").val();

            // make a webservice call
            $.ajax({ type: "POST",  
                url: "DirectSearchWebServices.asmx/GetTownLocations",  
                dataType: "xml",  
                data: "Prefix=" + prefix +"&affiliateID=" + AffiliateID+ "&providerID=" + ProviderID,
                processData: false,  
                error: function(XMLHttpRequest, textStatus, errorThrown) { ajaxError(XMLHttpRequest,textStatus, errorThrown); },  
                success: function(xml) { ajaxFinish(xml); }  
            });
        }
    }
       
    function ajaxFinish(xml)
    {
        // foreach "location" node
        $("Location", xml).each(function()
	    {
	        // get the values from xml
		    locationID = $("LocationID", this).text();
		    name = $("Name", this).text();
		    order = $("Order", this).text();
   	        // add the options to the dropdown list
   	        $('#County_TownDropDownList').append($('<option></option>').val(locationID).html(name));
	    });
    }

    function ajaxError(xmlObj,textStatus,errorThrown)
    {
        // Comment this out for live environments, and put a friendly error message
        alert("(Ajax error: "+textStatus+")");
        alert(xmlObj.responseText);
    }
    
    function GetTypedSearchCode()
    {
        // get the selected value from the county drop down
        var typedLocationName=$("#TypeLocation_gullTypedLocation").val();
        
        // if the prefix is not empty(please select) 
        if(typedLocationName != '')
        {
            // make a webservice call
            $.ajax({ type: "POST",  
                url: "DirectSearchWebServices.asmx/GetTypedSearchCode",  
                dataType: "xml",  
                data: "TypedLocationName=" + typedLocationName,  
                processData: false,  
                error: function(XMLHttpRequest, textStatus, errorThrown) { ajaxError(XMLHttpRequest,textStatus, errorThrown); },  
                success: function(xml) { ajaxTypeSearchCodeFinish(xml); }  
            });
        }
    }
    
    function ajaxTypeSearchCodeFinish(xml)
    {
        // get the code for the location from the xml
        code = $("string", xml).text();
        
        // set the hidden
        ContinueSearch(code);
    }
    
    /* ------------------ End JQuery functions ------------------- */

    function ContinueSearch(typedSearch)
    {
        var gullYearMonth = getField('ArrivalMonthYear_date_sel_mm').value.split("|");
		var gullYear = gullYearMonth[0];
		var gullMonth = gullYearMonth[1];
		var gullDaySel = getField('ArrivalDay_date_sel_dd').value;
		var gullUrl = getField('hdnBookingURL').value;
	    var gullAffiliateID = getField('hdnAffiliateID').value;
	    var gullProviderID = getField( 'hdnProviderID').value;
	    var gullNumAdults = getField('Adults_gullAdultsDDL').value;
	    var gullNumChildren = getField('Children_gullChildrenDDL');
	    var gullNumInfants = getField('Infants_gullInfantsDDL');
	    var gullNumNights = getField('Nights_gullNightsDDL');
	    var gullLocationDropDown = getField('County_CountyDropDownList');
	    var gullLocationSetByAffiliate = getField('hdnAffilateSetLocation');
		var gullPremName = getField('PropertyName_PropertyNameTextBox');
		var gullPremName = getField('PropertyName_PropertyNameTextBox');
		var gullAffilateVisitID = getField('hdnAffilateVisitID');
		var gullRedirectType = getField('hdnRedirectType');
		
		var gullLocation;
		
		if(gullLocationDropDown)
		{
		    gullLocation = gullLocationDropDown.value;
		}
		else if(gullLocationSetByAffiliate)
		{
		    gullLocation = gullLocationSetByAffiliate.value;
		}
		
		if(isValidDate(gullDaySel,gullMonth-1,gullYear))
		{
            //variable to hold our deepLink
            var deepLink;

            if (gullLocation == "" && typedSearch == "")
            {
                if(gullPremName)
                {
                    if(gullPremName.value == '')
                    {
                        alert('Please select a location.');
                        return;
                    }
                }
                else
                {
                    alert('Please select a location.');
                    return;
                }
            }

			//build the URL for deepLinking
			deepLink = gullUrl + "?affiliatevisitid=" + gullAffilateVisitID.value + "&affiliateid=" + gullAffiliateID + "&ProvID=" + gullProviderID  + "&IsAdvanced=1";
			
			if (typedSearch == '' || typedSearch == '/')
            {
                //var gullTownLevel = getField('hdnTownLevel'); 
			    var gullTown = getField('County_TownDropDownList');     
	
			    if(gullTown && gullTown.value != 'Any Town' && gullTown.value != '')
			    {
				    deepLink += "&hdnLocation=" + gullTown.value;
			    }
			    else
			    {
				    deepLink += "&hdnLocation=" + gullLocation;
			    }
            }
            else
            {
                deepLink  += "&hdnLocation=" + typedSearch;
            }

            var gullAccomType = getField('PropertyType_AccomTypesDropDownList');
			if(gullAccomType){
			    //var gullAccomType = getField('gullSelAccomType');
				deepLink += "&selAccomType=" + gullAccomType.value;
		    }
			else
			{			
			    var gullAccomType = getField('hdnPremType');
				deepLink += "&selAccomType=" + gullAccomType.value;
			}
			
			deepLink += "&selArriveDay=" + gullDaySel;
			deepLink += "&selArriveMonth=" + gullMonth;
			deepLink += "&selArriveYear=" + gullYear;
			deepLink += "&selNumAdults=" + gullNumAdults;	
			
			if(gullNumChildren == undefined)
			{ 
			    deepLink += "&selNumChildren=0";
			}
			else
			{
			    deepLink += "&selNumChildren=" + gullNumChildren.value;
			}
			if(gullNumInfants == undefined)
			{ 
			    deepLink += "&selNumInfants=0"; 
			}
			else
			{
			    deepLink += "&selNumInfants=" + gullNumInfants.value;
			}
			deepLink += "&selNumNights=" + gullNumNights.value;
            
            //var gullFacilities = getField('hdnShowFacilities');
            var gullFacilities =  getField('gullFac');
			//if(gullFacilities.value =='yes')
			if(gullFacilities)
			{
			    var s = new String('');
			    for (var facilCounter = 0; facilCounter< 10;facilCounter++)
				{
				    var gullFacilityChk = getField('Facilities_ctl0'+ facilCounter);
				    if ((gullFacilityChk) && (gullFacilityChk.checked))
					s += gullFacilityChk.value + ",";
				}

				if (s!='')
				{
					deepLink += "&strfacilities=" + s;
				}
			}
			
			//var gullIsShare = getField('hdnSharing');
			//if(gullIsShare.value == 'yes')
			var gullShare = getField('gullSelSharing');
			if(gullShare)
			{	
			    //var gullShare = getField('gullSelSharing');
				deepLink += "&selSharing=" + gullShare.value;
			}

            //var gullShowPrice = getField('hdnPrice');
            var gullPriceFrom = getField('Price_PriceFromTextBox');
			//if(gullShowPrice.value=='yes')
			if(gullPriceFrom)
			{
			    //var gullPriceFrom = getField('txtPriceFrom');
			    var gullPriceTo = getField('Price_PriceToTextBox');
				if(gullPriceTo.value == '')
				{
						deepLink += "&selPriceUpper=5000";
				}
				else
				{
					deepLink += "&selPriceUpper=" + gullPriceTo.value;
				}

				if(gullPriceFrom.value == '')
				{
					deepLink += "&selPriceLower=0";
				}
				else
				{
					deepLink += "&selPriceLower=" + gullPriceFrom.value;
				}
			}

            //var gullShowPremName = getField('hdnPremName');
			if(gullPremName && gullPremName.value!='')
			{
				deepLink += "&txtPremName=" + gullPremName.value;
			}
			
			//var gullShowPremGrade = getField('hdnGrade');
			var gullGradeAll = getField('Grade_AllStarCheckBox');
			if(gullGradeAll)
			{
			    //var gullGradeAll = getField('chkGradeAll');
			    var gullGrade1 = getField('Grade_OneStarCheckBox');
			    var gullGrade2 = getField('Grade_TwoStarCheckBox');
			    var gullGrade3 = getField('Grade_ThreeStarCheckBox');
			    var gullGrade4 = getField('Grade_FourStarCheckBox');
			    var gullGrade5 = getField('Grade_FiveStarCheckBox');
			    
				if (gullGradeAll.checked){
					deepLink += "&chkGradeAll=Y";}
				else{deepLink += "&chkGradeAll=N";}
				if (gullGrade1.checked){
					deepLink += "&chkGrade1=Y";}
				else{deepLink += "&chkGrade1=N";}
				if (gullGrade2.checked){
					deepLink += "&chkGrade2=Y";}
				else{deepLink += "&chkGrade2=N";}
				if (gullGrade3.checked){
					deepLink += "&chkGrade3=Y";}
				else{deepLink += "&chkGrade3=N";}
				if (gullGrade4.checked){
					deepLink += "&chkGrade4=Y";}
				else{deepLink += "&chkGrade4=N";}
				if (gullGrade5.checked){
					deepLink += "&chkGrade5=Y";}
				else{deepLink += "&chkGrade5=N";}
			}
			
			var gullHasOptional = getField('hdnoptional');
			if (gullHasOptional.value!='' && gullHasOptional.value!='/')
			{
				deepLink += "&" +  gullHasOptional.value;
			}
			
			deepLink += "&strAction=search&intInterPageSearchType=9&intDirectPremSpecificSearch=0" +
			"&strDirectSearchRootURL=" + document.location.href + "&selCurrency=978&SearchSource=10";

			typedSearch = '';
			//redirect page to our deepLink URL
			//window.location.href = deepLink;
			
		    if(gullRedirectType.value == '2') // Pop Up
		    {
		        window.open(deepLink,'Booking','resizable=1,status=1,menubar=0,toolbar=0,scrollbars=1,location=0,directories=0,width=1000,height=850,top=60,left=60');
		    }
		    else if(gullRedirectType.value == '3') // New Window
		    {
		        window.open(deepLink,'_blank','resizable=1,status=1,menubar=1,toolbar=1,scrollbars=1,location=1,directories=1');
		    }
		    else // Current
		    {
		        self.parent.location = deepLink;
		    }
		}
    }

	function SearchForAvailablity() 
	{
		var gullTypedLocation = getField('TypeLocation_gullTypedLocation');

		//if((gullTypedSearch.value == '' || gullTypedSearch.value == '/') && gullTypedLocation && gullTypedLocation.value != '')
		if(gullTypedLocation && gullTypedLocation.value != '')
		{   
		    GetTypedSearchCode();
		}
		else
		{
		    ContinueSearch('');
		}
	}

    function isValidDate(day,month,year)
	{
		/*
		Purpose: return true if the date is valid, false otherwise
		Arguments: day integer representing day of month
		month integer representing month of year
		year integer representing year
		Variables: dteDate - date object
		*/
		var dteDate;
		var todaysDateTime;
		todaysDateTime = new Date();

		//set up a Date object based on the day, month and year arguments
		//javascript months start at 0 (0-11 instead of 1-12)
		//dteDate=new Date(year,month,day,"23","59","59");
		dteDate=new Date(year,month,day,"23","59","59");
		
		if (dteDate>=todaysDateTime)
		{
			/*
			Javascript Dates are a little too forgiving and will change the date to a reasonable guess if it's invalid. We'll use this to our advantage by creating the date object and then comparing it to the details we put it. If the Date object is different, then it must have been an invalid date to start with...
			*/
			return ((day==dteDate.getDate()) && (month==dteDate.getMonth()) && (year==dteDate.getFullYear()));

		}
		else
		{
			return false;			
		}
	}

function showhideDiv(div)
{
    var gullBasicOptionDiv = getField('gullBasic');
    var gullOptGradeDiv = getField('gullAdvanced');
    var gullFacilitiesDiv = getField('gullFac');
    var gullBasicTab = getField('Tabs_gullBasicTab');
    var gullOptTab = getField('Tabs_gullOptionTab');
    var gullFacilTab = getField('Tabs_gullFacilitisTab');
    
    if(div == 'gullBasic')
    {
        gullBasicOptionDiv.style.display = 'block';
        if(gullOptGradeDiv)
            gullOptGradeDiv.style.display = 'none';
        if(gullFacilitiesDiv)
            gullFacilitiesDiv.style.display = 'none';
        gullBasicTab.className = 'gullCurrentTab';
        if(gullOptTab)
            gullOptTab.className = '';
        if(gullFacilTab)
            gullFacilTab.className = '';
    }
    else if(div == 'gullAdvanced')
    {
        gullBasicOptionDiv.style.display = 'none';
        if(gullOptGradeDiv)
        gullOptGradeDiv.style.display = 'block';
        if(gullFacilitiesDiv)
            gullFacilitiesDiv.style.display = 'none';
        gullBasicTab.className = '';
        if(gullOptTab)
            gullOptTab.className = 'gullCurrentTab';
        if(gullFacilTab)
            gullFacilTab.className = '';
    }
    else if(div == 'gullFac')
    {
        gullBasicOptionDiv.style.display = 'none';
        if(gullOptGradeDiv)
            gullOptGradeDiv.style.display = 'none';
        if(gullFacilitiesDiv)   
            gullFacilitiesDiv.style.display = 'block';
        gullBasicTab.className = '';
        if(gullOptTab)
            gullOptTab.className = '';
        if(gullFacilTab)
            gullFacilTab.className = 'gullCurrentTab';
    }
    
    var gullListArea = getField('as_gullTypedLocation');
    if (gullListArea)
	{
	    gullListArea.style.visibility = "hidden";
	}
	return false;
}

function gullSetSelectedIndex(DropDownControlID, ValueToMatch)
{
	if (ValueToMatch!='')
	{
        for(var i=0;i< getField(DropDownControlID).length;i++)
        {
            var ddlText = getField(DropDownControlID).options[i].value;
            if( ddlText == ValueToMatch)
            {
                getField(DropDownControlID).selectedIndex=i;
                break;
            }
        }  
	}
	else
	{
	    getField(DropDownControlID).selectedIndex = 0;
	}
}

function gullOut(Html)
{
    document.write(Html);
}


function gullOption(value, text)
{
    gullOut('<option value=' + value + '>' + text + '</option>');
}

function createNumericOnlyOption(maxOption, selectedNum)
{
    for (var Count = 1; Count <= maxOption; Count ++)
	{
	    if(Count == selectedNum)
	    {
		    gullOut('<option value=' + Count + ' selected="selected">' + Count + '</option>');
		}
		else
		{
		    gullOut('<option value=' + Count + '>' + Count + '</option>');
		}
	}
}

function getField(ID)
{
    return document.getElementById(ID);
}

function gullHidFld(idName, value)
{
    gullOut('<input type="hidden" id="'+ idName + '" name="'+ idName + '" value=' + value + ' />');
}

function gullChkFld(idName, value)
{
    if(value)
    {
        return '<input type="checkbox" value="'+value+'" id="' + idName + '" name="' + idName + '" />';
    }
    else
    {
        return '<input type="checkbox" value="Y" id="' + idName + '" name="' + idName + '" />';
    }
}

function gullHideIE6DropDowns(numberOfMatches)
{
    if(numberOfMatches <= 1 || numberOfMatches >= 6)
    getField("hdnLocation").className = 'gullHide';
    if(numberOfMatches == 2 || numberOfMatches >= 6)
    getField("gullSelTowns").className =  'gullHide';
    if(numberOfMatches == 3 || numberOfMatches >= 6)
    getField("gullSelAccomType").className =  'gullHide';
    if(numberOfMatches == 4 || numberOfMatches >= 6)
    getField("selNumChildren").className =  'gullHide';	
    if(numberOfMatches == 4 || numberOfMatches >= 6)
    getField("gullSelNumAdults").className =  'gullHide';
    if(numberOfMatches == 5 || numberOfMatches >= 6)
    getField("date_sel_dd").className =  'gullHide';
    if(numberOfMatches == 5 || numberOfMatches >= 6)
    getField("date_sel_mm").className =  'gullHide';
    if(numberOfMatches >= 6 || numberOfMatches >= 6)
    getField("gullSelNumNights").className =  'gullHide';
}

function gullShowIE6DropDowns()
{
    getField("hdnLocation").className = 'gullLocationCombo';
    getField("gullSelTowns").className =  'gullTowns';
    getField("gullSelAccomType").className =  'gullPremType';
    getField("selNumChildren").className =  'gullNumChildren';	
    getField("gullSelNumAdults").className =  'gullNumAdults';
    getField("date_sel_dd").className =  'gullDays';
    getField("date_sel_mm").className =  'gullMonthYear';
    getField("gullSelNumNights").className =  'gullNumNight';
}

// Unobtrusive JavaScript
function InitUnobtrusiveJavaScriptFunctions()
{
    // add function to change num nights if self catering its selected
    var gullAccomType = getField('gullSelAccomType');
    if (gullAccomType)
    {
        gullAccomType.onchange = function () {
            var gullNumNight = getField('gullSelNumNights');
            if(gullAccomType.value == 2)
                gullNumNight.value = 7;
            else
            {
                gullNumNight.value = 1;
            }
        }
    }
}

function OpenCalenderWindow()
{
    var gullDaySel = getField('ArrivalDay_date_sel_dd');
    var gullMonthSel = getField('ArrivalMonthYear_date_sel_mm');
    //var gullPremCode = getEle('hdnPremisesCode');
    var gullCalendarID = getField('hdnCalendarID');
    var gullBookNowID = getField('hdnBookNowID');

    eval("window.open('/DirectSearch/DirectSearchCalendar.aspx?&selectedDay="+gullDaySel.selectedIndex+"&selectedMonth="+gullMonthSel.selectedIndex+"&CalendarCssID="+gullCalendarID.value+"', '', 'toolbar=0,scrollbars=0,location=1,statusbar=0,menubar=0,resizable=1,width=170,height=235');");
}

function SetSelectedDay(day)
{
    var gullday = getField('ArrivalDay_date_sel_dd');
    gullday.selectedIndex = day; 
}

function SetSelectedMonthYear(monthYear)
{
    var gullMonthYear = getField('ArrivalMonthYear_date_sel_mm');
    gullMonthYear.selectedIndex = monthYear; 
}