﻿var catalogStart = true, catalogSelect = "", ispublic = false, SessionCookie, filterLoad2, combinefilter, ckRpt = false, prefix = 'TEA11';
pageSizeCatalogue = 25; currentPageCatalogue = 1;

$(document).ready(function () {
    ispublic = (location.toString().toLowerCase().indexOf("my").toString() == -1);
    catalogueInit();
});

function catalogueInit() {
    $("[name=keyword]").focus(function () {
        if ($(this).val() == "Enter a search term...") { $(this).val('').addClass("inuse"); }
        else { $(this).addClass("inuse"); }
    }).blur(function () {
        if ($(this).val() == "") { $(this).val('Enter a search term...').removeClass("inuse"); }
        else { $(this).addClass("inuse"); }
    });

    $("[name=keyword]").keypress(function (e) {
        if (e.which == 13) {
            doSearch();
            return false;
        }
    });

    SessionCookie = ggetUrlVars()["ck"];

    var combineCK, keywordCK, categoryCK, currentPageCatalogueCK;

    if (SessionCookie == "no") {
        $.cookie(prefix + "CombineS", "");
        $.cookie(prefix + "KeywordS", "");
        $.cookie(prefix + "CategoriesS", "");
        $.cookie(prefix + "CurrentPageCatalogS", "");
        SessionCookie = "rt";
        combineCK = null; keywordCK = null; categoryCK = null; currentPageCatalogueCK = null;
    } else {
        combineCK = $.cookie(prefix + "CombineS");
        keywordCK = $.cookie(prefix + "KeywordS");
        categoryCK = $.cookie(prefix + "CategoriesS");
        currentPageCatalogueCK = $.cookie(prefix + "CurrentPageCatalogS");
    }
    if (currentPageCatalogueCK != null) { currentPageCatalogue = currentPageCatalogueCK; }

    if (SessionCookie == undefined) {
        if (keywordCK != null || categoryCK != null || currentPageCatalogue != null) { SessionCookie = "rt"; }
    }

    if (ggetUrlVars()["tsid"] != undefined) {
        var labelParent = $("#catalogfilter").find("div.filter[name='timeslots'] .label").parent();
        filterLoad(labelParent, false, null);
        doSearch();
    } else {
        var labelParent = $("#catalogfilter").find("div.filter:eq(0) .label").parent();
        filterLoad(labelParent, false, null);

        if (SessionCookie == "rt") {
            if (keywordCK != null && keywordCK != "") { $("[name=keyword]").val(keywordCK); }
            if (combineCK != null && combineCK != "") { if (combineCK == "false") { combinefilter = false; filterCombine(); } }
            if (categoryCK != null && categoryCK != "") { category = categoryCK; filterLoad2(); }
            else { doSearch(); }
            expandCatalog();
        }
    }
    reset_sessions();
}

function toolTips() {
    $('#catalog_sessions #results').find('.add').tooltip({ delay: 0, fade: 250, extraClass: "orangeleft", positionLeft: false, showURL: false });
    $('#catalog_sessions #results').find('.remove').tooltip({ delay: 0, fade: 250, extraClass: "orangeleft", positionLeft: false, showURL: false });
    $('#catalog_sessions').find('.pgr_first').attr("title", "first").tooltip({ delay: 0, fade: 250, extraClass: "blueleft", positionLeft: false, showURL: false });
    $('#catalog_sessions').find('.pgr_previous').attr("title", "previous").tooltip({ delay: 0, fade: 250, extraClass: "blueleft", positionLeft: false, showURL: false });
    $('#catalog_sessions').find('.pgr_next').attr("title", "next").tooltip({ delay: 0, fade: 250, extraClass: "blueleft", positionLeft: false, showURL: false });
    $('#catalog_sessions').find('.pgr_last').attr("title", "last").tooltip({ delay: 0, fade: 250, extraClass: "blueleft", positionLeft: false, showURL: false });
}

