brand.account = brand.account || {};

brand.account.panel = {
    // summary: 
    //      Sets default states for "my account" link headers
    hasSetPanelLinks: false,
    accountConfig: null,

    init: function(accountConfig) { 
        //console.log("brand.account.panel.init, accountConfig = ",accountConfig);  
        if (!$("accountnav") || !accountConfig) { return; }
        var self = this;
        this.accountConfig = accountConfig;
        this.setState();
         
        this.setPanelLinks(); // in case the links are in panel_open
     
        //subscribe to "my mac" left nav onclick for non-account/checkout pages
        generic.events.observe("globalnav:getcontent/my_mac", function(event) {
            self.handlePanelRefresh({event: "show_panel"});
        });   
    },
    
    handlePanelRefresh: function(args) { 
        brand.account.panel.setPanelLinks();    
    }, 
    
    setPanelLinks: function() {
        //console.log("brand.account.setPanelLinks "+this.hasSetPanelLinks);
        if (this.hasSetPanelLinks) return;
    
        $$(".signout_link").each(function(s) { 
            this.hasSetPanelLinks = true;
            s.observe("click", brand.account.panel.signoutSubmit ); 
        });  
    }, 
    
    signoutSubmit: function() {
         ///console.log("brand.account.signoutSubmit"); 
         var onSuccess = function() {
             generic.events.fire({event:"cartCount:reset",msg:0});  
             location.replace('/account/signin.tmpl'); 
         }
         var onFailure = function() {
             console.log("brand.account.signoutSubmit: SIGNOUT failure");
         } 
         generic.jsonrpc.fetch({method:'rpc.form', params:[{'_SUBMIT':'signout'}], onSuccess:onSuccess, onFailure:onFailure});
    },
    
    setState: function() { 
        //console.log("brand.account.setState ");
        var pn = page_data.panel_nav["default"]; 
        var section, subsection, activeSection;
        var sections = this.accountConfig.sections
        if (pn) {
            try {
                section = pn.id;
                if (pn.item) subsection = pn.item.id;           
            }
            catch (err) { 
                console.log("setState: ",err);  
            }
        }

        if (section !== "account") return;
        
        // account landing id
        if (subsection === "index" || !pn.item) {
        	subsection = "account_index";
        }
         
        // find "active" subsection 
        for (i=0; i<sections.length; i++) {
            //console.log("test: "+sections[i] + " / " + section + " / " + subsection); 
            if (sections[i] === section || sections[i] === subsection) {
                activeSection = sections[i];  
                break;
            }
        }                
         
        // set section/subsection image states 
        var activeImg = $("hd_"+activeSection);
       
        // set section/subsection image states
        this.setImages(activeSection);
        
        // sign in image state:
        // page_data for sign in may masquerade as other pages so check content
        // to identify whether current page is signin page
        var signinContainerNode = $("signin-container");
        var signinLinkNode = $$("#signin_link img")[0];
        if (signinContainerNode && signinLinkNode) {
            var signinImg = new brand.img(signinLinkNode, ["sel"]);
            signinImg.changeSrc("sel");
        } else if (signinLinkNode) {
            new brand.rollover(signinLinkNode, null);
        };
    },
    
    setImages: function(activeSection) {
        // apply rollovers to each non-active section image
        // show sel state for active section image        
        var activeImg = "hd_"+activeSection;
        $$("#accountnav img.accountnav_hd").each( function(node) {
            if (activeImg !== node.id) {
                var r = new brand.rollover(node, null);
            } else {
                var aImg = new brand.img(node, ["sel"]);
                aImg.changeSrc("sel");
            }
        });
    }
};

/**
 * Email sign up for utility nav
 */
brand.account.emailSignup = {
    emailSignupJsonRpcPath: "email.signup",
     
    init: function(args) { 
        var self = this;
        var submitNode = args.submitNode;
        this.fieldNode = args.fieldNode;
        if (!submitNode || !this.fieldNode) return;
        submitNode.observe('click', self.validateEmail.bind(self));
        this.fieldNode.observe('keypress', self.validateEmail.bind(self));
    },
    
    validateEmail: function(event) { 
        if (!this.fieldNode) { return; } 
        
        if ( event.type === "keypress" && (event.keyCode != Event.KEY_RETURN) ) { 
            return false;           
        }
        var email = this.fieldNode;
        var popup; 
        var onSuccess = function() {
            brand.overlay.launch({
                foregroundNode: $("pop_email_valid"),
                displayInline: true,
                removeOnHide: false,
                displayDuration: 5000
            });
        }
        var onFailure = function() {
            brand.overlay.launch({
                foregroundNode: $("pop_email_invalid"),
                displayInline: true,
                removeOnHide: false,
                displayDuration: 5000
            });
        }
        var requestArgs = [{
            EMAIL_ADDRESS: email.value 
        }]; 
            
        if (brand.forms.isEmailAddress(email.value)) { 
            var d = generic.jsonrpc.fetch({method:this.emailSignupJsonRpcPath, params:requestArgs, onSuccess:onSuccess, onFailure:onFailure});
        } else { 
            onFailure();
        }
       
        Event.stop(event);

        return false;
    }
};

