﻿var SearchWSURL = '/Services/Search.asmx';

function callWebService(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) {
            alert("There was an error processing your request.\n"
                    + "[" + error.status + "]"
                    + " [" + error.statusText + "]");
        }
    });
    $(window).bind("beforeunload", function() {
        runningRequest.abort();
    });
}

function cruiselineSelectedIndexChanged() {
    if ($get(ddlCruiseline).value == '') {
        callWebService(SearchWSURL, 'GetShips', "{ isEmbedded: 'false'}", getShips_Callback);
    }
    else {
        var Calldata = "{'supplierCode':'" + $get(ddlCruiseline).value + "', isEmbedded: 'false'}";
        callWebService(SearchWSURL, 'GetShipsByCruiselineCode', Calldata, getShips_Callback);
    }

    $get(ddlShip).disabled = true;
}

function getShips_Callback(result) {
    //Get access to the dropdown box
    var ships = $get(ddlShip);

    //Clear it out
    ships.options.length = 0;

    ships.options[0] = new Option('Select a Ship', '');

    //Loop through all the ones returned from the service except the 'Any Ships' one, adding them to the list
    for (var i = 1; i < result.d.length; i++) {
        //Add the Child to the List
        ships.options[i] = new Option(result.d[i].Text, result.d[i].Value);
    }

    ships.disabled = false;
}

function validateSearch() {
    var line = $get(ddlCruiseline);
    var ship = $get(ddlShip);
    var destination = $get(ddlDestination);

    if (destination.selectedIndex == 0 && ship.selectedIndex == 0) {
        if (line.selectedIndex != 0)
            alert('Please select a ship');
        else
            alert('Please select a destination or ship');
        return false;
    }
    else
        return true;
}
