var successfulFirst = false;

$(document).ready(function () {

    $("#excursion-detail-content .box-tooltip").hover(
        function () {
            $("#header2010").css("z-index", 1);
            $("#excursion-detail-content .box-tooltip").css("z-index", 10000);
            $("#excursion-detail-content").css("position", "relative");
            $("#excursion-detail-content").css("z-index", 100001);
        },
        function () {
            $("#header2010").css("z-index", 500);
            $("#excursion-detail-content .box-tooltip").css("z-index", 1);
            $("#excursion-detail-content").css("position", "static");
            $("#excursion-detail-content").css("z-index", 1);
        }
        );

    setTimeout(function () {
        $(".right-col .box-tooltip").hover(
        function () {
            $(".body .right-col").css("z-index", 100);
        },
        function () {
            $(".body .right-col").css("z-index", 1);
        }
        );
    }, 2000);

    $("#ac-tabs.ui-tabs li a[href=#ac-tab-03]").click(function () {
        if ($(".comparecol").size() > 0) {
            $(".comparecol ul.compare-btns").css({ "position": "static" });
            $(".comparecol").equalizeCols();
            if ($(".comparecol").height() < 618) {
                $(".comparecol").css("height", "618px");
            }
            $(".comparecol ul.compare-btns").css({ "position": "absolute" });

            $(".right-col .box-tooltip").hover(
            function () {
                $(".body .right-col").css("z-index", 100);
            },
            function () {
                $(".body .right-col").css("z-index", 1);
            }
            );
        }
    });

    $("#favoritesItemsContainer .removeFavorite").live('click', function () {
        $("#favoritesItemsContainer .row .col1").removeAttr("style"); /*for some reason, .col1 has style="height:0"*/
        $("#favoritesItemsContainer .row .col1, #favoritesItemsContainer .row .col2").equalizeCols();
    });

    $("#ac-tabs.ui-tabs li a[href=#ac-tab-02]").click(function () {
        if ($("#favoritesItemsContainer").children().size() > 0) {
            $("#favoritesItemsContainer .row .col1").removeAttr("style"); /*for some reason, .col1 has style="height:0"*/
            $("#favoritesItemsContainer .row .col1, #favoritesItemsContainer .row .col2").equalizeCols();

            $(".right-col .box-tooltip").hover(
            function () {
                $(".body .right-col").css("z-index", 100);
            },
            function () {
                $(".body .right-col").css("z-index", 1);
            }
            );
        }
    });

    $("#ac-tabs.ui-tabs li a[href=#ac-tab-01]").click(function () {
        $("#activityItemsContainer .row .col1").removeAttr("style"); /*for some reason, .col1 has style="height:0"*/
        $("#activityItemsContainer .row .col1, #activityItemsContainer .row .col2").equalizeCols();
    });


    //Font Size 11
    $(".font-11").click(function () {
        /*$('.overview-title>h2').css('font-size', 11);*/
        $('.columns .single-col p').css('font-size', 11);
        $('.columns .single-col ul li').css('font-size', 11);
        $('.columns .single-col .title h2').css('font-size', 11);
        $('.columns .single-col .bluebox ul li').css('font-size', 11);
        //$('.description>p').css('font-size', 11);
        //$('.description>h3').css('font-size', 11);
        var columnHeight = $('.single-col').css('height');
        $('.middle-content #ac-tabs .columns').css('height', columnHeight); // 12-15-10 for the height issue with columns text resizing
        return false;
    });
    //Font Size 12
    $(".font-12").click(function () {

        /*$('.overview-title>h2').css('font-size', 12);*/
        $('.columns .single-col p').css('font-size', 12);
        $('.columns .single-col ul li').css('font-size', 12);
        $('.columns .single-col .title h2').css('font-size', 12);
        $('.columns .single-col .bluebox ul li').css('font-size', 12);
        //$('.description>p').css('font-size', 12);
        //$('.description>h3').css('font-size', 12);
        var columnHeight = $('.single-col').css('height');
        $('.middle-content #ac-tabs .columns').css('height', columnHeight); // 12-15-10 for the height issue with columns text resizing
        return false;
    });

    //Font Size 14
    $(".font-14").click(function () {
        /*$('.overview-title>h2').css('font-size', 14);*/
        $('.columns .single-col p').css('font-size', 14);
        $('.columns .single-col ul li').css('font-size', 14);
        $('.columns .single-col .title h2').css('font-size', 14);
        $('.columns .single-col .bluebox ul li').css('font-size', 14);
        //$('.description>p').css('font-size', 14);
        //$('.description>h3').css('font-size', 14);
        var columnHeight = $('.single-col').css('height');
        $('.middle-content #ac-tabs .columns').css('height', columnHeight); // 12-15-10 for the height issue with columns text resizing
        return false;
    });

    //$('img[src$=.png]').fixpng();
    //$(document).pngFix();
    $('#ac-tabs .rowElem').jqTransform();
    $('.searchSelect').jqTransform();
    //$('#dropdown-table').jqTransform();
    $('#ac-tabs').tabs();

    $(".box-tooltip").hover(
    function () {
        //$(".body .right-col").css("z-index", 100);
        $(this).find('div').show();

    },
   function () {
       $(this).find('div').hide();
       $(".body .right-col").css("z-index", 1);
   }
    );


    $("div#ac-tabs div").hover(
    function () {
        $(this).css('z-index', 500);
    },
   function () {
       $(this).css('z-index', 1);
   }
    );

    $("#favoritesItemsContainer").hover(
    function () {
        $(this).css('z-index', 500);
    },
   function () {
       $(this).css('z-index', 1);
   }
    );





    $("#compareItemsContainer > div").hover(
        function () {
            $(this).css('z-index', 15);
            $('.lef-col').css('z-index', 1);
        },
        function () {
            $(this).css('z-index', 1);
            $('.lef-col').css('z-index', 10);
        }
 );


    $("#favoritesItemsContainer .row .box-tooltip").hover(
        function () {
            $("#ac-tab-02 div.pos").css("z-index", 1); $('#favoritesItemsContainer .row').css('z-index', 500);
        },
        function () {
            $('#favoritesItemsContainer .row').css('z-index', 'auto'); $("#ac-tab-02 div.pos").css("z-index", 2);
        }
        );



    /******PHOTOS TAB*********/

    $("#ac-tab-02 .photos").each(function () {
        var o = $(this);
        //KJL:Changed the following line because the links to the photos are case sensitive
        //var src = o.find("img").attr("src").toLowerCase();
        var src = o.find("img").attr("src");
        //KJL:Changed the following line because we are using a single file, there is not thumbnail to replace
        //var href = src.replace("-thumb", "-full");
        var href = src;
        o.attr("href", href);
        if (typeof o.attr("alt") == "string" && o.attr("alt").length > 0) {
            var alt = o.attr("alt").substr(0, 45) + "...";
            var hov = "<span class='hover'>" + alt + "</span>";
            o.append(hov);
        }
    });

    $(".banner-content .mainphoto").each(function () {
        var o = $(this);
        //KJL:Changed the following line because the links to the photos are case sensitive
        //var src = o.find("img").attr("src").toLowerCase();
        var src = o.find("img").attr("src");
        //KJL:Changed the following line because we are using a single file, there is not thumbnail to replace
        var href = src.replace("_M", "_L");
        o.attr("href", href);
        if (typeof o.attr("alt") == "string" && o.attr("alt").length > 0) {
            var alt = o.attr("alt").substr(0, 45) + "...";
            var hov = "<span class='hover'>" + alt + "</span>";
            o.append(hov);
        }
    });

    $("a[rel='photos']").fancybox({
        'hideOnOverlayClick': false,
        'hideOnContentClick': false,
        'autoScale': true,
        'overlayColor': '#0a6ed3',
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'titlePosition': 'inside',
        'titleFormat': function (title, currentArray, currentIndex, currentOpts) {
            if (title.length) {
                return '<span id="fancybox-title-over">' + title + '</span>';
            } else {
                return true;
            }
        }
    });

    // IE 6 fix for Excursion Paging
    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
        $("table.excursionsPaging td.botpag ul").css("height", "100px");
        $("table.excursionsPaging td.cpagetot ul").css("height", "80px");

    }

    /***********VIDEOS TAB***********/

    if (window.getVids) {
        getVids();
    }

    $("#video-list a").live('click', function () {
        var vidId = $(this).attr("href").toLowerCase().split("=")[1];
        var title = $(this).text();
        var desc = $(this).attr('title');

        loadVideo(vidId);
        $("#vid-title").html(title);
        $("#vid-desc").html(desc);

        return false;
    });

    $(".middle-content #ac-tabs a[href='#ac-tab-03']").click(function () {
        $("#video-area .carousel-wrapper").jCarouselLite({
            btnNext: ".vid-next",
            btnPrev: ".vid-prev",
            speed: 900,
            scroll: 1,
            circular: false
        });

        $("body").bind('mousemove', function () {
            try {
                cueFirst($("body").data('bcVidObj')[0]);

                if (successfulFirst) {
                    $("body").unbind('mousemove');
                }

            } catch (e) { }

        });

        $(".middle-content #ac-tabs a[href='#ac-tab-01']").bind('focus', function () {
            pauseVideo();
            $(".middle-content #ac-tabs a[href='#ac-tab-01']").unbind('focus');
            $(".middle-content #ac-tabs a[href='#ac-tab-02']").unbind('focus');
        });

        $(".middle-content #ac-tabs a[href='#ac-tab-02']").bind('focus', function () {
            pauseVideo();
            $(".middle-content #ac-tabs a[href='#ac-tab-01']").unbind('focus');
            $(".middle-content #ac-tabs a[href='#ac-tab-02']").unbind('focus');
        });

    });

    //column and rows remover
    $('.removeRow').click(function () {
        $(this).closest('div.row').slideUp(700);
    });
    $('.removeCol').click(function () {
        $(this).closest('div').fadeOut(500);
    });

    //ui slider 
    $('#ageSlider').slider({
        min: 0,
        max: 21,
        step: 1,
        value: 21,
        slide: function (event, ui) {
            SetAgeValue(ui.value);
        }
    });
    //$('.finalAge').val($("#ageSlider").slider("value"));
    SetAgeValue($("#ageSlider").slider("value"));


    //ui price slider 
    $("#priceSlider").slider({
        range: true,
        min: 0,
        max: 500,
        step: 25,
        values: [0, 500],
        stop: function (event, ui) {
            SetPriceLabel($("#priceSlider").slider("option", "values"));
        },
        slide: function (event, ui) {
            SetPriceLabel($("#priceSlider").slider("option", "values"));
        }
    });

    SetPriceLabel($("#priceSlider").slider("option", "values"));

    //$(".finalPrice").val('$' + $("#priceSlider").slider("values", 0) + ' to $' + $("#priceSlider").slider("values", 1) + '+');

    $('.filter input[type="checkbox"]').click(function () {
        var inputCount = 0;
        var filterDiv = $(this).closest('div.filter').find('div.hidden-filters');
        // Count only checked checkboxes
        $(this).closest('div.filter').find('input[type="checkbox"]').each(function () {
            if ($(this).is(':checked')) {
                inputCount++;
            }
        });
        // If any check, set the flag to remain open
        if (inputCount > 0) {
            if (!$(filterDiv).hasClass('remain-open'))
                $(filterDiv).addClass('remain-open');
        }
        else
            $(filterDiv).removeClass('remain-open');
    });

    // sidebar excursion filter menu animation
    $("div.heading").click(function () {

        // close all open 'add-filters' lightboxes
        $('div.add-filters').each(function () { $(this).hide(); });

        var filterList = $(this).next('.filter').children('div.hidden-filters'); //$('#' + thisId + '+ div > div.hidden-filters'); // create variable for thisId's sibling 'div.filter' first child (the filter list)
        var addFilters = $(this).next('.filter').children('div.add-filters'); //$('#' + thisId + '+ div > div.add-filters'); // create variable for thisId's sibling 'div.filter' first child (the add filters lightbox)

        // check for 'active-item' class on clicked div (already selected)
        if ($(this).hasClass('active-item')) {

            // if true, remove 'active-item' class
            $(this).removeClass('active-item');

            // then check if the addFilters object has any checkboxes selected
            if (filterList.hasClass('remain-open')) {
                // only hide the addFilters lightbox - keep the filterList menu open with new class of "remain-open"
                //$(filterList).css('height', 'auto');
                $(addFilters).hide();
            }
            else {
                // no filters selected so hide and collapse both elements
                $(filterList).slideUp();
                $(addFilters).hide();
            }

            // Get list when < arrow clicked
            GetExcursions("1");

            return false;
        }
        // else if for clicked 
        else {

            // Remove the 'active-item' class from all heading elements
            $("div.heading").each(function () {
                $(this).removeClass('active-item');

            });


            $(this).addClass('active-item');
            $('div.filter > div:nth-child(1)').each(function () {

                if ($(this).hasClass('remain-open'))
                { $(addFilters).hide(); }
                else {
                    $(addFilters).hide();
                    $(this).slideUp();
                }

                //return false;
            });

            if ($(filterList).hasClass('remain-open')) {
                $(addFilters).fadeIn();
            }
            else { $(filterList).slideDown(); $(addFilters).fadeIn(); }


            return false;
        }
    });

    // filter close button
    $('.btn-close').click(function () {
        var cb = function () {
            return false;
        };
        GetExcursions("1"); // Added 12/27/2010
        closeFilters(cb);
        return false;
    });

    //
    $('#addExperiences input:checkbox').change(function () {
        if ($(this).is(':checked')) {
            $('<li />').appendTo('#hiddenExperiences ul').text($(this).val());
        }
        else {
            $('#hiddenExperiences li:contains(' + $(this).val() + ')').remove();
        }
    });
    $('#addActivityLevel input:checkbox').change(function () {
        if ($(this).is(':checked')) {
            $('<li />').appendTo('#hiddenActivityLevel ul').text($(this).val());
        }
        else {
            $('#hiddenActivityLevel li:contains(' + $(this).val() + ')').remove();
        }
    });
    $('#addDuration input:checkbox').change(function () {
        if ($(this).is(':checked')) {
            $('<li />').appendTo('#hiddenDuration ul').text($(this).val());
        }
        else {
            $('#hiddenDuration li:contains(' + $(this).val() + ')').remove();
        }
    });

    $("#priceSlider").bind("slidechange", function (event, ui) {
        //$('.hidden-filters').addClass('open').stop();
    });

   
   
   

});

