if(location.href.toLowerCase().indexOf('default2.aspx')==-1){
LoadScript("/cms/PageElements/2010/common/js/fancybox/cclfancybox.js");
LoadStyleSheet("/CMS/PageElements/2010/common/js/fancybox/cclfancybox.css");
}
// firebug degradiation
if (!("console" in window) || !("firebug" in console)) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group"
                 , "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i < names.length; ++i) window.console[names[i]] = function () { };
}
var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

var resizeCol = function () { $("#content-left, #content-body").equalizeCols(); };
var resetList = function () {
    $("#targetcruiselist, .paging, .no-results, .pagingInfo").fadeOut("normal", function () {
        $(".results-loading").fadeIn("fast");
        resizeCol();
        if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6) {

        }
    });
};

var pagePath = location.protocol + "//" + location.host + location.pathname;


var builtInteractions = function () {
    $("#qm1").css("z-index", 100);


    $(".cruise-item .title").live("mouseover", function () {
        $(this).css({ "cursor": "pointer", "background-position": "left bottom" });
    }).
   	live("mouseout", function () {
   	    $(this).css({ "cursor": "none", "background-position": "left top" });
   	}
	).live("click", function () {
	    $(this).find("a").trigger("click");
	    return false;
	});
    $('a.func-toggle').live("click", function (event) {
        var _href = $(this).attr('href');
        var _obj = $(_href);

        if (_obj.hasClass('hidden') == true) {
            _obj.slideDown("slow", function () { _obj.removeClass('hidden'); resizeCol(); });
            $(this).parent().addClass('show-hide-caption').trackLink({ buttonName: "Show Searchbox Feature" });
        } else {
            _obj.slideUp("slow", function () { _obj.addClass('hidden'); resizeCol(); });
            $(this).parent().removeClass('show-hide-caption').trackLink({ buttonName: "Hide Searchbox Feature" });
        }
        resizeCol();
        event.preventDefault();
        event.stopPropagation();
        //return false;
    });
    $('a.func-toggle-detail').live("click", function (event) {
        var _obj = $(this).parents('div.cruise-item')
        console.debug("func toggle detail");
        event.preventDefault();
        event.stopPropagation();

        if (_obj.hasClass('cruise-item-show') == true) {
            _obj.find(".sailings").slideUp("fast", function () {
                _obj.removeClass('cruise-item-show').trackLink({ buttonName: "Show Cruise Item" });
                resizeCol();
            });
        } else {
            _obj.find(".sailings").slideDown("fast", function () {
                setTableSize(event, true);
                _obj.addClass('cruise-item-show').trackLink({ buttonName: "Hide Cruise Item" });
                resizeCol();
            });
        }
        resizeCol();

        return false;
    });

    $("a.func-toggle-more").live("click", function (event) {

        var $cruiseItem = $(this).parents(".cruise-item");

        if ($cruiseItem.hasClass("cruise-item-show") == false) {
            $(".title a", $cruiseItem).trigger("click");
            setTableSize(event, true);
        }
        else {
            var hidden = $("tbody tr:hidden", $cruiseItem).length;

            if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 8) {
                var count = 0;
                $("tbody tr", $cruiseItem).each(function () {
                    if ($(this).css('display') == 'none') {
                        count++;
                    }
                });
                hidden = count;
            }

            if (hidden > 0)
                setTableSize(event, false); // changed because now initinally opened
        }
        /* function to figure out how many more rows to show if less than 10, show all, add in incriments of 5 */
        $(this).trackLink({ buttonName: "Show More Cruise Item" });
        event.preventDefault();
        event.stopPropagation();
        resizeCol();
        return false;
    });

    $("#area-favorites").addClass("closed");
    $('#area-favorites .btn-expand').live("click", function () {
        var $btn = $(this);
        var favCount = parseInt($("#area-favorites tbody td.dates:not(:empty)").length);

        if (favCount >= 0) {
            if ($("#area-favorites").hasClass("closed")) {
                $("#area-favorites .cruise-item").slideDown("normal", function () {
                    $(this).removeClass("hid");
                    $("#favcount").html($("#area-favorites tbody td.dates:not(:empty)").length);
                    $btn.parents("#area-favorites").removeClass("closed").trackLink({ buttonName: "Show Saved Favs" });
                    resizeCol();
                });

            }
            else {

                $("#area-favorites .cruise-item").slideUp("normal", function () {
                    $(this).addClass("hid");
                    $("#favcount").html($("#area-favorites tbody td.dates:not(:empty)").length);
                    $btn.parents("#area-favorites").addClass("closed");
                    $(this).buildFavs();
                    resizeCol();
                });
            }
        }

        correctLinks($('#targetarea-favorites'));

        return false;
    });

    var showMore = "Show <span></span> more";
    var viewMore = "View X date<span>s</span> &amp price<span>s</span> in this set";
    $(".expand").live("mouseover", function () {

        $(this).parent().addClass("hovered");

        if ($(this)[0].tagName.toLowerCase() == "div") {
            var classNames = $("ul", this).attr("class");
            var firstChild = $(".first-child a", this);
            firstChild.html(viewMore.replace(/X/, classNames)).addClass((parseInt(classNames) == 1) ? "single" : "");
        }
        return false;
    })
	.live("mouseout", function () {

	    $(this).parent().removeClass("hovered");

	    if ($(this)[0].tagName.toLowerCase() == "div") {

	        var classNames = $("ul", this).attr("class");
	        var firstChild = $(".first-child a", this);
	        firstChild.html(showMore).removeClass("single");
	    }
	    return false;
	});
    $("div.expand").live("mouseover", function () {
        $(this).css("cursor", "pointer");
    }).
	live("mouseout", function () {
	    $(this).css("cursor", "none");
	})
	.live("click", function () {
	    $(this).parents(".cruise-item").find("h3 a").trigger("click");

	});

    var helpHtml = "<p>This sailing has been added to your favorites at the top of the page. <a href='' class='view-favorites anchorLink'>View favorites</a></p>";


    $("#cruise-list tbody .star").live("click", function (event) {
        var lsSailDate = $(this).parent().parent().find("td").eq(1).text();
        if (lsSailDate.indexOf("(") > -1)
        {
            var liPosition = lsSailDate.indexOf("(");
            lsSailDate = lsSailDate.substring(0, liPosition);
        }
        var favCount = parseInt($("#area-favorites tbody tr td.dates:not(:empty)").length);
        var redraw = false;
        if (favCount + 1 < 21) {
            var $trParent = $(this).parents("tr").addClass("help")
            var cruiseId = $trParent.attr("id");
            var curUrl = "" + location.href;
            $(this).parent().addClass("selected");

            curUrl = (curUrl.indexOf("#") > 0) ? curUrl : curUrl + '#area-favorites';

            var $nextTd = $(this).parent().next();
            $nextTd
					.nextAll()
					.remove()
				.end()
				.attr("colSpan", 6)
				.html(helpHtml)
				.find("a.anchorLink")
				.attr("href", curUrl);


            redraw = true;
            //alert("redraw stars");
            $(this).attr("href", "#").trackLink({ buttonName: "Add Favs", evarTripId: cruiseId, favs: true });

            AddFavorite(cruiseId, redraw, lsSailDate);
            //alert("after add favs");
        }
        else { // have five trigger lightbox 
            $("#removeFavsLink").trigger("click");
        }
        //alert("end of function before event stop");
        event.preventDefault();
        event.stopPropagation();
        return false;
    });


    if ($.browser.msie) {
        if (parseInt($.browser.version, 10) == 7) {
            $(".cruise-item tr.expand li").css("display", "inline");
        }
    }


    $("#cruise-list a.view-favorites").live("click", function (event) {
        $(this).anchorAnimate();
        event.preventDefault();
        event.stopPropagation();
    });


    var selDates = $("#ctl00_BodyContentPlaceHolder_seldates");
    selDates.find("[value*=',']").addClass("optGroup").end().find("[value='']").addClass("optGroup");
    $("body", window).one("mousemove", function () {
        resizeCol();
    });



};
var rowIncr = 5;
var showMore = "Show <span></span> more";
function setTableSize(event, initinal) {
    var $targ = $(event.target);
    var $tbody = ($targ.parents(".detail").length == 1) ? $targ.parents(".detail").find("tbody") : $targ.parents(".cruise-item").find(".detail tbody");
    var totalRows = $("tr", $tbody).length;
    var rowsShowing = ($tbody.data("rowsActive")) ? parseInt($tbody.data("rowsActive").rowsShowing) :
	(($(".show", $tbody).length > 0) ? $(".show", $tbody).length : 0);
    var rowsHidden = (totalRows - rowsShowing > 0) ? totalRows - rowsShowing : totalRows;
    var rows = 0; var clickedCount = 1;
    var dataSetError = true;
    if (initinal) {

        if (totalRows > rowIncr || rowsHidden == rowIncr) {
            rows = rowIncr;
        }
        else if (rowsHidden < rowIncr) {
            rows = rowsHidden;
        }

        $("tr", $tbody).hide();
        $tbody.parent().find("tfoot li.first-child").show();

    }
    else {

        if (rowsShowing + rowIncr <= totalRows) {
            rows = rowsShowing + rowIncr;
        }
        else if (rowsShowing + rowIncr > totalRows) {
            rows = totalRows;
            var text = $("span", $targ).text();
            $("span", $targ).text("");
            $targ.unbind("click"); //.css("visibility", "hidden");
        }


        try {
            clickedCount = 1 + parseInt($tbody.data("rowsActive").clickedCount);
        }
        catch (e) { }
    }
    $tbody.data("rowsActive", { rowsShowing: rows, rowsHidden: rowsHidden, clickedCount: Math.ceil(rows / 5) });

    //console.debug("rowsActive %o ", $tbody.data("rowsActive"));

    var count = 1;
    if ($tbody.data("rowsActive").rowsHidden > 0) {
        if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 8) {
            var len = 0; var i = 0;

            if (initinal) {
                len = (rows > rowIncr || rows == rowIncr) ? rowIncr : rows;
            }
            else {
                var count = 0;
                $("tr", $tbody).each(function () {
                    if ($(this).css('display') == 'block') {
                        count++;
                    }
                });
                i = count;
                len = ((rows - i) > rowIncr || (rows - i) == rowIncr) ? rowIncr + i : rows;
            }

            for (; i < len; i++) {
                $("tr:eq(" + i + ")", $tbody).each(function () {

                    $(this).css("display", "block");
                });
                if (i + 1 == len) {
                    $("tr:eq(" + i + ")", $tbody).each(function () {

                        $(this).css("display", "block");
                        resizeCol();
                    });
                }

            }
            var $tBody = $targ.parents(".cruise-item").find(".detail tbody")
            var $moreStuff = $targ.parents(".cruise-item").find("tfoot .func-toggle-more span");
            if (rows < totalRows) {

                var extra = ((totalRows - len) > 4) ? "(5) " : (((totalRows - len) > 0) ? "(" + (totalRows - len) + ") " : "");
                $moreStuff.text(extra);
            }
            else {
                $moreStuff.text("");
                $moreStuff.parent().css("display", "none");
            }
            resizeCol();
        }
        else {
            var len = 0; var i = 0;

            if (initinal) {
                len = (rows > rowIncr || rows == rowIncr) ? rowIncr : rows;
            }
            else {
                var count = 0;
                $("tr", $tbody).each(function () {

                    if ($(this).css('display') == 'table-row' || $(this).css('display') == 'block') {
                        count++;
                    }
                });

                i = count;
                len = ((rows - i) > rowIncr || (rows - i) == rowIncr) ? rowIncr + i : rows;

            }

            for (; i < len; i++) {
                $("tr:eq(" + i + ")", $tbody).fadeIn("fast");
                if (i + 1 == len) {
                    $("tr:eq(" + i + ")", $tbody).fadeIn("fast", function () { resizeCol(); });
                }

            }
            var $tBody = $targ.parents(".cruise-item").find(".detail tbody")
            var $moreStuff = $targ.parents(".cruise-item").find("tfoot .func-toggle-more span");
            if (rows < totalRows) {

                var extra = ((totalRows - len) > 4) ? "(5) " : (((totalRows - len) > 0) ? "(" + (totalRows - len) + ") " : "");
                $moreStuff.text(extra);

            }
            else {
                $moreStuff.text("");
                $moreStuff.parent().css("display", "none");
            }
            resizeCol();
        }
    }
    resizeCol();
    return false;
}


