﻿sheetMgr = new Qww.Sheet.Mgr(
{   
    //SheetIDs: sheetIDs,
    OnActiveSheetChanged: function(mgr, prev) 
    {
        //alert("Sheet is now " + mgr.ActiveSheet);
    } 
});

var startOverButtonMgr = new Qww.Button.Mgr({ "ObjectID": 'BU_World_Lab_Top_Section_StartOver' });
var webOnOpenButtonMgr = new Qww.Button.Mgr({ "ObjectID": 'BU_FactLab_Global_or_National_Web_onopen' });

qwwHub.Register(
{
    OnAllAvqUpdateCompletesCalled: function() {

        if (!this.Sent) {
            webOnOpenButtonMgr.SendClick();

           this.Sent = true;
        }
    }
});

function onStartButtonClicked() {
    startOverButtonMgr.SendClick();
}

function onWebOnOpenButtonClicked() {
    webOnOpenButtonMgr.SendClick();
}

function Factlab_ResetCurrentSiteAndNavigateToOtherSite(url) {
    //onStartButtonClicked();
    
    var selectedLanguage = languageMaintainer.GetSelectedLanguage();

    // If the above returned "" then the language has not been changed.
    if (selectedLanguage != "") url = url + "?setlanguage=" + selectedLanguage + "&reset=true";

    window.location = url;
};

//function Factlab_NavigateToOtherSite(url) {
//    var selectedLanguage = languageMaintainer.GetSelectedLanguage();

//    // If the above returned "" then the language has not been changed.
//    if (selectedLanguage != "") url = url + "?setlanguage=" + selectedLanguage;

//    window.location = url;
//};

function ShowSettingsPopup() {
    tb_show('Settings', "#TB_inline?height=150&width=300&inlineId=CountrySourcePopupCtl1_visitorConfirmationPopUp", false);
};

var popUpVisibilityListboxMgr = new Qww.ListBox.Mgr({ "ObjectID": 'LB_FactLab_Global_or_National_PopUpManager' });

if (Factlab.IsResultsPage) {
    //onWebOnOpenButtonClicked();
    var topFilterVisibilityListboxMgr = new Qww.ListBox.Mgr({ "ObjectID": 'LB_World_Or_National_Lab_Top_Section_Selection_ShowFilter' });
    var fact1VisibilityListboxMgr = new Qww.ListBox.Mgr({ "ObjectID": 'LB_World_Or_National_Lab_Bottom_Section_Selection_ShowFact1' });
    var fact2VisibilityListboxMgr = new Qww.ListBox.Mgr({ "ObjectID": 'LB_World_Or_National_Lab_Bottom_Section_Selection_ShowFact2' });
    var fact3VisibilityListboxMgr = new Qww.ListBox.Mgr({ "ObjectID": 'LB_World_Or_National_Lab_Bottom_Section_Selection_ShowFact3' });

    function SingleRowListBoxToElementVisibilityMapper(listBoxMgr, showHideContainerElementId, mainElementIdToShowOrHide) {

        function getDelayedFunctionToRun(showHideContainerElementId, mainElementIdToShowOrHide, show) {

            return function() {

                if (show) {
                    $('#' + showHideContainerElementId + " span:nth-child(1)").hide();
                    $('#' + showHideContainerElementId + " span:nth-child(2)").show();
                    $('#' + mainElementIdToShowOrHide).show();
                }
                else {
                    $('#' + showHideContainerElementId + " span:nth-child(2)").hide();
                    $('#' + showHideContainerElementId + " span:nth-child(1)").show();
                    $('#' + mainElementIdToShowOrHide).hide();
                }
            };
        }

        listBoxMgr.Cfg.OnUpdate = function(lbm) {

            /*
            Note this relies on a structure something like:
            <* id=[elementIdToLinkTo]>
            <span>Localised Show Text</span>
            <span>Localised Hide Text</span>
            </*>
            */
            //debugger;

            //if (mainElementIdToShowOrHide == "topFilter") debugger;
            //debugger;

//            var LOOKUP = {};

//            for (var i = 1; i < 4; i++) {
//                LOOKUP["toggle" + i] = "factContainer" + i;
//            }

            if (parseInt(lbm.Results.All[0].State) == 0) {
                // Hide

                //setTimeout(getDelayedFunctionToRun(showHideContainerElementId, mainElementIdToShowOrHide, false), 10);

                setTimeout(function() {
                    $('#' + showHideContainerElementId + " span:nth-child(2)").hide();
                    $('#' + showHideContainerElementId + " span:nth-child(1)").show();
                    $('#' + mainElementIdToShowOrHide).hide();
                    //$('#' + LOOKUP[showHideContainerElementId]).hide();
                }, 10);

                $('#' + showHideContainerElementId)[0].IsShowing = false;

            }
            else {
                // state should be 2 - show

                //setTimeout(getDelayedFunctionToRun(showHideContainerElementId, mainElementIdToShowOrHide, true), 10);

                setTimeout(function() {
                    $('#' + showHideContainerElementId + " span:nth-child(1)").hide();
                    $('#' + showHideContainerElementId + " span:nth-child(2)").show();
                    $('#' + mainElementIdToShowOrHide).show();
                    //$('#' + LOOKUP[showHideContainerElementId]).show();

                }, 10);

                $('#' + showHideContainerElementId)[0].IsShowing = true;
            }

            $('#' + showHideContainerElementId + '_spinner').hide();
        };
    }

    new SingleRowListBoxToElementVisibilityMapper(topFilterVisibilityListboxMgr, 'toggle5', 'topFilter');
    new SingleRowListBoxToElementVisibilityMapper(fact1VisibilityListboxMgr, 'toggle1', 'fact1');
    new SingleRowListBoxToElementVisibilityMapper(fact2VisibilityListboxMgr, 'toggle2', 'fact2');
    new SingleRowListBoxToElementVisibilityMapper(fact3VisibilityListboxMgr, 'toggle3', 'fact3');
}

