﻿// Cruise search helper scripts.
var IgluCruiseSearch =
{
    // Search webservice URL.
    SearchWSURL: '/Services/Search.asmx',

    //Is this an EmbeddedSearch? So we can refine the criteria...
    IsEmbeddedSearch: false,

    SearchTypeSuffix: '',

    // Cached Cruise/flight departure points.
    CruiseDepPointsGroup: null,
    FlyDepPointsGroup: null,

    // Search options from previous searches by this client.
    PreviousSearchOptions: null,

    getSearchControl: function (controlIndex) {
        return getElement(searchControlIds[controlIndex]);
    },

    createOption: function (value, text) {
        var newOption = document.createElement('option');
        newOption.setAttribute('value', value);
        newOption.innerHTML = text;
        return newOption;
    },

    createOptionGroup: function (label) {
        var newGroup = document.createElement('optgroup');
        newGroup.setAttribute('label', label);
        return newGroup;
    },

    bindList: function (select, group, groupIndex, list) {
        var insertSeperator;
        if (list.length > 1) {
            insertSeperator = list[1].IsTopItem;
        }
        for (var index = 0; index < list.length; index++) {
            var newOption = document.createElement('option');

            if (groupIndex == null)
                newOption.setAttribute('value', list[index].Value);
            else
                newOption.setAttribute('value', groupIndex + '#' + list[index].Value);

            newOption.innerHTML = list[index].Text;

            if (group == null) {
                if (insertSeperator && !list[index].IsTopItem && index > 1) {
                    var seperator = document.createElement('option');
                    seperator.innerHTML = '-------------------------';
                    seperator.setAttribute('value', '');
                    seperator.disabled = true;
                    select.appendChild(seperator);
                    insertSeperator = false;
                }
                select.appendChild(newOption);
            }
            else
                group.appendChild(newOption);
        }
    },

    //Retrieve saved session search criterion, to keep the user's selections in the form.
    getPreviousSearchOptions: function () {
        searchCallWebService(IgluCruiseSearch.SearchWSURL, "GetPreviousSearchOptions", "{isEmbedded: '" + this.IsEmbeddedSearch.toString() + "'}", function (result) {
            IgluCruiseSearch.PreviousSearchOptions = result.d;
        })
    },

    /*Populate all the Destinations*/
    populateDestinations: function () {
        var ddlDestination = IgluCruiseSearch.getSearchControl('Destination');
        ddlDestination.disabled = true;

        var create = function (result) {
            //Clear it out, and re-bind
            emptyNode(ddlDestination);
            IgluCruiseSearch.bindList(ddlDestination, null, null, result);

            //Set the Previously selected Destination.
            if (IgluCruiseSearch.PreviousSearchOptions != null)
                if (IgluCruiseSearch.PreviousSearchOptions.SelectedDestination != null)
                    ddlDestination.value = IgluCruiseSearch.PreviousSearchOptions.SelectedDestination;

            ddlDestination.disabled = false;
        };

        searchCallWebService(IgluCruiseSearch.SearchWSURL, 'GetDestinations' + IgluCruiseSearch.SearchTypeSuffix, null, function (result) { if (result != null) create(result.d) });
    },

    /*Populate all the Cruise Types*/
    populateCruiseTypes: function () {
        var ddlCruiseType = IgluCruiseSearch.getSearchControl('CruiseType');
        ddlCruiseType.disabled = true;

        var create = function (result) {
            //Clear it out, and re-bind
            emptyNode(ddlCruiseType);
            IgluCruiseSearch.bindList(ddlCruiseType, null, null, result);

            //Set the Previously selected cruise type
            if (IgluCruiseSearch.PreviousSearchOptions.SelectedCruiseType != null)
                ddlCruiseType.value = IgluCruiseSearch.PreviousSearchOptions.SelectedCruiseType;

            ddlCruiseType.disabled = false;

            // call the method to check cruise type changes, it's lightweight and should fail gracefully ifdep points aren't yet popuplated.
            CruiseTypeIndexChanged();
        };
        searchCallWebService(IgluCruiseSearch.SearchWSURL, 'GetCruiseTypes' + IgluCruiseSearch.SearchTypeSuffix, null, function (result) { create(result.d) });
    },

    /*Populate all the Cabin MetaData Types*/
    populateCabinMetaTypes: function () {
        var ddlCabinMetaType = IgluCruiseSearch.getSearchControl('CabinType');

        // The dropdown may not be present, depending on which control is using this script. check first.
        if (ddlCabinMetaType != null) {
            ddlCabinMetaType.disabled = true;
            searchCallWebService(IgluCruiseSearch.SearchWSURL, 'GetCabinMetaTypes' + IgluCruiseSearch.SearchTypeSuffix, null, function (result) { create(result.d) });
        }

        var create = function (result) {
            //Clear it out, and re-bind
            emptyNode(ddlCabinMetaType);
            IgluCruiseSearch.bindList(ddlCabinMetaType, null, null, result);

            if (IgluCruiseSearch.PreviousSearchOptions.SelectedCabinType != null) {
                ddlCabinMetaType.value = IgluCruiseSearch.PreviousSearchOptions.SelectedCabinType;
                if (ddlCabinMetaType.value == 5)
                    $('.chkSingleCss').attr('checked', true);
                else
                    $('.chkSingleCss').attr('checked', false);
            }

            ddlCabinMetaType.disabled = false;
        };

    },

    /*Populate all the departure Points*/
    populateDepPoints: function () {
        var ddlDepPoints = IgluCruiseSearch.getSearchControl('DepartFrom');
        ddlDepPoints.disabled = true;

        emptyNode(ddlDepPoints);
        ddlDepPoints.appendChild(IgluCruiseSearch.createOption('', 'Any Departure Point'));

        //Create & Add the Cruise From/Fly from groups to the option
        var CruiseFrom = this.createOptionGroup('Cruise From:');
        var FlyFrom = this.createOptionGroup('Fly From:');
        ddlDepPoints.appendChild(CruiseFrom);
        ddlDepPoints.appendChild(FlyFrom);

        var create = function (group, groupIndex, result, saveList) {
            //Clear it out, and re-bind
            IgluCruiseSearch.bindList(ddlDepPoints, group, groupIndex, result);
            ddlDepPoints.disabled = false;
            // call the method to check cruise type changes, it's lightweight, and saves us replicating logic.
            CruiseTypeIndexChanged();

            //Mark the previously selected departure point.
            if (IgluCruiseSearch.PreviousSearchOptions.SelectedDepartFrom != null) {
                // ie6
                try {
                    $(ddlDepPoints).val(IgluCruiseSearch.PreviousSearchOptions.SelectedDepartFrom);
                } catch (ex) {
                    setTimeout("$('" + ddlDepPoints + "').val('" + IgluCruiseSearch.PreviousSearchOptions.SelectedDepartFrom + "')", 1);
                }
            }
        };
        searchCallWebService(IgluCruiseSearch.SearchWSURL, 'GetSeaDepartureStations', null, function (result) { create(CruiseFrom, 0, result.d); IgluCruiseSearch.CruiseDepPointsGroup = CruiseFrom; });
        searchCallWebService(IgluCruiseSearch.SearchWSURL, 'GetAirDepartureStations' + IgluCruiseSearch.SearchTypeSuffix, null, function (result) { create(FlyFrom, 1, result.d); IgluCruiseSearch.FlyDepPointsGroup = FlyFrom; });
    },

    /*Populate all the CruiseLines */
    populateCruiseLines: function () {
        var ddlCruiseLines = IgluCruiseSearch.getSearchControl('CruiseLine');
        ddlCruiseLines.disabled = true;

        var create = function (result) {
            //Clear it out, and re-bind
            emptyNode(ddlCruiseLines);
            IgluCruiseSearch.bindList(ddlCruiseLines, null, null, result);

            //Set the previously selected cabin metatype
            if (IgluCruiseSearch.PreviousSearchOptions != null)
                if (IgluCruiseSearch.PreviousSearchOptions.SelectedCruiseLine != null)
                    ddlCruiseLines.value = IgluCruiseSearch.PreviousSearchOptions.SelectedCruiseLine;

            ddlCruiseLines.disabled = false;
        };
        searchCallWebService(IgluCruiseSearch.SearchWSURL, 'GetCruiseLines' + IgluCruiseSearch.SearchTypeSuffix, null, function (result) { if (result != null) create(result.d) });
    },

    /*Populate all the CruiseShips (or just the ones for the previously selected cruise line. */
    populateShips: function () {
        var ddlShips = IgluCruiseSearch.getSearchControl('Ship');
        ddlShips.disabled = true;

        var create = function (result) {
            //Clear it out, and re-bind
            emptyNode(ddlShips);
            IgluCruiseSearch.bindList(ddlShips, null, null, result);

            //Set the previously selected cabin metatype
            if (IgluCruiseSearch.PreviousSearchOptions != null)
                if (IgluCruiseSearch.PreviousSearchOptions.SelectedShip != null)
                    ddlShips.value = IgluCruiseSearch.PreviousSearchOptions.SelectedShip;

            ddlShips.disabled = false;
        };

        if (IgluCruiseSearch.PreviousSearchOptions == null || IgluCruiseSearch.PreviousSearchOptions.SelectedCruiseLine == null) {
            searchCallWebService(IgluCruiseSearch.SearchWSURL, 'GetShips' + IgluCruiseSearch.SearchTypeSuffix, null, function (result) { create(result.d) });
        }
        else {
            var Calldata = "{'supplierCode':'" + IgluCruiseSearch.PreviousSearchOptions.SelectedCruiseLine + "'}";
            searchCallWebService(IgluCruiseSearch.SearchWSURL, 'GetShipsByCruiselineCode' + IgluCruiseSearch.SearchTypeSuffix, Calldata, function (result) { create(result.d) });
        }
    },

    /*Populate all the CruiseShips (or just the ones for the previously selected cruise line. */
    populateDates: function () {
        var ddlDay = IgluCruiseSearch.getSearchControl('Day');
        var ddlMonth = IgluCruiseSearch.getSearchControl('Month');

        if (ddlDay == null && ddlMonth == null) {
            //Do we have the text version?
            var txtDate = IgluCruiseSearch.getSearchControl('LeavingDate');
            if (txtDate != null && IgluCruiseSearch.PreviousSearchOptions.SelectedDate != null)
                $find('txtStartDate').set_Text(IgluCruiseSearch.PreviousSearchOptions.SelectedDate);

            return;
        }

        //If we are an embedded search, we need to be a bit more strict with the dates that we bind...
        if (this.IsEmbeddedSearch) {
            var createEmbeddedDates = function () {
                emptyNode(ddlDay);
                ddlDay.appendChild(IgluCruiseSearch.createOption("", "Any Day"));

                //If the month selected is Any, then just bind 1 to 31 to the Day List
                if ($(this).val() == '' && ddlMonth.options.length > 2) {
                    for (var i = 1; i <= 31; i++)
                        ddlDay.appendChild(IgluCruiseSearch.createOption(i, i));
                }
                else {
                    //Otherwise, let's work out how many days we have selected inside this month. For example, in an EmbeddedSearch
                    //it may run across two months, but starting on the 10th of Jan and ending on the 23rd of March. So we need to ensure
                    //that when they are in Jan, they can only see 10th -> 31st and when they are in March, that they can see from the 1st -> 23rd.
                    var startIndex = 1, endIndex = 31;

                    //Do we even have any Date Criteria for this Embedded
                    if (minDate != null && maxDate != null) {
                        //Is the start and end of this embedded search one month? I.e. Only January?
                        if (minDate.getMonth() == maxDate.getMonth() && minDate.getYear() == maxDate.getYear()) {
                            //Set the Max and Min date for the single month
                            startIndex = minDate.getDate();
                            endIndex = maxDate.getDate();
                        }
                        //Or, have we selected the first month of the criteria? So we should only bind days from the start...
                        else if ($(this).val() == minDate.getMonth() + '/' + minDate.getFullYear())
                            startIndex = minDate.getDate();
                        //Or, have we selected the last month of the criteria? So we should only bind days upto the end...
                        else if ($(this).val() == maxDate.getMonth() + '/' + maxDate.getFullYear())
                            endIndex = maxDate.getDate();
                    }

                    //Loop through the Start and End index that we have sleected and bind that to the DropDownList
                    for (var i = startIndex; i <= endIndex; i++)
                        ddlDay.appendChild(IgluCruiseSearch.createOption(i, i));
                }
            };

            //When they change the month, we need to check to make sure we bind the correct days to the DropDownList
            $(ddlMonth).change(function () {
                createEmbeddedDates();
            });

            createEmbeddedDates();
        }

        ddlDay.disabled = false;

        searchCallWebService(IgluCruiseSearch.SearchWSURL, 'CruiseMonths' + IgluCruiseSearch.SearchTypeSuffix, null, function (result) { if (result != null) create(result.d) });

        var create = function (result) {
            ddlMonth.disabled = false;
            //Clear it out, and re-bind
            emptyNode(ddlMonth);
            IgluCruiseSearch.bindList(ddlMonth, null, null, result);

            if (IgluCruiseSearch.PreviousSearchOptions != null)
                if (IgluCruiseSearch.PreviousSearchOptions.SelectedMonth != null) {
                    try {
                        $(ddlMonth).val(IgluCruiseSearch.PreviousSearchOptions.SelectedMonth);
                    } catch (ex) {
                        setTimeout("$('" + ddlMonth + "').val('" + IgluCruiseSearch.PreviousSearchOptions.SelectedMonth + "')", 1);
                    }
                }

            ddlMonth.disabled = false;

            var selectedDay = 0;

            if (IgluCruiseSearch.PreviousSearchOptions != null) {
                if (IgluCruiseSearch.PreviousSearchOptions.SelectedDay != null) {
                    selectedDay = IgluCruiseSearch.PreviousSearchOptions.SelectedDay;
                }
            }
            bindDayDropDown(selectedDay);
        };
    },

    populateStarRating: function () {
        var starRating = IgluCruiseSearch.getSearchControl('StarRating');

        if (starRating != null && IgluCruiseSearch.PreviousSearchOptions != null && IgluCruiseSearch.PreviousSearchOptions.SelectedRating != null) {
            try {
                $(starRating).val(IgluCruiseSearch.PreviousSearchOptions.SelectedRating);
            } catch (ex) {
                setTimeout("$('" + starRating + "').val('" + IgluCruiseSearch.PreviousSearchOptions.SelectedRating + "')", 1);
            }
        }
    },

    populatePriceRange: function () {
        var priceRange = IgluCruiseSearch.getSearchControl('PriceRange');

        if (priceRange != null && IgluCruiseSearch.PreviousSearchOptions != null && IgluCruiseSearch.PreviousSearchOptions.SelectedPriceRange != null) {
            try {
                $(priceRange).val(IgluCruiseSearch.PreviousSearchOptions.SelectedPriceRange);
            } catch (ex) {
                setTimeout("$('" + priceRange + "').val('" + IgluCruiseSearch.PreviousSearchOptions.SelectedPriceRange + "')", 1);
            }
        }
    },

    bindDuration: function () {
        var ddlDuration = IgluCruiseSearch.getSearchControl('Duration');

        if (IgluCruiseSearch.PreviousSearchOptions.SelectedDuration != null) {
            if (IgluCruiseSearch.IsEmbeddedSearch) {
                if (IgluCruiseSearch.PreviousSearchOptions.SelectedDuration != '0,9999') {
                    $(ddlDuration).find('option[value!="' + IgluCruiseSearch.PreviousSearchOptions.SelectedDuration + '"]').remove();
                }
            }
            try {
                $(ddlDuration).val(IgluCruiseSearch.PreviousSearchOptions.SelectedDuration);
            } catch (ex) {
                setTimeout("$('" + priceRange + "').val('" + IgluCruiseSearch.PreviousSearchOptions.SelectedPriceRange + "')", 1);
            }
        }
    },

    bindFlex: function () {
        var ddlFlex = IgluCruiseSearch.getSearchControl('Flexibility');

        if (IgluCruiseSearch.PreviousSearchOptions.SelectedFlex != null) {
            try {
                $(ddlFlex).val(IgluCruiseSearch.PreviousSearchOptions.SelectedFlex);
            } catch (ex) {
                setTimeout("$('" + ddlFlex + "').val('" + IgluCruiseSearch.PreviousSearchOptions.SelectedFlex + "')", 1);
            }
        }
    },

    bindIncludePorts: function () {
        var txtIncludePorts = IgluCruiseSearch.getSearchControl('IncludePorts');
        if (txtIncludePorts != null && IgluCruiseSearch.PreviousSearchOptions.IncludePorts != null) {
            $find("bhvPorts").set_Text(IgluCruiseSearch.PreviousSearchOptions.IncludePorts);
        }
    },

    bindSort: function () {
        var hdnSort = IgluCruiseSearch.getSearchControl('SortOrder');
        if (hdnSort != null && IgluCruiseSearch.PreviousSearchOptions.SortOrder != null)
            try {
                $(hdnSort).val(IgluCruiseSearch.PreviousSearchOptions.SortOrder);
            } catch (ex) {
                setTimeout("$('" + hdnSort + "').val('" + IgluCruiseSearch.PreviousSearchOptions.SortOrder + "')", 1);
            }
    },

    SingleCabin: function (checked) {
        if (checked) {
            $('.cabinTypeCss').val(5)
    
        }
        else {
            $('.cabinTypeCss').val(0);
    
        }
    },

    MultipleCabins: function (checked) {
        if (checked) {
    
            $('.chkSingleCss').attr('checked', true);
        }
        else {    
            $('.chkSingleCss').attr('checked', false);
        }
    }
};