// Close filters
function closeFilters(callbackFunc) {
    $("div.heading").each(function () {

        // close all open 'add-filters' lightboxes
        $('div.add-filters').each(function () { $(this).hide(); });

        var filterList = $(this).next('.filter').children('div.hidden-filters'); //$('#' + thisId + '+ div > div.hidden-filters'); // create variable for thisId's sibling 'div.filter' first child (the filter list)
        var addFilters = $(this).next('.filter').children('div.add-filters'); //$('#' + thisId + '+ div > div.add-filters'); // create variable for thisId's sibling 'div.filter' first child (the add filters lightbox)

        // check for 'active-item' class on clicked div (already selected)
        if ($(this).hasClass('active-item')) {

            // if true, remove 'active-item' class
            $(this).removeClass('active-item');

            // then check if the addFilters object has any checkboxes selected
            if (filterList.hasClass('remain-open')) {
                // only hide the addFilters lightbox - keep the filterList menu open with new class of "remain-open"
                //$(filterList).css('height', 'auto');
                $(addFilters).hide();
            }
            else {
                // no filters selected so hide and collapse both elements
                $(filterList).slideUp();
                $(addFilters).hide();
            }

            // Get list when < arrow clicked
            GetExcursions("1");

            return false;
        }

    });

}

function closeforgot() {
    $('#dialog-forgot').dialog('close');
    return false;
}