function done(context) {

    var lastPage = context.LastPage;
    var currPage = (context.CurrentPage == null) ? 1 : context.CurrentPage;


    //  var showDbl = $.query.GET("showDbl");
    $("#condText3").hide();
    $("#condText4").hide();
    if (context.ShowDouble == false) {
        $("#condText4").show();
    }

    else {
        $("#condText3").show();
    }

    $(".paging").buildPager({
        last: lastPage,
        curr: currPage,
        range: searchOptions.itemsPerPage,
        count: context.TotalResultsCount,
        showingRange: context.CurrentResultsCount
    });

    try {
        if (context.TotalResultsCount > 0) {
        }
    }
    catch (e) { console.debug("error %o", e); }

    if (context.TotalResultsCount > 0) {


        var itineraries = $('#cruise-list').mapDirective({
            '.cruise-item': 'itn <- Itineraries',
            'a.func-toggle-detail': 'itn.ItnDescriptionText',
            'p.cruise-from span': 'itn.FromPriceText',
            'a.departFrom': 'itn.DeparturePortText',
            'a.departFrom[href]': '/cms/search2/lightboxes/PortsOfCall.aspx#{itn.DeparturePortHref}',//&KeepThis=true&TB_iframe=true&width=630&height=570',
            'a.shipName': 'itn.ShipText',
            'a.shipName[title]+': 'itn.ShipText',
            'a.shipName[href]': '/cms/search2/lightboxes/shiphighlights.aspx#{itn.ShipHref}',//&KeepThis=true&TB_iframe=true&width=714&height=580',
            'th.interior a[href]': '/cms/search2/lightboxes/stateroom.aspx#{itn.INHref}',//&KeepThis=true&TB_iframe=true&width=756&height=750',
            'th.ocean a[href]': '/cms/search2/lightboxes/stateroom.aspx#{itn.OVHref}',//&KeepThis=true&TB_iframe=true&width=756&height=750',
            'th.balcony a[href]': '/cms/search2/lightboxes/stateroom.aspx#{itn.OBHref}',//&KeepThis=true&TB_iframe=true&width=756&height=750',
            'th.suites a[href]': '/cms/search2/lightboxes/stateroom.aspx#{itn.SUHref}',//&KeepThis=true&TB_iframe=true&width=756&height=750',
            'div.expand .count': 'itn.HiddenSailingsCount',
            'div.expand li[class]': function (int) {

                return (int.item.HiddenSailingsCount < 2) ? "single" : "";
            },
            'tfoot .showRows[class]+': function (int) {
                return (int.item.HiddenSailingsCount < 6) ? "hid" : "";
            },
            'tfoot .func-toggle-more span': function (int) {
                return "(" + ((int.item.HiddenSailingsCount > 5) ? 5 : int.item.HiddenSailingsCount) + ") ";
            },
            'p.btn-details a[href]': '/BookingEngine/ProductView/#{itn.DetailsHREF}'
        });

        var sailings = $('table.detail', itineraries)
  .mapDirective({
      'tbody tr': 's <- itn.Sailings',
      'tbody tr[class]+': function (s) {
          var oddEven = (s.pos % 2 == 0) ? 'even' : 'odd';
          var firstLast = (s.pos == 0) ? 'first-child' : (s.pos == s.items.length - 1) ? 'last-child' : '';
          var display = (s.item.Style != null) ? s.item.Style : "";

          return oddEven + ' ' + firstLast + ' ' + s.item.Style;
      },
      'tbody tr[id]': 's.SailingId',
      'td.dates': 's.CalendarDaysText',
      'td.interior': 's.INPriceText',
      'td.ocean': 's.OVPriceText',
      'td.balcony': 's.BAPriceText',
      'td.suites': 's.STPriceText',
      'td.details a[href]': '/BookingEngine/ProductView/#{s.DetailsHREF}'
  });

        var ports = $('span.ports', itineraries)
  .mapDirective({
      'a': 'p <- itn.Ports',
      'a.portName': 'p.PortText',
      'a.portName[href]': '/cms/search2/lightboxes/PortsOfCall.aspx#{p.PortHref}'//&KeepThis=true&TB_iframe=true&width=630&height=570'

  });
        try {
            $('div.sailings', itineraries).html(sailings);
        }
        catch (e) {
            $('div.sailings', itineraries)[0].innerHTML = sailings;
        }
        try {
            $('span.ports', itineraries).html(ports);
        }
        catch (e) {
            $('span.ports', itineraries)[0].innerHTML = ports;
        }
        if (!compiled) {
            $p.compile(itineraries, 'itinerary');
            compiled = true;
            searchOptions.firstLoad = false;
        }

        var html = $p.render('itinerary', context);
        var targCruise = $('#targetcruiselist');
        try {
            targCruise.html(html);
        }
        catch (e) {
            targCruise[0].innerHTML = html;
        }

        targCruise.fadeIn("fast", function () {
            $(".results-loading, .no-results").hide();
            $(".paging").show("normal");


            builtInteractions();
            searchOptions.failCnt = 0;
            cache.unshift(jQuery.extend(true, {}, cclSailing)); //cclSailing //buildNewUrl(""));
            if (cache.length > 11) {
                cache.pop();
            }


        });

        correctLinks($('#targetcruiselist'));

        if ($.browser.msie && parseInt(jQuery.browser.version) < 8) {
            $("#targetcruiselist .cruise-item").stackOrderIEFix();
        }
        else if ($.browser.msie && parseInt(jQuery.browser.version) == 8) {
            $("a.more-details").each(function (a) {
                var text = $(this).text();
                var imgPath = $(this).css("backgroundImage");
                var path = new String(imgPath.match(/\(.*\)/gi));
                path = path.substring(2);
                path = path.substring(0, path.length - 2);
                $(this).css({ "text-indent": 0, "background": "none" }).text("");
                $("<img>").attr("src", path).attr("title", text).appendTo($(this));

            });

            $("#targetcruiselist a.star").each(function (a, domEl) {
                var text = $(domEl).text();
                var imgPath = $(domEl).css("backgroundImage");
                var path = new String(imgPath.match(/\(.*\)/gi));
                path = path.substring(2);
                path = path.substring(0, path.length - 2);

                if ($(domEl).parent().hasClass("selected")) {
                    path = path.replace("favourite-icn.png", "favorite-icon-on.png");
                }
                else {
                    path = path.replace("favourite-icn.png", "favorite-icon-off.png");
                }
                $(domEl).css({ "text-indent": 0, "background": "none" }).text("");
                $("<img>").attr("src", path).attr("title", $(domEl).attr('title')).appendTo($(domEl));

                $(domEl).hover(function () {
                    if (!$(this).parent().hasClass("selected")) {
                        var img = $(this).find("img");
                        var src2 = new String(img.attr("src")).replace("-off", "-on");
                        $(this).find("img").attr("src", src2);
                    }
                }, function () {
                    if (!$(this).parent().hasClass("selected")) {
                        var img = $(this).find("img");
                        var src2 = new String(img.attr("src")).replace("-on", "-off");
                        $(this).find("img").attr("src", src2);
                    }
                }).live("click", function (event) {

                    var img = $(this).find("img");
                    var src2 = new String(img.attr("src")).replace("-off", "-on");
                    $(this).find("img").attr("src", src2); // look at combining 
                    alert("click for star");
                    event.preventDefault();
                    event.stopPropagation();
                });
            });


        }
        setSearchResultsTooltips();
    }
    else {
        $(".paging, .results-loading").hide();
        $(".no-results").fadeIn("fast", function () {
            $(".paging, .results-loading").hide("fast");
        });
    }
   // tb_init('#targetcruiselist a.thickbox, #targetcruiselist area.thickbox, #targetcruiselist input.thickbox');
    resizeCol();
    if ($.browser.msie && (parseInt($.browser.version) == 7 || parseInt($.browser.version) == 8) && location.href.toLowerCase().indexOf("search2/default2.aspx")==-1) {
        $("#content-body").css('height', 0); 
    } 
}

