/*
 * File: brand.globalnav.GlobalNav
 * Auth: Steph Shindler & Mina Kumar
 */
                                         
/*

Communication up/down hierarchy:
    - GlobalSet: onChildClick called from children: Accordion
    - PanelNavSet: onChildClick called from children: PanelSubNav
    - PanelNavSet & GlobalSet: setActiveItem called from children: PanelNav._setActive (sets ActiveItem for PanelNavSet & GlobalSet AND SETS Accordion.ActiveSubItem)
    - PanelSubNav/ProductSubNav: onParentClick called from parent: PanelNav


1st LEVEL:
-----------------------
2 Accordions & 2 Panel Navs:
    - gnav_products, gnav_artistry
    - pnav_givingback, pnav_mymac ("pnav" instead of "gnav" because these are PanelNav trigger/headers, so their panel gets named after them; pnav_givingback_panel

2nd LEVEL (GENERAL): 
-----------------------
This level can either be a single PanelNav or multiple PanelNavs owned by a PanelNavSet:
    - Option A: 1 PanelNavSet + 1 Panel
        - multiple PanelNavs
    - Option B: 1 PanelNav + 1 Panel
    
Attachment notes:
    - PanelNavSet gets instantiated as *sort of* a child of the Accordion above it.  There is no DOM parent/placement since it does not have a template/node associated w/ it, but it has to be able to talk to the Accordion to set Accordion.ActiveSubItem
    - PanelNav attachment requires 2 things: 
        (1) place the panelnav header/trigger node in the correct place in the DOM = pass PanelNav node to Accordion's addSubItem method which does a dojo.place
        (2) place the panelnav widget object in its place in the widget hierarchy = pass parentId prop on instantiation which sets widget parent, allowing us to mimic dijit's getParent() method in PanelNav
    - Panels get created by either PanelNavSet._addPanel (if Panel is associated with a set of PanelNavs) or PanelNav._addPanel (if Panel is associated w/ only 1 PanelNav)

3rd LEVEL (GENERAL): 
-----------------------
Each PanelNav (2nd level) has 1 PanelSubNav or an extension of PanelSubNav:
    - PanelSubNav: Div container for panel content associated w/ a single PanelNav link
    - ProductSubNav: container template that includes nodes for ProductCategoryDetail & a category Accordion     
    
*/ 

brand.globalnav = { abort: false };

