
var departFromGlobalVals = [];
var destinationGlobalVals = [];
var durationGlobalVals = [];
var clickType; //0= reset;  1 = DepartFrom ; 2= Destination ; 3 = Duration
var initFlag;
var originalCall;

var monthGrouping = { "Fall": [9, 10, 11],
    "Winter": [12, 1, 2],
    "Spring": [3, 4, 5],
    "Summer": [6, 7, 8]
};

var destMap = { A: ["A", "AG", "AN", "AS"],
    M: ["M", "MB", "MR"],
    C: ["C", "CE", "CS", "CW"],
    V: ["BM", "CN"]
}

/*
function parseQuery(qs, options) {
var q = (typeof qs === 'string' ? qs : decodeURIComponent(window.location.search)), o = { 'f': function(v) {
return unescape(v).replace(/\+/g, ' ');
} 
}, options = (typeof qs === 'object' && typeof options === 'undefined') ? qs : options, o = jQuery.extend({}, o, options), params = {};
jQuery.each(q.match(/^\??(.*)$/)[1].split('&'), function(i, p) {
p = p.split('=');
p[1] = o.f(p[1]);
params[p[0]] = params[p[0]] ? ((params[p[0]] instanceof Array) ? (params[p[0]].push(p[1]), params[p[0]]) : [params[p[0]], p[1]]) : p[1];
});
return params;
}*/


function parseQuery(url) {

    var obj = {};

    obj.params = {};

    var temp = url.split("?");

    var path = temp[0];

    var paramsTemp = temp[1];

    if (paramsTemp) {

        obj["path"] = temp[0];

        paramsArr = paramsTemp.split("&");

        obj.params.length = paramsArr.length;

        var tempArr = null;

        for (var i = 0, len = paramsArr.length; i < len; i++) {

            tempArr = paramsArr[i].split("=");

            obj.params[tempArr[0]] = tempArr[1];

        }

    }

    return obj.params;



} // end urlToObj


function indexInArray(arr, val) {
    return $.inArray(val, arr);
}
function removeSplice(arr, val, index) {
    var tmp = new Array();
    var itm = arr[index];
    //console.debug("remove splice item %s  index %d  arr %o", itm, index, arr);
    if (index > -1) {
        arr[index] = arr[arr.length - 1];
        //console.debug("updated arr %o", arr);
        arr.pop();
        //console.debug("after pop arr %o len: %d", arr, arr.length);
        tmp = arr.sort();
    }
    else {
        tmp = arr;
    }
    return tmp;
}


var searchXmlObj = { deport: [], duration: [], dates: [], destination: [] };

