var searchSvcURL = "/domaindata/CCLSearch.svc/GetSearchResultsAsync";
var favoritesSvcURL = "/BookingEngine/SailingSearch/GetFavorites";
var searchSvcRESTURL = "/BookingEngine/SailingSearch/Get";
var COOKIE_NAME = 'FAVSBSK';
var COptions = {
    path: '/',
    expires: 90
};
var FAVORITE_DELIM = "|";
var DATE_DELIM = "&";

function AddFavorite(sailingID, redraw, asSailDate)
{
    if (!asSailDate)
    {
        return;
    }
    var strCurrentValue = null;
    var lbIsCountLessThan21 = true;
    if (document.cookie.search(COOKIE_NAME) < 0)
    {
        $.cookie(COOKIE_NAME, "", COptions);
    }
    try
    {
        strCurrentValue = $.cookie(COOKIE_NAME);
    }
    catch (e)
    {}
    if (strCurrentValue != "" && strCurrentValue != null)
    {
        if (strCurrentValue.indexOf(sailingID) < 0)
        {
            var favs = strCurrentValue.split(FAVORITE_DELIM);
            lbIsCountLessThan21 = favs.length + 1 < 21;
            if (lbIsCountLessThan21)
            {
                var date = new Date(asSailDate);
                if (strCurrentValue != "")
                {
                    strCurrentValue += (FAVORITE_DELIM + sailingID + DATE_DELIM + date.toDateString());
                }
                else
                {
                    strCurrentValue = new String(sailingID + DATE_DELIM + date.toDateString());
                }
                $.cookie(COOKIE_NAME, strCurrentValue, COptions);
            }
            else
            {
                $("#removeFavsLink").trigger("click");
            }
        }
    }
    else
    {
        var date = new Date(asSailDate);
        if (strCurrentValue != "" && strCurrentValue != null)
        {
            strCurrentValue += (FAVORITE_DELIM + sailingID + DATE_DELIM + date.toDateString());
        }
        else
        {
            strCurrentValue = new String(sailingID + DATE_DELIM + date.toDateString());
        }
        $.cookie(COOKIE_NAME, strCurrentValue, COptions);
    }
    if (redraw && lbIsCountLessThan21)
    {
        GetFavorites(favoritesDone, failed)
    }
}

function FavoriteExists(sailingId)
{
    var returnVal = false;
    try
    {
        strCurrentValue = $.cookie(COOKIE_NAME);
    }
    catch (e)
    {}
    if (strCurrentValue != "" && strCurrentValue != null && strCurrentValue.indexOf(sailingId) >= 0)
    {
        returnVal = true;
    }
    return returnVal;
}

function RemoveFavorite(sailingID, redraw)
{
    if (document.cookie.search(COOKIE_NAME) > -1)
    {
        var strCurrentValue = $.cookie(COOKIE_NAME);
        var favorites = strCurrentValue.split(FAVORITE_DELIM);
        var newStrCookieValue;
        for (var i = 0; i < favorites.length; i++)
        {
            if (favorites[i].search(sailingID) >= 0) favorites.splice(i, 1);
        }
        newStrCookieValue = favorites.join(FAVORITE_DELIM);
        $.cookie(COOKIE_NAME, newStrCookieValue, COptions);
        UpdateFavoritesHeaderCount();
    }
    if (redraw) GetFavorites(favoritesDone, failed)
}

function RemoveFavs(removeArr, delCookie)
{
    for (var i = 0, len = removeArr.length; i < len; i++)
    {
        RemoveFavorite(removeArr[i], false);
    }
}

function UpdateFavorites(availableArr, aoSailingDates)
{
    $.cookie(COOKIE_NAME, null);
    for (var i = 0, len = availableArr.length; i < len; i++)
    {
        AddFavorite(availableArr[i], false, aoSailingDates[i]);
    }
}

function GetFavorites(callback, error)
{
    var url = favoritesSvcURL;
    $.ajax(
    {
        url: url,
        data: "",
        type: "GET",
        processData: true,
        contentType: "application/json",
        timeout: 30000,
        dataType: "json",
        success: callback,
        error: error
    });
}
var cache = new Array();