brand.globalnav.GlobalNav = Class.create(
{
    // summary:
    //      Iterates through site.loader.config hierarchy and applies correct classes
    //      to each level of the nav tree (section, super-category, category and detail/product). 
    //        Compares data with page_data.panel_nav to check for default state of the nav.
    
    config: null,
    _configKeys: {},
    defaultState: {}, // item hierarchy of default panel
    defaultNavCreated: false,
    globalNavSetId: "",

    initialize: function(args) {
        this.config = args.config;
        this.defaultState = args.defaultState;
        this.globalNavSetId = args.globalNavSetId; 
         
        // start loading: iterates through config hierarchy      
        this.initSections.bind(this).delay(1);
    },
    
    initSections: function() {
        // summary:
        //      Iterates through top-level sections (as passed from config)
       
        var sections = this.config.items;
        var defaultSection = this.defaultState.id;
        var self = this; 
        
        sections.each(function(section, idx) {
            // check for default section
            var isDefaultSection = false; // reset for every loop instance
            if (section.id === defaultSection) {
                isDefaultSection = true;
            }
            self._configKeys[section.id] = { idx: idx, items: {} };
                        
            // section has a set of panel navs
            if (section.items && (section.items.length > 0)) {
                self.initPanelNavSet(section, isDefaultSection);

            // item is a direct link from left nav
            } else if (section.uri && !section.content) {
                self.initHeader({type: "pnav", item: section, isdefault: isDefaultSection, containerId: self.globalNavSetId, domParent: "globalnav"});
                
            // section has only 1 panel nav
            } else {                
                if (section.id === "search") {
                    self.initSearch(section);
                    
                } else if (!section.hasLoaded) { 
                    // pnav at this level (section) has been loaded declaratively
                    // but not psubnav, so load new subnav                  
                    //console.log("GlobalNav.initSections -> initPanelSubNav");
                    self.initPanelSubNav(section, isDefaultSection, section); // section is pnavItem at this level, so item & parent args are same
                }
            }
                    
        });
    
    },
    
    initPanelNavSet: function(section, isDefaultSection) {  
        
        // summary:
        //      Loop through 2nd level scenario A:
        //      1 PanelNavSet (n PanelNavs) to 1 Panel (i.e. Products)
        //      Displays PanelNav links as Accordion of top-level/left-hand links
  
        var pnavset = new brand.globalnav.PanelNavSet({
            id: "pnavset_"+section.id, 
            parentId: "gnav_"+section.id
        });  
        
        var defaultPnav = this.defaultState.item;
        var defaultPnavId = (defaultPnav ? defaultPnav.id : null);
        var accordionContainer = $(pnavset.parentId).widget;
       
        var self = this;        
        section.items.each(function(pnavItem, idx) {
            
            self._configKeys[section.id].items[pnavItem.id] = { idx: idx }; 

            // isDefaultPanel: is PanelSubNav instance associated w/ default category
            var isDefaultPanel = false;
            if (!self.defaultNavCreated && (pnavItem.id === defaultPnavId)) {
                isDefaultPanel = true;
            }

            // item is a direct link from left nav
            if (pnavItem.uri && !pnavItem.content) { 
                self.initHeader({type: "pnav", item: pnavItem, isdefault: isDefaultPanel, containerId: accordionContainer.id});
            
            //  item has a panel to populate w/ content
            } else {
                
                if (isDefaultPanel) {  
                    self.initHeader({type: "pnav", item: pnavItem, isdefault: isDefaultPanel, containerId: accordionContainer.id});
                } else { 
                    //console.log("GlobalNav.initPanelNavSet: create PanelNav "+ "pnav_"+pnavItem.id + " / " +accordionContainer.containerNode.id);
                    //create PanelNav for the set
                    var pnav = new brand.globalnav.PanelNav({
                        id: "pnav_"+pnavItem.id, 
                        parentId: "pnavset_"+section.id, // widget parent *NOT* DOM parent
                        domParent: accordionContainer.containerNode, //jstest  
                        displayName: pnavItem.name,
                        hdPath: pnavItem.header,
                        sectionId: section.id,
                        item: pnavItem
                    });
                    
                    // attaches sub item node to Accordion node
                    // (does not establish widget parent/child relationship)                    
                    //JSTEST accordionContainer.addSubItem(pnav.domNode);
                    
                    // now that pnav has a place in the DOM, start it up:
                    pnav.startup(); 
                }
                
                // continue to subnav level
                self.initPanelSubNav(pnavItem, isDefaultPanel, section);

            }
                            
        });
        
        // now that all the left-hand supercategories have been populated, set the state of the gnav accordion
        if (isDefaultSection) {
            accordionContainer.open();
        }
           
    },

    initPanelSubNav: function(pnavItem, isDefaultPanel, parentItem) {   
         //console.log("GlobalNav.initPanelSubNav "); 
        
        // summary:
        //      Creates each instance of either a PanelSubNav or ProductSubNav
        //      associated with parent PanelNav
        
        var hasLoaded = false;

        // default PanelSubNav args
        var psubnavArgs = {
            id: "psubnav_"+pnavItem.id,
            parentId: "pnav_"+pnavItem.id,  
            isDefaultPanel: isDefaultPanel,
            itemId: pnavItem.id
        }

 
        if (pnavItem.id === "discontinued") {
            psubnavArgs.content = pnavItem.content;
            //psubnavArgs.templatePath = "/js/brand/globalnav/templates/DiscontinuedSubNav.html";
            psubnavArgs.templatePath = "jsTemplates.globalnav.DiscontinuedSubNav";
            var psubnav = new brand.globalnav.PanelSubNav(psubnavArgs);
            
        // prodcat sub-sections & looks
        } else if (parentItem && parentItem.id === "products" || pnavItem.content.widget === "ProductSubNav") {
              //console.log("GlobalNav.PanelSubNav - prodcat sub-sections & looks"); 
       
            // create ProductSubNav (extension of PanelSubNav) for the PanelNav
            psubnavArgs.content = (pnavItem.content ? pnavItem.content : parentItem.content);
            var psubnav = new brand.globalnav.ProductSubNav(psubnavArgs);
            
        // cms-generated & other nav types
        } else {
             //console.log("GlobalNav.PanelSubNav - cms-generated & other nav types"); 
         
            var content = pnavItem.content;
            var isCMS = false;
            var isDefaultCMS = false;

            // get psubnav class to use
            var psubnavClass = "PanelSubNav"; // use PanelSubNav by default
            if (pnavItem.content.widget) {
                psubnavClass = pnavItem.content.widget;
            }

            // global nav tmp writes out cms html navs for default state (non-prod cat only)
            if (content && content.cms && content.handleAs === "html") {
                //console.log("GlobalNav.PanelSubNav - global nav tmp writes out cms html navs");  
             
                hasLoaded = true;
                isCMS = true;
                
                if (isDefaultPanel) {
                    isDefaultCMS = true;                    
                    // set rollovers & default/detail states in html/cms nav content
                    this.initCMSDisplay({isdefault: isDefaultCMS});
                } 
            }
            
            if (!isDefaultCMS) { 
                //console.log("GlobalNav.PanelSubNav - !isDefaultCMS");  
                psubnavArgs.content = content;
                var psubnav = new brand.globalnav[psubnavClass](psubnavArgs);
                
                // hide content while it loads
                // domNode ex: psubnav_CAT163
                //psubnav.domNode.style.visibility = "hidden";
                
            }
        }
        
        // render default panel content
        if (isDefaultPanel && !hasLoaded) {
              //console.log("GlobalNav.PanelSubNav - render default content"); 
            this.getPanelContent({psubnav: psubnav, sectionId: parentItem.id, item: pnavItem});
        }
    },
    
    getPanelContent: function(args) { 
        //console.log("GlobalNav.getPanelContent "); 
        // summary:
        //      Handles request for file (as specified in config) containing content
        //      for panel (PanelSubNav) associated with a given left-hand nav link

        var psubnav = args.psubnav;  
        var self = this;
        if (psubnav.id === "psubnav_my_mac") {
            $(psubnav.id).removeClassName("hidden");
            generic.events.fire({event:"globalnav:getcontent/my_mac"});  
        } else {
            var handleAs = (psubnav.content.handleAs === "html" ? "text" : "json-comment-optional");
            //var url = "/js/brand/globalnav/data/" + psubnav.itemId + ".txt"; // for testing
            var url = psubnav.content.url + (psubnav.content.param ? ("?" + psubnav.content.param + "=" + psubnav.itemId) : "");
             
      new Ajax.Request(url, {
        method: 'get',
        onSuccess:  function(transport) {  
            var data = transport.responseText;
            this.initPanelContent(data, args); 
            // Would like this to be here, instead of initPanelContent, but don't want to have to evalJSON twice EF
            //generic.events.fire({event:"panel:prodcat", msg:{ data: data, request: args}});
        }.bind(this) 
     }); 
        }
        
    },
    
    initPanelContent: function(data, panelArgs) {
        // summary:
        //      Handles response (as html or json) from getPanelContent
        console.log("GlobalNav.initPanelContent ");   
        
        var psubnav = panelArgs.psubnav; 
        
        // place html content
        if (psubnav.content.handleAs === "html") {            
            psubnav.addSubItem(data);
            
            // set rollovers in html/cms nav content
            if (psubnav.content.cms) {  
                this.initCMSDisplay({scopeNode: psubnav.id});
            }
        
        // loop thru json data to render content variations
        } else {                               
            var sectionId = panelArgs.sectionId;
            var pnavItemId = (panelArgs.item ? panelArgs.item.id : panelArgs.itemId);
            //console.log("GlobalNav.initPanelContent: json "+ sectionId +  " / " + pnavItemId);               
                                     
            // response will either be an array of items or an object that contains the item array further down the tree
            if (typeof data === "string") data = data.evalJSON(true); 
            var items = data; // default
            generic.events.fire({event:"panel:prodcat", msg:{ data: data, request: psubnav}});

            if (typeof data === "object") {
                // ex: prodcat data
                if (data.sections) {
                    items = data.sections[0].items;
                
                // ex: faves (SectionDescSubNav)
                } else if (data.items) {
                    items = data.items;
                    // pass additional data props (above items)
                    if (typeof psubnav.setContent === "function") {
                        psubnav.setContent(data);
                    }
                }
            }
 
            // get content hierarchy type
            var useProductCategories = false; // flag true if prod content has 2-levels deep (categories & detail items) 
            if (sectionId === "products" || pnavItemId === "looks") {        
                useProductCategories = items.any(function(item) { 
                    if (item.items) return true; 
                });   
                //console.log("GlobalNav.initPanelContent: useProductCategories "+useProductCategories); 
            }
            // prodcat special case: discontinued nav 
            if (pnavItemId  == "discontinued") {
               //console.log("GlobalNav.initPanelContent: discontinued");  
            
               this.initDiscontinued(items, psubnav, panelArgs.item);
           
            //prodcat: if item hierarchy goes 2-levels deep
            } else if (useProductCategories) {            
                //console.log("GlobalNav.initPanelContent: prodcat: if item hierarchy goes 2-levels deep");   
                this.initProductCategories(items, psubnav, sectionId, pnavItemId);
                
            //prodcat & other sections w/ only 1 level deep
            } else { 
                 //console.log("GlobalNav.initPanelContent: prodcat & other sections w/ only 1 level");   
                // if no section defined, item is the section
                if (sectionId === "") {
                    sectionId = pnavItemId;
                } 
                
                // get default context
                var hasItemInDefaultCategory = false; // flag true if in default category & category contains default detail item 
                if (psubnav.isDefaultPanel) {
                    
                    // default detail item
                    var defaultDetail = this.getDefaultDetail(); 
                    hasItemInDefaultCategory = items.any(function(detailItem) { 
                        return (!!(detailItem.id === defaultDetail.id));
                    })
                    //console.log("GlobalNav.initPanelContent: hasItemInDefaultCategory "+hasItemInDefaultCategory);    
                    // PanelSubNav
                    if (hasItemInDefaultCategory) {
                        psubnav.setDefaultState();
                    }
                }                
 
                var self = this; 
                
                items.each(function(detailItem, idx) {   
                     //console.log("GlobalNav.initPanelContent: items"+idx + ": "+detailItem.id+" / "+psubnav.id);    
                    // check for header links or detail modules
                   if (detailItem.type === "header_link") {
                        var isdefaultDetail = false;
                        if (defaultDetail && (detailItem.id === defaultDetail.id)) {
                            isdefaultDetail = true;
                        }
                        self.initHeader({type: "psubitem", item: detailItem, isdefault: isdefaultDetail, containerId: psubnav.id});
                    
                    // detail module
                    } else {         
                        var detail = self.initDetail({
                            item: detailItem,
                            sectionId: sectionId,
                            pnavItemId: pnavItemId,
                            defaultItem: defaultDetail,
                            isInDefaultCategory: hasItemInDefaultCategory,
                            parentId: psubnav.id,
                            domParentId: psubnav.containerNode /**,
                            domInsertionMethod: function(d) {
                                // add item to PanelSubNav
                                psubnav.addSubItem(d.domNode);
                            }**/
                        }); 
                    } 
                });                
                
            }
            
        }//end loop through json
          
        // hide progress, show content 
        //$(psubnav.id).show(); //JSTEST  
        psubnav.onChildrenLoaded({ hasLoaded: true });
    },

    initProductCategories: function(supercatItems, psubnav, sectionId, pnavItemId) {
        // summary:
        //      Adds category and product level widgets that render category-detail modules
        //      (ProductCategoryDetail), category accordion headers (Accordion) and product-detail
        //      modules (Detail).
        //      These instances are attached to their parent instance of ProductSubNav
        //console.log("GlobalNav.initProductCategories: "+supercatItems.length); 
        
        var self = this;
        var defaultSupercat = this.defaultState.item;
        var defaultCat = (defaultSupercat ? defaultSupercat.item : null);
        var defaultCatId = (defaultCat ? defaultCat.id : null);
        var useAccordionMode = false; // flag true shows accordion headers as initial state (rather than category detail modules). used for default state of spp's & cat-level mpp's
        var hasMixedDetail = false; // flag true if category level includes non-category (childless) items.  Ex: brush-play detail link in Brushes category list

        // default detail
        if (psubnav.isDefaultPanel && defaultCat) { 
            var defaultDetail;
            try {
                defaultDetail = defaultCat.item;
            }
            catch (err) { }
        }
     
        supercatItems.each(function(catItem, catidx) {
              //console.log("GlobalNav.initProductCategories supercatItems "+catidx+": "+  catItem.id);
            var hasChildren = true; // flag true when item is a category w/ child detail items (i.e. will display as accordion group)
            
            if (!catItem.items) {
                //console.log("GlobalNav.initProductCategories id: "+catItem.id + " has no children");
                hasChildren = false;
                hasMixedDetail = true;
            }
            
            // get default context            
            var isDefaultCat = false; // default category w/ in default ProductSubNav
            var hasItemInDefaultCategory = false; // flag true if category contains default detail item
            // nav is rendering default state of psubnav and has levels beyond supercat
            if (psubnav.isDefaultPanel && defaultCat) {            
                useAccordionMode = true;             

                // verify that category contains a default detail
                // (usually true. false ex: mpp)
                if (catItem.id == defaultCatId) {
                    isDefaultCat = true;
                    if (defaultDetail) {
                        hasItemInDefaultCategory = true;
                    }
                }
            }

            // add detail module for item
            if (!useAccordionMode || !hasChildren) {
		if (catItem.header_image_height != '') {
                  var hdHeight = catItem.header_image_height; 
		}
		else {
		  var hdHeight = '';
		}
                //console.log("GlobalNav.initProductCategories: add detail module for item");
                var dargs = {
                    id: "psubcat_"+catItem.id,   
                    displayName: catItem.name,
		    hdHeight: hdHeight,
                    hdPath: catItem.header,
                    description: catItem.description,
                    thumbPath: catItem.thumbnail,
                    sectionId: sectionId,
                    pnavItemId: pnavItemId,
                    parentId: psubnav.id
                }
                //console.log("GlobalNav.initProductCategories "+dargs.id+" / " +psubnav.id);
                // add detail link
                if (!hasChildren) {
                    //console.log("GlobalNav.initProductCategories: !hasChildren"); 
                    dargs.item = catItem;
                    dargs.isInDefaultCategory = hasItemInDefaultCategory; 
                    dargs.domInsertionMethod = function(d) {
                        psubnav.addSubItem(d.domNode, psubnav.detailLinksContainerNode);
                    }
                    
                    var detail = self.initDetail(dargs);
                    return; 
                
                // add category detail
                } else if (!useAccordionMode) {
                    //console.log("GlobalNav.initProductCategories - !useAccordionMode "+dargs); 
                   
                    var altDetailConfig = self.getAltTemplateConfig(catItem);
                    if (altDetailConfig) {
                        dargs.template = dargs.template || {} ;
                        dargs.template.detail = dargs.template.detail || {} ;
                        dargs.template.detail = generic.mixin(dargs.template.detail, altDetailConfig);
                    } 
                    
                    psubnav.addCategoryDetail(dargs);
                } 
            }
            
            var img = catItem.header.replace(/200/g, "250");  //MK: use clip
            var subnavAccordion = psubnav.addCategoryAccordion({
                id:"psubcat_"+catItem.id,
                displayName: catItem.name,
                hdPath: img,
                description: catItem.description
            });                     
            
            catItem.items.each(function(detailItem, idx) {
               //console.log("GlobalNav.initP catItems "+idx+": "+ detailItem.id + "/" + subnavAccordion.id);
                 /*
                Detail:
                    - creates product-level detail html module
                
                Attachment notes:
                    Detail node gets passed to Accordion's addSubItem method 
                */
                
                var detail = self.initDetail({
                    item: detailItem,
                    sectionId: sectionId,
                    pnavItemId: pnavItemId,
                    defaultItem: defaultDetail,
                    isInDefaultCategory: hasItemInDefaultCategory,
                    parentId: psubnav.id,
                    domParent: subnavAccordion.containerNode
                    
                     /** 
                    domInsertionMethod: function(d) {
                        // add detail item to Accordion
                        subnavAccordion.addSubItem(d.domNode);
                    }**/
                });                
               
            }); // end: catItems foreach
                
                
            // accordion has items, so toggle its display for default category state
            psubnav.setCategoryState({
                accordion: subnavAccordion,
                useAccordionMode: useAccordionMode,
                isDefaultCat: isDefaultCat, 
                hasItemInDefaultCategory: hasItemInDefaultCategory
            });
            
        });
        
        // psubnav content loaded, so toggle display for default panel state
        psubnav.setPanelState({ hasMixed: hasMixedDetail });
     
    },
   
    initDetail: function(args) { 
        // summary:
        //      Instantiates appropriate Detail widget class and properties according to
        //      content type. 
        
        // args
        var item = args.item;
        var config = brand.globalnav.config;
        var sectionId = args.sectionId;
        var pnavItemId = args.pnavItemId;  
    //console.log("GlobalNav.initDetail " +args.item.id + " / " + args.parentId + " / " +args.pnavItemId); 
        
        // get config if needed
        var sk = (sectionId ? this._configKeys[sectionId] : null);
        var sectionConfig = (sk ? this.config.items[sk.idx] : null);
        var pnk = (sectionConfig ? sk.items[pnavItemId] : null);
        var pnavItemConfig = (pnk ? sectionConfig.items[pnk.idx] : sectionConfig);       
        
        
        // get image paths from path fields or from image base depending on what is given
        //MK var hdPath = "";
        var hdPath = item.header;
        var hdHeight = item.header_image_height; 
        var thumbPath = item.thumbnail; 
        
         
        
        // set if default
        var isInDefaultCategory = (args.isInDefaultCategory ? args.isInDefaultCategory : false);         
        var isdefault = false;
        if (isInDefaultCategory) {
            if (args.isdefault) {
                isdefault = args.isdefault;
            } else {
                var defaultId = (args.defaultItem ? args.defaultItem.id : null);
                if (item.id == defaultId) {
                    isdefault = true;
                }
            }
        }
        
        var itemName = (item.name ? item.name : "");
 
        // parameters that always get passed to detail-level widgets
        var wArgs = {
            id: "psubitem_" + item.id,
            displayName: itemName,
            hdPath: hdPath,
            hdHeight: hdHeight,
            thumbPath: thumbPath,
            thumbRolloverPath: item.thumbnail_rollover,
            url: item.uri,
            isdefault: isdefault,
            parentId: args.parentId,
            isInDefaultCategory: isInDefaultCategory
        }
        if (args.domParent) wArgs.domParent = args.domParent;
        if (args.domInsertionMethod) wArgs.domInsertionMethod = args.domInsertionMethod;
            
        // optional parameters
        // description:
        wArgs.description = (item.description ? item.description : null);
        // template:
        var t;
        if (args.template) {
            t = args.template;
        } else if (pnavItemConfig && pnavItemConfig.template) {
            t = pnavItemConfig.template;
        } else if (sectionConfig && sectionConfig.template) {
            t = sectionConfig.template;
        }
        if (t) {
            wArgs.template = t;
        }
        
        //console.log("GlobalNav.initDetail: add " +wArgs.id + " / " + wArgs.parentId); 
         
        // check for alternate "type" property: defines display styles for individual items that may differ from group
        var altDetailConfig = this.getAltTemplateConfig(item);
        if (altDetailConfig) {
            wArgs.template = ( wArgs.template ? wArgs.template : {} );
            wArgs.template.detail = ( wArgs.template.detail ? wArgs.template.detail : {} );
            generic.mixin(wArgs.template.detail, altDetailConfig);
        }       
            
        var detail = new brand.globalnav.Detail(wArgs);
       
        /**JSTEST on create
        if (args.onCreate) {
             console.log("GlobalNav.initDetail " +detail.domNode); 
            args.onCreate(detail);
        }       **/
        
        // now that detail node has a place in the DOM, start it up:
       //JSTEST detail.startup();
        
        return detail;
    },

    getAltTemplateConfig: function(item) {
        var dconfig = false;
        if (item.type) {
            var altTypes = this.config.altTypes;        
            var ait = altTypes[item.type];
            
            // if alt type is defined, pass it in template props
            if (ait && ait.detail) {  
                dconfig = ait.detail;
            }
        }        
        return dconfig;
    },
     
    initHeader: function(args) { //type, item, isdefault, containerId, domParent
        // summary:
        //      Creates instance of Header for items that don't open a panel or accordion
        //      (including default state of a PanelNav link) 
        var item = args.item;
        if (!args.item)  return;
        var h = new brand.globalnav.Header({
            id: args.type+"_"+item.id,
            displayName: item.name,
            hdPath: (item.header ? item.header : ""),
            url: (item.uri ? item.uri : null),
            isdefault: args.isdefault,
            parentId: args.containerId,
            domParent: args.domParent
        }); 
    },

    initSearch: function(sectionConfig) {
        // summary:
        //      
        
        var id = sectionConfig.id;
        var self = this; 
        
        // check for default
        var isDefaultPanel = false;
        if (this.defaultState.query && (this.defaultState.item.id === id)) {
            isDefaultPanel = true;
        }
        
        if (!isDefaultPanel) {
            var pnavManager = new brand.globalnav.panelManager({
                id: "pnav_" + id, 
                parentId: this.globalNavSetId,
                sectionId: id,
                item: sectionConfig
            });
            
            pnavManager.startup();
        }
     
      var psubnav = new brand.globalnav.PanelSubNav({
            //templatePath: "/js/brand/globalnav/templates/SearchSubNav.html",
            templatePath: "jsTemplates.globalnav.SearchSubNav",
            id: "psubnav_" + id,
            parentId: "pnav_" + id,
            isDefaultPanel: isDefaultPanel,
            itemId: id,
            cache: false,
            callback: function() {
                var search = new brand.search({
                config: sectionConfig,
                panelManagerId: "pnav_" + id,
                parentId: self.globalNavSetId,
                isDefaultPanel: isDefaultPanel
                 });
            }
        }); 
    },
    
    initDiscontinued: function(items, psubnav, sectionConfig) {  
        //console.log("GlobalNav.initDiscontinued ");  
        var self = this;
          
         // populate DiscontinuedSubNav.html-specific nodes
        psubnav.panelDescriptionNode.innerHTML = items.panel_description;
        psubnav.searchDescriptionNode.innerHTML = items.description;
      
        // featured goodbyes detail link
        var defaultDetail = this.getDefaultDetail();
        var isdefaultDetail = (defaultDetail.id === "featured_goodbyes" ? true : false);
        var featured = sectionConfig.content.featured;
        featured.description = items.featured_description;
     
        var detail = self.initDetail({
            item: featured,
            template: sectionConfig.template, // JSTEST: changes by STEPH
            isdefault: isdefaultDetail,
            isInDefaultCategory: isdefaultDetail,
            parentId: psubnav.id,
            domInsertionMethod: function(detail) { 
                psubnav.addSubItem(detail.domNode, psubnav.featuredNode);
            }
        });
                        
        // show subnav content
        psubnav.onChildrenLoaded();
 
        var dsearch = new brand.search({
            config: sectionConfig,
            isDefaultPanel: psubnav.isDefaultPanel,
            progressNode: $("disc_search_progress")
        }); 

    },
    
    getDefaultDetail: function(args) {
        // summary:
        //
        //      Find terminus/detail item in page_data.panel_nav.default
        //      args.includeParent: returns object starting with parent of terminus
        //console.log("GlobalNav.getDefaultDetail");
        var d = p = this.defaultState;
        var defaultSubsection = this.defaultState.item; // supercat-level for prodcat.  sub-section level for non-prodcat
        var includeParent = ((args && args.includeParent) ? args.includeParent : false);
        if (defaultSubsection) {
            // step down
            if (defaultSubsection.item) {
                d = defaultSubsection.item; // (ex: products - nails - spp)
                p = defaultSubsection;
                if (d.item) {
                    p = d;
                    d = d.item; // (ex: products - eyes - primer - spp)
                }
                
            // at detail level (ex: giving back - back to mac)
            } else {
                d = defaultSubsection;
            }
        }
        
        return (includeParent ? {detail: d, parent: p} : d);
    },
        
    initCMSDisplay: function(args) {
        // summary:
        //
        //      Sets rollovers for linked images
        //      If is default nav: finds image header in cms nav that matches id
        //      of current page.  Sets image to "on" state

        var scopeNode = (args.scopeNode ? args.scopeNode : "panel_open");
        var defaultImgId = null;
        var rollover;
        var defaultImg; 

        // find image associated with default page state
        if (args.isdefault) {        
            var d = this.getDefaultDetail({ includeParent: true });
                        
            defaultImgId = "image_" + d.detail.id;
            // if default image isn't found, check for match in parent section id
            if (!$(defaultImgId)) {
                var pId = "image_" + d.parent.id;
                if ($(pId)) {
                    defaultImgId = "image_" + d.parent.id;
                }
            }
        } 
        
       // find images in specified nav, apply rollovers
       var imgs = $$("#" + scopeNode + " a img");
       imgs.each(
            function(imgn) {
                if (imgn.id === defaultImgId) {
                    defaultImg = new generic.img(imgn, ["off","on"]);
                    defaultImg.changeSrc("on");
                } else {
                   rollover = new generic.rollover(imgn, null);
                }
            }
        );
    
    }
    
});

 

