// MPP functions
brand.mpp = brand.mpp || {};


// for mpp product modules
brand.mpp.item = {
   
    is_shaded: false,

    // input field (as add to bag btn) that holds sku path 
    // value of currently selected color sku
    skuField: "", 
    
    // page/content type
    type: "mpp",
    
    // this can be used when products which contain the same product
    // id are going to appear on the same page. Setting to true,
    // will append the path of the first sku instead of a product id to nodes
    altNodeId: false,
    
    // this is used in the case that products have the same id.
    // the type used if this is true is the time to ensure that
    // ids are unique for swatches
    altType: false,
    
    init: function(args) {
        //console.log("brand.mpp.item.init: "+args.type);
    
        var products = args.data;
        var cartConfirmMsg;  
        var self = this;
        this.altNodeId = (args.altNodeId ? args.altNodeId : false );
        this.altType = (args.altType ? args.altType : false );
        if (args.type) { this.type = args.type; }
        var video_prod = args.video_prod || false;
        if (!products) return;

        products.each(function(prod, idx) {
            var is_shaded = (prod.shaded == 1);
            var nodeId = prod.product_id;
            if (self.altNodeId) {
                nodeId = prod.skus[0].path;
            } else if (video_prod) {
                // use "video_PRODXXX" for nodeId
                nodeId = self.type +'_'+ nodeId;
            }
            prod.video_prod = video_prod;

            // proceed if node exists in html
            if ($(nodeId)) {
                
                // init cart confirm
                var created = false;
                if (!$("cart_confirm-" + nodeId)) {
                    created = true;
                    cartConfirmMsg = new brand.product.cartConfirm({
                        id: "cart_confirm-" + nodeId,
                        is_shaded: is_shaded,
                        prodName: prod.name,
                        nodeToReplace: $("cart_confirm_placeholder-" + nodeId)
                    });
                } 
                
                var msgProps;
                if (is_shaded && args.shadedMessageProps) {
                    msgProps = args.shadedMessageProps;                    
                } else if (args.messageProps) {
                    msgProps = args.messageProps;                    
                }

                // set up product photo rollover
                if (prod.image_small_rollover) {
                    self.initPhotoRollover(prod, nodeId);
                }
                    
                if (is_shaded && created) {
                    // set up swatches
                    var type = (self.altType ? (new Date()).getTime() : self.type);
                    self.initSwatch(prod, cartConfirmMsg, type, msgProps, nodeId);
                } else {
                    // non-shaded: 1st sku is default add-to-bag button value
                   self.initButton(prod, cartConfirmMsg, msgProps, nodeId);
                }
                
            }
        }); // end forEach products
       
    },
    
    initSwatch: function(prod, cartConfirmMsg, type, msgProps, nodeId) {
        //console.log("initSwatch: "+nodeId + " " + $("swatch_colors_placeholder-" + nodeId));
        if (!$("swatch_colors_placeholder-" + nodeId)) return; // page_data has incorrect/extra content
        
        var smooshImgLg = prod.skus[0].smoosh;
        var skuFieldId = "prod_sku_cart_add-" + nodeId;        
         
        // init quick buy popover
        var cartAddMsg = this.initCartPopover(prod, nodeId, {
            is_shaded: true,
            skuFieldId: skuFieldId,
            smooshPath: (smooshImgLg.replace ? smooshImgLg.replace(/168x168/g, "56x56") : "/images/common/blank.gif"),
            smooshId: "smoosh_img_cart_add-" + nodeId,
            cartConfirm: cartConfirmMsg             
        });
        
        // mixin alternate properties for text values, favorites remove, etc...
        if (msgProps) {
            cartAddMsg = Object.extend(cartAddMsg, msgProps);
        }
        
        // sku field is in CartAdd template, so now it's available
        var skuField = $(skuFieldId);
      
        // init swatch color squares
        var swatch = new brand.product.hexSwatchSet({
            product: prod,
            skuField: skuField,
            productType: type,
            
            // on swatch select:
            onSelectCallback: function(selectedChild) {
                // quick buy
                cartAddMsg.sku = selectedChild.sku;
                cartAddMsg.show();
                // tell cartConfirm which sku has been selected
                cartConfirmMsg.sku = selectedChild.sku;
            }
            
        }, $("swatch_colors_placeholder-" + nodeId));
    },
    
    initButton: function(prod, cartConfirmMsg, msgProps, nodeId) {  
        //console.log("brand.mpp.item.initButton");        
        var skuFieldId = "prod_sku-" + nodeId;
        var skuField = $(skuFieldId);
        
        // if shoppable, init add button
        if ( skuField ) {        
            cartConfirmMsg.sku = prod.skus[0];
            skuField.value = prod.skus[0].path;
            
            var cartAddBtn = brand.product.addButton({
                addButtonNode: skuField,
                callback: function(response) {
                    //console.log("brand.product.initButton cartAddBtn: cartConfirmMsg");  
                    cartConfirmMsg.show({ response: response });
                }
            });
    
            // mixin alternate properties for text values, favorites remove, etc...
            if (msgProps) {
                cartConfirmMsg.setDisplayProperties(msgProps.confirm);
            }
        }
        
        // handle remove button for favorites
        if (this.type === "favorites") {
            var removeNode = $("btn_favorites_remove-" + nodeId);
            if (removeNode) {
                var removeBtn = brand.product.addButton({
                    addButtonNode: removeNode,
                    itemType: "favorites",
                    skuField: skuField,
                    action: "delete",
                    callback: function(response) {
                        if (msgProps.callbackRemoveButton) {
                            msgProps.callbackRemoveButton({ removeNodeId: removeNode.id, skuFieldValue: removeNode.id });   
                        }
                    }
                }); 
            }
        }
    },

    initCartPopover: function(product, nodeId, args) {
       //console.log("brand.mpp.item.initCartPopover: "+this.type);
       
        var cartAddClass = brand.product.cartAdd;
        var popArgs = {
            id: "cart_add-" + nodeId,
            is_shaded: false,
            prodName: product.name,
            price: product.price,
            product_price_with_tax: product.price_with_tax,
            nodeToReplace: $("cart_add_placeholder-" + nodeId)
        }
        popArgs = Object.extend(popArgs, args);

        if (this.type === "favorites") {
            cartAddClass = brand.product.cartAddFromFavorites;
            popArgs.isRemovable = true;
        }
        var cartAddMsg = new cartAddClass(popArgs); 
        
        return cartAddMsg;
    },
    
    initPhotoRollover: function(product, containerId) {
        var containerNode = $(containerId);
        if (!containerNode) return;
        var imgNode = containerNode.select("a img.thumb")[0];
        var img = product.image_small;
        var altImg = product.image_small_rollover;       
        if (!img || !altImg || !imgNode) return;
        var preloaded = new Image();
        preloaded.src = altImg; 
       
        var over = function(e) {
            e.target.src = preloaded.src;
        }
    
        var out = function(e) {
            e.target.src = img;
        }
        imgNode.observe("mouseover", over);
        imgNode.observe("mouseout", out);   
    }
}


