document.observe("dom:loaded", function() {
//Event.observe(window, "load", function() {
    
    try{
        setCMSHeightExceptions(); // set 'no-cms-height-calculation' on relevant cms pages
        setCMSHeight();
    }
    catch(err) { console.log("setCMSHeight error = "+err) };

    generic.init(); 
    generic.overlay.getRBKeys();
    generic.overlay.initLinks();
    generic.checkout.cart.getCartTotals();

    toolbox.init();

    initArtistList();
   
    // Add to cart overlays for "shoppables" links
    if (site && site.product && site.product.shoppableLinks) {
        site.product.shoppableLinks.init();
    }
    
    //Show/Hide triggers
    Effect.OpenUp = function(element) {
      element = $(element);
      new Effect.BlindDown(element, arguments[1] || {});
    }

    Effect.CloseDown = function(element) {
      element = $(element);
      new Effect.BlindUp(element, arguments[1] || {});
    }

    Effect.Combo = function(element) {
      element = $(element);
      if(element.style.display == 'none') { new Effect.OpenUp(element, arguments[1] || {}); }
      else { new Effect.CloseDown(element, arguments[1] || {}); }
    }

});

document.observe("cart:countsUpdated", function(){
    //console.log( "cart:countsUpdated event caught" );
    var cartCount = generic.checkout.cart.getTotalItems();
    var subtotal = generic.checkout.cart.getSubtotal();

    if ($('global_cart_count')) {
        $('global_cart_count').update(cartCount);
    }

    if ($('global_subtotal')) {
        $('global_subtotal').update('$' + subtotal.toFixed(2));
    }
});