function getSessions(skPag) {
    if (!$("#catalog_sessions").is(":visible")) return;

    $("#catalog_sessions").find("#topicsloading").html("Retrieving Sessions in the Catalogue...").fadeIn("fast");
    if (skPag) {
        var qs = getSearchQS("#srch") + '&take=' + pageSizeCatalogue + '&skip=0';
    } else {
        var qs = getSearchQS("#srch") + '&take=' + pageSizeCatalogue + '&skip=' + (pageSizeCatalogue * (currentPageCatalogue - 1));
    }
    url = getRootPath() + "ws/sessions.aspx?" + qs
    $.ajax({
        type: "GET",
        url: url,
        cache: false,
        dataType: "html",
        success: function (data) {
            $("#catalog_sessions .right").html("");
            $("#catalog_sessions h2").unbind("click");
            $("#catalog_sessions h2").removeClass("blueOn");
            if (data) {
                if (data.indexOf('class="topic clearfix"') == -1) {
                    $("#catalog_sessions .catalog_type").css({ 'cursor': 'none' });
                    if (data.indexOf('<div id="total_items">0</div>') > 0 && data.indexOf("html") < 0) {
                        if ($("#srch").find("input").serialize().indexOf("Keyword=&Categories=&") > -1) {
                            $('#catalog_sessions').find('#results').html("<div class=none><p>There are no sessions currently in the Catalogue.</p></div>" + data);
                        } else {
                            $('#catalog_sessions').find('#results').html("<div class=none><p>No sessions matched your search.</p></div>" + data);
                            if (combinefilter == true && multipleCats == true) { $('#catalog_speakers').find('#results .none').append("<p>Suggestion: <a href='javascript:filterCombine()'>Turn off combine filtering</a> to retrieve results from all selected filters.</p>"); }
                        }
                    } else {
                        $('#catalog_sessions').find('#results').html('<div class="errbox" style="margin-top:15px;"><p>Error #1024: Unable to retrieve sessions.</p></div>');
                    }
                    $("#catalog_sessions .catalog_type strong span").html(0);
                } else {
                    currentPageCatalogue = 1;
                    $('#catalog_sessions').find('#results').html(data);
                    $("#catalog_sessions .catalog_type strong span").html($("#catalog_sessions").find("#total_items").text());
                    $("#catalog_sessions h2").click(function () { expandCatalog(true); });
                    $("#catalog_sessions .right").html("Show more");
                    $("#catalog_sessions h2").addClass("blueOn");
                    $("#catalog_sessions").find("#results").css({ "height": "400px", "overflow": "auto" });
                    catalogStart = false;
                }
                if ($('#catalog_sessions').find('#current_page').size() > 0) {
                    $('#catalog_sessions').find('#CurrentPage').val($('#catalog_sessions').find('#current_page').text());
                } else {
                    $('#catalog_sessions').find('#CurrentPage').val("0");
                }
                if ($('#catalog_sessions').find('#total_items').size() > 0) {
                    $('#catalog_sessions').find('#NumberOfItems').val($('#catalog_sessions').find('#total_items').text());
                } else {
                    $('#catalog_sessions').find('#NumberOfItems').val("0");
                }
                $(".speakername").unbind('click').bind('click', function () { speakerPopup($(this).attr("rid"), $(".speakerdeets[sid='" + $(this).attr("sid") + "']")); });
                $(".speakerdeets .button_close").live('click', function () { speakerClose($(this)); });
                setSessionActions();
                reset_sessions();
                toolTips();
            }
            else {
                $('#catalog_sessions').find('#results').html('<div class="errbox" style="margin-top:15px;"><p>Error #1025: Unable to retrieve sessions.</p></div>');
                $("#catalog_sessions").find("#total_items").html("0");
            }
            $("#catalog_sessions").find("#topicsloading").fadeOut("slow");
        },
        error: function (data) {
            $('#catalog_sessions').find('#results').html('<div class="errbox" style="margin-top:15px;"><p>Error #1026: Unable to retrieve sessions.</p></div>');
            $("#catalog_sessions").find("#topicsloading").fadeOut("slow");
            $("#catalog_sessions").find("#total_items").html("0");
        }
    });
}

