brand.view = {};
    
brand.view.setFormSelectors = function() {
    console.log("brand.view.setFormSelectors");
    $$("INPUT[type=text]").invoke("addClassName","inputText");
    $$("INPUT[type=password]").invoke("addClassName","inputPassword"); 
    $$("INPUT[type=image]").invoke("addClassName","inputImage"); 
}

brand.view.colorNav = {
   abort: false,
   placeholder: "color_nav_placeholder",
   flashid: "color_nav",
   offW: 8,
   onW: 90,
   timer: null,
 
   embed: function() { 
        if (brand.view.colorNav.abort) return;
        
        if (generic.env.isSafari) {
            var cn = $("color_nav_container");
            if (cn) { cn.style.display = "none"; }
            this.placeholder = "color_nav_placeholder_standalone";
            this.flashid = "color_nav_standalone";
        } 
        
        var params = {
            menu: "false",
            movie: "/flash/color_nav/color_nav.swf",
            flashvars: {
                gradient_uri: "/flash/color_nav/assets/color_gradient.png",
                application_uri: "/flash/color_play/index.tmpl",
                application_query_string: "?colorplaysample="
            }
        };
    
        var attr = {
            id: this.flashid,
            name: this.flashid,
            data: "/flash/color_nav/color_nav.swf",
            width: this.offW
        };
        
        if (generic.flash.playerversion) {
            attr.playerversion = generic.flash.playerversion;
        }
 
        if ($(this.placeholder)) generic.flash.embed(attr, params, this.placeholder);  
    },
    setWidth: function(e) {    
        if (e=="mouseover") { 
             clearTimeout(brand.view.colorNav.timer);  
             $(this.flashid).style.width = this.onW + "px";  
        } else {     
             brand.view.colorNav.timer = setTimeout(function(){    
                 $(brand.view.colorNav.flashid).style.width = brand.view.colorNav.offW + "px";     
             }, 600);
        }
    
    }    
}
    
//Simulate fixed bottom position
brand.view.bottomFixed = Class.create({  
    node: null,  // node: DOM element to position 
    minTop: 0, // minTop: Number minimum pixels for node.style.top 
    isLoaded: false,

    initialize: function(args) {
        if (!args.node) return false;
        this.node = args.node;
        this.s = this.node.style;
        this.fromBottom = parseInt(this.node.getStyle("bottom"), 10);
        if (args.minTop) {
            this.minTop = args.minTop;
            this.hasMinTop = true;
        } else {
            this.hasMinTop = false;
        }
        this.position();
        this.s.visibility = "visible";
        this.s.bottom = '';
        
        // set scroll events
        var self = this;
        Event.observe(window, 'scroll', function() {
                self.onScroll();
        });
        Event.observe(window, 'resize', function() {
                self.onScroll();
        });

        this.loaded();
    },
    loaded: function() {
        this.isLoaded = true;
    },
    position: function() {  
        var h = window.pageYOffset ||
        document.documentElement.scrollTop;
        h = (h ? h : 0);
        var shiftY = ((h + document.documentElement.clientHeight) - (this.node.offsetHeight + this.fromBottom));    
        if (this.currentY != shiftY) {  
            var changeBy = shiftY;      
            if (this.hasMinTop && (changeBy <= this.minTop)) {
                changeBy = this.minTop;
            }
            this.currentY = changeBy;
            this.s.top = (changeBy + 'px');  
        }   
    },
    onScroll: function() {   
        this.position();
    }
});


/*
 * utilityNav:
 * sets up visual toggling of utility nav button fields
 * hooks up email & locator fields to emailSignup & locator classes if applicable
 * NOTE: search initialized from brand.search Class
 */