function SearchFilter(failedFilter, x) {
    var url = "/BookingEngine/FindACruise/Get";


    if (x.length == 0) {

        var xArrObj = [];

        var dat = "";

        var dates = $("#ctl00_BodyContentPlaceHolder_seldates option:selected").val();
        if (dates != "") {
            dat = dates;
        }
        else {
            dat = "";
        }
        if (dat.length > 0) {
            xArrObj.push("dat=" + dat);
        }

        var dest = "";
        //console.debug("DestinationCodes %o", cclSailing.DestinationCodes);
        if (cclSailing.DestinationCodes != null && cclSailing.DestinationCodes.length > 0) {
            try {
                if (typeof cclSailing.DestinationCodes == "string") {
                    dest = cclSailing.DestinationCodes;
                }
                else {
                    dest = cclSailing.DestinationCodes.join(",");
                }

            } catch (e) { }

        }
        if (dest.length > 0) {
            xArrObj.push("dest=" + dest);
        }

        var dur = "";
        //console.debug("DurationCodes %o", cclSailing.DurationCodes);
        if (cclSailing.DurationCodes != null && cclSailing.DurationCodes.length > 0) {
            //console.debug("DurationCodes %o", cclSailing.DurationCodes);
            try {
                if (typeof cclSailing.DurationCodes == "string") {
                    dur = cclSailing.DurationCodes;
                }
                else {
                    dur = cclSailing.DurationCodes.join(",");
                }

            } catch (e) { }
        }
        if (dur.length > 0) {
            xArrObj.push("dur=" + dur);
        }

        var embkCode = "";
        //console.debug("PortCodes %o", cclSailing.PortCodes);
        if (cclSailing.PortCodes != null && cclSailing.PortCodes.length > 0) {
            try {
                if (typeof cclSailing.PortCodes == "string") {
                    embkCode = cclSailing.PortCodes;
                }
                else {
                    embkCode = cclSailing.PortCodes.join(",");
                }


            } catch (e) { /*alert("error"+e);*/ }
        }
        if (embkCode.length > 0) {
            xArrObj.push("embkCode=" + embkCode);
        }

        x = xArrObj.join("&");
        //console.debug("x update %s", x);
        //alert("findcruiseservice : "+x);
    }


    $.ajax({
        url: url,
        data: x,
        async: true,
        type: "GET",
        processData: true,
        contentType: "application/xml",
        timeout: 15000, dataType: "xml",
        error: failedFilter,
        success: function (xml) {

            //  var comStr = jQuery.queryStringParser(x)['embkCode'] + ',' + jQuery.queryStringParser(x)['dur'] + ',' + jQuery.queryStringParser(x)['dest'];

            var q = parseQuery(x);
            var comStr = q.embkCode + ',' + q.dur + ',' + q.dest;
            var today = false;

            //alert("search filter " +comStr);

            var arrQuery = comStr.split(",");
            searchXmlObj.deport = [];
            searchXmlObj.duration = [];
            searchXmlObj.dates = [];
            searchXmlObj.destination = [];


            var today = false;
            $(xml).find('today').each(function () {
                today = true;
            })

            if (today) {
                failedFilter();
                //return false;
                searchXmlObj.deport = (cclSailing.PortCodes != null) ? cclSailing.PortCodes : [];
                searchXmlObj.duration = (cclSailing.DurationCodes != null) ? cclSailing.DurationCodes : [];
                searchXmlObj.destination = (cclSailing.DestinationCodes != null) ? cclSailing.DestinationCodes : [];
                /*
                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;
                */
            }
            else {
                var valTemp = null;
                $(xml).find('i').each(function () {
                    //	console.debug("i", $(this).text());
                    valTemp = $(this).text();
                    if (valTemp.match(/[A-Z]{3}/)) {
                        searchXmlObj.deport.push(valTemp);
                    }
                    else if (valTemp.match(/\d{6}/)) {
                        searchXmlObj.dates.push(valTemp);
                    }
                    else if (valTemp.match(/D\d{1}/)) {
                        searchXmlObj.duration.push(valTemp);
                    }
                    else {
                        searchXmlObj.destination.push(valTemp);
                    }
                });

            }

            //console.debug("searchXmlObj %o  deport %o  duration %o", searchXmlObj, searchXmlObj.deport, searchXmlObj.duration);

            //console.debug("duration len %d", searchXmlObj.duration.length);

            $("#departures input:checkbox, #duration input:checkbox, #destinations input:checkbox").attr("disabled", "disabled").parent().addClass("disabled");

            if (searchXmlObj.deport.length > 0) {
                var deport = searchXmlObj.deport;
                //alert("departFromGlobalVals " + departFromGlobalVals);
                //console.debug("departObj %o departures %o", deport, $("#departures"));
                for (var i = 0, len = deport.length; i < len; i++) {
                    //console.debug("deport %s", deport[i]);
                    //alert("depart "+deport[i]);
                    var foundItem = $("#departures input[value='" + deport[i] + "']");
                    foundItem.removeAttr("disabled").parent().removeClass("disabled").prependTo($("#departfrom ul"));
                }
                $("#departures input:checked").parent().prependTo($("#departfrom ul"));

                // fix for ie6

                //alert("ie6 "+(jQuery.browser.msie && (parseInt(jQuery.browser.version, 10) == 6)));
                if (jQuery.browser.msie && (parseInt(jQuery.browser.version, 10) == 6)) {
                    $("#departures input").each(function () {
                        if ($(this).data("active")) {
                            //alert("departure active " + $(this).val());
                            $(this).parent().prependTo($("#departfrom ul"));
                            $(this).attr("checked", "checked");
                        }
                    });


                }

            }
            else if (today) {
                //console.debug("no departure ports");
                $("#departures input").removeAttr("checked", "checked").removeAttr("disabled").parent().removeClass("disabled");
            }

            if ($("#departures .disabled input:checked").attr("checked")) {
                $("#departures .disabled input:checked").removeAttr("disabled").parent().removeClass("disabled");
            }
            $("#departfrom .disabled").appendTo($("#other-ports ul"));
            $("#other-ports").hide();

            if (searchXmlObj.duration.length > 0) {
                var duration = searchXmlObj.duration;
                //console.debug("durationObj %o duration %o", duration, $("#duration"));
                for (var i = 0, len = duration.length; i < len; i++) {
                    var foundItem = $("#duration input[value='" + duration[i] + "']");
                    foundItem.removeAttr("disabled").parent().removeClass("disabled");
                }
            }
            else if (today) {
                //console.debug("no durations");
                $("#duration input").removeAttr("checked").removeAttr("disabled").parent().removeClass("disabled");
            }
            if ($("#duration .disabled input:checked").attr("checked")) {
                $("#duration .disabled input:checked").removeAttr("disabled").parent().removeClass("disabled");
            }



            if (searchXmlObj.destination.length > 0) {
                var destArr = searchXmlObj.destination;
                var destinations = $("#destinations");
                var tmpItm = null;
                destArr.sort();

                //console.debug("destObj %o  destArr %o", destinations, destArr);
                //alert("destinationGlobalVals " + destinationGlobalVals);
                // find all the sington values
                for (var i = 0, len = destArr.length; i < len; i++) {
                    //alert("destArr " + destArr[i] + "  found " +destinations.find("[value*='"+destArr[i]+"']"));
                    var foundItem = destinations.find("input[value*='" + destArr[i] + "']")
                    //console.debug("i: %d  len: %d  destArr %o \ndestArrItm %o item %o", i, len, destArr, destArr[i], foundItem);
                    //alert(i +" len: " + len + " destArr " + destArr[i] + " fouditem " + foundItem);
                    if (foundItem.length == 1) {

                        foundItem.removeAttr("disabled").parent().removeClass("disabled").prependTo($("#destination ul"));
                        destArr = removeSplice(destArr, destArr[i], i);
                        i = -1;
                        len = destArr.length;
                    }
                    else if (foundItem.length > 1) {
                        foundItem = destinations.find("input[value='" + destArr[i] + "']");
                        //console.debug("multiple found updating %o", foundItem);

                        foundItem.removeAttr("disabled").parent().removeClass("disabled").prependTo($("#destination ul"));
                        destArr = removeSplice(destArr, destArr[i], i);
                        i = -1;
                        len = destArr.length;
                    }

                }




            }
            else if (today) {
                //console.debug("no destinations");
                $("#destinations input").removeAttr("checked").removeAttr("disabled").parent().removeClass("disabled");
            }
            // has to be outside loop for when service doesnt return node and still checked
            $("#destinations input:checked").parent().prependTo($("#destination ul"));
            if ($("#destinations .disabled input:checked").attr("checked")) {
                $("#destinations .disabled input:checked").removeAttr("disabled").parent().removeClass("disabled");
            }
            $("#destination .disabled").appendTo($("#other-destinations ul"));
            $("#other-destinations").hide();
            if (jQuery.browser.msie && (parseInt(jQuery.browser.version, 10) == 6)) {
                $("#destination").find("input").each(function () {

                    if ($(this).data("active")) {
                        //alert("destination active " + $(this).val());
                        $(this).parent().prependTo($("#destination ul"));
                        $(this).attr("checked", "checked");

                    }
                });

                //var foundItem = $("#departures input[value='"+ports[i]+"']").attr("checked", "checked").removeAttr("disabled").parent().removeClass("disabled").prependTo($("#departfrom ul"));


            }
        }
    });

}


