
brand.product.productOverlay = Class.create(Widget, { 

    isOpen: false,
    position: {},
    lockToNode: null,
    templateString: "",
    baseClass: "",
    widgetsInTemplate: false,
    itemCount: 0,

    initialize: function($super, arguments) {
        //console.log("brand.product.productOverlay.init: "+arguments.id); 
        $super(arguments); 
    },
    
    open: function(args) {
        if (this.isOpen) { return; }
        var self = this;

        brand.overlay.launch({
            foregroundNode: this.domNode,
            displayInline: true,
            removeOnHide: false,
            onClose: function() {
                self.onClose();
            }
        });

        if (this.lockToNode) {
            // calculate height to get top offset 
            var t, h = 0;
            h = this.domNode.getHeight();
            t = (h * -1);
            this.position = {offsetTop: t};
            // position in relation to specified node
            var offsetTop = (this.position.offsetTop ? this.position.offsetTop : 0);
            var offsetLeft = (this.position.offsetLeft ? this.position.offsetLeft : 0);
            this.domNode.clonePosition(this.lockToNode, { setWidth: false, setHeight: false, offsetLeft: offsetLeft, offsetTop: offsetTop });
        } else {
            if (this.position.top) this.domNode.style.top = this.position.top+"px";
            if (this.position.left) this.domNode.style.left = this.position.left+"px";
        }       
        this.isOpen = true;
    },
    
    show: function(args) {
        //console.log("brand.product.productOverlay.show ",args);  
        //if (this.isOpen) { return; }
        if (this.isOpen) {
            this.close();
        }
        var response = (args && args.response ? args.response : null);
        this._updateDisplay(response);
        this.open(args);
    },
    
    getErrors: function(response) {
        var errors;
        var key;
        if (response && response.getMessages()) {
            errors = {};
            var messages = response.getMessages();
            for (var i = 0; i < messages.length; i++) {
                if (messages[i].text) {
                    key = messages[i].key;
                    errors[key] = messages[i];
                }
            }
        }
        return errors;
    },
    
    close: function() {
        //node.style.left = "-5000px";
        //this.domNode.style.display = "none";
        //this.isOpen = false;
        brand.overlay.hide();
        this.onClose();
    },
    
    // NEEDED?
    onClose: function() { 
        this.isOpen = false;
        //if (this.closeCallback) this.closeCallback();
    }
    
});


brand.product.cartAdd = Class.create( brand.product.productOverlay,
{
    //templatePath: "/js/brand/product/templates/cartAdd.html",
    templatePath: "jsTemplates.product.cartAdd",
    
    is_shaded: false,
    _enabled: true,
    
    // sku: Object
    // sku object from page_data
    sku: null,
    
    // template vars
    prodName: "",
    smooshPath: "/images/common/blank.gif",
    hex: "",
    price: "",
    smooshImgStore: {},
    
    initialize: function($super, arguments) {
        //console.log("brand.product.cartAdd init, args = ",arguments);
        this.templateString = false; //overrides productOverlay  
        $super(arguments);
    },
    
    postCreate: function() {
        //console.log("brand.product.cartAdd postCreate "+this.id);
        if (this.smooshId) this.smooshNode = $(this.smooshId);
        var button = (this.skuField ? this.skuField : $(this.skuFieldId));
        var self = this;
        if (button) {
            // add to cart button
            var prodBtn = brand.product.addButton({
                addButtonNode: button,
                callback: function(response) {
                    if (self.callback) {
                        self.callback(response);
                    }
                    self.close();
                    self.cartConfirm.show({ response: response });
                }
            });
        }
    },
    
    setConfirmProperties: function(args) {
        // used to set display properties of confirm on CartAdd popover callback (ex: for favorites vs. checkout message)
        this.cartConfirm.setDisplayProperties(args);
    },
    
    show: function($super, arguments) {
        generic.events.fire({event:"productmessage:cartadd/show", msg:this.sku});
        //console.log("brand.product.cartAdd.show: ", this.prodName); 
        $super(arguments); 
    },
    
    _updateDisplay: function() {
        var sku = this.sku;
        //console.log("CartAdd._updateDisplay: sku = "+this.sku);
        if ( this.smooshNode ) {
            this.smooshNode.style.backgroundColor = sku.color[0];
            this.smooshNode.src = this.smooshPath; // sets to blank to reset before loading next
            var smooshImg = sku.smoosh;
            if (typeof smooshImg === "object") {
                smooshImg = sku.smoosh[0];
            }
            var imgStore = brand.loadImage({
                node: this.smooshNode,
                imagePath: smooshImg.replace(/168x168/g, "56x56"),
                imageStore: this.smooshImgStore,
                imgId: sku.sku_id
            });
            this.smooshImgStore = imgStore;
        }
        this.swatchTitleNode.innerHTML = sku.shade_name;
        
        // set sku value
        var button = (this.skuField ? this.skuField : $(this.skuFieldId));
        button.value = sku.path;

        // inventory status
        site.product.inventoryStatus({
            shoppable: sku.shoppable,
            message: sku.inventory_status_message,
            messageNode: this.inventoryStatusNode,
            buttonNode: this.addToBagNode,
            containerNode: this.domNode
        });
        
        // "finish" name
        this.finishNameNode.innerHTML = (sku.finish ? "("+sku.finish+")" : "");
    }

});