brand.view.utilityNav = {
    
    formelements: {},    
    buttonsets: {},
    
    init: function() {

        // button/form field toggling
        var container = $("utilitynav");
        if (!container) return false;
        var nodes = container.select('.utilitynav_button');
        var self = this;

        nodes.each(function(node) {
            // button/form pair toggling relies on naming convention: utilitynav_[button or form]_[pair name]
            if (!node.id) return;
            var name = node.id.replace(/utilitynav_button_/g, "");
            var formnode = $("utilitynav_form_" + name);

            // get form element id's being used (not all locale's may have same elements)
            //var ftext = dojo.query("input[type=text]", formnode);
            var fieldnode = formnode.select("input[type=text]")[0];            
            var fieldsubmit = formnode.select("input[type=image]")[0];
            
            if (name && formnode && fieldnode) {
                self.buttonsets[node.id] = name;
                self.buttonsets[fieldnode.id] = name;
                self.buttonsets[fieldsubmit.id] = name;
                
                self.formelements[name] = { field: fieldnode, submit: fieldsubmit };
                node.observe("click", function() {
                    self.showForm(node);
                });
                fieldnode.observe("blur", function() {
                    self.showButton(fieldnode);
                });
                fieldsubmit.isfocused = false;
                fieldsubmit.onfocus = function() { 
                    this.isfocused = true;
                }
                fieldsubmit.observe("blur", function() {
                    self.showButton(fieldsubmit);
                });
            }       
        });

        // form submits: email signup & locator     
        if (this.formelements.email) {
            this.initEmailSignup(this.formelements.email);
        }
        if (this.formelements.locator) {
            this.initLocator(this.formelements.locator);
        }

    },

    showForm: function(node) {
        var shownode, hidenode;
        var hidenode = node;
        var name = this.buttonsets[node.id];
        var shownode = $("utilitynav_form_" + name);
        this.toggle(hidenode, shownode);
        
        // focus on field
        var focusnode = (this.formelements[name] ? $(this.formelements[name].field) : null);
        if (!focusnode) { return; }
        focusnode.focus();
        focusnode.value = "";
        focusnode.isfocused = true;
    },

    showButton: function(node) {
        var shownode, hidenode;
        node.isfocused = false;
        var name = this.buttonsets[node.id];
        var self = this;
        var submitbtn = $(this.formelements[name].submit);
        var field = $(this.formelements[name].field);
        var hidenode = $("utilitynav_form_" + name);
        var shownode = $("utilitynav_button_" + name);
        
        // wait for animation to finish
        var pause = function() {
            if (!submitbtn.isfocused && !field.isfocused) {
                self.toggle(hidenode, shownode);           
            }
        }
        setTimeout(pause, 200);
    },
    
    toggle: function(hidenode, shownode) {
        if (hidenode && shownode) {
            hidenode.style.display = "none";
            shownode.style.display = "block";
        }
    },
    
    initEmailSignup: function(formelements) {
        if (site.account && site.account.emailSignup) {
            site.account.emailSignup.init({
                submitNode: formelements.submit,
                fieldNode: formelements.field
            });
        } else {
            console.log("(site || brand).account.emailSignup not found");
        }

    },
    
    initLocator: function(formelements) {
        if (site.locator) {
            site.locator.init({
                submitNode: formelements.submit,
                fieldNode: formelements.field
            });
        } else {
            console.log("(site || brand).locator not found");
        }

    }
}


brand.view.overlay = { 
    params: {  
            wmode: "transparent"
    },
    attr: {
            id : "page_overlay",
            name: "page_overlay",
            height: "84",
            width:"245",  
            bgcolor: "#000" 
    },
    embed: function() {
        if (!$("page_overlay_div")) return; 
        var params = this.params;
        var attr = this.attr;
        params.movie = $("page_overlay_div").getAttribute("swf");
    attr.data = $("page_overlay_div").getAttribute("swf");
        generic.flash.embed(attr, params, "page_overlay_div");  
    },
    close: function() {  //called by teh shipping swf
        $("page_overlay_container_div").addClassName("page_overlay_container_div_closed"); 
    console.log("brand.view.overlay.close()");
    }
    
}
      

brand.view.footer = {  
    adjust: function() { 
        if (generic.env.isIE6) {
            var footerNode = $("footernav");
            this.initIELayerFix(footerNode);
            var footer = new brand.view.bottomFixed({
                node: footerNode
            });
        }
        
        var utilityNav = new brand.view.bottomFixed({
            node: $("utilitynav"),
            minTop: 400
        }); 
        
        //country chooser drop-up
        var footerMenu = new generic.menu({
            menu: "countries_container",
            target: "countries_hd"
        }); 
    
    },
    
    // IE workaround:
    // Puts an iframe behind the footer in IE so windowed elements (<select>'s) don't show through
    initIELayerFix: function(footer) {
        if (!footer) return;
        var iframe = new Element('iframe', { "id": "footer_iframe", "href": "/includes/blank.html", "frameborder": "0",  "marginwidth": "0", "marginheight": "0", "scrolling": "no" });
        footer.insert({ "top": iframe });
        var footerContent = $("footernav_content");
        var offset = iframe.offsetHeight;       
        // move the footer content up so it's on top of the iframe
        if (footerContent) {
            footerContent.style.marginTop = "-" + offset + "px";
        }
    }
}   
    