/* =jQuery Plugins*/
(function ($) {

    $.fn.stackOrderIEFix = function () {
        var zIndexNumber = 1000;
        return this.each(function () {
            $(this).css('zIndex', zIndexNumber);
            zIndexNumber -= (zIndexNumber <= 0) ? 0 : 10;
        });
    }; /********EQUALIZE HEADER ************/
    $.fn.equalizeHeaders = function () {
        var height = 0,
            reset = $.browser.msie ? "1%" : "auto";
        return this.css("height", reset).each(function () {
            height = Math.max(height, $(this).outerHeight(true));
        }).each(function () {
            var _this = $(this);
            var h = height - _this.height();
            var top = parseInt(h / 2);
            var bottom = h - top;
            _this.css({
                'padding-top': top,
                'padding-bottom': bottom
            });
        });
    };
    /********EQUALIZE************/
    $.fn.equalizeCols = function () {
        var height = 0,
            reset = $.browser.msie ? "1%" : "auto";

        return this.css("height", reset).each(function () {
            height = Math.max(height, $(this).outerHeight(true));
        }).css("height", height).each(function () {
            var h = $(this).outerHeight(true);
            if (h > height) {
                $(this).css("height", height - (h - height));
            };
        });
    };

    /**************************/
    /********FIX PNG************/
    jQuery.fn.pngFix = function (settings) {

        // Settings
        settings = jQuery.extend({
            blankgif: 'blank.gif'
        }, settings);

        var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
        var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

        if (jQuery.browser.msie && (ie55 || ie6)) {

            //fix images with png-source
            jQuery(this).find("img[src$=.png]").each(function () {

                jQuery(this).attr('width', jQuery(this).width());
                jQuery(this).attr('height', jQuery(this).height());

                var prevStyle = '';
                var strNewHTML = '';
                var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
                var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
                var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
                var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
                var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
                var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
                if (this.style.border) {
                    prevStyle += 'border:' + this.style.border + ';';
                    this.style.border = '';
                }
                if (this.style.padding) {
                    prevStyle += 'padding:' + this.style.padding + ';';
                    this.style.padding = '';
                }
                if (this.style.margin) {
                    prevStyle += 'margin:' + this.style.margin + ';';
                    this.style.margin = '';
                }
                var imgStyle = (this.style.cssText);

                strNewHTML += '<span ' + imgId + imgClass + imgTitle + imgAlt;
                strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;' + imgAlign + imgHand;
                strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
                strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
                strNewHTML += imgStyle + '"></span>';
                if (prevStyle != '') {
                    strNewHTML = '<span style="position:relative;display:inline-block;' + prevStyle + imgHand + 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;' + '">' + strNewHTML + '</span>';
                }

                jQuery(this).hide();
                jQuery(this).after(strNewHTML);

            });

            // fix css background pngs
            jQuery(this).find("*").each(function () {
                var bgIMG = jQuery(this).css('background-image');
                if (bgIMG.indexOf(".png") != -1) {
                    var iebg = bgIMG.split('url("')[1].split('")')[0];
                    jQuery(this).css('background-image', 'none');
                    jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
                }
            });

            //fix input with png-source
            jQuery(this).find("input[src$=.png]").each(function () {
                var bgIMG = jQuery(this).attr('src');
                jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
                jQuery(this).attr('src', settings.blankgif)
            });

        }

        return jQuery;

    };

})(jQuery);


var paging; // = { PagingInfo: { PageCount: 5, TotalItemCount: 42, PageNumber: 2, PageSize: 10, PageIndex: 0, HasPreviousPage: true, HasNextPage: true, IsFirstPage: true, IsLastPage: false} };

$(document).ready(function () {

    $(".excursionsPaging div.jqTransformSelectWrapper ul li a").click(function () {
        GetExcursions("1");
    });

    $(".favoritesPaging div.jqTransformSelectWrapper ul li a").click(function () {
        GetPresaleFavorites();
    });

});