function filterLoad2() {
    var filterOpen = new Array();
    var fo = 0;
    if (category != undefined) {
        var categoryArr = category.split(",");
        for (var fc = 0; fc < categoryArr.length; fc++) {
            filtercat = $("#catalogfilter").find("option[value=" + categoryArr[fc] + "]");
            if ($(filtercat).text().length > 0) {
                filterOpen[fo] = $(filtercat).parent().parent().parent();
                fo++;
            }
        }
        for (var fc = 0; fc < categoryArr.length; fc++) {
            filtercat = $("#catalogfilter").find("input[value=" + categoryArr[fc] + "]");
            if ($(filtercat).val() != undefined) {
                if ($(filtercat).val().length > 0) {
                    filterOpen[fo] = $(filtercat).parent().parent().parent().parent().parent().parent();
                    fo++;
                }
            }
        }
    }

    var filterOpenUn = new Array();
    if (filterOpen.length == 0) {
        doSearch();
        var labelParent = $("#catalogfilter").find("div.filter:eq(0) .label").parent();
        filterLoad(labelParent, false, null);
    }
    else {
        for (var fc = 0; fc < filterOpen.length; fc++) {
            var hasfc = false;
            for (var fc2 = 0; fc2 < filterOpenUn.length; fc2++) {
                if ($(filterOpen[fc]).find(".label").text() == $(filterOpenUn[fc2]).find(".label").text()) { hasfc = true; }
            }
            if (hasfc == false) {
                filterOpenUn[filterOpenUn.length] = filterOpen[fc];
                filterReLoad($(filterOpen[fc]).find(".label").parent(), false, null);
            }
        }
    }
}

function filterReLoad(labelParent, showPop, popLink) {
    var labelName = $(labelParent).find(".label").text().toLowerCase();
    var labelPops = " class='labelSearch labelLink'";
    if (labelName == "country" || labelName == "state" || labelName == "industry") { labelPops = " class='labelSearch'"; }
    if ($(labelParent).find("select").length) {
        $(labelParent).find(".element div").remove();
        $(labelParent).find(".element").prepend("<div></div>");
        $(labelParent).find("div").html("<ul></ul>").hide();
        $(labelParent).find("div").addClass("fscroll");
        $(labelParent).find("div").prepend('<input type="text" value="Search Filter..." class="filterfind">');
        filterFind($(labelParent).find("div input"));
        var selectName = $(labelParent).find("select").attr("name");
        $(labelParent).find("option").each(function (index) {
            if (jQuery.trim($(this).text()) != "" && jQuery.trim($(this).text()) != "--") {
                var labelInput = '<input type="checkbox" id="' + $(this).val() + '" name="' + selectName + '" value="' + $(this).val() + '" />';
                var labelText = $(this).text();
                var labelClass = '';
                var attr = $(this).attr('selected');
                if (attr !== 'undefined' && attr !== false) { labelClass = ' class="checked"'; }
                $(labelParent).find("div ul").append("<li><span class='labelInput'><label" + labelClass + ">" + labelInput + "</label></span><span" + labelPops + ">" + jQuery.trim(labelText) + "</span></li>");
                if (attr !== 'undefined' && attr !== false) { $(labelParent).find("div ul li:last").find("input").attr('checked', true); }
            }
        });
        var category = ggetUrlVars()["categories"];
        if (category != undefined) {
            category = category.replace(/%20/g, " ");
            category = category.replace(/\+/g, " ");
            var categoryArr = category.split(",");
            for (var fc = 0; fc < categoryArr.length; fc++) {
                var fcfield = $(labelParent).find("div ul li:Contains(" + decodeURI(categoryArr[fc]) + "):first");
                if ($(fcfield).text().length > 0) {
                    $(fcfield).find("input").attr('checked', true);
                    $(fcfield).find("label").addClass("checked");
                }
            }
        }
        $(labelParent).find("select").remove();
        filterSetup(labelParent);
    }

    if (ckRpt == false) {
        var SessionCookie = ggetUrlVars()["ck"];
        ckRpt = true;
        var categoryCK = $.cookie(prefix + "CategoriesS");
        if (categoryCK != undefined) {
            var categoryCKArr = categoryCK.split(",");
            for (var fc = 0; fc < categoryCKArr.length; fc++) {
                var fcfield = $("#catalogfilter").find("input[value=" + categoryCKArr[fc] + "]");
                if ($(fcfield).val() != undefined) {
                    if ($(fcfield).val().length > 0) {
                        $(fcfield).attr('checked', true);
                        $(fcfield).parent().parent().find("label").addClass("checked");
                    }
                }
            }
        }
        doSearch();
    }

    $(labelParent).find("div.fscroll").removeClass("fscrollani");
    $(labelParent).find("div").slideToggle(function () { if (showPop) { filterDetailPop(popLink, true); } $(labelParent).find("div.fscroll").addClass("fscrollani"); });
    $(labelParent).find(".label").toggleClass("labelOn");
}