function failed(msg, status, error) {
    builtInteractions();
    $(".paging, .results-loading").hide();
    $(".no-results").fadeIn();

}


function favoritesDone(context) {
    // add call to update header count
    favoritesDoneHeader(context); // header sync count
    if (context.Itineraries != null) {
        if ($("#area-favorites .cruise-item").length == 0) {
            $("#area-favorites").append(favsItem);
        }


        var itineraries = $('#area-favorites').mapDirective({
            'div.cruise-item': 'itn <- Itineraries',
            'h3.itnTitle': 'itn.ItnDescriptionText',
            'a.departFrom': 'itn.DeparturePortText',
            'a.departFrom[href]': '/cms/search2/lightboxes/PortsOfCall.aspx#{itn.DeparturePortHref}',//&KeepThis=true&TB_iframe=true&width=630&height=570',
            'a.shipName': 'itn.ShipText',
            'a.shipName[title]+': 'itn.ShipText',
            'a.shipName[href]': '/cms/search2/lightboxes/shiphighlights.aspx#{itn.ShipHref}', //&KeepThis=true&TB_iframe=true&width=700&height=580',
            'th.interior a[href]': '/cms/search2/lightboxes/stateroom.aspx#{itn.INHref}',    //&KeepThis=true&TB_iframe=true&width=700&height=580',
            'th.ocean a[href]': '/cms/search2/lightboxes/stateroom.aspx#{itn.OVHref}',       //&KeepThis=true&TB_iframe=true&width=700&height=580',
            'th.balcony a[href]': '/cms/search2/lightboxes/stateroom.aspx#{itn.OBHref}',     //&KeepThis=true&TB_iframe=true&width=700&height=580',
            'th.suites a[href]': '/cms/search2/lightboxes/stateroom.aspx#{itn.SUHref}',      //&KeepThis=true&TB_iframe=true&width=700&height=580',
            'p.btn-details a[href]': '/BookingEngine/ProductView/#{s.DetailsHREF}'
        });

        var sailings = $('table.detail', itineraries).mapDirective({
            'tbody tr': 's <- itn.Sailings',
            'tbody tr[class]+': function (s) {
                var oddEven = (s.pos % 2 == 0) ? 'even' : 'odd';
                var firstLast = (s.pos == 0) ? 'first-child' : (s.pos == s.items.length - 1) ? 'last-child' : '';
                return oddEven + ' ' + firstLast;
            },
            'tbody tr[id]': 's.SailingId',
            'td.dates': 's.CalendarDaysText',
            'td.interior': 's.INPriceText',
            'td.ocean': 's.OVPriceText',
            'td.balcony': 's.BAPriceText',
            'td.suites': 's.STPriceText',
            'td.details a[href]': '/BookingEngine/ProductView/#{s.DetailsHREF}'
        });

        var ports = $('span.ports', itineraries)
  .mapDirective({
      'a': 'p <- itn.Ports',
      'a.portName': 'p.PortText',
      'a.portName[href]': '/cms/search2/lightboxes/PortsOfCall.aspx#{p.PortHref}' //&KeepThis=true&TB_iframe=true&width=630&height=570'

  });
        //alert("fav sailings drawing - begin");
        try {
            $('div.favsailings', itineraries).html(sailings);
        }
        catch (e) {
            $('div.favsailings', itineraries)[0].innerHTML = sailings;
        }
        //ie is throwing an error

        try {
            $('span.ports', itineraries).html(ports);
        }
        catch (e) {
            $('span.ports', itineraries)[0].innerHTML = ports;
        }
        // ie is throwing an error

        if (!favcompiled) {
            $p.compile(itineraries, 'f5');
            favcompiled = true;
        }

        var htmlFavs = $p.render('f5', context);

        try {
            $('#targetarea-favorites').html(htmlFavs);
        }
        catch (e) {
            $('#targetarea-favorites')[0].innerHTML = htmlFavs;
        }
        // ie throwing error
        //alert("fav sailings drawing - end");

        if (favcompiled)
            $('#targetarea-favorites').fadeIn("fast");

        if ($.browser.msie && parseInt(jQuery.browser.version) < 8) {
            $("#targetarea-favorites .cruise-item").stackOrderIEFix();
        }


        $("#favcount").html($("#area-favorites tbody td.dates:not(:empty)").length)
        if ($("#favcount").text() == 1) {
            $(".area-title .btn-expand").parent().removeClass("closed");
        }




        $("#area-favorites tbody .star").live("click", function (event) {
            var $header = $("#area-favorites .area-title h2 span");
            var $rows = $("#area-favorites tbody tr")
            var tr = $(this).parent().parent();
            var trId = tr.attr("id");
            var $item = $(this).parents(".cruise-item");
            var $areaFavs = $(this).parents("#area-favorites");
            var favCount = $("#favcount");

            //alert("clicked to remove a star");

            tr.fadeOut("normal", function () {

                var $tBody = tr.parent();

                try {
                    tr.remove();
                }
                catch (e) {
                    //alert("remove row error" + tr[0].innerHTML);
                    if (tr[0].innerHTML.length > 0) {
                        //alert("len gt than 0");
                        try {
                            tr[0].innerHTML = "";
                        }
                        catch (e) {

                        }
                    }
                }

                //alert("tbody tr visible " + $("tbody tr:visible",$areaFavs).length);
                if ($("tbody tr:visible", $areaFavs).length == 0) {
                    //alert("favs = 0 need to close");
                    $item.fadeOut("normal", function () {
                        try {
                            $(this).remove();
                        }
                        catch (e) {
                            //alert("remove favs error, no tables");
                        }
                        resizeCol();

                        favCount.text("0");
                        $('#area-favorites').addClass("closed");

                    });
                    RemoveFavorite(trId, true);



                }
                else {

                    //alert("favs > 0 remove table");

                    //alert("item length "+$("tbody tr:visible",$item).length + "\ninner html"+$("tbody tr:visible",$item).html());
                    if ($("tbody tr:visible", $item).length == 0) {
                        //alert("fadeout row then remove");

                        $item.fadeOut("normal", function () {
                            try {
                                $item.remove();
                            }
                            catch (e) {
                                //	alert("remove fav table some left");
                            }
                            console.log("doing the fadeout row then remove");


                            favCount.text($("#area-favorites tbody tr:visible").length);
                            resizeCol();

                        });

                    }
                    RemoveFavorite(trId, false);


                    favCount.text($("#area-favorites tbody tr:visible").length);
                    resizeCol();

                }
                favCount.text($("#area-favorites tbody tr:visible").length);
            });
            //console.debug("len %d", $("#area-favorites tbody tr:visible").length);
            favCount.text($("#area-favorites tbody tr:visible").length);
            return false;
        });
        $("#area-favorites tbody .remove").live("click", function (event) {
            $(this).prev().trigger("click"); event.preventDefault(); event.stopPropagation();
        });

        //tb_init('#area-favorites a.thickbox, #area-favorites area.thickbox, #area-favorites input.thickbox');
        $("#removeFavsLink").each(function () {
	        $(this).removeClass('thickbox');
	        $(this).attr('rel', 'modal');
	         $(this).cclfancybox2({ showNavArrows: false, href: $(this).attr('href'), type: "iframe", width: 540, height:680, scrolling: "yes", overlayColor: "#004497" }); //$(this).attr("href"), 728, 2257);
	     });
	     $(".area-title a.share").each(function () {
	         $(this).removeClass('thickbox');
	         $(this).attr('rel', 'modal');
	         $(this).cclfancybox2({ showNavArrows: false, href: $(this).attr('href'), type: "iframe", width: 680, height: 540, scrolling: "no", overlayColor: "#004497" }); //$(this).attr("href"), 728, 2257);
	     });
	
	setFavoriteResultsTooltips();
    }
}