function setPaging(paging) {

    if (!paging)
        $(".pagingTable").removeClass('pagingTableOn').addClass('pagingTableOff');

    else {

        $("." + paging.ListType + "Paging").find(".pagingTable").removeClass('pagingTableOff').addClass('pagingTableOn');

        var $prev = $("." + paging.ListType + "Paging").find('.cell_prev').children();
        var $next = $("." + paging.ListType + "Paging").find('.cell_next').children();
        /*
        if (paging.HasPreviousPage)
        $prev.css({ 'display': 'inline', 'visibility': 'visible' });
        else $prev.css({ 'display': 'none', 'visibility': 'hidden' });

        if (paging.HasNextPage)
        $next.css({ 'display': 'inline', 'visbility': 'visible' });
        else
        $next.css({ 'display': 'none', 'visbility': 'hidden' });

        */
        var items = $("." + paging.ListType + "Paging").find('.table_page_row').find('a');
        //var items = $('.table_cell_page_numbers').find('a');
        items.each(function () {
            $(this).remove();
        });



        if (paging.HasPreviousPage) {
            link = "<a name='prev' class='prev paging_link' href='javascript:void(0)'>&laquo;Previous&nbsp;</a>";
            //$('.table_cell_page_numbers').append(link);

            $("." + paging.ListType + "Paging").find('.table_cell_page_numbers').append(link);
        }


        if (paging.PageCount > 1) {
            for (var i = 1; i <= paging.PageCount; i++) {
                var link;
                if (i == paging.PageNumber)
                    link = "<a name='" + i + "' class='selected paging_link' href='javascript:void(0)'>" + i + "&nbsp;</a>";
                else
                    link = "<a name='" + i + "' class='notselected paging_link' href='javascript:void(0)'>" + i + "&nbsp;</a>";
                //$('.table_cell_page_numbers').append(link);
                $("." + paging.ListType + "Paging").find('.table_cell_page_numbers').append(link);
            }
            if (paging.HasNextPage) {
                link = "<a name='next' class='next paging_link' href='javascript:void(0)'>&nbsp;Next&raquo;</a>";
                //$('.table_cell_page_numbers').append(link);
                $("." + paging.ListType + "Paging").find('.table_cell_page_numbers').append(link);
            }

            //$('.table_cell_page_numbers').find('a').click(function () {
            $("." + paging.ListType + "Paging").find('.table_cell_page_numbers').find('a').click(function () {
                UpdatePageChange(this, paging.ListType);
            });



            $prev.click(function () {
                UpdatePageChange(this, paging.ListType);
            });

            $next.click(function () {
                UpdatePageChange(this, paging.ListType);
            });
        }
    }
}

function UpdatePageChange(obj, listType) {
    var $selected = $("." + listType + "Paging").find('.table_page_row').find('.selected').attr('name');
    var $clicked = $(obj).attr('name');
    var selectedPageNum;
    if ($selected != $clicked) {
        if ($clicked == 'prev')
            selectedPageNum = GetPrevPageNumber($selected);
        else if ($clicked == 'next') {
            selectedPageNum = GetNextPageNumber($selected);
        }
        else selectedPageNum = parseInt($clicked);
    }
    else selectedPageNum = 0;

    if (selectedPageNum != 0) {
        if (listType == "excursions")
            GetExcursions(selectedPageNum);
        else
            GetPresaleFavorites(selectedPageNum);
    }
}

function GetPrevPageNumber(currentPage) {
    var pageNum = parseInt(currentPage);
    if (pageNum == 1)
        return 1;
    else return pageNum - 1;
}

function GetNextPageNumber(currentPage) {
    var pageNum = parseInt(currentPage);
    return pageNum + 1;
}
// end paging functionality


/*
var resizeTimer = null;
$(window).bind('resize', function () {
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(adjustLightbox, 100);
});
*/
$('.btn-login').click(function () {
    //submitLogin();
});

$('.btn-register').click(function () {
  //submitRegistration();
});

function CheckIfUserLoggedIn() {
    $.ajax({
        type: 'POST',
        url: '/Activities/Guest/IsLoggedInUser',
        data: {},
        success: function (data, textStatus, XMLHttpRequest) {
            if (data == "True") {
                $('#LoginBox').hide();
                return true;
            } else {
                $('#LoginBox').show();
                return true;
            }
        }
    });
}

function GetSeed() {
    $.ajax({
        type: 'POST',
        url: '/Activities/Guest/GetSeed',
        data: {},
        success: function (data, textStatus, XMLHttpRequest) {
            return data;
        }
    });
}


function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));


    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }

}

function makeSecureURL(url) {
    if (url.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        return url;
    }
    else {
        url = url.replace("http://www", "https://secure");
        return url;
    }

}




function logincallback(rtndata) {
    $('#imgLoginProcessing').hide();
    if (rtndata == "") {
        GetPresaleFavorites();
        closelogin();
        $('#LoginBox').hide();
    } else {
        //alert(rtndata)
        $('#lblLoginErrorMessage').text(rtndata);
        
    }
 }

 function registrationcallback(rtndata) {
     $('#imgRegisterProcessing').hide();
     if (rtndata == "") {
         GetPresaleFavorites();
         closelogin();
         $('#LoginBox').hide();
     } else {
         $('#lblRegisterErrorMessage').text(rtndata);

     }
 } 

function submitRegistration() {
    var valid = $("#formregister").valid();
    if (!valid) return;

    var password = $('#RegistrationPassword').val();
    var email = $('#RegistrationEmail').val(); 
    var firstname = $('#FirstName').val();
    var lastname = $('#LastName').val(); 

    $('#imgRegisterProcessing').show();
    var url = getBaseURL();
    if (url.indexOf('http://localhost') != -1) {
        url += 'Guest/Register'
    } else {
        url += 'Activities/Guest/Register';
        url = makeSecureURL(url);
    }
    $.ajax({
        url: url,
        dataType: 'jsonp',
        jsonpCallback: "registrationcallback",
        jsonp: "callback",
        data: { firstName:firstname, lastName:lastname, password:password, email:email }
    });


//    $.ajax({
//        type: 'POST',
//        url: '/Activities/Guest/Register',
//        data: { firstName: $('#FirstName').val(), lastName: $('#LastName').val(), password: $('#RegistrationPassword').val(), email: $('#RegistrationEmail').val() },
//        success: function (data, textStatus, XMLHttpRequest) {
//            $('#imgRegisterProcessing').hide();
//            if (data == "") {
//                GetPresaleFavorites();
//                closelogin();
//                $('#LoginBox').hide();
//            } else {
//                $('#lblRegisterErrorMessage').text(data);
//            }
//        },
//        error: function () {
//            $('#lblRegisterErrorMessage').text('Failed to register')
//           .css({ 'display': 'block' });

//            $('#imgRegisterProcessing').hide();
//        }
//    });

}

// favorites functionality
function addFavorite(id) {
    // omniture reporting
    s.linkTrackVars = 'prop51,eVar54';
    s.prop51 = id;
    s.eVar54 = s.prop51;
    //s.eVar54 = s.getValOnce(s.eVar54, "excursion_fav", 0);
    s.tl(this, 'o', 'Shore Excursion|Save to Favorites');
    var s_code = s.t(); if (s_code) document.write(s_code);

    var classSelector = "[class^=addfavorite_" + id + "]";
    //var classSelector = ".addfavorite_" + id;
    var url = '/Activities/Favorites/Add';
    var image = $(classSelector).find('img'); //.attr('src');
    var src = $(classSelector).find('img').attr('src');

    $.ajaxSetup({ "async": false, "cache": false });
    $.getJSON(url, { activityId: id }, function (data) {
        var response = eval(data);
        if (data.Success) {
            if (src != undefined) {
                if (src.indexOf('_saved') == -1) {
                    src = src.replace('_save', '_saved');
                    $(classSelector).removeAttr("href");
                    $(classSelector).find('img').attr('src', src);
                    $(classSelector).find('img').attr('alt', "SAVED TO FAVORITES");
                }
            }
            if (eval("typeof GetPresaleCompares  == 'function'")) {
                $('.favoriteCount').text(data.Count);
                //GetPresaleCompares();
                GetPresaleFavorites();
            }
        } else {
            // alert(data.Message);
        }

    });
    $.ajaxSetup({ "async": true });
};

