﻿/* panelStateController - controller obj for sliding panels */

// initialise
// + data (UIPreferencesJsonData)
this.panelStateController = function(data){

    var PNL_BASKET = 'pnlBasket';
    var PNL_WISH_LIST = 'pnlWishList';

    var _panelStates;

    // in mem of panel states from UIPreferencesJsonData
    initPanelStates(data.PanelState);
    
   

    // initialise
    // + cb (function) - callback to execute on complete
    this.init = function(cb){

        // iterate all panels
        $(".sidePanel, .midPanel").each(function(){
        
            var jqThis = $(this);
        
            var isSidePanel = jqThis.attr("class") == "sidePanel";
            
            // ensure top / bottom
            if(isSidePanel &&  jqThis.find(".top").length == 0)
                jqThis.prepend("<div class=\"top\"></div>");
            
            if(jqThis.find(".bottom").length == 0)
                jqThis.append("<div class=\"bottom\"></div>");
                
            // establish panels
            var id = jqThis.attr("id");
            var ps = establishPanelState(id, "1");
            
            // initialise the panel
            var header = jqThis.find(".header");
            
            ps.initialise(header, function(){ persistCurrentState(); });
        
            
        });
        
        persistCurrentState();
        
        if(typeof(cb) == 'function') cb();
        
    };
    
    // set the visibility of the specified panel
    // id (string) the panel to show / hide
    // visible (bool) show or hide
    // persist (bool) persist the current state?
    this.setPanelVisibility = function(id, visible, persist){
        var pnl = getPanelState(id);
        var targetVisibility = visible ? "1" : "0";
        var hasChanged = pnl.visibility != targetVisibility;
        if(true == hasChanged){
            pnl.visibility = targetVisibility;
            pnl.update();
            if(true == persist) persistCurrentState();
        };
    };
    
    // shows the panel with specified id
    // id (string) the panel to show
    this.showPanel = function(id){
        this.setPanelVisibility(id, true, true);
    };
    
    // hides the panel with specified id
    // id (string) the panel to hide
    this.hidePanel = function(id){
        this.setPanelVisibility(id, false, true);
    };
    
    // show / hide the basket panel
    this.setBasket = function(visible){
        this.setPanelVisibility(PNL_BASKET, visible, true);
    };
    
    // show / hide the wish list panel
    this.setWishList = function(visible){
        this.setPanelVisibility(PNL_WISH_LIST, visible, true);
    };
    
    // set the visibility of all children of the selected element
    /// parentID (string) - the parent element
    /// selector (string) - e.g. ".midPanel"
    /// visible (bool) - visibility of panel after change
    this.setChildPanels = function(parentID, selector, visible){
    
        var psc = this;
        var persist = false;
        
        $("#" + parentID).find(selector).each(function(){
            var id =$(this).attr("id");
            
            psc.setPanelVisibility(id, visible, false);
            persist = true;
        });
        
        if(true == persist) persistCurrentState();
    
    };
    
    // initialise all panels
    function initPanelStates(data){
        
        if(null == _panelStates || _panelStates == ''){
            _panelStates = new Array();
        };
        
        // TODO - use a to KeyVal - shared with cookiesToQueryString etc
        var panelStateArray = data.split(',');
        for(var i in panelStateArray){
            var kv = panelStateArray[i];
            if(kv != null && kv.indexOf("=") != -1){
                var kva = kv.split('=');
                _panelStates[i] = new panelState(kva[0], kva[1]);
            };
        };
        
    };
    
    
    
    function establishPanelState(id, defaultVisibility){
        
        var result = getPanelState(id);
        
        if(null == result){
            // new panel - default
            result = new panelState(id, defaultVisibility);
            addPanelState(result);
        };
        
        return result;
    };
    
    function getPanelState(id){
        var result = null;
        for(var i in _panelStates){
            if(_panelStates[i].id == id){
                result = _panelStates[i];
                break;
            };
        };
        return result;
    };
    
    function addPanelState(value){
        _panelStates[_panelStates.length] = value;
    };
    
    // persist current state
    function persistCurrentState(){
    
        // TODO - gen to qs method
        var state = "";
        for(var i in _panelStates){
            state += _panelStates[i].getCookieValue();
            if(i != _panelStates.length - 1){
                state += ",";
            };
        };
        
        $mb.jsonLoader.setPanelState(state, function(data){ canHandleJSON(data); });
    
    };
    
};

// obj for panelState info
// + id (string) element id
// + visibility (string) 0 or 1
this.panelState = function(id, visibility){
    
    this.id = id;
    this.visibility = visibility;
    
    this.anchor;                // jQuery - trigger anchor
    this.header;                // jQuery - header div
    this.main;                  // jQuery - main div
    
    this.getCookieValue = function(){
        return this.id + "=" + this.visibility;
    };
    
    // initialise
    // + header (jQuery) the header div
    // + onClickCallBack (function - no params)
    this.initialise = function(header, onClickCallBack){
        
        this.header = header;
        
        
        if(this.header.find(".arrow").length == 0){

        
            // wrap header
            var headerHtml = this.header.html();
            
            // TODO - we should be getting this from styleSettings.js (clientRootUrl) but it is not properly initialised before this is called :|
            // see comments in styleSetting.js .loadUIPreferences();
            
            var transGifHtml = "<img src=\"" + APPLICATION_ROOT + "client/global/img/trans.gif\" width=\"11\" height=\"11\" border=\"0\"/>";
            this.header.html("<div class=\"arrow\"><a href=\"javascript:;\">" + transGifHtml + "</a></div><div class=\"title\">" + headerHtml + "</div>&nbsp;<br clear=\"all\"/>");

            this.anchor = this.header.find(".arrow").find("a");
            
            var ps = this;
            
            // register click
            this.anchor.click(function(){
                
                var main = $(this).parent().parent().next();
                
                main.slideToggle(function(){
                    ps.toggle();
                    onClickCallBack();
                });
                
                return false;
                
            });
                
            this.update();
            
            this.initialised = true;
        
        };
    
        
    };
    
    // update the visibility of dom elements based on the panel state
    this.update = function(){
        var main = $("#" + this.id).find(".main");
        if(this.isVisible()){
            main.slideDown();
        }else{
            main.slideUp();
        };
        this.setAnchorProps();
    };
    
    this.toggle = function(){
        this.visibility = this.isVisible() ? "0" : "1";
        this.setAnchorProps();
    };
    
    this.setAnchorProps = function()
    {
        // set arrow state and title text according to visibility
        var isVisible = this.isVisible();
        this.anchor.attr("class",  isVisible ? "right" : "down")
                    .attr("title", "Click here to " + (isVisible ? "hide" : "show"));
    };
    
    this.isVisible = function(){
        return this.visibility == "1";
    };

};    