function updateUrl(selectObj) {
    var $selObj = $(selectObj);
    var selected = $("option:selected", $selObj).val();
    var id = $selObj.attr("id");
    var newUrl = "";
    var updateUrl = false;

    if (id == 'sel-sortby') {
        var valSel = setSortExpression(selected, "string");
        cclSailing.SortExpression = valSel;
        cclSailing.DestinationCodes = $.query.GET('dest');
        cclSailing.PageSize = $("#sel-sortcount option:selected").val();
        updateUrl = true;
    }
    else if (id == "sel-sortcount") {
        var sortBy = $("#sel-sortby option:selected").val();
        var valSel = setSortExpression(sortBy, "string");
        cclSailing.SortExpression = valSel;
        cclSailing.DestinationCodes = $.query.GET('dest');
        cclSailing.PageSize = selected;
        updateUrl = true;
    }

    else if (id == "ctl00_BodyContentPlaceHolder_seldates") {

        resetList();


        var opt = $("option[value='" + $selObj.val() + "']", $selObj).attr("selected", true);
        //console.debug("selected val %s", selected);
        if (opt.hasClass("optGroup")) {

        }
        else if (selected != "") {

            var startMonth = selected.substring(0, 2);
            var startYear = selected.substring(2);

            var endMonth = selected.substring(0, 2);
            var endYear = selected.substring(2);


            cclSailing.FromDate = "" + startMonth + "" + startYear;
            cclSailing.ToDate = "" + endMonth + "" + endYear;

        }
        else {
            cclSailing.FromDate = cclSailing.ToDate = null;
        }

        $(this).trackLink({ buttonName: "Modify Search Box Feature" });

    }
    else if (id == "sel-state") {
        resetList();

        cclSailing.StateCode = $selObj.val();
        SetRateCriteriaCookieState($selObj.val())
        $(this).trackLink({ buttonName: "Modify Search Box Feature" });
        // async update
        //console.log("updated state");
    }
    else if (id == "numGuests") {
        resetList();
        cclSailing.NumGuests = selected;
        updateUrl = false;
    }

    if (updateUrl) {
        var newSearch = buildNewUrl(newUrl)
        location.search = newSearch;
    }
    else {
        cclSailing.SearchAsync(done, failed, cclSailing.PageSize, cclSailing.PageNumber, cclSailing.SortExpression);
        SearchFilter(failed, "");
    }

    return updateUrl;
}