function expandCatalog(IsLoaded) {
    var catalog = "#catalog_sessions";
    var size = parseInt($(catalog + " .catalog_type strong span").text());

    if (IsLoaded) {
        if (catalogStart) {
            $(catalog + " .right").html("Show more");
            $(catalog).find("#results").css({ "height": "400px" });
            $(catalog + " .pager").slideDown();
            catalogStart = false;
        } else if ($(catalog + " h2").hasClass("blueOn")) {
            $(catalog + " .right").html("Show less");
            $(catalog).find("#results").css({ "height": "auto" }).slideDown();
            $(catalog + " .pager").slideDown();
            catalogStart = true;
        } 
    } else {
        $(catalog + " .pager").slideUp();
    }
}

function filterCombine() {
    if (combinefilter) { combinefilter = false; $("#filterCombine").removeClass("filterOn").addClass("filterOff"); }
    else { combinefilter = true; $("#filterCombine").removeClass("filterOff").addClass("filterOn"); }
    doSearch();
}

var ct = "", multipleCats = false;
function doSearch() {
    if (SessionCookie != "no") { $.cookie(prefix + "KeywordS", ky); }

    var applySize = $(".labelInput .checked").size();
    if (applySize > 0) {
        filtersSet = true;
        $("#filterappy").css({ "background-color": "#f15c44", "color": "#ffffff" }).text("Clear filters");
        $("#filterappy").unbind("click").click(function () { clearFilter() });
    } else {
        filtersSet = false;
        $("#filterappy").css({ "background-color": "#ffffff", "color": "#005a84" }).text("Apply filters");
        $("#filterappy").unbind("click").click(function () { doSearch(); });
    }

    var ky = ($("[name=keyword]").size() > 0) ? $("[name=keyword]").val() : "";
    if (ky == "Enter a search term...") { ky = ""; }
    ct = "";
    multipleCats = false;
    $('input[name^=filter_category]:checked').each(function () {
        if (ct != "") { ct += ","; multipleCats = true; }
        ct += $(this).val();
    });
    $("#Keyword").val(ky);
    if (combinefilter) {
        $("#Categories").val(ct);
        $("#oc").val("");
    } else {
        $("#Categories").val("");
        $("#oc").val(ct);
    }

    if (SessionCookie == "no") {
        combinefilter = null; ky = null; ct = null;
    }
    $.cookie(prefix + "CombineS", combinefilter);
    $.cookie(prefix + "KeywordS", ky);
    $.cookie(prefix + "CategoriesS", ct);

    if (SessionCookie == "rt") {
        getResults(false);
    }
    else {
        currentPageCatalogue = 0;
        pageSizeCatalogue = parseInt($('#catalog_sessions').find('#PageSize').val());

        $.cookie(prefix + "CurrentPageCatalogS", currentPageCatalogue);
        getResults(true);
    }
    $('body').scrollTo($('h1'), 500);
}