function miniSearchStartUp()
{
    IgluCruiseSearch.populateDestinations();
    IgluCruiseSearch.populateCruiseLines();
    IgluCruiseSearch.populateShips();
    IgluCruiseSearch.populateDates();
}

////Start up, this will initialise the form, hiding/showing everything that is required
function searchStartUp(isEmbedded) {
    //Is this for an EmbeddedSearch?
    if (typeof isEmbedded == "boolean" && isEmbedded) {
        IgluCruiseSearch.IsEmbeddedSearch = isEmbedded;
        IgluCruiseSearch.SearchTypeSuffix = '_Embedded';
    } else {
        IgluCruiseSearch.IsEmbeddedSearch = false;
    }

    IgluCruiseSearch.getPreviousSearchOptions();

    //Wait until we have the Search Options back...
    var interval = setInterval(function() {
        if (IgluCruiseSearch.PreviousSearchOptions != null) {
            //We have our Search options, kill the interval
            clearInterval(interval);

            //Bind the required fields...
            IgluCruiseSearch.populateDestinations();
            IgluCruiseSearch.populateCruiseTypes();
            IgluCruiseSearch.populateCabinMetaTypes();
            IgluCruiseSearch.populateDepPoints();
            IgluCruiseSearch.populateCruiseLines();
            IgluCruiseSearch.populateShips();
            IgluCruiseSearch.populateDates();
            IgluCruiseSearch.populatePriceRange();
            IgluCruiseSearch.populateStarRating();
            IgluCruiseSearch.bindDuration();
            IgluCruiseSearch.bindFlex();
            IgluCruiseSearch.bindIncludePorts();
            IgluCruiseSearch.bindSort();
        }
    }, 10);
};

