
function SearchShow(bChanged) {

    f.GetObject('lblSearch_Arriving').innerHTML = 'Arriving';
    f.GetObject('lblSearch_Departing').innerHTML = 'Departing';

    f.GetObject('lblRoom1').innerHTML = 'Guests';

    var iRooms = n.SafeInt(dd.GetText('ddlRooms'));
    var sRoomTitle = f.GetValue('hidRoomTitle');

    //show room selection and labels
    var iChildren;
    for (var i = 1; i < 5; i++) {
        f.ShowIf('trRoom' + i, i <= iRooms);

        iChildren = n.SafeInt(dd.GetText('ddlRoom' + i + 'Children'));
        f.ShowIf('txtRoom' + i + 'ChildAge1', iChildren > 0 && i <= iRooms);
        f.ShowIf('txtRoom' + i + 'ChildAge2', iChildren > 1 && i <= iRooms);
        f.ShowIf('txtRoom' + i + 'ChildAge3', iChildren > 2 && i <= iRooms);
        f.ShowIf('txtRoom' + i + 'ChildAge4', iChildren > 3 && i <= iRooms);
        f.ShowIf('txtRoom' + i + 'ChildAge5', iChildren > 4 && i <= iRooms);
        f.ShowIf('txtRoom' + i + 'ChildAge6', iChildren > 5 && i <= iRooms);
        f.ShowIf('trRoom' + i + 'ChildAges', iChildren > 0 && i <= iRooms);

        f.GetObject('lblRoom' + i).innerHTML = sRoomTitle + ' ' + i;

    }

    //set first room label
    if (iRooms == 1) {

        f.GetObject('lblRoom1').innerHTML = 'Guests';
    }

    //if the selection's changed then fire the onchange of the country dropdown
    if (bChanged) {
        dd.SetIndex('sddDepartingFrom', 0);
        f.GetObject('sddDepartingFrom').onchange();
    }
}


var sFillListPath = '/WebServices/Search.asmx';

// county selected
function SearchCountrySelected() {

    var oResort = f.GetObject('sddGeographyLevel3ID');
    if (n.SafeInt(dd.GetValue(oResort)) > 0) {
        f.SetValue('hidRestoreResort', dd.GetValue(oResort));
    }
    dd.Clear(oResort);

    //add an all option
    dd.AddOption(oResort, 'Select...', 0);
    
    //scan through the array 'filtering' on countryid	
    var iLastRegionID = -1;
    var iRegionID, sRegion, iResortID, sResort;
        
    for (var i = 0; i < aResortMatrix.length; i++) {

        iRegionID = aResortMatrix[i][1];
        sRegion = aResortMatrix[i][2];
        iResortID = aResortMatrix[i][3];
        sResort = aResortMatrix[i][4];

        //if it's a new region then add the appropriate bit
        if (iRegionID != iLastRegionID && sRegion != '') {
            dd.AddOption(oResort, sRegion, 'r' + iRegionID, 'ddregion');
        }

        //add the resort
        dd.AddOption(oResort, sResort, iResortID);

        iLastRegionID = iRegionID;

    }

    //if we have a value to restore then do so
    var sRestoreResort = f.GetValue('hidRestoreResort');
    if (sRestoreResort != '') {
        dd.SetValue(oResort, sRestoreResort);
        f.SetValue('hidRestoreResort', '');
    }

}

function ClearSearchDropdown(sDropdown) {
    dd.Clear(sDropdown);
}