function getResults(skPag) {
    getSessions(skPag);
}

function reset_sessions() {
    if ($("#catalog_sessions").is(":visible")) setPager("sessions");
    spsFilter();
}

function clearFilter() {
    $("#filterappy").unbind("click").click(function () { doSearch() });
    $("#catalogfilter label").removeClass("checked")
    $("#catalogfilter input").attr('checked', false);
    $("[name=keyword]").val('Enter a search term...').removeClass("inuse");
    doSearch();
}

function setPager() {
    var pageSize, currentPage;
    pageSize = pageSizeCatalogue;
    currentPage = currentPageCatalogue;

    var catalog = "#catalog_sessions";
    $(catalog + " .pgr_current_page").text($(catalog).find('#CurrentPage').val());
    $(catalog + " .pgr_total_items").text($(catalog).find('#NumberOfItems').val());
    currentPage = parseInt($(catalog).find("#CurrentPage").val());
    var total_itemsSession = parseInt($(catalog).find("#NumberOfItems").val());

    var sp_startSession = (pageSize * (currentPage - 1)) + 1;
    var sp_endSession = sp_startSession + pageSize - 1;
    if (sp_endSession > total_itemsSession) sp_endSession = total_itemsSession;
    if (sp_endSession < 1) sp_endSession = total_itemsSession;
    if (sp_endSession == 0 && total_itemsSession == 0) sp_startSession = 0;
    var total_pagesSession = Math.ceil((total_itemsSession / pageSize));
    if (total_pagesSession < 1) total_pagesSession = 1;

    $(catalog + " a.pgr_first," + catalog + " a.pgr_previous," + catalog + " a.pgr_next," + catalog + " a.pgr_last").removeClass("off").addClass("on");
    if (currentPage <= 1) $(catalog + " a.pgr_first," + catalog + " a.pgr_previous").removeClass("on").addClass("off");
    if (currentPage >= total_pagesSession) $(catalog + " a.pgr_next," + catalog + " a.pgr_last").removeClass("on").addClass("off");

    $(catalog + " .pgr_current_page_goto").val(currentPage);
    $(catalog + " .pgr_total_pages").text(total_pagesSession);
    $(catalog + " .pgr_span_start").text(sp_startSession);
    $(catalog + " .pgr_span_end").text(sp_endSession);

    if (catalogStart) {
        if (total_itemsSession == 0) { $(catalog).find("#results").css({ "height": "auto" }); }
    }
}

function doPageExpo(d, el, pl) {
    if (pl == "bot") {
        try { $(this).scrollTo($("#catalog_sessions").find("#pagertop"), 500); }
        catch (dopex) { }
    }
    var total_itemsSession = parseInt($("#catalog_sessions").find("#NumberOfItems").val());
    var total_pagesSession = Math.ceil((total_itemsSession / pageSizeCatalogue));
    var b = false;
    currentPageCatalogue = $("#catalog_sessions").find("#CurrentPage").val();
    if (d == 'f') { if (currentPageCatalogue != 1) { currentPageCatalogue = 1; b = true; } }
    else if (d == 'p') { if (currentPageCatalogue > 1) { currentPageCatalogue--; b = true; } }
    else if (d == 'n') { if (currentPageCatalogue < total_pagesSession) { currentPageCatalogue++; b = true; } }
    else if (d == 'l') { if (currentPageCatalogue < total_pagesSession) { currentPageCatalogue = total_pagesSession; b = true; } }
    else if (d == 'g') {
        if (window.event.keyCode != 13) return;
        var gp = parseInt($(el).val());
        if (gp > 0 && gp <= total_pagesSession) { currentPageCatalogue = gp; b = true; }
    } else if (d == 'r') { b = true; }
    $.cookie(prefix + "CurrentPageCatalogS", currentPageCatalogue);
    $.cookie(prefix + "PageSizeCatalogueS", pageSizeCatalogue);
    if (b) getSessions(false);
    return false;
}