// Show/Hide appropriate groups (sea/air departures) in the departure points select, based on the selected cruisetype.
function CruiseTypeIndexChanged (){
    var ddlCruiseType = IgluCruiseSearch.getSearchControl('CruiseType');
    var ddlDepPoints = IgluCruiseSearch.getSearchControl('DepartFrom');
    
    var optionGroups = ddlDepPoints.getElementsByTagName("optGroup");

    if (IgluCruiseSearch.CruiseDepPointsGroup != null && IgluCruiseSearch.FlyDepPointsGroup != null) {
        
        emptyNode(ddlDepPoints);
        ddlDepPoints.appendChild(IgluCruiseSearch.createOption('', 'Any Departure Point'));

        switch ($(ddlCruiseType).val()) {
            case "":
                ddlDepPoints.appendChild(IgluCruiseSearch.CruiseDepPointsGroup);
                ddlDepPoints.appendChild(IgluCruiseSearch.FlyDepPointsGroup);
                break;
            case "CRO":
                ddlDepPoints.appendChild(IgluCruiseSearch.CruiseDepPointsGroup);
                break;
            case "CRS":
            case "FCR":
            case "SCR":
                ddlDepPoints.appendChild(IgluCruiseSearch.FlyDepPointsGroup);
                break;
            default:
                ddlDepPoints.appendChild(IgluCruiseSearch.CruiseDepPointsGroup);
                ddlDepPoints.appendChild(IgluCruiseSearch.FlyDepPointsGroup);
                break;
        }
    }
    // Reset the departure point selection.
    ddlDepPoints.selectedIndex = 0;
}