brand.globalnav.GlobalSet = Class.create(Widget, 
{
    // summary:
    //      Container for set of nav items in left-nav. 
    //      Items/children are mixed widget types (Accordion, PanelNav and Header) 
    //      Children communicate about state changes with each other via the NavSet parent
    
    // activeItemId: String
    // currently active/open child widget id
    activeItemId: "",
     
    // _objChildren: Object
    // storage for children not gettable/settable via other methods
    _objChildren: {},
    
    initialize: function($super, properties) {
    $super(properties);     
    },
    
    addChild: function(child) {
        // summary:
        //      Stores child instances of objects not gettable/settable via other methods
        //      Ex: non-dijit brand.globalnav.panelManager
        
        this._objChildren[child.id] = child;  
    },
    
    getChild: function(childId) {
        // summary:
        //      Returns objects stored via addChild
        //console.log("brand.globalnav.GlobalSet.getChild: "+childId); 
        var child = false; 
        for (var i=0;i< this.children.length;i++) {
              if (this.children[i].id == childId) {
                child = this.children[i];
                break;
              }
        }  
        return child;
    },
 
    setActiveItem: function(/* String */itemId) {
        this.activeItemId = itemId;
    },

    onChildClick: function(/* String */sectionId,/* Boolean */fromDefault) {
        // summary:
        //      Called by child widgets
        //      Captures events occuring further down in navigation hierarchy
        //      If change is being triggered by default link, closes activeItem, but keeps
        //      default accordion 
        //console.log("GlobalSet.onChildClick "+this.activeItemId +" / "+ sectionId  +" / "+  fromDefault)
        if (this.activeItemId && (this.activeItemId !== sectionId || fromDefault)) {
        
            // get dijit
            var activeItem = $(this.activeItemId).widget;
            // otherwise, look for non-dijit child
            if (!activeItem) {
                try {
                    var gset = $(globalNavSetId).widget;
                    activeItem = this.getChild(this.activeItemId);
                }
                catch(err){};
            }
            
            var defaultId = (fromDefault ? sectionId : ""); 
            activeItem.close(defaultId);
            
        } 
    }
    
});