sheetMgr.ScanForPanelsToManage();

Qww.Ctls.Debug = false;

Qww.Ctls.DropDown.Mgr.ScanForAndCreate();
Qww.Ctls.DropDownMultiSelect.Mgr.ScanForAndCreate();
Qww.Ctls.ScrollingMultiSelect.Mgr.ScanForAndCreate();
Qww.Ctls.TextObject.Mgr.ScanForAndCreate();
Qww.Ctls.Button.Mgr.ScanForAndCreate();
//Qww.Ctls.AmMap.Mgr.ScanForAndCreate();
Qww.Ctls.Chart.Mgr.ScanForAndCreate();
Qww.Ctls.LeftMenu.Mgr.ScanForAndCreate();
Qww.Ctls.Search.Mgr.ScanForAndCreate();
Qww.Ctls.Search2.Mgr.ScanForAndCreate();
Qww.Ctls.CustomTableRenderer.Mgr.ScanForAndCreate();
Qww.Ctls.CustomCheckBoxList.Mgr.ScanForAndCreate();
//Qww.Ctls.GoogleMap.Mgr.ScanForAndCreate();

function LanguageMaintainer(languageTextBoxId, lanaguageListBoxId) {

    function getQueryVar(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable) {
                return pair[1];
            }
        }
        return null;
    }

    this.GetInitialisationSets = function() {

        var sets = [];

        var language = getQueryVar("setlanguage");
        var reset = getQueryVar("reset");

        var hasLanguageSet = (language && language != '');

        if (reset == 'true') {
            sets.push(new Qww.QvsConnectorSet(null, Qww.ListBox.Mgr.CommandPrefix + "BU_World_Lab_Top_Section_StartOver", "action", "", !hasLanguageSet));
        }

        if (hasLanguageSet) {
            var objectId = lanaguageListBoxId;

            var applicationID = null;
            // code copied from Qww.ListBox.Mgr.SearchAndClose

            sets.push(new Qww.QvsConnectorSet(null, Qww.ListBox.Mgr.CommandPrefix + objectId + ".Caption", "search", language, false));
            sets.push(new Qww.QvsConnectorSet(null, Qww.ListBox.Mgr.CommandPrefix + objectId + ".Caption", "closesearch", "accept", true));
        }

        return sets;
    };

    var initialLanguage = "";
    
    function onLanguageUpdated(txtMgr)
    {
        if (initialLanguage == "") initialLanguage = txtMgr.Text;
    };
    
    var txtObj = new Qww.TextObject.Mgr({ 'ObjectID': languageTextBoxId, OnUpdate: onLanguageUpdated});

    this.GetSelectedLanguage = function() {
        return txtObj.Text;
    };

    $(document).ready(function() {
        
        $("[jumptosite]").each(function() {

            var elem = $(this);
            var siteId = elem.attr('jumptosite');

            $(elem).click(function(e) {
                window.location = siteId + "/default.aspx?setlanguage=" + txtObj.Text + "&reset=true";
                //window.location = siteId + "/default.aspx";
                return true;
            });
        });

        //        var language = getQueryVar("language");

        //        if (language && language != '') {
        //            setTimeout(function() {
        //                //Qww.ListBox.Mgr.SearchAndClose(null, lanaguageListBoxId, language, true);
        //            }, 2500); // seems we need a delay here otherwise page hangs. Should look into sending this in initial request.
        //        }

    });

    qwwHub.Register(this);
}

// This object checks for a language=??? in the query string and updates the selected language 
// accordingle. It also wires up and elements with a jumptosite=?? attribute to navigate to the 
// specified site with the current selected language
var languageMaintainer = new LanguageMaintainer('TX_SELECTED_LANGUAGE', 'LB_FactLab_Global_or_National_Langselector');
new Qww.TextObject.Mgr(
{
    "ObjectID": 'TX_TOP_FILTER_COUNT',
    "OnUpdate": function(oTxt) {
        Factlab.TopFilterHasSelection = oTxt.Text != '0';
    }
});