function CCLSailingSearchRequest()
{
    this.FromDate = null;
    this.ToDate = null;
    this.DestinationCodes = null;
    this.DurationCodes = null;
    this.PortCodes = null;
    this.IsOver55 = false;
    this.IsPastGuest = false;
    this.PageNumber = 1;
    this.PageSize = 5;
    this.SortExpression = "FromPrice";
    this.StateCode = null;
    this.ShipCodes = null;
    this.NumGuests = 2;
    this.AddShipCodes = function AddShipCodes(newShip)
    {
        if (this.ShipCodes != null) this.ShipCodes.push(newShip);
        else this.ShipCodes = new Array(newShip);
    };
    this.RemoveShipCodes = function RemoveShipCodes(removeShip)
    {
        if (jQuery.inArray(removeShip, this.ShipCodes) > -1)
        {
            var tempArr = new Array();
            jQuery.each(this.ShipCodes, function (i, val)
            {
                if (val != removeShip)
                {
                    tempArr.push(val);
                }
            });
            this.ShipCodes = tempArr;
        }
    };
    this.AddPortCode = function AddPortCode(newPortCode)
    {
        var tempArr = new Array();
        $("#departures input:checkbox").each(function ()
        {
            if ($(this).attr("checked"))
            {
                tempArr.push($(this).val());
            }
        });
        this.PortCodes = tempArr;
    };
    this.RemovePortCode = function RemovePortCode(removePortCode)
    {
        var tempArr = new Array();
        $("#departures input:checkbox").each(function ()
        {
            if ($(this).attr("checked"))
            {
                tempArr.push($(this).val());
            }
        });
        this.PortCodes = tempArr;
    };
    // updated use as template
    this.AddDurationCode = function AddDurationCode(newDurationCode)
    {
        var tempArr = new Array();
        $("#duration input:checkbox").each(function ()
        {
            if ($(this).attr("checked"))
            {
                tempArr.push($(this).val());
            }
        });
        this.DurationCodes = tempArr;
    };
    this.RemoveDurationCode = function RemoveDurationCode(removeDurationCode)
    {
        var tempArr = new Array();
        $("#duration input:checkbox").each(function ()
        {
            if ($(this).attr("checked"))
            {
                tempArr.push($(this).val());
            }
        });
        this.DurationCodes = tempArr;
    };
    this.AddDestinationCode = function AddDestinationCode(newDestinationCode)
    {
        var tempArr = new Array();
        $("#destinations input:checkbox").each(function ()
        {
            if ($(this).attr("checked"))
            {
                tempArr.push($(this).val());
            }
        });
        this.DestinationCodes = tempArr;
    };
    this.RemoveDestinationCode = function RemoveDestinationCode(removeDestinationCode)
    {
        var tempArr = new Array();
        $("#destinations input:checkbox").each(function ()
        {
            if ($(this).attr("checked"))
            {
                tempArr.push($(this).val());
            }
        });
        this.DestinationCodes = tempArr;
    };
    this.ToJSON = function ()
    {
        return JSON.stringify(this);
    };
    this.SearchAsync = function SearchAsync(callback, error, pageSize, pageNumber, sortExpression)
    {
        var url = searchSvcRESTURL;
        jQuery.query.SET('pageSize', (parseInt(pageSize) > 0) ? pageSize : 5);
        jQuery.query.SET('pageNumber', (parseInt(pageNumber) > 0) ? pageNumber : 1);
        var sortVal = sortExpression;
        if (sortExpression.length > 0)
        {
            sortVal = sortExpression;
        }
        else
        {
            tmp = $("#sel-sortby option:selected").val();
            sortVal = setSortExpression(tmp, "string");
        }
        jQuery.query.SET('sort', sortVal);
        var x = null;
        if (searchOptions.firstLoad)
        {
            x = jQuery.query.toString();
            //console.debug("first load %s  indexOf %d  %b", x, x.indexOf("?"), (x.indexOf("?")>-1));
            var discountObj = GetRateCriteriaCookie();
            if (discountObj)
            {
                if (x.toLowerCase().indexOf('senior') < 0 && discountObj.Senior)
                {
                    if (x.length > 0) x = x + "&Senior=" + discountObj.Senior;
                    else x = "Senior=" + discountObj.Senior;
                }
                if (x.toLowerCase().indexOf('pastguest') < 0 && discountObj.PastGuest)
                {
                    if (x.length > 0) x = x + "&PastGuest=" + discountObj.PastGuest;
                    else x = "PastGuest=" + discountObj.PastGuest;
                }
                if (x.toLowerCase().indexOf('statecode') < 0 && discountObj.StateCode)
                {
                    if (x.length > 0) x = x + "&StateCode=" + discountObj.StateCode;
                    else x = "StateCode=" + discountObj.StateCode;
                }
            }
            searchOptions.firstLoad = false;
        }
        else
        {
            x = buildNewUrl("");
        }
        if (x.indexOf("?") > -1) x = x.substring(1)
        //console.debug("query data %s", x);
        $.ajax(
        {
            url: url,
            data: x,
            type: "GET",
            processData: true,
            timeout: 30000,
            dataType: "json",
            success: callback,
            error: error
        });
    };
    this.Search = function Search(callback, error, pageSize, pageNumber, sortExpression)
    {
        var url = searchSvcURL;
        this.PageSize = pageSize;
        this.PageNumber = pageNumber;
        this.SortExpression = sortExpression;
        var x = this.ToJSON();
        x = "{\"request\":" + x + "}";
        $.ajax(
        {
            url: url,
            data: x,
            async: false,
            type: "POST",
            processData: true,
            contentType: "application/json",
            timeout: 10000,
            dataType: "json",
            success: callback,
            error: error
        });
    };
    this.SearchPrev = function SearchPrev(callback, error, cookieData)
    {
        callback = (callback) ? callback : done;
        error = (error) ? error : failed;
        var url = searchSvcURL;
        var strCurrentValue = cookieData;
        var preSearch = strCurrentValue.split(FAVORITE_DELIM);
    };
    this.SearchReset = function SearchReset()
    {
        this.DestinationCodes = null;
        this.DurationCodes = null;
        this.FromDate = null;
        this.IsOver55 = false;
        this.IsPastGuest = false;
        this.PageNumber = 1;
        this.PageSize = 5;
        this.PortCodes = null;
        this.SortExpression = "FromPrice";
        this.StateCode = null;
        this.ToDate = null;
        this.ShipCodes = null;
        RemoveRateCriteriaCookiePastGuest();
        RemoveRateCriteriaCookieSenior();
        SetRateCriteriaCookieState('st');
        location.search = "?src=ms"
    };
}
var sortVals = ["FromPrice", "FromPrice DESC", "DurationDays", "DeparturePortCode", "ItineraryCode", "FirstSailDate"]