function buildNewUrl(newUrl) {
    var dest = "";
    var serviceCall = false;


    if (newUrl.length > 0) {
        serviceCall = true;
    }

    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) {
        $.query.SET("dest", dest);
    }
    else {
        $.query.REMOVE("dest");
    }

    // Set the number of guests
    var numGuests =
            cclSailing.NumGuests && cclSailing.NumGuests.toString().length > 0 ? cclSailing.NumGuests : 2;
    $.query.SET("numGuests", numGuests);
    // -----

    var dur = "";
    if (cclSailing.DurationCodes != null && cclSailing.DurationCodes.length > 0) {
        try {
            if (typeof cclSailing.DurationCodes == "string") {
                dur = cclSailing.DurationCodes;
            }
            else {
                dur = cclSailing.DurationCodes.join(",");
            }

        } catch (e) { }
    }

    if (dur.length > 0) {
        $.query.SET("dur", dur);
    }
    else {
        $.query.REMOVE("dur");
    }

    var embkCode = "";
    if (cclSailing.PortCodes != null && cclSailing.PortCodes.length > 0) {
        try {
            if (typeof cclSailing.PortCodes == "string") {
                embkCode = cclSailing.PortCodes;
            }
            else {
                embkCode = cclSailing.PortCodes.join(",");
            }


        } catch (e) { }

    }
    if (embkCode.length > 0) {
        $.query.SET("embkCode", embkCode);
    }
    else {
        $.query.REMOVE("embkCode");
    }
    // single values

    $.query.REMOVE("startDate");
    $.query.REMOVE("endDate");
    $.query.REMOVE("cruiseMonth");
    $.query.REMOVE("minDays");
    $.query.REMOVE("maxDays");
    $.query.REMOVE("portName");
    $.query.REMOVE("src");
    $.query.REMOVE("destinationText");

    var dat = ""
    var dates = $("#ctl00_BodyContentPlaceHolder_seldates option:selected").val();
    if (dates != "") {
        dat = dates;
    }
    else {
        dat = "";
    }

    try {
        if (dat.length > 0) {
            $.query.SET("dat", dat);
        }
        else {
            $.query.REMOVE("dat");
        }
    }
    catch (e) {
        $.query.REMOVE("dat");
    }

    var senior = (cclSailing.IsOver55) ? "Y" : "N";
    $.query.SET("Senior", senior);

    var pastGuest = (cclSailing.IsPastGuest) ? "Y" : "N";
    $.query.SET("PastGuest", pastGuest);

    if (cclSailing.StateCode != null) {
        $.query.SET("StateCode", cclSailing.StateCode);
    }

    if (cclSailing.PageNumber > 0) {
        var num = 1;
        if (!serviceCall)
            num = cclSailing.PageNumber;
        else
            cclSailing.PageNumber = num;

        $.query.SET("pageNumber", cclSailing.PageNumber);
    }

    if (cclSailing.PageSize > 0) {
        var val = $("#sel-sortcount").val();
        $.query.SET("pageSize", val);
    }
    if (cclSailing.SortExpression.length > 0) {
        var val = $("#sel-sortby").val();
        setSortExpression(val, "string");
        $.query.SET("sort", cclSailing.SortExpression);
    }

    //takes care of the tgo parameter being set to "undefined" on paging
    if ($.query.GET('tgo') === true) {
        $.query.SET('tgo', '');
    }

    //console.debug("query %s", $.query.toString().substring(1));
    return $.query.toString().substring(1).replace(/%2C/g, ",");
}