function removeFavorite(id) {
    var url = '/Activities/Favorites/Remove';
    var classSelector = "[class^=addfavorite_" + id + "]";
    //var classSelector = ".addfavorite_" + id;
    var image = $(classSelector).find('img'); //.attr('src');
    var src = $(classSelector).find('img').attr('src');

    $.ajaxSetup({ "async": false, "cache" : false });
    $.getJSON(url, { activityId: id }, function (data) {
        var response = eval(data);

        if (data.Success) {
            //$("#favoritesItemsContainer").find("#favorite_" + id).remove();
            //$('.favoriteCount').text(data.Count);

            if (src != undefined) {
                src = src.replace('_saved', '_save');
                $(classSelector).find('img').attr('src', src);
                $(classSelector).find('img').attr('alt', "SAVE TO FAVORITES");
                $(classSelector).attr('href', "javascript:void(0);");
            }
            if (eval("typeof GetPresaleFavorites  == 'function'")) {
                $('.favoriteCount').text(data.Count);
                GetPresaleFavorites();
            }
        } else {
            alert(data.Message);
        }

    });
    $.ajaxSetup({ "async": true });
};
// end favorites functionality


// compare functionality
function toggleCompare(id) {
    var image = $(".addcompare_" + id).find('img');
    var src = $(".addcompare_" + id).find('img').attr('src');

    // btnDelete will be true if "Remove from Compares" button clicked or if "Remove" clicked from compare tab
    var blnDelete;
    var url;
    if (src == undefined) {
        blnDelete = true
    }
    else {
        blnDelete = src.indexOf("btn_remove_compare") >= 0;
    }

    if (blnDelete) {
        url = '/Activities/Compare/Remove';
    }
    else {
        url = '/Activities/Compare/Add';
        // omniture reporting
        s.linkTrackVars = 'prop52,eVar54';
        s.prop52 = id;
        s.eVar54 = s.prop52;
        //s.eVar54 = s.getValOnce(s.eVar54, "excursion_fav", 0);
        s.tl(this, 'o', 'Shore Excursion|Add to Compare');
        var s_code = s.t(); if (s_code) document.write(s_code);
    }

    $.ajaxSetup({ "async": false, "cache": false });
    $.getJSON(url, { activityId: id }, function (data) {
        var response = eval(data);
        if (data.Success) {
            // update count in tab header
            $('.compareCount').text(data.Count);

            // add or delete items and update images
            if (blnDelete) {
                $("#compareItemsContainer").find("#compare_" + id).remove();
                if (src != undefined) {
                    src = src.replace('btn_remove_compare', 'btn_add_to_compare');
                    $(".addcompare_" + id).find('img').attr('alt', "ADD TO COMPARE");
                    $(".addcompare_" + id).find('img').attr('src', src);
                }
            }
            else {
                GetPresaleCompares();
                if (src != undefined) {
                    src = src.replace('btn_add_to_compare', 'btn_remove_compare');
                    $(".addcompare_" + id).find('img').attr('alt', "REMOVE FROM COMPARE");
                    $(".addcompare_" + id).find('img').attr('src', src);
                }
            }
        } else {
            alert(data.Message);
        }
    });
    $.ajaxSetup({ "async": true, "cache": true });
};





function EnableDisableActivityTypes(data) {
    if (data) {
        var types = data.EnabledActivityTypes;
        if (types) {
            var $inputTypes = $("#tblExperiences").find("input");
            for (var i = 0; i < $inputTypes.length; i++) {
                var match = false;
                var $type = $($inputTypes[i]);
                var $val = $type.val();
                for (var j = 0; j < types.length; j++) {
                    if ($val == types[j]) { match = true; break; }
                }
                if (match) { $type.removeAttr("disabled"); $type.next('label').css('color', '#0067C9'); }
                else { $type.attr("disabled", true); $type.next('label').css('color', '#ccc'); }
            }

        }
    }
}

// ----------------------------------
// List Page - Supporting Functions
// ----------------------------------
// Start -> Look for stop at the bottom

// Use to set an Age level on the filter
function SetAgeValue(value) {
    switch (value) {
        case 0:
            $('.finalAge').val("No minimum age");
            break;
        case 21:
            $('.finalAge').val("Mission & vission");
            break;
        default:
            $('.finalAge').val("Ages up to " + value);
            break;
    }
    if (value < 30 && !$("#hiddenMinimumAge").hasClass("remain-open"))
        $("#hiddenMinimumAge").addClass("remain-open");
    else if (value == 21)
        $("#hiddenMinimumAge").removeClass("remain-open");
}

// Use to set a price label on the filter
function SetPriceLabel(values) {
    var low = values[0];
    var high = values[1];
    var plusChar = "";
    if (high == 500)
        plusChar = "+";
    $(".finalPrice").val('$' + $("#priceSlider").slider("values", 0) + ' to $' + $("#priceSlider").slider("values", 1) + plusChar);

    if (low == 0 && high == 500)
        $("#hiddenPriceRange").removeClass("remain-open");
    else if (!$("#hiddenPriceRange").hasClass("remain-open"))
        $("#hiddenPriceRange").addClass("remain-open");
}


//window.onunload = SaveState;

// Save the filter options
function SaveSettings() {
    lastsettings = GetPageSettings();
}

// Restore the filter options
function RestoreSettings() {
    if (lastsettings)
        RestoreFilters(lastsettings);
}

function SaveState() {
    $.post("/Activities/Excursions/SaveState", GetPageSettings(), function (data) {
    });
}

function SaveStateMyRes() {
    var settings = GetPageSettings();
    setttings.LastPage = "1";
    $.post("/Activities/Excursions/SaveState", settings, function (data) {
    });
}

// Save the state before navigating to another page
function SaveStateAndNavigate(url) {
    $.post("/Activities/Excursions/SaveState", GetPageSettings(), function (data) {
        document.location = url;
    });
}

function RestoreFilter(selector, list) {
    if (list) {
        var items = list.split(",");
        for (i = 0; i < items.length; i++) {
            var selectorId = "#" + selector + "_" + items[i].replace(" ", "_");
            $(selectorId).attr('checked', 'true');

            switch (selector) {
                case "exfilter":
                    $('<li />').appendTo('#hiddenExperiences ul').text($(selectorId).val());
                    break;
                case "hrfilter":
                    $('<li />').appendTo('#hiddenDuration ul').text($(selectorId).val());
                    break;
                case "lvfilter":
                    $('<li />').appendTo('#hiddenActivityLevel ul').text($(selectorId).val());
                    break;
            }
        }

        // Open the filters
        if (selector == "exfilter" && list.length > 0 && !$('#hiddenExperiences').hasClass('remain-open')) {
            $('#hiddenExperiences').addClass('remain-open');
            $('#hiddenExperiences').slideDown();
        }

        if (selector == "hrfilter" && list.length > 0 && !$('#hiddenDuration').hasClass('remain-open')) {
            $('#hiddenDuration').addClass('remain-open');
            $('#hiddenDuration').slideDown();
        }

        if (selector == "lvfilter" && list.length > 0 && !$('#hiddenActivityLevel').hasClass('remain-open')) {
            $('#hiddenActivityLevel').addClass('remain-open');
            $('#hiddenActivityLevel').slideDown();
        }

        // Todo: Age and Price

    }
}