function failedFilter() {
    //alert("A Call to the Server failed in the left filter");

    $("#departures input:checkbox, #duration input:checkbox, #destinations input:checkbox").removeAttr("disabled").parent().removeClass("disabled");

}


var oembkCodes;
var odest;
var odur;
var ostartdate;
var oenddate;


function buildFilters(query, prevSearch) {

    var q = parseQuery(query);
    //alert("ebmk code " +q.embkCode + "  dest" + q.dest);
    //	console.debug("buildFilters %o", q);



    // date range
    var src = q.src;
    var cruiseMonth = q.cruiseMonth;
    var startDate = q.startDate;
    var endDate = q.endDate;
    var dat = (q.dat) ? decodeURIComponent(q.dat) : "";
    var dur = (q.dur) ? decodeURIComponent(q.dur) : "";
    var x;
    //alert("cruise month " + cruiseMonth);
    //	console.debug("cruise month %s", cruiseMonth);
    if (src == "qp") {
        //	console.debug("cruiseMonth %s startDate %s  endDate %s", cruiseMonth, startDate, endDate);

        var date = new Date(startDate);
        var month = date.getMonth() + 1;
        var monthAugment = new String((month < 10) ? "0" + month : month);
        var sortStuff = monthAugment + "" + date.getFullYear();
        //console.debug("month: %s year: %o", month, date.getFullYear(), sortStuff);

        var dateEnd = new Date(endDate);
        var monthEnd = dateEnd.getMonth() + 1;
        var monthEndAugment = new String((monthEnd < 10) ? "0" + monthEnd : monthEnd);
        var sortStuffEnd = monthAugment + "" + dateEnd.getFullYear();

        //console.debug("end month: %s year: %o", monthEnd, dateEnd.getFullYear(), sortStuffEnd);

        if ((dateEnd.getFullYear() - date.getFullYear()) != 3) {
            $("#ctl00_ContentPlaceHolder1_seldates option[value='" + sortStuff + "']").attr("selected", true);
            if (startDate) {
                cclSailing.FromDate = sortStuff;
            }
            if (endDate) {
                cclSailing.ToDate = sortStuffEnd;
            }
            var monthNum = parseInt(1 + date.getMonth());
            monthNum = new String((monthNum < 10) ? "0" + monthNum : monthNum);

            dat = "" + monthNum + date.getFullYear();
            //console.debug("qp dat %s  month %s", dat, date.getMonth());
        }
        else {
            //console.log("set to any month");
            cclSailing.FromDate = null;
            cclSailing.ToDate = null;
            dat = "";
            $("#ctl00_ContentPlaceHolder1_seldates option[value='']").attr("selected", true);
        }
    }
    else if (dat.length > 0) {

        var datArr = "";
        if (dat.indexOf(",") > -1) {
            datArr = dat.split(",").sort();
            //console.debug("arr cruise month %s datArr %o", dat, datArr); 

            var startMonth = datArr[0].substring(0, 2);
            var startYear = datArr[0].substring(2);

            var endMonth = datArr[datArr.length - 1].substring(0, 2);
            var endYear = datArr[datArr.length - 1].substring(2);


            cclSailing.FromDate = "" + startMonth + "" + startYear;
            cclSailing.ToDate = "" + endMonth + "" + endYear;

            $("#ctl00_ContentPlaceHolder1_seldates option[value='" + datArr.join(",") + "']").attr("selected", true);

            //console.debug("selected %o", $("#ctl00_ContentPlaceHolder1_seldates option:selected").val() );
            if ($("#ctl00_ContentPlaceHolder1_seldates option:selected").val() == "") {

                $("#ctl00_ContentPlaceHolder1_seldates option[value='" + datArr[0] + "']").attr("selected", true);
            }

            //console.debug("fromDate %o, toDate %o", cclSailing.FromDate, cclSailing.ToDate);			
        }
        else {
            //console.debug("cruise month %s", dat);

            var month = dat.substring(0, 2);
            var year = dat.substring(2);

            //alert("month " + month + " year " +year);
            //console.debug("single: month %s  year %s", month, year);
            /*
            var shortMName = monthNames[parseInt(month)-1];
            sortStuff = shortMName + " " + year;
            */
            $("#ctl00_BodyContentPlaceHolder_seldates option[value='" + dat + "']").attr("selected", true);

            //cal last day of month
            cclSailing.FromDate = "" + month + "" + year;
            cclSailing.ToDate = "" + month + "" + year;
            //alert("fromdate " + cclSailing.FromDate + " toDate " + cclSailing.ToDate);
            //console.debug("fromDate %o, toDate %o  dat %o  last day %o", cclSailing.FromDate, cclSailing.ToDate, dat, lastDay);
        }


    }
    else {
        $("#ctl00_ContentPlaceHolder1_seldates option[value='']").attr("selected", true);
    }

    var discountObj = GetRateCriteriaCookie();
    if (discountObj == null) { discountObj = ""; }
    //console.debug("discount obj %o  senior %o", discountObj, discountObj.Senior);

    // special discounts
    var senior = q.Senior;
    //console.debug("senior %o", senior);
    //if (senior == "Y") {

    $("#chk-special-rate-over").each(function () {
        // insert cookie check
        if (senior == "Y" || discountObj.Senior == "Y") {
            cclSailing.IsOver55 = true;
            $(this).attr("checked", "checked");
            // set rate criteria cookie also
            SetRateCriteriaCookieSenior();
        }
    })

    //}

    var pastguest = q.PastGuest;
    $("#chk-special-rate-guest").each(function () {
        // insert cookie check
        if (pastguest == "Y" || discountObj.PastGuest == "Y") {
            cclSailing.IsPastGuest = true;
            $(this).attr("checked", "checked")
            // set rate criteria cookie also
            SetRateCriteriaCookiePastGuest();
        }
    })

    // insert cookie check
    var state = q.StateCode;
    if (state != "" || discountObj.StateCode) {
        var st = (state && state.length > 0) ? state : discountObj.StateCode;
        //console.debug("st %s state %s  StateCode %s", st, state, discountObj.StateCode);
        $("#sel-state option[value='" + st + "']").attr("selected", true);
        cclSailing.StateCode = state;
        //resetList();
        //cclSailing.SearchAsync(done, failed, searchOptions.pageSize, 1, searchOptions.sortExpression);
    }

    // run on page load
    var minDays = q.minDays;
    var maxDays = q.maxDays;

    if (minDays != "" && maxDays != "") {
        dur = new Array();
        if (minDays == "2" && maxDays == "5") {
            var val = "D1";
            dur.push(val);
            $("#duration input[value='" + val + "']").attr("checked", "checked");
            cclSailing.AddDurationCode(val);
        }
        if (minDays == "6" && maxDays == "9") {
            var val = "D2"
            dur.push(val);
            $("#duration input[value='" + val + "']").attr("checked", "checked");
            cclSailing.AddDurationCode(val);

        }
        if (minDays == "10") {
            dur.push("D3");
            $("#duration input[value='" + val + "']").attr("checked", "checked");
            cclSailing.AddDurationCode("D3");
        }

    }
    // duration in query str

    if (dur) {
        var duration = (q.dur) ? q.dur.split(",") : dur;
        var $dur = $("#duration");
        cclSailing.DurationCodes = duration;
        //unckeck all the inputs first (reset)
        $dur.find('input').attr('checked', false);
        for (var i = 0, len = duration.length; i < len; i++) {
            //console.debug("setting %s", duration[i]);
            $dur.find("input[value*='" + duration[i] + "']").attr("checked", "checked");
        }
        dur = cclSailing.DurationCodes;
        $dur.data("dur", dur);
    }
    $("#duration input:checked").each(function () {
        cclSailing.AddDurationCode($(this).val());
    });



    var dest0;
    var embkCode0;
    var dat0;
    var dur0;


    // need test dont think its working correctly
    // dur0 = (q.dur) ? q.dur : "";

    dest0 = (q.dest) ? q.dest : "";
    dest0 = unescape(dest0);
    //        console.debug("dest0 %o", dest0);
    //alert("dest0 " + dest0);


    //alert(dest0);
    if (dest0.length > 0) {

        var destTemp = dest0.split(",");
        var destObj = $("#destinations");
        var newArr = [];
        //var destObj = [];
        var multiMap = { C: false, A: false, M: false, V: false };

        destObj.find("input").removeData("active");
        //			console.debug("destTemp %o", destTemp);
        for (var i = 0, len = destTemp.length; i < len; i++) {
            if (jQuery.inArray(destTemp[i], destMap.C) > -1 && !multiMap.C) {
                newArr.push("C", "CW", "CE", "CS");
                destObj.find("input[value='" + destMap.C + "']").attr("checked", "checked").data("active", true);
                multiMap.C = true;

            }
            else if (jQuery.inArray(destTemp[i], destMap.A) > -1 && !multiMap.A) {
                newArr.push("A", "AG", "AN", "AS");
                destObj.find("input[value='" + destMap.A + "']").attr("checked", "checked").data("active", true);
                multiMap.A = true;
            }
            else if (jQuery.inArray(destTemp[i], destMap.M) > -1 && !multiMap.M) {
                newArr.push("M", "MB", "MR");
                destObj.find("input[value='" + destMap.M + "']").attr("checked", "checked").data("active", true);
                multiMap.M = true;
            }
            else if (jQuery.inArray(destTemp[i], destMap.V) > -1 && !multiMap.V) {
                destObj.find("input[value='" + destMap.V + "']").attr("checked", "checked").data("active", true);
                newArr.push("V", "BM", "CN");
                multiMap.V = true;
            }
            else {
                newArr.push(destTemp[i]);
                destObj.find("input[value='" + destTemp[i] + "']").attr("checked", "checked").data("active", true);
            }
        }
        dest0 = newArr.join(",");
        //destinationGlobalVals = dest0;
        //			console.debug("dest0", dest0);
    }
    $("#destinations input:checked").each(function () {
        cclSailing.AddDestinationCode($(this).val());
    });





    // embkCode = PortCodes
    embkCode0 = (q.embkCode) ? q.embkCode : "";
    embkCode0 = unescape(embkCode0);

    //		console.debug("embkCode0 %s", embkCode0);
    var $departures = $("#departures");
    if (embkCode0.length > 0) {
        cclSailing.PortCodes = embkCode0;
        var ports = embkCode0.split(",");
        $departures.find("input").removeData("active");
        //alert("ports " + ports + " len "+ports.length);
        for (var i = 0, len = ports.length; i < len; i++) {
            $departures.find("input[value='" + ports[i] + "']").attr("checked", "checked").data("active", true);
            //alert("departures " + $departures.find("[value='"+ports[i]+"']").length + " " +$departures.find("[value='"+ports[i]+"']").attr("checked") + " " +ports[i]);
        }
        departFromGlobalVals = ports;
    }
    $("#departures input:checked").each(function () {
        cclSailing.AddPortCode($(this).val());
    });

    //console.debug("embkCode %s", embkCode0);

    dat0 = dat;

    //	console.debug("before assgnment dur %s dest0 %s embkCode %s dat %s  x: %s", dur0, dest0, embkCode0, dat0, x);
    //	dur0 = (dur0 == "") ? dur0 : ((cclSailing.DurationCodes) ? cclSailing.DurationCodes.join(",") : "");
    //	dest0 = (dest0 == "") ? dest0 : ((cclSailing.DestinationCodes)? cclSailing.DestinationCodes.join(",") : "");
    //	embkCode0 = (embkCode0 == "") ?embkCode0 : ((cclSailing.PortCodes) ? cclSailing.PortCodes.join(","): "");
    var xArrObj = [];
    x = "";
    if (dat0.length > 0) {
        xArrObj.push("dat=" + dat0);
    }
    if (dest0.length > 0) {
        xArrObj.push("dest=" + dest0);
    }
    if (dur.length > 0) {
        xArrObj.push("dur=" + dur);
    }
    if (embkCode0.length > 0) {
        xArrObj.push("embkCode=" + embkCode0);
    }

    x = xArrObj.join("&");

    //x = "dur=" + dur + "&dest=" + dest0 + "&embkCode=" + embkCode0 + "&dat=" + dat0;
    //console.debug("after   dur %s dest0 %s embkCode %s dat %s  x: %s len %d", dur0, dest0, embkCode0, dat0, x, x.length);

    /*
    clickType = 0;
    SearchFilter(failed,x);
    originalCall = x;
    */
    if (x.length > 5) {
        //console.debug("calling service");
        SearchFilter(failedFilter, x);
        originalCall = x;
    }
    else {
        failedFilter();
    }


    //set sorting & paging,
    // console.debug("in left filter params %o", q);
    var searchVar = setSortExpression(q.sort, "string");
    cclSailing.SortExpression = searchVar;
    cclSailing.PageSize = searchOptions.pageSize = (q.pageSize == "") ? 1 : q.pageSize;
    cclSailing.PageNumber = q.pageNumber;

    //cclSailing.SearchAsync(done, failed, searchOptions.pageSize, 1, searchOptions.sortExpression)
    $("#sel-sortcount option[value='" + cclSailing.PageSize + "']").attr("selected", true);
    // console.debug("left filter: expression %o %s paging %d   size: %o", cclSailing.SortExpression, searchVar, cclSailing.PageNumber, cclSailing.PageSize);
    // console.debug("select boxes: sort %s   pageNumber %s  resultSize %s", $("#sel-sortby").val(), cclSailing.PageNumber, $("#sel-sortcount").val());
    resizeCol();

}