function CruiseLineChanged() {
    var ddlCruiseLine = IgluCruiseSearch.getSearchControl('CruiseLine');
    var ddlCruiseShip = IgluCruiseSearch.getSearchControl('Ship');

    var bindShips = function(result) {
        //Clear it out, and re-bind
        ddlCruiseShip.disabled = true;
        emptyNode(ddlCruiseShip);
        IgluCruiseSearch.bindList(ddlCruiseShip, null, null, result);
        ddlCruiseShip.disabled = false;
    }

    if($(ddlCruiseLine).val() == "") {
        searchCallWebService(IgluCruiseSearch.SearchWSURL, 'GetShips' + IgluCruiseSearch.SearchTypeSuffix,null, function(result) { bindShips(result.d) });
    } else {
        var Calldata = "{'supplierCode':'" + $(ddlCruiseLine).val() + "', isEmbedded: '" + IgluCruiseSearch.IsEmbeddedSearch.toString() + "'}";
        searchCallWebService(IgluCruiseSearch.SearchWSURL, 'GetShipsByCruiselineCode',Calldata , function(result) { bindShips(result.d) });
    }
}

// Triggered when the user selects a cruiseship - Set the cruise line dropdown to select that ship's supplier.
function CruiseShipChanged()
{
    if (!IgluCruiseSearch.IsEmbeddedSearch)
    {
        var ddlCruiseLine = IgluCruiseSearch.getSearchControl('CruiseLine');
        var ddlCruiseShip = IgluCruiseSearch.getSearchControl('Ship');

        var ChangeLine = function(result)
        {
            ddlCruiseLine.disabled = true;
            $(ddlCruiseLine).val(result);
            ddlCruiseLine.disabled = false;
        }

        if ($(ddlCruiseShip).val() != "")
        {
            var Calldata = "{ 'shipId':" + $(ddlCruiseShip).val() + ", isEmbedded: '" + IgluCruiseSearch.IsEmbeddedSearch.toString() + "'}";
            searchCallWebService(IgluCruiseSearch.SearchWSURL, 'GetCruiseLineCodeByShipId', Calldata, function(result) { ChangeLine(result.d) });
        }
    }
}