var cclSailing = new CCLSailingSearchRequest();
var searchOptions = new Object();
var compiled = false;
var favcompiled = false;
var favsItem = null;
searchOptions.lastPage = -1;
searchOptions.itemsPerPage = 5;
searchOptions.sortExpression = "FromPrice DESC";
searchOptions.currPage = 1;
searchOptions.lastPage = -1;
searchOptions.firstLoad = true;
searchOptions.failCnt = 0;


$(document).ready(function () {

    var page = $.query.GET("pageNumber");
    var querySort = $.query.GET("sort");
    var size = $.query.GET("pageSize");
    $("#sel-sortby option[value='" + querySort + "']").attr("selected", true);
    $("#sel-sortcount option[value='" + size + "']").attr("selected", true);

    if (jQuery.browser.msie) {
        $("body").attr("id", "ie");
    }

    favsItem = $("#area-favorites .cruise-item").clone(true);
    builtInteractions();
    $("#area-favorites").buildFavs();

    if (page == "")
        cclSailing.SearchAsync(done, failed, 5, 1, "FromPrice");
    else
        cclSailing.SearchAsync(done, failed, size, page, querySort);

    $("#content-body").buildCruises(cclSailing);
    resizeCol();

    $("#mysavedcruises a").click(function (event) {
        $('#area-favorites .btn-expand').trigger("click");
        event.preventDefault(); event.stopPropagation();
        return false;
    });

    var lbShowFavorites = $.query.GET("sf");
    if (lbShowFavorites == "true") {
        setTimeout(DoShowFavorites, 500);
    }

    $('.tooltipnarrowsearch').cclqtip('<img style="margin-right: 10px" src="/cms/pageelements/2010/new-header/img/icon-help13x13.gif" alt="" /><span style="font-weight: bold;color:#0f65b8" >Number of Travelers Notice:</span>', '<span style="color:#898989" >The number of travelers is per stateroom. Only one stateroom can be booked at a time.</span>', 'topRight', 'bottomLeft', null, null);

});

function DoShowFavorites() {
    $('#area-favorites .btn-expand').click();
}

function pagingEvent(pageNum, event) {
    cclSailing.PageNumber = pageNum;

    var newSearchUrl = buildNewUrl("");

    event.preventDefault();
    event.stopPropagation();
    location.replace(pagePath + "?" + newSearchUrl);
}