function setSortExpression(value, type)
{
    var foundLoc = (parseInt(value) > -1) ? parseInt(value) : ((jQuery.inArray(value, sortVals) > -1) ? jQuery.inArray(value, sortVals) : 0);
    $("#sel-sortby option[value='" + foundLoc + "']").attr("selected", true);
    searchOptions.sortExpression = sortVals[foundLoc];
    return (type == "number") ? foundLoc : sortVals[foundLoc];
}
var destCodes = {
    "C": ",CW,CE,CS",
    "A": "A,AG,AN,AS",
    "M": "M,MB,MR",
    "V": "V,BM,CN"
};
var urlParams = ["embkcode: %o", "dest: %s", "dur: %s", "minDays: %s", "maxDays: %s", "startDate: %s", "endDate: %s", "Senior: %s", "PastGuest: %s", "StateCode: %s", "pageNum: %s", "sort: %s", "shipCode: %s", "items: %s", "cruiseMonth: %s"]; /* urlencode/decode */
$.extend(
{
    URLEncode: function (c)
    {
        var o = '';
        var x = 0;
        c = c.toString();
        var r = /(^[a-zA-Z0-9_.]*)/;
        while (x < c.length)
        {
            var m = r.exec(c.substr(x));
            if (m != null && m.length > 1 && m[1] != '')
            {
                o += m[1];
                x += m[1].length;
            }
            else
            {
                if (c[x] == ' ') o += '+';
                else
                {
                    var d = c.charCodeAt(x);
                    var h = d.toString(16);
                    o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
                }
                x++;
            }
        }
        return o;
    },
    URLDecode: function (s)
    {
        var o = s;
        var binVal, t;
        var r = /(%[^%]{2})/;
        while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '')
        {
            b = parseInt(m[1].substr(1), 16);
            t = String.fromCharCode(b);
            o = o.replace(m[1], t);
        }
        return o;
    }
});