brand.product.cartAddFromFavorites = Class.create( brand.product.cartAdd, {

    // isRemovable: Boolean
    // Use/show remove button
    isRemovable: true,
    
    postCreate: function($super, arguments) {    
        $super(arguments); 
        //console.log("brand.product.cartAddFromFavorites.postCreate");
           
        // set up remove button
        if (this.isRemovable) {     
            var self = this;      
            var removeBtn = brand.product.addButton({
                addButtonNode: self.removeNode,
                skuField: $(self.skuFieldId),
                itemType: "favorites",
                action: "delete",
                callback: function(response) {
                    if (self.callbackRemoveButton) {
                        self.callbackRemoveButton({ removeNodeId:self.removeNode.id, skuFieldValue:$(self.skuFieldId).value });
                    }
                    self.close();
                    //self.cartConfirm.show({ response: response });
                }
            });        
            this.removeNode.removeClassName("hidden");
        }
    }

});


brand.product.cartConfirm = Class.create( brand.product.productOverlay,
{
    //templatePath: "/js/brand/product/templates/cartConfirm.html",
    templatePath: "jsTemplates.product.cartConfirm",
     
    is_shaded: false,
    prodName: "",
    useLeftAlign: false,
    
    // sku: Object
    // sku object from page_data
    sku: null,
    
    // type: String
    // item type for count in cookie (optional) ex: "favorites"
    type: "cart",
    
    initialize: function($super, arguments) {
        // default text
        this.text_addedMessageCheckout = site.product.rb.added_to_shopping_bag;
        this.text_addedMessageFavorites = site.product.rb.added_to_favourites;
        this.text_add_to_bag = site.product.rb.add_to_bag;
        this.text_thank_you = site.product.rb.thank_you;
        this.text_favorites = site.product.rb.favorites;
        this.text_checkout = site.product.rb.checkout;
        this.text_sorry = site.product.rb.sorry;
        this.text_continue_shopping = site.product.rb.continue_shopping;
    
        $super(arguments);
    },
  
    postCreate: function() {
        //this.cartHandler = generic.checkout.cart;
        this.shadeNameDash = this.shadeNameNode.innerHTML;
    },
    
    show: function($super, arguments) {
        var confirmNode = this.domNode;
        if (this.useLeftAlign) {
            confirmNode.addClassName("pop-confirm-align-left");
            confirmNode.removeClassName("pop-confirm-align-default");
        } else {
            confirmNode.addClassName("pop-confirm-align-default");
            confirmNode.removeClassName("pop-confirm-align-left");
        } 
        $super(arguments); 
    },
    
    setDisplayProperties: function(args) {
       // used to set display properties of confirm (ex: for favorites vs. checkout message) 
       brand.updateProperties.apply(this, [args]);
    },
    
    _updateDisplay: function(response) {
        //console.log("brand.product.cartConfirm._updateDisplay "+response.getError()); 
        
        // check for error
        var hasErrors = response ? response.getError() : false;
        var hasFssMessage = false;
                 
        // show error
        if (hasErrors) {  
            this.errorMessageNode.innerHTML = response.getMessages() ? response.getMessages()[0].text : ""; 
            this.cartConfirmErrorNode.removeClassName("hidden");
            this.cartConfirmDisplayNode.addClassName("hidden");  
        } 
        
        // show confirm message 
        else {
            this.cartConfirmDisplayNode.removeClassName("hidden");
            this.cartConfirmErrorNode.addClassName("hidden");  
            
            try { 
                //this.itemCount = this.cartHandler.getItemCount(this.type);
                //this.itemCount = this.cartHandler.getTotalItems();   
                //this.itemCountNode.innerHTML = this.itemCount.toString();
                this.prodNameNode.innerHTML = this.prodName;
                if (this.is_shaded && this.sku.shade_name) {
                    this.shadeNameNode.innerHTML = this.shadeNameDash + this.sku.shade_name;
                } else {
                    this.shadeNameNode.innerHTML = "";
                }
                
                if (this.type === "favorites") {
                    this.domNode.addClassName("cart-confirm-overlay-container-favorites");
                    this.addedMessageNode.innerHTML = this.text_addedMessageFavorites; 
                } else {
                    this.domNode.removeClassName("cart-confirm-overlay-container-favorites");
                    this.addedMessageNode.innerHTML = this.text_addedMessageCheckout;
                    var data = response.getData();
                    var fssMessage = "";
                    var fssMessageNode = this.cartConfirmDisplayNode.select(".cart-confirm-fss-message")[0];
                    if (fssMessageNode && data && data.trans_data) {
                        fssMessage = data.trans_data.free_shipping_message;
                        if (fssMessage && fssMessage.length > 1 && fssMessage != null) {
                            hasFssMessage = true;
                            fssMessageNode.innerHTML = fssMessage;
                            fssMessageNode.style.display = "block";
                        }
                    }
                    if (!hasFssMessage) fssMessageNode.hide();
                }
            } catch(e) {
                console.log("brand.product.cartConfirm._updateDisplay e: "+e.description);
            }
        }
    }

});