// right column tool kit functions
var toolbox = {
    timeoutDuration: 1000,
    viewedCookieRegex: /(?:^|;\s+?)toolboxViewed\=(.*?)(?:$|;)/,

    // login nodes and behaviors
    // need a method for setting and resetting since html is replaced via toolboxSigninSuccess callback
    setNodes: function() {
        this.loginContainerNode = $('func-login');
        this.loginNode = $('login');
        var timerLogin;
        var timeoutDuration = this.timeoutDuration;
        var self = this;
        if (this.loginNode != undefined && this.loginContainerNode) { 
            this.loginNode.observe('mouseover', self.cancelFade.bind(self));
            this.loginContainerNode.observe('mouseover', self.cancelFade.bind(self));
            this.loginContainerNode.observe('mouseover', function(event) {
                if (timerLogin) {
                  clearTimeout(timerLogin);
                }
                [self.cartContainerNode, self.shopContainerNode].invoke('removeClassName', 'active');
                [self.cartNode, self.shopNode].invoke('hide');
                this.addClassName('active');
                self.loginNode.show();      
            });
            this.loginContainerNode.observe('mouseout', function(event) {
                var that = this;
                timerLogin = setTimeout(function() {
                  that.removeClassName('active');
                  self.loginNode.hide();
                }, timeoutDuration);
            });
        }
    },
    
    setViewed: function() {
      var expiresDate = new Date(),
          expiresElapsed = 1,
          value; // In days.

      expiresDate.setDate(expiresDate.getDate()+expiresElapsed);
      value = "1; expires="+expiresDate.toUTCString()+"; path=/";
      document.cookie = "toolboxViewed="+value;
    },

    isViewed: function() {
      var isFound = document.cookie.match(this.viewedCookieRegex);
      return isFound;
    },

    init: function() {
        var fadeEnabled = (location.pathname.indexOf("/macpro/member_voice") !== 0),
            timerCart,
            timerShop,
            effectFade,
            passwordTyped = false,
            self = this,
            timeoutDuration,
            // nodes
            loginSubmitNode = $('loginSubmit'),
            usernameNode = $('username'),
            passwordNode = $('toolbox_password'),
            cartContainerNode = this.cartContainerNode = $('func-cart'),
            cartNode = this.cartNode = $('cart'),
            shopContainerNode = this.shopContainerNode = $('func-shop'),
            shopNode = this.shopNode = $('shop');

        // If on member_voice, don't show and set mouse off threshold to 0.
        if (fadeEnabled == false) {
          this.timeoutDuration = 0;
        }
        // If they've already viewed, don't show them the fade-out, but keep
        // mouse-off threshold.
        else if (this.isViewed()) {
          fadeEnabled = false;
        }
        // If they're not on member_voice, and they haven't viewed it yet,
        // set viewed.
        else {
          this.setViewed();
        }
        timeoutDuration = this.timeoutDuration;

        this.setNodes();
        
        if (this.loginNode != undefined && this.loginContainerNode) { 
            this.loginContainerNode.removeClassName('active');
            if (fadeEnabled) {
                this.loginNode.show();
                this.effectFade = new Effect.Fade('login', { duration: 8, afterFinish: function() {
                    self.effectFade = false;
                }});
            }

            [cartNode, shopNode].invoke('hide');
            cartContainerNode.observe('mouseover', function(event) {
                if(timerCart) {
                  clearTimeout(timerCart);
                }
                [self.loginContainerNode, shopContainerNode].invoke('removeClassName', 'active');
                [self.loginNode, shopNode].invoke('hide');
                this.addClassName('active');
                cartNode.show();       
            });
            cartContainerNode.observe('mouseout', function(event) {
                var that = this;
                timerCart = setTimeout(function() {
                  that.removeClassName('active');
                  cartNode.hide();
                }, timeoutDuration);
            });
            shopContainerNode.observe('mouseover', function(event) {
                if(timerShop) {
                  clearTimeout(timerShop);
                }
                [self.loginContainerNode, cartContainerNode].invoke('removeClassName', 'active');
                [self.loginNode, cartNode].invoke('hide');
                this.addClassName('active');
                shopNode.show();       
            });
            shopContainerNode.observe('mouseout', function(event) {
                var that = this;
                timerShop = setTimeout(function() {
                  that.removeClassName('active');
                  shopNode.hide();
                }, timeoutDuration);
            });
            if (loginSubmitNode) loginSubmitNode.observe('click', toolboxSignin);
            if(usernameNode) {
                usernameNode.observe('keypress', function(event) {
                    if(event.keyCode == Event.KEY_RETURN) {
                        toolboxSignin(event);
                        Event.stop(event);
                    }
                });
                usernameNode.observe('focus',function(event) {
                    clearValueIf(this,'Email Address');
                });
            }
            if (passwordNode && !generic.env.isIE) {
                passwordNode.setAttribute('type', 'text');
                passwordNode.observe('focus', function(event) {
                  if(passwordTyped == false) {
                    passwordTyped = true;
                    clearValueIf(this,'password');
                    passwordNode.setAttribute('type', 'password');
                  }
                });
                passwordNode.observe('keypress', function(event) {
                    // Show password as text until the user types into the field.
    //                if(passwordTyped == false) {
    //                  this.value = "";
    //                  $('toolbox_password').setAttribute('type', 'password');
    //                  clearValueIf(this,'password');
    //                  passwordTyped = true;
    //                }
                    if(event.keyCode == Event.KEY_RETURN) {
                        toolboxSignin(event);
                        Event.stop(event);
                    }
                });       
            }
        }
    },
    
    cancelFade: function(event) {
    try {
        if (this.effectFade) {
            this.effectFade.cancel();
            this.loginNode.appear({duration: 0.3});
            this.effectFade = false;
        }
    } catch(e) {
        console.log("cancelFade e = ",e);
    }
}
};

// clear field on initial focus (ie, if current field value is same as default
var clearValueIf = function(field,clearValue) {
    if (field.value === clearValue) {
        field.value='';
    }
} 


// Artist list function - show/hide name
var initArtistList = function() {
    $$('ul.artist-list li div').each(Element.hide);
    $$('ul.artist-list li').each(function(el){
        el.onmouseover  = function(){ 
            this.addClassName('hover');  
            this.down(1).show();
        }
        el.onmouseout  = function(){  
            this.removeClassName('hover');
            this.down(1).hide(); 
        }
        el.onclick = function(){  
            self.location.href = this.down(1).down(1).href;
        }
    });
};
    

var setCMSHeight = function() {
    var h = 0;
    var contentNode = $("content_main");
    if (!contentNode) return;
    var footerNode = $("footer");
    var nodes = $$("#content_main .cms_layer");

    // not a cms page or don't treat it like one, so show footer and return
    if ($$("body")[0].hasClassName("no-cms-height-calculation") || contentNode.hasClassName("no-cms-height-calculation") || (nodes.length == 0)) {
        if (footerNode) footerNode.style.visibility = "visible";
        return;
    }

    var thisNodeBottom;
    var lastNode = nodes[0];
    var lastNodeBottom = 100; // arbitrary non-zero min

    // get top & height value to figure out which node the CMS intends as last node
    nodes.each(function(node, ix) { 
        thisNodeBottom = parseInt(node.style.top) + parseInt(node.style.height);
        if (lastNode && lastNodeBottom) {
            if (lastNodeBottom < thisNodeBottom) {
                lastNodeBottom = thisNodeBottom;
                lastNode = node; 
            }
        }
    });
    
    // check if height was misset by cms
    var specifiedHeight = parseInt(lastNode.style.height); // get value before setting auto
    lastNode.style.height = "auto";
    var actualHeight = parseInt(lastNode.clientHeight); 
    if (actualHeight > specifiedHeight) {
        lastNodeBottom = parseInt(lastNode.style.top) + actualHeight;
    }
        
    // use top+height value of last node to set height for whole container
    contentNode.style.height = (lastNodeBottom + "px");
    if (footerNode) footerNode.style.visibility = "visible";
};