function RestoreSearch() {

    //if the user has gone back via the back button then we're potentially in trouble
    //just make sure everything's visible that should be
    var sSearchMode = GetSearchMode();
    var bRedisplay = false;

    //few problem areas to check - run through flight plus hotel first
    if (sSearchMode == 'FlightsPlusHotel') {

        //if departure is selected and country isn't visible then return true
        if (dd.GetValue('sddDepartureFrom') > 0 && f.GetObject('sddGeographyLevel1ID').options.length == 1) {
            DepartureSelected(dd.GetValue('sddDepartureFrom'));
            bRedisplay = true;
        }

        //if destination is selected and airport isn't visible then return true
        if (dd.GetValue('sddGeographyLevel1ID') > 0 && f.GetObject('sddAirportID').options.length == 1) {
            CountrySelected(dd.GetValue('sddGeographyLevel1ID'));
            bRedisplay = true;
        }

        //if airport is selected and resort isn't visible then return true
        if (dd.GetValue('sddAirportID') > 0 && f.GetObject('sddGeographyLevel3ID').options.length == 1) {
            airportselected(dd.getvalue('sddAirportID'));
            bRedisplay = true;
        }


    }

    //now run through hotel only
    if (sSearchMode == 'HotelOnly') {

        //if departure is bvisible then return true
        if (f.Visible('divFlights')) {
            bRedisplay = true;
        }

        //if destination is selected and resort isn't visible then return true
        if (dd.GetValue('sddGeographyLevel1ID') > 0 && f.GetObject('sddGeographyLevel3ID').options.length == 1) {
            SearchCountrySelected(dd.GetValue('sddGeographyLevel1ID'));
            bRedisplay = true;
        }
    }


    //if we've got more than one room or any children on the first room redisplay 
    if (n.SafeInt(dd.GetText('ddlRooms')) > 1 || n.SafeInt(dd.GetText('ddlRoom1Children')) > 0) {
        bRedisplay = true;
    }


    if (bRedisplay) { SearchShow(); }

}



function Search(sPath, iPropertyID, dArrivalDate, iDuration, dDepartureDate) {

    //validate first
    var sWarning = SearchValidate();

    //if all's well then continue else pop up the warning
    if (sWarning == '') {


        //show the modal popup
        ShowWaitMessage();

        //do some new stuff
        var sSearchParameters = PackageSearch(iPropertyID, dArrivalDate, iDuration, dDepartureDate);
        oSearch.Go(sSearchParameters, sPath);

    } else {
        //might need your own bespoke script
        FormHandler.ShowInformation(sWarning);
    }

}


function SearchValidate() {

    f.Hide('divNoResults');

    //declare error variables
    var bGeographyError = false;
    var bBookAheadError = false;

    if (dd.GetValue('sddGeographyLevel3ID') < 1) {
        bGeographyError = true;
        f.SetClass('sddGeographyLevel3ID', 'dropdown error');
    } else {
        f.SetClass('sddGeographyLevel3ID', 'dropdown');
    }

    //book ahead days
    //check date isn't before today
    var oCalendar = new Calendar(null, 'calArrivalDate');
    var dToday = d.GetDateOnly(new Date());
    if (oCalendar.CurrentDate < d.AddDays(dToday, f.GetIntValue('hidWebBookAheadDays'))) {
        bBookAheadError = true;
        f.AddClass('calArrivalDate_Day', 'error');
    } else {
        f.RemoveClass('calArrivalDate_Day', 'error');
    }



    var iRooms = n.SafeInt(dd.GetText('ddlRooms'));

    //check child ages
    var iChildren, iChildAge, bChildAgeErrors = false;
    for (var iRoom = 1; iRoom <= iRooms; iRoom++) {

        iChildren = n.SafeInt(dd.GetText('ddlRoom' + iRoom + 'Children'));

        for (var iChild = 1; iChild <= iChildren; iChild++) {

            var oTextbox = f.GetObject('txtRoom' + iRoom + 'ChildAge' + iChild)
            iChildAge = n.SafeInt(f.GetValue(oTextbox));
            if (iChildAge < 2 || iChildAge > 18) {
                f.SetClass(oTextbox, 'textbox number error');
                bChildAgeErrors = true;
            } else {
                f.SetClass(oTextbox, 'textbox number');
            }

        }
    }

    var sWarning = '';
    if (bChildAgeErrors || bGeographyError || bBookAheadError) {
        sWarning += bGeographyError ? 'Please make sure you have selected the Location for your search' : '';
        sWarning += bBookAheadError ? (bGeographyError ? '|' : '') + 'Please select an Arrival Date at least ' + f.GetValue('hidWebBookAheadDays') + ' Days after today' : '';
        sWarning += bChildAgeErrors ? (bGeographyError || bBookAheadError ? '|' : '') + 'Please make sure all Child Ages are specified between 2 and 18 years old' : '';
    }
    return sWarning;
}