(function ($) {
    $.fn.equalizeCols = function () {

        var height = 0;
        this.css("height", "auto").each(function () {

            height = Math.max(height, jQuery(this).outerHeight(true));
        });
        // code to fix ie8 broken dynamic content height issue
        heightAdj = (jQuery.browser.msie && (parseInt(jQuery.browser.version) == 8)) ? height / 2 : height;
        this.css("height", height);

        if (jQuery.browser.msie && (parseInt(jQuery.browser.version) == 8)) {
            this.each(function (a, domEl) {
                if (a == 1) {
                    $(domEl).css("height", heightAdj);
                }
            });

        }


        return this;
    };
    $.fn.shareForm = function () {
        var yourEmail = "Please enter your email address";
        var toEmail = "(add an email address)";
        return this.each(function () {
            var shareForm = $("#share_favorites");
            var aTag = $(".repeaterControl a", shareForm);
            var repeatSection = $(".toRepeater", shareForm).html();
            var $repeatLi = $("<li class='toRepeater'></li>").html(repeatSection);

            $('#from-email, input[id^="to-email"]').focus(function () {
                currText = ($(this).val() == yourEmail || $(this).val() == toEmail) ? "" : currText;

                $(this).val(currText);
            });
            $('#from-email, input[id^="to-email"]').blur(function () {

                currText = ($(this).val() == "") ? (($(this).attr("id") == "from-email") ? yourEmail : toEmail) : $(this).val();
                $(this).val(currText);
            });

            var count = 0

            aTag.live('click', function (event) {

                var $newLi = $repeatLi.clone(true);
                var textField = $(":text", $newLi);
                textField.blur(function () {
                    currText = ($(this).val() == "") ? (($(this).attr("id") == "from-email") ? yourEmail : toEmail) : $(this).val();
                    $(this).val(currText);
                }).focus(function () {
                    currText = ($(this).val() == yourEmail || $(this).val() == toEmail) ? "" : currText;

                    $(this).val(currText);
                });
                var oldId = textField.attr("id");
                textField.attr("id", oldId + "_" + count);
                $(this).parent().before($newLi);
                count++;
            });
            var limit = $('.word_count').parent().attr("class");
            $('.word_count').each(function () {
                var length = limit - $(this).val().length;
                // update characters  
                $(this).parent().find('.counter').html(length + ' characters remaning');
                // bind on key up event  
                $(this).keyup(function () {
                    // get new length of characters  
                    var new_length = limit - $(this).val().length;
                    // get new length of words  
                    // update  
                    var $remaining = $(this).parent().find('.counter');
                    var ouputStr = new String();

                    if (new_length < 0) {
                        $remaining.addClass("error");
                        outputStr = Math.abs(new_length) + ' characters over';
                    }
                    else {
                        $remaining.removeClass("error");
                        outputStr = new_length + ' characters remaining';
                    }

                    $remaining.html(outputStr);
                });
            });

        });
    };

    $.fn.buildPager = function (options) {
        // new recheck paging
        var defaults = {
            first: -1,
            last: -1,
            itemsPerPage: 5,
            curr: -1,
            block: 'paging',
            prevSpan: $(".paging .prev"),
            nextSpan: $(".paging .next"),
            count: -1,
            showingRange: "-1 - -5"
        };
        var opts = $.extend(defaults, options);

        return this.each(function () {

            if (opts.count == 0) return;

            searchOptions.currPage = opts.curr;
            searchOptions.lastPage = opts.last;
            searchOptions.count = opts.count;
            searchOptions.showingRange = opts.showingRange;

            var startNum, endNum;

            startNum = (opts.curr > 0) ? Math.ceil(opts.curr / opts.range) : 1;
            if (startNum != 1) {
                startNum = (startNum - 1) * opts.range + 1
            }
            endNum = startNum + opts.range - 1
            if (endNum > opts.last) {
                endNum = opts.last;
                if (endNum - opts.range > 1)
                    startNum = endNum - opts.range;
            }
            //if(startNum == endNum)



            if (!searchOptions.showingRange) {
                var range = new Array();
                if (opts.curr == 1) {
                    range[0] = opts.curr;
                    range[1] = parseInt(opts.curr) + parseInt(searchOptions.itemsPerPage) - 1;
                }
                else {
                    range[1] = parseInt(opts.curr) * parseInt(searchOptions.itemsPerPage);
                    range[0] = parseInt(range[1]) - parseInt(searchOptions.itemsPerPage) + 1;

                }
                searchOptions.showingRange = range.join(" - ");

            }
            $('#currentCount').html(searchOptions.showingRange);
            $('#totalCount').html(searchOptions.count);
            $(".pagingInfo").fadeIn("fast");
            var paging = "";
            var aTag = "<a href='#' class='page'>|</a>";
            var spanTag = "<span>|</span>";



            for (var i = startNum; i <= endNum; i++) {
                if (opts.curr == i) {
                    paging += spanTag.replace(/[|]/, i);
                }
                else {
                    paging += aTag.replace(/[|]/, i);
                }
            }
            $(".pages").html($(paging));
            $(".paging").fadeOut("normal");
            // build paging
            $(".paging .pages a").live("click", function (event) {
                pagingEvent($(this).text(), event)
            });

            if (parseInt(searchOptions.currPage) - 1 <= 0) {
                opts.prevSpan.hide();
            }
            else {
                opts.prevSpan.show().live("click", function (event) {
                    resetList();
                    pagingEvent(parseInt(searchOptions.currPage) - 1, event)
                });
            }
            //console.debug("currpage %d  last page %d  compare %b  opts.next %s", (parseInt(searchOptions.currPage, 10)+1), parseInt(searchOptions.lastPage), 
            //(parseInt(searchOptions.currPage, 10)+1 > parseInt(searchOptions.lastPage)), opts.nextSpan);
            if ((parseInt(searchOptions.currPage, 10) + 1) > parseInt(searchOptions.lastPage) && opts.nextSpan != null) {
                opts.nextSpan.css("visibility", "hidden");
            }
            else {

                opts.nextSpan.show().live("click", function (event) {
                    pagingEvent(parseInt(searchOptions.currPage) + 1, event)

                });
            }

            resizeCol();
        });

    };
    $.fn.stackOrderIEFix = function () {
        var zIndexNumber = 500;
        return this.each(function () {
            $(this).css('zIndex', zIndexNumber);
            zIndexNumber -= (zIndexNumber <= 0) ? 0 : 10;
        });
    };
    $.fn.buildCruises = function (cclSailing) {

    };
    $.fn.anchorAnimate = function (settings) {

        settings = jQuery.extend({
            speed: 1100
        }, settings);

        return this.each(function () {
            var caller = this;
            //alert("anchor Animate");

            var locationHref = location.hash;
            //alert("locationHref " + locationHref + "caller " + $(caller).attr("href"));
            var elementClick = ($(caller).attr("href") != "#") ? $(caller).attr("href") : "q" + $(caller).attr("id");
            //alert(elementClick);

            var destination = $("" + locationHref).offset().top - 200;
            //console.debug("locationHref %s  element Click %s  dest %s", locationHref, elementClick, destination);
            //alert("in the click passthrough ");

            $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination }, settings.speed, function () {
                $('#area-favorites .btn-expand').trigger("click");
            });
            return false;

        });
    };
    $.fn.buildFavs = function () {
        GetFavorites(favoritesDone, failed);
    };
})(jQuery);