// Restore the filters (can be used for local searches)
function RestoreFilters(setting) {

    // Restore Filters
    RestoreFilter("lvfilter", setting.Levels);
    RestoreFilter("hrfilter", setting.Duration);
    RestoreFilter("exfilter", setting.Experiences);

    if (setting.Age) {
        try {
            $("#ageSlider").slider("option", "value", Number(setting.Age));
            SetAgeValue(setting.Age); // @management-courses.js
            if ($("#hiddenMinimumAge").hasClass("remain-open"))
                $('#hiddenMinimumAge').slideDown();
        }
        catch (e) { }
    }

    if (setting.Prices) {
        try {
            var arPrices = setting.Prices.split(",");
            var nprices = new Array();
            nprices[0] = Number(arPrices[0]);
            nprices[1] = Number(arPrices[1]);
            $("#priceSlider").slider("option", "values", nprices);
            SetPriceLabel(nprices); // @management-courses.js
            if ($("#hiddenPriceRange").hasClass("remain-open"))
                $("#hiddenPriceRange").slideDown();
        } catch (e) { }
    }

}

// Restore the state from session
function RestoreState() {

    ResetFilters(null);
    $.ajaxSetup({ cache: false });
    $.getJSON("/Activities/Excursions/RestoreState", null, function (page) {

        // Save the settings from session to local
        // Later the object is removed from session
        var destination = page.Destination;
        var experiences = page.Experiences;
        var port = page.Port;
        var levels = page.Levels;
        var duration = page.Duration;
        var prices = page.Prices;
        var age = page.Age;
        var sortIndicator = page.SortIndicator;
        var pagesize = page.PageSize;
        var tabIndex = page.TabIndex;

        // Page Variable
        lastpage = page.LastPage;

        // Restore Filters
        RestoreFilters(page);

        // Restore Sorting
        $(".excursionsPaging").find("#ssort").val(sortIndicator);
        var index = $("#ssort").attr("selectedIndex");
        if (index) {
            var text = $("#ssort :selected").text();
            $(".excursionsPaging div.jqTransformSelectWrapper ul li a").removeClass("selected");
            $(".excursionsPaging div.jqTransformSelectWrapper ul li a[index='" + index + "']").addClass("selected");
            $(".excursionsPaging div.jqTransformSelectWrapper div:first span").html(text);
        }

        // Restore Paging
        $(".excursionsPaging").find("#spage").val(pagesize);
        index = $("#spage").attr("selectedIndex");
        if (index) {

            var text = $("#spage :selected").text();
            $(".excursionsPaging .cpagetot div.jqTransformSelectWrapper ul li a").removeClass("selected");
            $(".excursionsPaging .cpagetot div.jqTransformSelectWrapper ul li a[index='" + index + "']").addClass("selected");
            $(".excursionsPaging .cpagetot div.jqTransformSelectWrapper div:first span").html(text);
        }

        // Restore Paging
        // Todo:

        // Restore Tab
        var $tabs = $('#ac-tabs').tabs();
        $tabs.tabs('select', Number(tabIndex));

        // Restore Content
        if (destination) {
            var url = "/Activities/Excursions/GetDestinations";
            $.ajaxSetup({ cache: false });
            $.getJSON(url, null, function (data) {
                UpdateDestination(data, destination);
                if (shoppingMode == "Browse")
                    UpdatePort(destination, port, GetExcursionsLastPage);
                else
                    UpdatePort(null, port, GetExcursionsLastPage);
            });
        }

        // Remove Navigation Information From Session
        $.ajaxSetup({ cache: false });
        $.post("/Activities/Excursions/ResetState", null, function (data) {

            GetPresaleFavorites("1");

            GetPresaleCompares();

        });

    });
}

function GetExcursionsLastPage() {
    GetExcursions(lastpage);
    //GetExcursions("1");
}

function GetPageSettings() {

    var port = GetCboValue(".cport", "sport");
    var destination = GetCboValue(".cdestination", "sdestination");
    var pricesArr = $("#priceSlider").slider("option", "values");
    var prices = pricesArr.join(",");
    var levels = GetListFromClass("lvfilter");
    var experiences = GetListFromClass("exfilter");
    var age = $("#ageSlider").slider("option", "value");
    var duration = GetListFromClass("hrfilter");
    var sortIndicator = $(".excursionsPaging").find("#ssort").val();
    var pageSize = $(".excursionsPaging").find("#spage").val();
    var $tabs = $('#ac-tabs').tabs();
    var tabIndex = $tabs.tabs('option', 'selected');

    // Returnt the object
    return { Destination: destination, Port: port, Prices: prices, Levels: levels, Experiences: experiences, Duration: duration, Age: age, SortIndicator: sortIndicator, LastPage: lastpage, PageSize: pageSize, TabIndex: tabIndex };
}

function IsNullOrEmpty(value) {
    return (value == null || value.length == 0);
}

function AllFiltersNull() {

    var settings = GetPageSettings();

    return (settings.Age == "21" && IsNullOrEmpty(settings.Duration) && IsNullOrEmpty(settings.Experiences) &&
                IsNullOrEmpty(settings.Levels) && settings.Prices == "0,500");

}

//
function ResetSliders() {
    try {

        $("#ageSlider").slider("option", "value", 30);
        var age = $("#ageSlider").slider("option", "value");
        SetAgeValue(age);

        var alist = new Array();
        alist.push(0);
        alist.push(500);

        $("#priceSlider").slider("option", "values", alist);
        SetPriceLabel(alist);

        // Get the excursion after the filters are reset

    } catch (e) {

    }
}

// Reset Filters
function ResetFilters(delegate) {

    $('.hrfilter').attr('checked', false);
    $('.exfilter').attr('checked', false);
    $('.lvfilter').attr('checked', false);

    //$('.curr-filter').html("");
    $("#hiddenExperiences ul").html("");
    $("#hiddenActivityLevel ul").html("");
    $("#hiddenDuration ul").html("");

    $('div.hidden-filters').removeClass('remain-open').hide();

    var cb = function () { return false; };
    closeFilters(cb);

    ResetSliders();

    if (delegate)
        delegate();
    //GetExcursions("1");

}

// Display a progress icon
function DisplayProgressIcon(show, selector) {
    var progressIconHtml = "<center><img src=\"" + progressIconUrl + "\" alt=\"\" /></center>";

    if (show)
        $(selector).html(progressIconHtml);
    else
        $(selector).html("");
}