//triggered when a user selects a cruise ship in admin
function AdminCruiseShipchanged() 
{    
    if (!IgluCruiseSearch.IsEmbeddedSearch) {
        var lblCruiseLine = IgluCruiseSearch.getSearchControl('CruiseLine');
        var ddlCruiseShip = IgluCruiseSearch.getSearchControl('Ship');

        var ChangeLine = function(result) 
        {
            lblCruiseLine.disabled = true;
            $(lblCruiseLine).text(result);
            lblCruiseLine.disabled = false;
        }
        
       
        if ($(ddlCruiseShip).val() != "") {
            var Calldata = "{ 'shipId':" + $(ddlCruiseShip).val() + ", isEmbedded: '" + IgluCruiseSearch.IsEmbeddedSearch.toString() + "'}";
            searchCallWebService(IgluCruiseSearch.SearchWSURL, 'GetCruiseLineNameByShipId', Calldata, function(result) { ChangeLine(result.d) });
        }
    }
}

// Set the date dropdowns according to the datepicker.
function dateSelected(value, instance) 
{
    var ddlDays = IgluCruiseSearch.getSearchControl('Day');
    var ddlMonth = IgluCruiseSearch.getSearchControl('Month');
    var selectedDate = new Date(Date.parse(value));
    
    var monthString = String(selectedDate.getMonth() + 1);
        
    //Zero-pad the month, if necessary.
    if (monthString.length == 1) {
        monthString = "0" + monthString;
    }

    monthString += "/" + String(selectedDate.getFullYear());
    $(ddlMonth).val(monthString);

    if (instance.currentDay != 0)
        $(ddlDays).val(selectedDate.getDate());
    else
        $(ddlDays).val("");
}