jQuery.fn.fadeIn = function (speed, callback) {
    return this.animate({ opacity: 'show' }, speed, function () {
        if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 8) {
            this.style.removeAttribute('filter');
        }
        if (jQuery.isFunction(callback))
            callback();
    });
};

jQuery.fn.fadeOut = function (speed, callback) {
    return this.animate({ opacity: 'hide' }, speed, function () {
        if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 8) {
            this.style.removeAttribute('filter');
        }
        if (jQuery.isFunction(callback))
            callback();
    });
};

jQuery.fn.trackLink = function (options) {
    // trackLink
    var defaults = {
        prop: "28",
        linkTrackVars: "28",
        linkTrackEvents: "None",
        trackEventName: 'Search Page Click',
        sprop: "28",
        evar: "27",
        evarTripId: "Cruise",
        favs: false,
        buttonName: 'default click'
    };

    if (!s_account) var s_account = "carnivalprod"


    /*
    if ( (window.location.toString().indexOf("uatcarnival.com")>-1 ) || (window.location.toString().indexOf("syscarnival.com") >-1) || (window.location.toString().indexOf("dev.carnival.com") >-1) ){
	
    s_account="carnivaldev"
	
    }

	
	
    var opts = $.extend(defaults, options);
    var s=s_gi(s_account); 
	
    if(opts.favs){
    // add to favs
    s.linkTrackVars='prop'+opts.prop + ',eVar'+opts.evar;
    s.linkTrackEvents=opts.linkTrackEvents;
    s.prop28 = opts.buttonName;
    s.eVar27 = opts.evarTripId;
    }
    else {
		
    s.linkTrackVars='prop'+opts.prop; 
    s.linkTrackEvents=opts.linkTrackEvents;
    s.prop28 = opts.buttonName;
    	
    }
    s.tl(this,'o',opts.trackEventName);
    */

};

function setSearchResultsTooltips() {
    var showDbl = $.query.GET("showDbl");
    if (showDbl == '') {
        showDbl = 'False';
    }
    var cond = '<span style="color:#898989" >';
    if (showDbl == 'False') {
        cond += "Pricing is displayed as an average rate based on number of travelers. Cruises prices are updated 4 times a day and subject to change without notice.";
    }
    else {
        cond += "Pricing is displayed based on double occupancy rates. Staterooms may be available for other occupancies. Cruises prices are updated 4 times a day and subject to change without notice.";
    }
    cond += '</span>';



    $('#targetcruiselist p.cruise-from').cclqtip(
        '<img class="tooltip" style="margin-right: 10px" src="/cms/pageelements/2010/new-header/img/icon-help13x13.gif" alt="" /><span style="font-weight: bold;color:#0f65b8" >Pricing Notice:</span>',
        cond,
        'topMiddle',
        'bottomMiddle',
            null,
            null);


    $('#targetcruiselist .favs .info').cclqtip(
        '<img class="tooltip" style="margin-right: 10px" src="/cms/pageelements/2010/new-header/img/icon-help13x13.gif" alt="" /><span style="font-weight: bold;color:#0f65b8" >Save to Favorites:</span>',
        'Click the "star" icon next to a sailing to save it to your favorites.',
        'topMiddle',
        'bottomMiddle',
            null,
            null);
			


}

function setFavoriteResultsTooltips() {
    var showDbl = $.query.GET("showDbl");
    if (showDbl == '') {
        showDbl = 'False';
    }
    var cond = '<span style="color:#898989" >';
    if (showDbl == 'False') {
        cond += "Pricing is displayed as an average rate based on number of travelers. Cruises prices are updated 4 times a day and subject to change without notice.";
    }
    else {
        cond += "Pricing is displayed based on double occupancy rates. Staterooms may be available for other occupancies. Cruises prices are updated 4 times a day and subject to change without notice.";
    }
    cond += '</span>';

    $('#area-favorites .favs .info').cclqtip(
        '<img class="tooltip" style="margin-right: 10px" src="/cms/pageelements/2010/new-header/img/icon-help13x13.gif" alt="" /><span style="font-weight: bold;color:#0f65b8" >Save to Favorites:</span>',
        'Click the "star" icon next to a sailing to save it to your favorites.',
        'topMiddle',
        'bottomMiddle',
            null,
            null);

}

function correctLinks(ctx) {
    ctx.find(".body .info .shipName").each(function () {
        $(this).removeClass('thickbox');
        $(this).attr('rel', 'modal');
        //$(this).cclfancybox2({ showNavArrows: false, href: $(this).attr('href'), type: "iframe", width: 728, height: 800, overlayColor: "#004497" }); //$(this).attr("href"), 728, 2257);
	$(this).cclfancybox($(this).attr("href"),726,2500);

        if (ctx.selector == '#targetarea-favorites')
            $(this).attr("onclick", "return false;");
    });
    ctx.find(".body .info .portName").each(function () {
        $(this).removeClass('thickbox');
        $(this).attr('rel', 'modal');
        $(this).cclfancybox($(this).attr("href"), 660, 660);

    });

    ctx.find('.body .detail thead tr th.interior a, .body .detail thead tr th.ocean a, .body .detail thead tr th.balcony a, .body .detail thead tr th.suites a').each(function () {
        $(this).removeClass('thickbox');
        $(this).attr('rel', 'modal');
    });
    ctx.find('.body .detail thead tr th.interior a, .body .detail thead tr th.ocean a, .body .detail thead tr th.balcony a, .body .detail thead tr th.suites a').cclfancybox($(this).attr("href"), 666, 960);


    ctx.find(".body .info .departFrom").each(function () {
        $(this).removeClass('thickbox');
        $(this).attr('rel', 'modal');
        $(this).cclfancybox($(this).attr('href') + '&city=' + $.URLEncode($(this).text()), 660, 560);

        if (ctx.selector == '#targetarea-favorites')
            $(this).attr("onclick", "return false;");
    });
}