/**
 * favorites cart & swatch functionality
 */
brand.mpp.initFavorites = function() {
    //console.log("site.product.favoritesMpp");
    var data = page_data.catalog.mpp.products;
    var itemContainerNode = $("favorites-product-container");

    var removeFavorite = function(args) {
       //console.log("site.product.favorites.removeButton "+args.removeNodeId+"/"+args.skuFieldValue);  
       if (!args||!args.removeNodeId) return; 
       var catprodsku = args.removeNodeId.split("-")[1];
       if (!catprodsku) return; 
       
       var productNode = $(catprodsku); 
       var swatches = productNode.select(".swatchset-hex-container")[0];
       var removeNode;
       
       // if product is unshaded or has only 1 swatch, remove the product
       if (!swatches || swatches.select(".swatch_hex_container").length==1) { 
           removeNode = productNode;
       }
       // else just remove the swatch
       else if (args.skuFieldValue) {
           var skuId = args.skuFieldValue.split("SKU")[1]; 
           removeNode = $("swatch_SKU"+skuId);
       }
       
       //console.log("removeNode: "+removeNode.id);
       if (removeNode) {
           removeNode.remove();
           
           // check for empty list
           var items = itemContainerNode.select("div.rel_prod");
           if (items.length < 1) {
               var noItemNode = $("no-favorites-message");
               if (noItemNode) noItemNode.removeClassName("hidden");
               if (itemContainerNode) itemContainerNode.hide();
           }
       }
    };
    
    site.mpp.item.init({
        data: data,
        initButtons: true,
        type: "favorites",
        
        // configure confirm messages for cart or favorites remove
        messageProps: {
            //confirm: confirm_props,
            callbackRemoveButton: removeFavorite 
        },
        shadedMessageProps: {
            //callback: function(response) {
                //this.setConfirmProperties(confirm_props); // MERGE NOTE: not sure this was correct
            //},
            callbackRemoveButton: removeFavorite  
        }

    });  
};