function GetListFromClass(css) {

    var list = "";

    var boxes = "";

    $('.' + css).each(function (index) {
        var checked = $(this).attr('checked');
        //alert(index + ': ' + );

        if (checked) {

            var item = $(this).context.name.replace(css + "_", "");

            list += item + ',';

            boxes += "<input type=\"checkbox\" disabled=\"disabled\" checked=\"checked\" /> " + item + "<br/>";

            //$("#selectedexperiences").append(cbox + "<br/>");

        }
    });

    if (list.length > 0)
        list = list.substr(0, list.length - 1);

    if (boxes != null && boxes.length > 0)
        $("#selectedexperiences").append("<label>Selected Experiences:</label><br/>" + boxes);

    return list;

}

function GetCboValue(css, element) {

    var index = $(css + " div.jqTransformSelectWrapper ul li a[class=\"selected\"]").attr("index");

    if (index == undefined)
        return null;

    var cbo = document.getElementById(element);

    if (cbo == null)
        return;

    return cbo.options[index].value;

}

function GetExcursions(currentPage) {

    if (!currentPage)
        currentPage = "1";

    lastpage = currentPage;

    var settings = GetPageSettings();

    var excursionsurl = "/Activities/Excursions/GetExcursions";

    DisplayProgressIcon(true, "#activityItemsContainer");

    $('.excursionsCount').text(0);
    $("#selectedexperiences").html("");

    if (settings.Port && settings.Port == "0") {
        DisplayProgressIcon(false, "#activityItemsContainer");
        $("#activityItemsContainer").html($("#welcomediv").html());
        return;
    }

    if (settings.Port) {

        $.ajaxSetup({ "cache": false });
        $.getJSON(excursionsurl, { portCode: settings.Port, Destination: settings.Destination, Prices: settings.Prices,
            Levels: settings.Levels, Experiences: settings.Experiences, CurrentPage: currentPage, PageSize: settings.PageSize, Duration: settings.Duration,
            Age: settings.Age, SortIndicator: settings.SortIndicator, ShopMode: shoppingMode
        }, function (data) {

            var list = data.Items;
            var paging = data.PagingInfo;

            // Show the total excursions on the tab
            $('.excursionsCount').text(paging.TotalItemCount);

            if (list != null && list.length > 0) {
                // Reset Results
                $("#activityItemsContainer").html("");

                var markup = $("#activityItemsTemplate").html();
                $.template("activityItemsTemplate", markup);
                $.tmpl("activityItemsTemplate", list).appendTo("#activityItemsContainer");

                // Hide items not in buy mode
                if (shoppingMode != "Buy" && shoppingMode != "Email")
                    $(".changemode").html("");

                //$(".addtooltip").addClass("box-tooltip1");

                $('#activityItemsContainer .box-tooltip').hover(
                        function () {
                            $(this).find('div').show();
                        }, function () {
                            $(this).find('div').hide();
                        });

                $("#activityItemsContainer .row").each(function (index) {
                    var col1H = $(this).find(".col1").height();
                    var col2H = $(this).find(".col2").height();
                    if (col1H > col2H)
                        $(this).find(".col2").height(col1H);
                    else
                        $(this).find(".col1").height(col2H);
                });

                $("#ac-tab-01 a.savestate").click(function (event) {
                    SaveStateAndNavigate($(this).attr("href"));
                    event.preventDefault();
                });

                /*$('.row div').equalizeCols();
                (function ($) {
                $.fn.equalizeCols = function () {
                var height = 0,
                reset = $.browser.msie && $.browser.version < 7 ? "1%" : "auto";

                return this.css("height", reset).each(function () {
                height = Math.max(height, this.offsetHeight);
                }).css("height", height).each(function () {
                var h = this.offsetHeight;
                if (h > height) {
                $(this).css("height", height - (h - height));
                };
                });
                };
                })(jQuery);*/

                // Activate the enabled activity types
                EnableDisableActivityTypes(data);

                $('html, body').animate({ scrollTop: 0 }, 0);

            }
            else if (list != null && list.length == 0)
                if (AllFiltersNull())
                    $("#activityItemsContainer").html($("#norexcursionsdiv").html());
                else
                    $("#activityItemsContainer").html($("#noresultsdiv").html());

            setPaging(paging);

        });
    }
    else
        DisplayProgressIcon(false, "#activityItemsContainer");

}


function GetPresaleTransfers() {

    currentPage = "1";
    lastpage = currentPage;
    //var settings = GetPageSettings();

    var excursionsurl = "/Activities/Transfers/GetTransfers";
    DisplayProgressIcon(true, "#transferItemsContainer");

    $('.transferCount').text(0);


    $.ajaxSetup({ "cache": false });
    $.getJSON(excursionsurl, null, function (data) {
        var list = data.Items;
        var paging = data.PagingInfo;

        // Show the total excursions on the tab
        $('.transferCount').text(list.length); //paging.TotalItemCount);

        if (list != null && list.length > 0) {
            // Reset Results
            $("#transferItemsContainer").html("");

            var markup = $("#transferItemsTemplate").html();
            $.template("transferItemsTemplate", markup);
            $.tmpl("transferItemsTemplate", list).appendTo("#transferItemsContainer");


            $('#transferItemsContainer .box-tooltip').hover(
                    function () {
                        $(this).find('div').show();
                    }, function () {
                        $(this).find('div').hide();
                    });

            $("#transferItemsContainer .row").each(function (index) {
                var col1H = $(this).find(".col1").height();
                var col2H = $(this).find(".col2").height();
                if (col1H > col2H)
                    $(this).find(".col2").height(col1H);
                else
                    $(this).find(".col1").height(col2H);
            });

            $("#ac-tab-01 a.savestate").click(function (event) {
                SaveStateAndNavigate($(this).attr("href"));
                event.preventDefault();
            });


            $('html, body').animate({ scrollTop: 0 }, 0);

        }
        else if (list != null && list.length == 0)
            if (AllFiltersNull())
                $("#transferItemsContainer").html($("#norexcursionsdiv").html());
            else
                $("#transferItemsContainer").html($("#noresultsdiv").html());

        //setPaging(paging);

    });
}