//Get an Element in the Document, based on it's ID. Shorthand for document.getElementById(controlId)
function getElement(controlId) {
    return document.getElementById(controlId);
}

function emptyNode(el) {
        while (el.hasChildNodes())
            el.removeChild(el.firstChild);
}

// Call a .net webservice.
function searchCallWebService(webServiceUrl, webMethodName, data, delegateFunction) {    
    var url = webServiceUrl + "/" + webMethodName;
    
    if(data == null || data.length == 0)
    {
        data = '{}';
    }

    var runningRequest = $.ajax({
        type: "POST",
        url: url,
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: delegateFunction,
        error: function(error) {
            if (error.status == 200 ||
                error.status == 12030 ||
                error.status == 12031) 
            {
                searchCallWebService(webServiceUrl, webMethodName, data, delegateFunction);
            }
            else {
                alert("There was an error processing your request.\n"
                    + "[" + error.status + "]"
                    + " [" + error.statusText + "]");
            }
        }
    });
    $(window).bind("beforeunload", function() {
        runningRequest.abort();
    });
}

function trim(targetString)
{
    return targetString.replace(/^\s+|\s+$/g, '');
}

function monthSelectChanged() {
    var ddlDays = IgluCruiseSearch.getSearchControl('Day');
    bindDayDropDown($(ddlDays).val());
}