//search webservice stuff
var oSearch = new WebService();
oSearch.Go = function(sParameters, sPath) {
    aParams = new Array(['sParameters', sParameters]);
    bBackOneLevel = (sPath == undefined || sPath == '') ? false : true;
    sPath = (sPath == undefined || sPath == '') ? '/webservices/search.asmx' : sPath;
    this.RunWebService(sPath, 'http://intuitivesystems', 'Search', aParams, this, false);
}


oSearch.Done = function(oXML) {

    var oReturn = new SearchResult(this.GetTagValue(oXML, 'PropertyCount'),
		this.GetTagValue(oXML, 'FlightCount'), this.GetTagValue(oXML, 'SeparateFlight'));

    var iPropertyCount = n.SafeInt(oReturn.PropertyCount);
    var iFlightCount = n.SafeInt(oReturn.FlightCount);
    var sPage = f.GetValue('hidPagename');

    if (GetSearchMode() == 'FlightsPlusHotel' && oReturn.SeparateFlight == 'true' && iPropertyCount > 0) {
        window.location = '/flightresults.aspx';
    } else if (iPropertyCount > 0 || sPage == 'Results') {
        window.location = '/results.aspx';
    } else {
        FormHandler.ShowWarning("Your search returned no results. Please try again using different criteria.");
        HideWaitMessage();
    }
}

function SearchResult(PropertyCount, FlightCount, SeparateFlight) {
    this.PropertyCount = PropertyCount;
    this.FlightCount = FlightCount;
    this.SeparateFlight = SeparateFlight;
}

function GetSearchMode() {

    var sMode;
    if (f.GetObject('divChoose') != null) {

        if (f.GetObject('radFlightPlusHotel').checked) {
            sMode = 'FlightsPlusHotel';
        } else {
            sMode = 'HotelOnly';
        }
    } else {
        sMode = 'HotelOnly';
    }

    return sMode;
}



function PackageSearch(iPropertyID, dArrivalDate, iDuration, dDepartureDate) {

    var sReturn = '';

    //search mode
    sReturn += 'SearchMode=' + GetSearchMode() + '|';


    //autocompletes (only want the hidden control that stores the value)
    var aHiddens = f.GetObjectsByIDPrefix('acp');
    for (var i = 0; i <= aHiddens.length - 1; i++) {
        if (s.Right(aHiddens[i].id, 6) == 'Hidden') {
            sReturn += aHiddens[i].id + '=' + f.GetValue(aHiddens[i].id) + '|';
        }
    }


    //textboxes
    var aTextboxes = f.GetElementsByClassName('input', 'textbox');
    for (i = 0; i < aTextboxes.length; i++) {
        sReturn += aTextboxes[i].id + '=' + f.GetValue(aTextboxes[i].id) + '|';
    }


    //dropdowns
    var aDropdowns = f.GetElementsByClassName('select', 'dropdown');
    var sValue;
    for (i = 0; i < aDropdowns.length; i++) {

        if (aDropdowns[i].options.length == 0) {
            sValue = 0;
        } else {
            sValue = dd.GetValue(aDropdowns[i].id);
            if (sValue == '') {
                sValue = dd.GetText(aDropdowns[i].id);
            }
        }
        sReturn += aDropdowns[i].id + '=' + sValue + '|';
    }


    //checkboxes
    var aCheckboxes = f.GetElementsByClassName('input', 'checkbox');
    for (i = 0; i < aCheckboxes.length; i++) {
        sReturn += aCheckboxes[i].id + '=' + f.GetObject(aCheckboxes[i].id).checked + '|';
    }

    //if we've got values passed in then replace existing shite and put ours on the end
    if (iPropertyID != undefined) {
        sReturn += 'PropertyID=' + iPropertyID + '|';
    }

    if (dArrivalDate != undefined) {
        sReturn += 'ArrivalDate=' + dArrivalDate.getDate() + '/' + (dArrivalDate.getMonth() + 1) + '/' +
	        dArrivalDate.getFullYear() + '|';
    }

    if (iDuration != undefined) {
        sReturn += 'Duration=' + iDuration + '|';
    }

    if (dDepartureDate != undefined) {
        sReturn += 'DepartureDate=' + dDepartureDate.getDate() + '/' + (dDepartureDate.getMonth() + 1) + '/' +
	        dDepartureDate.getFullYear() + '|';
    }

    sReturn += ('sddGeographyLevel1ID=' + f.GetValue('hidGeographyLevel1ID')) + '|';
    return sReturn;
}