brand.product.swatchCard = Class.create( brand.product.cartAdd,
{

    templatePath: "jsTemplates.product.swatchCard",
    //templatePath: "/js/brand/product/templates/swatchCard.html",
    
    skuPath: "",
    closeOnClickOutside: null,
    isMultiShadedSingleSku: false, // 3+ multi-shaded prods have only 1 sku per prod
    swatchIdx: null, // idx to id single sku shades
    
    initialize: function($super, arguments) {
        this.setProperties(arguments);
        this.price = this.price;
        var sku = this.skus[0];
        this.text_limited = site.product.rb.limited;
        this.text_macpro = site.product.rb.macpro;
    
        $super(arguments, true);
        
        if (this.isMultiShadedSingleSku) {
            this.domNode.addClassName("swatchcard-container-singlesku");
        }
    },

    postCreate: function($super) {
        // set nodes specfic to this class
        var id = this.id;
        this.skuField = $("prod-sku-"+id);
        this.shadeNameNode = $("shade-name-"+id);
        this.smooshNode = $("smoosh-img-"+id);
        this.descriptionNode = $("shade-description-"+id);
        this.finishNode = $("shade-finish-"+id);
        this.finishDescriptionNode = $("shade-finish-description-"+id);
        this.limitedNode = $("limited-flag");    
        this.proNode = $("pro-flag");
        this.inventoryStatusNode = $("inventory-status-"+id);
        $super();
        
        // if popover should close when user clicks outside of it
        if (this.closeOnClickOutside && this.closeOnClickOutside.enable) {
            var self = this; 
            $(document.body).observe("click", function(e) {        
                if (!self.isOpen) return;
                self.close();
            });
    
            var stopPropagation = function(e) {
                e.stopPropagation();
            }
    
            this.domNode.observe("click", stopPropagation);
    
            var nodesToExclude = this.closeOnClickOutside.nodesToExclude;
            if (nodesToExclude) {
                nodesToExclude.each(function(node) {
                    node.observe("click", stopPropagation);
                });
            }
        }
    },

    onSwatchSelect: function(args) {
        this.sku = args.sku;
        var swatchNode = args.swatchNode;
        this.skuField.value = this.sku.path;
        var useLeftAlign = false;
        this.swatchIdx = (args.swatchIdx >= 0 ? args.swatchIdx : null);
        
        // get child of swatchNode: swatchNode doesn't return proper values
        // from clonePosition (because of float?)
        this.lockToNode = swatchNode.select(".swatch-thumb")[0];
        
        // get column position of swatch thumb
        var getRightColumn = function() {
            var classes = $w(swatchNode.className)
            var classCount = classes.length;
            if (classCount.length < 1) return false;
            var hasClass = false;
            
            var searchIn = ["thumb-col5", "thumb-col6", "thumb-col7"];
            for (var i=0; i<classCount; i++) {
                if (searchIn.indexOf(classes[i]) != -1) {
                    hasClass = true;
                    break;
                }               
            }
            
            return hasClass;
        }
        useLeftAlign = getRightColumn();
        
        // add class by column position
        var node = this.domNode;
        if (useLeftAlign) {
            node.addClassName("pop-card-align-left");
            node.removeClassName("pop-card-align-default");
        } else {
            node.addClassName("pop-card-align-default");
            node.removeClassName("pop-card-align-left");
        }
        // pass these settings to the cart confirm obj
        var cartConfirm = this.cartConfirm;
        cartConfirm.setDisplayProperties({ type: "cart", lockToNode: this.lockToNode, useLeftAlign: useLeftAlign });
        
        // close other popovers if open
        if (cartConfirm.isOpen) {
            cartConfirm.close();
        }      
        this.show();
    },
    
    _updateDisplay: function() {
        //console.log("swatchCard._updateDisplay: sku = "+this.sku);
        var sku = this.sku;
        var swatchIdx = this.swatchIdx;
        var smoosh, imgId, shadeName, description;
        
        // data per single sku item array (multi-shaded)
        if (this.isMultiShadedSingleSku && (swatchIdx >= 0)) {
            smoosh = sku.smoosh[swatchIdx];
            imgId = swatchIdx;
            shadeName = sku.shade_name[swatchIdx];
            description = sku.shade_description[swatchIdx];
            
        } else {
        // data per individual sku
            smoosh = sku.smoosh;
            imgId = sku.sku_id;
            shadeName = sku.shade_name;
            description = sku.shade_description;
            
            // content that displays for solo/duo skus
            // mac pro & limited flags
            if (this.limitedNode) {
                if (sku.limited_life == 1) {
                    this.limitedNode.show();
                } else {
                    this.limitedNode.hide();
                }
            }
            if (this.proNode) {
                if (sku.pro_product == 1) {
                    this.proNode.show();
                } else {
                    this.proNode.hide();
                }
            }
            
            // update inventory status
            site.product.inventoryStatus({
                shoppable: sku.shoppable,
                message: sku.inventory_status_message,
                messageNode: this.inventoryStatusNode,
                containerNode: this.domNode
            });         
        }
        
        this.smooshNode.src = this.smooshPath; // sets to blank to reset before loading next
        var imgStore = brand.loadImage({
            node: this.smooshNode,
            imagePath: smoosh,
            imageStore: this.smooshImgStore,
            imgId: imgId
        });
        this.smooshImgStore = imgStore;
        
        this.shadeNameNode.update(shadeName);
        this.finishNode.innerHTML = (sku.finish && sku.finish_description ? "("+sku.finish+")" : "");
        this.finishDescriptionNode.update(sku.finish_description);
        this.descriptionNode.update(description);
    }
    
});