/*
 * heightHandler:
 * manage height changes for/caused by absolutely positioned elements
 */
brand.view.heightHandler = { 
    pagetype: null,
    min: 620,
    winh: 0, // re-saved everytime window height changes
    bodyh: 0,
    bodyhOriginal: 0, // onload is saved as original height of body
    bodyhWithoutPanel: 0, // current body height w/out additional height of sliding panel
    offset: 18, // height as offset by footer
    isCMS: false,
    spacer: null, // node to resize to affect body height
    excludeOnResize: [ "color_play" ], // has no color bar to reset height to & contains it's own resize functions
    excludeOnload: [ "color_play", "locator" ],
    isLoading: false,
    isResizing: false,
    timer: null,
    isIE6: false,
    hasCMSLayers:false,
    
    init: function() { 
        this.hasCMSLayers = !!$$("#main_content_td .cms_layer").length; 
        if (this.hasCMSLayers) this.cmsCleanup(); 
        
        // ignore pages that don't have the global nav
        var gnav = $("globalnav_container");
        if (!gnav) { return; }
        var spacer = $("column_spacer");        
        if (generic.env.isIE6) {
            this.isIE6 = true;
            var colorNav = $("color_nav_td");
            spacer = (colorNav ? colorNav : spacer); //if no color nav, don't set its height 
        }
        this.spacer = spacer;
        
        this.setPageType();
            
        // get offset for footer
        var fnnode = $("footernav");
        this.offset = (fnnode ? fnnode.offsetHeight : this.offset);        
        
        // ensure that winh doesn't result in negative value later
        this.winh = this.getWindowHeight();
        if (this.winh <= this.offset) {
            this.winh = (this.offset * 2);
        }
        
        if (this.pagetype !== "home") {
            //this.bodyhOriginal = (this.isCMS ? this.getCMSHeight() : this.getBodyHeight());
            this.bodyhOriginal = this.getBodyHeight(); 
            this.bodyh = this.bodyhOriginal; 
        }
        
        this.onLoad(); 
        
        //JSTEST set up handlers
        /**dojo.subscribe("/panelnav/event/show", this, function(args) {
            this.onPanel("show", args);
            //console.log("panelnav/event/show for "+args.id);
        });
        dojo.subscribe("/panelnav/event/hide", this, function(args) {
            this.onPanel("hide", args);
        });

        if (this.excludeOnResize).indexOf(this.pagetype)) == -1) { 
            dojo.connect(window, "onresize", this, "onResize");
        }**/
        
        this.isLoading = false;        
    },
     
   cmsCleanup: function() { 
      // if (generic.env.isIE6) return; // SS: Something in here is throwing an error in IE6.  Comment out until fixed
       var cmsBlocks = []; 
       $$("#main_content_td .cms_layer").each(function($_) {  
            pushNew(cmsBlocks,$_.ancestors()[0]);
       });
       cmsBlocks.each(function($_) { 
            if (!$_.hasClassName("noCMSCleanup")) {
            	 parseCMSLayers($_);
            }
       }); 
      
   function parseCMSLayers(parentDiv) { 
    var moved = false; 
    if (parentDiv.hasClassName("hidden")) {  
        moved = true;
        parentDiv.origLeft = parentDiv.style.left;  
        parentDiv.style.left = "-5000px";
        parentDiv.removeClassName("hidden");
    }
    var input = parentDiv.select(".cms_layer");  
    var output = input.sort(function(a,b){return parseInt(a.style.top) - parseInt(b.style.top)}); 
    
    var outputRows = [];
    var outputFinal = [];
    outputRows[0] = [];
    var oIndex = 0;
    var previousTop = 0;
    
    for (var i=0;i<output.length;i++) { 
        output[i].style.height = "auto";  
        output[i].cmsTop = parseInt(output[i].style.top); 
        output[i].actualHeight = parseInt(output[i].clientHeight);   
        output[i].impliedTopMargin = (i==0) ? output[i].cmsTop : output[i].cmsTop - output[i-1].cmsTop - output[i-1].actualHeight; 
        //console.log(output[i].id + " " + output[i].actualHeight);
        previousTop = (i==0) ? output[i].style.top : output[i-1].style.top;
        
        if (output[i].style.top==previousTop) {//same row
             
        } else {//next row
            outputRows[oIndex] = outputRows[oIndex].sort(function(a,b){return  parseInt(a.style.left) -  parseInt(b.style.left)});    
            oIndex++; 
            outputRows[oIndex] = [];
        }
        outputRows[oIndex].push(output[i]);
    }
    outputRows[oIndex] = outputRows[oIndex].sort(function(a,b){return  parseInt(a.style.left) -  parseInt(b.style.left)}); 
  
    var o = {}; var css = ""; 
    var adjust = (parentDiv.id == "main_content_td" ) ? 476 : 0;
    for (var i=0;i<outputRows.length;i++) { 
        for (var j=0;j<outputRows[i].length;j++) { 
            o = outputRows[i][j]; 
            css = "position:relative;"
            css += "width:" + o.style.width + ";";  
            css += "height:" + o.actualHeight + "px;";
            css += "margin-left:" + (parseInt(o.style.left)-adjust) + "px;";
            css += "margin-top:" + o.impliedTopMargin + "px;"; 
            o.style.cssText = css;  
            parentDiv.appendChild(o);
        } 
    }   
 
    if (moved) { 
         parentDiv.addClassName("hidden")
         parentDiv.style.left = parentDiv.origLeft; 
    }  
   }
    
      function pushNew(arr,o) {  
        var n = true;
        for (var i=0;i<arr.length;i++) {
        if (arr[i]==o) {n = false;break;}
        }
        if (n) arr.push(o);   
       }      
       
       //temp
      //document.body.style.height =  ($("main_table").scrollHeight + $("footernav").clientHeight + 50) +  "px"; 
       try {
        var colorNav = (generic.env.isSafari) ? $("color_nav_standalone") : $("color_nav");  
       colorNav.style.height = ($("main_table").scrollHeight + $("footernav").clientHeight + 50) +  "px"; 
       } catch(e) {}
    },

    onLoad: function() {
        if (this.excludeOnload.indexOf(this.pagetype) > -1) {
            if (!generic.env.isIE6) {
                return;
            } else if (!$("color_nav_container")) {
                return;
            }
        }
        this.isLoading = true;        
        var h = (this.winh > this.min) ? this.winh : this.min; 
        var spacer = this.spacer;
  
        // home page: set height of spacer column to match window
        if (this.pagetype === "home") {  
            h = (this.winh - this.offset);
            this.spacer = spacer = $("main_content");
            spacer.style.height = h + "px";
            
        // default: for sub pages
        } else {  
       
            // if body is shorter than window, set height to match window
            if (!this.hasCMSLayers && (h >= this.bodyh)) {    
                //console.log("body shorter than window");
                spacer.style.height = h + "px";  
                
      // cms content or IE6: cases where taller body requires explicitly setting spacer height. (cms body height is ignored by page & ie6 color bar height has to be set explicitly 
            //} else if (this.isCMS || this.isIE6) {   
            
            //cms content handled by CMSCleanup
            } if (generic.env.isIE6) {
                var colorNav = (generic.env.isSafari) ? $("color_nav_standalone") : $("color_nav");  
                if (colorNav) { 
                        var maxh = (2800 > this.bodyh) ? 2800 : this.bodyh;
                    if (generic.env.isIE) { 
                         colorNav.style.height = this.bodyh + "px";  
                    } 
                    else if (generic.env.isSafari) {  
                      colorNav.style.height = maxh + "px";   
                    }
                else {   
                         setTimeout(function(){colorNav.style.height=maxh+"px";}, 2000); 
                    } 
                }  
                       
                spacer.style.height = this.bodyh + "px"; 
                //console.log("CMS/IE6 page spacer h = "+spacer.style.height+" real h = "+spacer.offsetHeight);
            
            // for flash browsers, set spacer height to at least window initially, since flash could resize itself to shorter than window w/out triggering the resize event
            } else if (this.pagetype === "flash_browser") {
                spacer.style.height = h + "px";
            }
        }

        this.bodyhOriginal = this.bodyh = this.bodyhWithoutPanel = h;
    },
    
    setPageType: function() {
        var pd = page_data;
        if (!pd) return;
        if (this.pagetype) { 
            type = this.pagetype;
        } else {
            try {
                this.pagetype = pd.panel_nav["default"].id;
            }
            catch (e) { }
        }
        this.isCMS = (pd ? pd.cms_generated : null);
    },

    onPanel: function(action, args) {
        if (this.isResizing) { return; }
        var type = args.type;
        var parentId = args.parentId;
        // ignore gnav accordion
        if (parentId === "globalnav_container" && type === "accordion") {
            return;
        }
              
        var spacer = this.spacer;
        var id = args.id;
        if (type === "panel") {
            this.activePanelId = id;
        }
        var panelId = this.activePanelId;
        var panel = $(panelId);
        if (!panel) { return; } // ex: open panels
        this.isResizing = true; // set isResizing after all non-returnable conditions met
        var self = this;
                
        //alert("/panelnav/event/"+action+", id = "+id+" panel to check = "+panelId+" type = "+type+" panel node = "+panel+" parent id = "+parentId);
    
        // wait for animation to finish
        var pause = function() {
            if (action === "hide" && type === "panel") {
                var h = self.bodyhWithoutPanel;
                // compare pre-panel open body height against window height
                if (h < self.winh) {
                    h = self.winh;
                }
                //console.log("CLOSE: h = "+h+" self.bodyhWithoutPanel = "+self.bodyhWithoutPanel);
                spacer.style.height = h + "px";
                self.bodyh = h;
            } else if (action === "show") {
                var panelh = panel.offsetHeight;
                //alert("OPEN: panel h = "+panelh+" bodyh = "+self.bodyh);
                // compare against window & last known body height
                // (getting current body height here not consistent across browsers)
                if (panelh > self.winh && panelh > self.bodyh) {
                    spacer.style.height = panelh + "px";
                    self.bodyh = panelh;
                }           
            }
            self.isResizing = false;
        }
        setTimeout(pause, 600); // note: should be equal to or greater than duration of open/close Panel sliding       
    },
    
    onResize: function() {
        if ((this.isResizing || this.isLoading) && !this.isIE6) { return; }
        var winh = this.getWindowHeight();
        var bodyh = this.bodyh;        
        var page = this.pagetype;
        if (winh > bodyh) {  
            this.doResize(page, winh);
        } else if (page === "home") { // page is home & winh is less than bodyh
            if ((winh < this.min) && (this.min > bodyh)) { 
                this.doResize(page, this.min);
            }
            
        // workaround for IE6: when contents in main body change dynamically (ex: elements load/display after page load), then we have to get/set height again
        } else if (generic.env.isIE6) {            
            bodyh = this.getBodyHeight();
            if (bodyh != this.bodyh) {
                this.doResize(page, bodyh);
                this.bodyh = bodyh;
            }
        }
        this.winh = winh;
    },
    
    doResize: function(page, elementh) {
        var timer = this.timer;
        var spacer = this.spacer;
        var offset = this.offset;
        var h = elementh;
        var self = this;
        var resize = function() {
            if (page === "home") { h = (elementh - offset); }
            spacer.style.height = h + "px";
            self.bodyh = self.bodyhWithoutPanel = h;
        };      
    
        // avoid IE resize recursion
        if (generic.env.isIE) {
            if (timer) clearTimeout(timer);
            timer = setTimeout(resize, 300);
        } else {
            resize();
        }     
    },
    
    getBodyHeight: function() { 
        var h = document.body.scrollHeight;
        return h;
    },
    
    getWindowHeight: function() {
        var h;
        if (typeof window.innerHeight !== 'undefined') {
            h = window.innerHeight;
        } else {
            h = document.documentElement.clientHeight;
        }
        return h;
    },
    
    getCMSHeight: function() {
        var h = 0;
        var nodes = $$("#main_content_td .cms_layer");
        if (nodes.length==0) { return 800 }; /** cms_generated flag inaccurately set **/
        var last = nodes[nodes.length - 1];   
        //var lasth = parseInt(last.style.height);       
        last.style.height = "auto"; //in case it is misset by cms
        var lasth = parseInt(last.clientHeight); 
        var lastt = parseInt(last.style.top); 
        h = (lasth + lastt + 40); // add 40 slop
        return h;
    }
    
}
 