function validateDateDropdowns() {
    var ddlDays = IgluCruiseSearch.getSearchControl('Day');
    var ddlMonth = IgluCruiseSearch.getSearchControl('Month');

    if($(ddlMonth).val().split("/").length == 2 && $(ddlDays).val() != "Any")
    {
        try {
            var resultDate = $.datepicker.parseDate("d/mm/yy", $(ddlDays).val() + "/" + $(ddlMonth).val());
        } catch (err) {
            var resultMonth = $(ddlMonth).val().split("/")[0];
            var resultYear = $(ddlMonth).val().split("/")[1];
            var numDaysInMonth = 32 - new Date(parseInt(resultYear,10), parseInt(resultMonth,10) - 1, 32).getDate();

            try {
                $(ddlDays).val(numDaysInMonth);
            } catch (err2) {
                setTimeout("$('" + ddlDays + "').val('" + numDaysInMonth + "')", 1);
            }
        }
    }
}

function bindDayDropDown(targetIndex) {
    var ddlDay = IgluCruiseSearch.getSearchControl('Day');
    var ddlMonth = IgluCruiseSearch.getSearchControl('Month');

    ddlDay.disabled = true;
    emptyNode(ddlDay)
    ddlDay.appendChild(IgluCruiseSearch.createOption("Any", "Any Day"));

    if ($(ddlMonth).val().split("/").length == 2) {
        var resultMonth = $(ddlMonth).val().split("/")[0];
        var resultYear = $(ddlMonth).val().split("/")[1];
        var actualTargetDate = new Date(parseInt(resultYear,10), parseInt(resultMonth,10) - 1, 32);
        var numDaysInMonth = 32 - actualTargetDate.getDate();
        if (!isNaN(targetIndex)) {
            targetIndex = Math.min(numDaysInMonth, targetIndex);
        }
        
        for (var i = 1; i <= numDaysInMonth; i++)
            ddlDay.appendChild(IgluCruiseSearch.createOption(i, i));
    } else {
        // it's probably the "Any" option, just bind to 31.
        for (var i = 1; i <= 31; i++) {
            ddlDay.appendChild(IgluCruiseSearch.createOption(i, i));
        }
    }

    if (!isNaN(targetIndex)) {
        // ie6
        try {
            $(ddlDay).val(targetIndex);
        } catch (ex) {
            setTimeout("$('" + ddlDay + "').val('" + targetIndex + "')", 1);
        }
    }
    ddlDay.disabled = false;
}

//kicks off a search using the enter key
function searchPostBack(e, buttonToClick) { if (e.keyCode == 13) $get(buttonToClick).click(); }