function GetPresaleFavorites(currentPage) {

    if (!currentPage)
        currentPage = "1";
    var url = "/Activities/Favorites/GetExcursions";

    //get the total items per page
    var pageSize = $(".favoritesPaging").find('#spage').val();
    var sortIndicator = $(".favoritesPaging").find("#ssort").val();

    //DisplayProgressIcon(true, "#favoritesItemsContainer");

    //$("#selectedexperiences").html("");

    $.ajaxSetup({ "async": true, "cache": false });
    $.getJSON(url, { CurrentPage: currentPage, PageSize: pageSize, SortIndicator: sortIndicator }, function (data) {

        var list = data.Items;
        var paging = data.PagingInfo;

        if (list != null) {
            // Reset Results
            $('.favoriteCount').text(paging.TotalItemCount);
            $("#favoritesItemsContainer").html("");

            var markup = $("#favoriteItemsTemplate").html();
            $.template("favoriteItemsTemplate", markup);

            $.tmpl("favoriteItemsTemplate", list).appendTo("#favoritesItemsContainer");
            //only add items not already rendered
            //$.each(list, function (index, item) {
            //    if ($("#favorite_" + item.ShoreExCode).length == 0)
            //        $.tmpl("favoriteItemsTemplate", item).appendTo("#favoritesItemsContainer");
            //});

            // Hide items not in buy mode
            if (shoppingMode != "Buy" && shoppingMode != "Email")
                $(".changemode").html("");

            $('#favoritesItemsContainer .box-tooltip').hover(
                    function () {
                        $(this).find('div').show();
                    }, function () {
                        $(this).find('div').hide();
                    });

            $("#favoritesItemsContainer .row").each(function (index) {
                var col1H = $(this).find(".col1").height();
                var col2H = $(this).find(".col2").height();
                if (col1H > col2H)
                    $(this).find(".col2").height(col1H);
                else
                    $(this).find(".col1").height(col2H);
            });

            $("#ac-tab-02 a.savestate").click(function (event) {
                SaveState();
            });
            $("#ac-tab-02 a.savestatemyres").click(function (event) {
                SaveStateMyRes();
            });

            //$('#tab-02 .row div').equalizeCols();
            /*$('.row div').equalizeCols();
            (function ($) {
            $.fn.equalizeCols = function () {
            var height = 0,
            reset = $.browser.msie && $.browser.version < 7 ? "1%" : "auto";

            return this.css("height", reset).each(function () {
            height = Math.max(height, this.offsetHeight);
            }).css("height", height).each(function () {
            var h = this.offsetHeight;
            if (h > height) {
            $(this).css("height", height - (h - height));
            };
            });
            };
            })(jQuery);*/

            setPaging(paging);

            //$('html, body').animate({ scrollTop: 0 }, 0);

        }

    });
    $.ajaxSetup({ "async": true, "cache": true });
}

function GetPresaleCompares() {

    var url = "/Activities/Compare/GetExcursions";

    //DisplayProgressIcon(true, "#comparesItemsContainer");

    $.ajaxSetup({ "async": true, "cache": false });
    $.getJSON(url, function (data) {

        var list = data.Items;
        var paging = data.PagingInfo;

        if (list != null) {
            // Reset Results
            $('.compareCount').text(paging.TotalItemCount);
            //$("#compareItemsContainer").html("");

            //var markup = $("#compareItemsTemplate").html();
            //$.template("compareItemsTemplate", markup);
            //$.tmpl("compareItemsTemplate", list).appendTo("#compareItemsContainer");
            $.each(list, function (index, item) {
                if ($("#compare_" + item.ShoreExCode).length == 0) {
                    var markup = $("#compareItemsTemplate").html();
                    $.template("compareItemsTemplate", markup);
                    $.tmpl("compareItemsTemplate", item).appendTo("#compareItemsContainer");
                }
            });

            // Hide items not in buy mode
            if (shoppingMode != "Buy" && shoppingMode != "Email")
                $(".changemode").html("");

            $('#compareItemsContainer .box-tooltip').hover(
                    function () {
                        $(this).find('div').show();
                    }, function () {
                        $(this).find('div').hide();
                    });

            $("#ac-tab-03 a.savestate").click(function (event) {
                SaveState();
            });
            $("#ac-tab-03 a.savestatemyres").click(function (event) {
                SaveStateMyRes();
            });

            //$('html, body').animate({ scrollTop: 0 }, 0);

        }

    });
    $.ajaxSetup({ "async": true, "cache": true });

}

function pausecomp(millis) {
    var date = new Date();
    var curDate = null;


    do { curDate = new Date(); }
    while (curDate - date < millis);
}

function ResetTransform(objectId) {
    $(objectId).parent().removeClass("jqtransformdone");
}

function UpdatePort(destinationCode, targetPortCode, fn) {

    var url = "";

    if (destinationCode == null || destinationCode == "ALL")
        url = "/Activities/Excursions/GetAllPorts";
    else
        url = "/Activities/Excursions/GetPortsOfCall";

    //fire off the request, passing it the id which is the MakeID's selected item value
    $.getJSON(url, { itinerary: null, destination: destinationCode }, function (data) {

        //Todo: Remove so that filters don't reset
        //ResetFilters();

        //Clear the Model list  
        $(".cport").html("<select id=\"sport\" name=\"port\"></select>");
        $("#sport").parent().removeClass("jqtransformdone");

        $.each(data, function (index, optionData) {
            $("#sport").append("<option value='"
                                + optionData.Value
                                + "'>" + optionData.Text
                                + "</option>");
        });

        // Set the target port code
        if (targetPortCode != null && targetPortCode.length > 0)
            $("#sport").val(targetPortCode);

        $('.cport').jqTransform();

        $(".cport div.jqTransformSelectWrapper ul li a").click(function () {

            var cb = function () { return false; };

            closeFilters(cb);

            //Todo: removed so that filters are not reset after selecting a port
            //ResetFilters();

            GetExcursions("1");
        });

        if (fn)
            fn();


    });


}

function UpdateDestination(data, targetDestinationCode) {


    //Clear the Model list
    $(".cdestination").html("<select id=\"sdestination\" name=\"destination\"></select>");
    $("#sdestination").parent().removeClass("jqtransformdone");

    //$("#sdestination").empty();

    $.each(data, function (index, optionData) {
        //alert(index);
        $("#sdestination").append("<option value='"
                    + optionData.Value
                    + "'>" + optionData.Text
                    + "</option>");
    });

    // Set the target port code
    if (targetDestinationCode != null && targetDestinationCode.length > 0)
        $("#sdestination").val(targetDestinationCode);

    $('.cdestination').jqTransform();

    $(".cdestination div.jqTransformSelectWrapper ul li a").click(function () {

        // Do not execute event in buy mode
        if (shoppingMode == "Buy")
            return;

        // Get the hidden dropdown box index at the selected element in the ul list
        var index = $(".cdestination div.jqTransformSelectWrapper ul li a[class=\"selected\"]").attr("index");
        // Find the value in dropdown box
        var value = document.getElementById("sdestination").options[index].value;
        // Show it
        UpdatePort(value, null, GetExcursions);

        var cb = function () { return false; };

        closeFilters(cb);

    });
}

function padleft(val, ch, num) {
    var re = new RegExp(".{" + num + "}$");
    var pad = "";
    if (!ch) ch = " ";
    do {
        pad += ch;
    } while (pad.length < num);
    return re.exec(pad + val)[0];
}

function padright(val, ch, num) {
    var re = new RegExp("^.{" + num + "}");
    var pad = "";
    if (!ch) ch = " ";
    do {
        pad += ch;
    } while (pad.length < num);
    return re.exec(val + pad)[0];
}

// End List Support Functions