function CalculateDepartureDate() {

    //determine the search mode
    var sMode = GetSearchMode();

    //check date isn't before today
    var oCalendar = new Calendar(null, 'calArrivalDate');
    var dToday = d.GetDateOnly(new Date());
    if (oCalendar.CurrentDate < dToday) {

        alert(sMode == 'FlightsPlusHotel' ? 'Please select a Departure Date today or later' : 'Please select an Arrival Date today or later');
        oCalendar.SetDate(d.Year(dToday), d.Month(dToday), d.Day(dToday));
    }

    var iDuration = parseInt(dd.GetText('ddlDuration'));

    if (isNaN(iDuration) == false) {

        var dDeparture = d.AddDays(oCalendar.CurrentDate, iDuration);

        oCalendarDepart = new Calendar(null, 'calDepartureDate');
        oCalendarDepart.SetDate(d.Year(dDeparture), d.Month(dDeparture), d.Day(dDeparture));
    }
}

function CalculateNewDuration() {

    //get old dates
    oCalendar = new Calendar(null, 'calArrivalDate');
    oCalendarDepart = new Calendar(null, 'calDepartureDate');
    var dArrival = oCalendar.CurrentDate;
    var dDeparture = oCalendarDepart.CurrentDate;

    //work out new duration
    var iDuration = d.DateDiff(dArrival, dDeparture) - 1;

    //check duration is >= 1 and end date ain't before start date
    var sWarning = '';
    if (iDuration < 0) {
        sWarning = 'You must select a Departure Date at least one date after the Arrival Date';
    } else if (iDuration > 29) {
        sWarning = 'The maximum number of nights you can book is 29';
    }

    if (sWarning == '') {
        dd.SetText('ddlDuration', iDuration);
    } else {

        //pop up a warning
        alert(sWarning);

        CalculateDepartureDate();
    }

}


function FlightReSearch(StartDate, EndDate) {

    var aStartDate = StartDate.split('/');
    oStartDate = new Calendar(null, 'calArrivalDate');
    oStartDate.SetDate(aStartDate[0], n.SafeInt(aStartDate[1]), n.SafeInt(aStartDate[2]));

    var aEndDate = EndDate.split('/');
    oEndDate = new Calendar(null, 'calDepartureDate');
    oEndDate.SetDate(aEndDate[0], n.SafeInt(aEndDate[1]), n.SafeInt(aEndDate[2]));

    Search();
}

function FlightAlternativeFlight(StartDate, Duration) {

    var aStartDate = StartDate.split('/');
    oStartDate = new Calendar(null, 'calArrivalDate');
    oStartDate.SetDate(aStartDate[0], n.SafeInt(aStartDate[1]), n.SafeInt(aStartDate[2]));

    dd.SetText('ddlDuration', Duration);
    CalculateDepartureDate();
    Search();

}


function NoFlightRowOver(oEvent) {
    var oRow = f.GetObjectFromEvent(oEvent).parentNode;
    f.SetClass(oRow, 'hover');
}

function NoFlightRowOut(oEvent) {
    var oRow = f.GetObjectFromEvent(oEvent).parentNode;
    f.SetClass(oRow, '');
}

function NoFlightSelect(oEvent) {
    var oRow = f.GetObjectFromEvent(oEvent).parentNode;
    var aBits = oRow.id.split('_');

    var sDate = s.Replace(aBits[1], '-', '/');
    var iDuration = aBits[2];

    FlightAlternativeFlight(sDate, iDuration);

}