$(document).ready(function () {
    //console.log("build left filter");
    buildFilters(location.search);

    //reset in the begining
    $('#ctl00_BodyContentPlaceHolder_seldates').val('')
    var ng = (parseQuery(location.href)).numGuests;
    $('#numGuests').val('2');
    if (ng) {
        $("#numGuests option").each(function () {
            if ($(this).val() == ng) {
                cclSailing.NumGuests = ng;
                $(this).attr("selected", true);
            }

            /*else {
            $(this).attr("selected",false);
            }*/
        });
    }

});
$(window).load(function () {
    $(".reset, .resetSearchResults").live("click", function (event) {
        //console.log("Should be resetting the left nav");
        $("#content-left").find(":checkbox").removeAttr("disabled").removeAttr("checked").parent().removeClass("disabled");

        $("#content-left, .options").find("select").each(function () {
            $("option:first", $(this)).attr("selected", true);
        });
        cclSailing.SearchReset();

        $(this).trackLink({ buttonName: "Reset" });

        event.preventDefault();
        event.stopPropagation();
        return false;
    });

    $("div.no-results a.prevSearchResult").live("click", function (event) {
        //	console.debug("cache %o", cache);
        /*
        for(var i=0, len = cache.length; i < len; i++){
        console.debug("%d: %s", i, cache[i].PortCodes);
        }
        */
        var q = cache[0];
        if (cache.length == 0) {
            //console.debug("no prev entry");
            cclSailing.SearchReset();
            return false;
        }
        //console.debug("query %o", q);


        //buildFilters(q);
        //resetList();
        cclSailing = q;
        cclSailing.SearchAsync(done, failed, cclSailing.PageSize, cclSailing.PageNumber, cclSailing.SortExpression);
        SearchFilter(failedFilter, "");

        $(this).trackLink({ buttonName: "Previous Search Result" });
        event.preventDefault();
        event.stopPropagation();
        cache.shift();
        return false;
    });
    // add handlers for duration
    $("#duration input:checkbox").live("click", function (event) {
        //console.debug("dur %o  val %s  checked %s \ndurationCodes %o", $(this), $(this).val(), $(this).attr("checked"),
        //		cclSailing.DurationCodes);												
        if ($(this).attr("checked")) {
            //console.debug("adding sailing %s arr %o", $(this).val(), cclSailing.DurationCodes);
            cclSailing.AddDurationCode($(this).val());
        }
        else {
            //console.debug("remove sailing %s  arr %o", $(this).val(), cclSailing.DurationCodes);
            cclSailing.RemoveDurationCode($(this).val());
        }
        resetList();
        cclSailing.SearchAsync(done, failed, searchOptions.pageSize, 1, searchOptions.sortExpression);
        // update left selections
        //console.debug("DurationCodes %o", cclSailing.DurationCodes);
        SearchFilter(failedFilter, "");
        $(this).trackLink({ buttonName: "Modify Search Box Feature" });

    });
    // set click handler for port checkboxes
    $("#departures").find("input:checkbox").live("click", function (event) {
        //alert("updated the embark code:"+ $(this).val()+ " checked val: "+$(this).attr("checked") );
        if ($(this).attr("checked")) {
            cclSailing.AddPortCode($(this).val());
            $(this).data("active", true);
            //alert("added port code " + $(this).val());
        }
        else {
            cclSailing.RemovePortCode($(this).val());
            $(this).removeData("active");
        }
        //console.debug("cclSailing portcodes %o", cclSailing.PortCodes);
        resetList();
        cclSailing.SearchAsync(done, failed, searchOptions.pageSize, 1, searchOptions.sortExpression);
        SearchFilter(failedFilter, "");
        $(this).trackLink({ buttonName: "Modify Search Box Feature" });

    });
    $("#destinations input:checkbox").live("click", function () {
        //alert("dest clicked");
        if ($(this).attr("checked")) {
            //alert("added " + $(this).val() + " to cclObj");
            cclSailing.AddDestinationCode($(this).val());
            $(this).data("active", true);
        }
        else {
            cclSailing.RemoveDestinationCode($(this).val());
            $(this).removeData("active");
        }
        resetList();
        cclSailing.SearchAsync(done, failed, searchOptions.pageSize, 1, searchOptions.sortExpression);
        SearchFilter(failedFilter, "");
        $(this).trackLink({ buttonName: "Modify Search Box Feature" });

    });

    // other filters
    $("#chk-special-rate-guest").live("click", function (event) {
        cclSailing.IsPastGuest = $(this).attr("checked");

        if (cclSailing.IsPastGuest) {
            SetRateCriteriaCookiePastGuest();
        }
        else {
            RemoveRateCriteriaCookiePastGuest();
        }

        //console.debug("pastGuest %s  checked %b",cclSailing.IsOver55, $(this).attr("checked"));
        resetList();
        cclSailing.SearchAsync(done, failed, searchOptions.pageSize, 1, searchOptions.sortExpression);
        $(this).trackLink({ buttonName: "Modify Search Box Feature" });

    });
    $("#chk-special-rate-over").live("click", function () {
        cclSailing.IsOver55 = $(this).attr("checked");

        if (cclSailing.IsOver55) {
            SetRateCriteriaCookieSenior();
        }
        else {
            RemoveRateCriteriaCookieSenior();
        }

        //console.debug("senior %s  checked %b",cclSailing.IsOver55, $(this).attr("checked"));
        resetList();
        cclSailing.SearchAsync(done, failed, searchOptions.pageSize, 1, searchOptions.sortExpression);
        $(this).trackLink({ buttonName: "Modify Search Box Feature" });

    });
});

	

	  