var toolboxSigninSuccess = function(result) {
    var data = result.getData();
    var url = document.URL;
    if(url.match("/macpro/members/")) {
        window.location = "/macpro/members/index.tmpl";
    } else {
        var loginNode = $('func-login');
        generic.templatefactory.get({path: '/macpro/templates/toolbox_signed_in.tmpl'}).evaluateCallback({
            object: {
                name: data.userinfo.first_name
            },
            callback: function(html) {
                loginNode.replace(html);
                toolbox.setNodes();
            }
        });
    }
}

var toolboxSigninFailure = function(result) {
    var errorObjectsArray = result.getMessages();
    var errListNode = $('toolboxSignin').select("ul.login-alert")[0];
    generic.showErrors(errorObjectsArray, errListNode, $('toolboxSignin'));
    errListNode.removeClassName('hidden');
    toolboxPasswordHint();
}

var toolboxSignin = function (event) {
    var username = $('username').value;
    var password = $('toolbox_password').value;
    generic.jsonrpc.fetch({
       params: [{
          "EMAIL_ADDRESS": username,
          "PASSWORD": password,
          "_SUBMIT": "signin"
       }],
       onSuccess: toolboxSigninSuccess,
       onFailure: toolboxSigninFailure
    });
}

var toolboxPasswordHint = function() {
    generic.jsonrpc.fetch({
        method: 'user.passwdHint',
        params: [{
            "EMAIL_ADDRESS": $('username').value
        }],
        onSuccess : toolboxPasswordHintSuccess,
        onFailure : toolboxPasswordHintFailure
    });
}

var toolboxPasswordHintSuccess = function(result) {
    var responseData = result.getValue();
    if (responseData) {
        generic.templatefactory.get({path: '/templates/password-hint.tmpl'}).evaluateCallback({
            object: {
                hint: responseData
            },
            callback: function(html) {
                $('toolbox-password-hint').update(html);
                $('pwd-reset').observe('click', function(evt) {
                    evt.preventDefault();
                    toolboxRequestPassword();
                });
            }
        });
    } else {
        // user not found
        $('toolbox-password-hint').innerHTML = '';
        generic.showErrors([{
            text: brx.account.forgotPasswordEmailNotFound
        }], $('toolbox-password-hint'));
        generic.showErrorState($('username'));
    }
}

var toolboxPasswordHintFailure = function(result) {
    var messages = result.getMessages();
    var errorKey = messages[0].key;
    if (errorKey === 'user.missing_password_hint') {
        toolboxRequestPassword();
    } else if(errorKey == 'user.password_reset'){
        generic.templatefactory.get({path: '/macpro/templates/password-already-reset.tmpl'}).evaluateCallback({
            callback: function(html) {
                $('toolbox-password-hint').update(html);
                $('pwd-reset').observe('click', function(evt) {
                    evt.preventDefault();
                    toolboxRequestPassword();
                });
            }
        });
    } else {
        generic.showErrors(errorObjectsArray, errListNode);
        generic.showErrorState(brx.account.signinEmailInput);
    }
};

var toolboxRequestPassword = function() {
    var email = $('username').value;
    var hiddenEmailNode = $('toolbox-reset-form-hidden-email');
    hiddenEmailNode.writeAttribute('value', email);
    $('toolbox-reset-hidden-form').submit();
}

function openFullWindow(url, name, w, h) {
    var w = window.open(url, name, "menubar=1, toolbar=1, resizable=1, scrollbars=1, width=" + w + ", height=" + h);
};

// Set 'no-cms-height-calculation' page attribute for CMS pages where
// it's not possible for the html to be edited via cms/template
var setCMSHeightExceptions = function() {
    // membership benefits page
    var benefitsContainerNode = $("benefits_container");
    if (benefitsContainerNode && benefitsContainerNode.select(".foldouts")[0]) {
        $$("body")[0].addClassName("no-cms-height-calculation");
    }
};