function resetFields() {
    //rest controls

    $('select[id$="ddlDestination"] option:first').attr("selected", "selected");
    $('select[id$="ddlCruiseLine"] option:first').attr("selected", "selected");
    $('select[id$="ddlShip"] option:first').attr("selected", "selected");
    // rebuild the ship list
    IgluCruiseSearch.PreviousSearchOptions.SelectedCruiseLine = null;
    IgluCruiseSearch.PreviousSearchOptions.SelectedShip = null;
    IgluCruiseSearch.populateShips();
    $('select[id$="ddlCruiseType"] option:first').attr("selected", "selected");
    $('select[id$="ddlDay"] option:first').attr("selected", "selected");
    $('select[id$="ddlMonth"] option:first').attr("selected", "selected");
    $('select[id$="ddlFlex"] option:first').attr("selected", "selected");
    $('select[id$="ddlDuration"] option:first').attr("selected", "selected");
    $('select[id$="ddlDepartFrom"] option:first').attr("selected", "selected");
    $('select[id$="ddlCabinType"] option:first').attr("selected", "selected");
    
    //on refine page only
    if ($('input[id$="txtPorts"]').length > 0) {
        $('input[id$="txtPorts"]').val('');
        $find("bhvPorts")._onBlur();
    }
    $('select[id$="ddlStarRating"] option:first').attr("selected", "selected");
    $('select[id$="ddlPrice"] option:first').attr("selected", "selected");
    $('select[id$="ddlSortOrder"] option:first').attr("selected", "selected");

    //reset the search in session
    searchCallWebService('/Services/Search.asmx', 'SearchObjectReset', '', null)
}

function sendEnquiry() {
    var name = $('#txtEnquiryName').val();
    var PhoneNum = $('#txtEnquiryNumber').val();
    var MobileNum = $('#txtMobileNumber').val();
    var Email = $('#txtEnquiryEmail').val();
    var Desc = $('#txtEnquiryDescription').val();

    // must have name, phone number or email address, and ideal cruise
    if (name == '' || name == 'Your Name - required') {
        if ((PhoneNum == '' || PhoneNum == 'Phone No (inc area code)') && ( Email == '' || Email == 'Your Email Address')) {
            if (Desc == '' || Desc == 'Please include the Ship and Sailing Date - required') {
                alert('Your name, phone number or email address, and ideal cruise is required');
                $('.spnRequired').show();
                return;
            }
            alert('Your name, phone number or email address is required');
            $('#spnRequiredName').show();
            $('#spnRequiredNumber').show();
            $('#spnRequiredEmail').show();
            return;
        }
        alert('Your name is required');
        $('#spnRequiredName').show();
        return;
    }
    else if ((PhoneNum == '' || PhoneNum == 'Phone No (inc area code)') && ( Email == '' || Email == 'Your Email Address')) {
        if (Desc == '' || Desc == 'Please include the Ship and Sailing Date - required') {
            alert('Your phone number or email address, and ideal cruise is required');
            $('#spnRequiredNumber').show();
            $('#spnRequiredEmail').show();
            $('#spnRequiredDesc').show();
            return;
        }
        alert('Your phone number or email address is required');
        $('#spnRequiredNumber').show();
        $('#spnRequiredEmail').show();
        return;
    }
    else if (Desc == '' || Desc == 'Please include the Ship and Sailing Date - required') {
        alert('Your ideal cruise is required');
        $('#spnRequiredDesc').show();
        return;
    }

    // use regex to test for valid email address
    var regex = /(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3})/;
    if (!regex.test(Email)) {
        alert('Please enter a valid email address.');
        return;
    }

    // initiate loading gif
    $('#divLoading').fadeIn(200);

    // everything is a-ok so call the webservice
    setTimeout(function () {
        searchCallWebService(
            '/Services/Search.asmx',
            'SendEnquiry',
            JSON.stringify({ 'Name': name, 'Email': Email, 'Number': PhoneNum, 'MobileNumber': MobileNum, 'EnquiryDesc': Desc }),
            function (result) {
                $('#divLoading').fadeOut(500, function () {
                    $('#divEnquiry').slideUp(500, function () {
                        $('#divEnquiryReceived').slideDown(200);
                    });
                });
            });
    }, 500);
}

function waterMark(textBoxId, cssWMClass, text) {
    var txtBox = $('#' + textBoxId);

    txtBox.addClass(cssWMClass).val(text);

    // Remove the water mark if there is text in the textbox
    txtBox.focus(function () {
        $(this).filter(function () {
            return $(this).val() == '' || $(this).val() == text;
        }).removeClass(cssWMClass).val('');
    });
    // Apply water mark if there is no text in the textbox
    txtBox.blur(function () {
        $(this).filter(function () {
            return $(this).val() == '';
        }).addClass(cssWMClass).val(text);
    });
}

