 
brand.product = {};
brand.product.productDisplay = { //JSTest Steph, is this only for mpp?  
   
    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.product.productDisplay.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 = (self.altNodeId ? prod.skus[0].path : prod.product_id); 
            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.sub_line, // TODO: JP-specific configuration
                        nodeToReplace: $("cart_confirm_placeholder-" + nodeId)
                    }); 
                } 
                
                var msgProps;
                if (is_shaded && args.shadedMessageProps) {
                    msgProps = args.shadedMessageProps;                    
                } else if (args.messageProps) {
                    msgProps = args.messageProps;                    
                }
                      
                if (is_shaded && created) {
                    // set up swatches
                    var type = (self.altType ? (new Date()).getTime() : self.type);
                    self.initSwatch(prod, cartConfirmMsg, type, msgProps);
                } else {
                    // non-shaded: 1st sku is default add-to-bag button value
                   self.initButton(prod, cartConfirmMsg, msgProps);
                }
                
            }
        }); // end forEach products
       
    },
    
    initSwatch: function(prod, cartConfirmMsg, type, msgProps) { 
        var nodeId = (this.altNodeId ? prod.skus[0].path : prod.product_id);
        //console.log("initSwatch: "+nodeId + " " + $("swatch_colors_placeholder-" + nodeId));
        if (!$("swatch_colors_placeholder-" + nodeId)) return; //page_data has extra wrongful 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(/168x168/g, "56x56"),
            smooshId: "smooshImg_cart_add-" + nodeId,
            cartConfirm: cartConfirmMsg             
        });
        
        // mixin alternate properties for text values, favorites remove, etc...
        if (msgProps) {
            cartAddMsg = generic.mixin(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.SwatchContainer({
            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) {  
        //console.log("brand.product.productDisplay.initButton"); 
        var nodeId = (this.altNodeId ? prod.skus[0].path : prod.product_id);        
        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;
            
            // note: shouldn't be needed for non-shaded prod:
            /*
            var cartAddMsg = this.initCartPopover(prod, nodeId, {
                skuFieldId: skuFieldId,
                cartConfirm: cartConfirmMsg             
            }); 
            */
            var cartAddBtn = new brand.product.productButton({
                node: skuField,
                callback: function(resp) {
                    console.log("brand.product.initButton cartAddBtn: cartConfirmMsg");  
                    cartConfirmMsg.show(resp);
                }
            });
        
    
            // 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 = new brand.product.productButton({
                    node: removeNode,
                    valueField: removeNode, 
                    cartType: "favorites",
                cartAction: "remove",
                method: "alterCollection",
                action: "delete", 
                    callback: function(resp) {
                        if (msgProps.callbackRemoveButton) {
                            msgProps.callbackRemoveButton({removeNodeId:removeNode.id,skuFieldValue:removeNode.id});   
                        }
                    }
                }); 
            }
        }
    },

    initCartPopover: function(product, nodeId, args) {
       //console.log("brand.product.productDisplay.initCartPopover: "+this.type);
       
        var cartAddClass = brand.product.CartAdd;
        var popArgs = {
            id: "cart_add-" + nodeId,
            is_shaded: false,
            prodName: product.sub_line,
            price: product.price,
            product_price_with_tax: product.price_with_tax,
            nodeToReplace: $("cart_add_placeholder-" + nodeId)
        }
        popArgs = generic.mixin(popArgs, args);
        
        if (this.type === "favorites") {
            cartAddClass = brand.product.CartAddFromFavorites;
            popArgs.isRemovable = true;
        }
        var cartAddMsg = new cartAddClass(popArgs); 
        
        return cartAddMsg;
    }
};


// SPP functions
// swatch display for color grid & name list
brand.product.initSwatchSet = function(args) {
    //console.log("brand.product.initSwatchSet "+args.node.id); 
    if (!args.node) { return; }
    var swatchContainer;
    var swatchArgs = args.swatchArgs;
    swatchArgs.parentId = args.node; //JSTEST trial
    var hexField = args.pageArgs.hexField; 
    var product = swatchArgs.product;
    var skuField = swatchArgs.skuField;
    var filters = {};
    var cartConfirm = args.pageArgs.cartConfirm;
    swatchArgs.isSingleSku = args.pageArgs.isSingleSku;
    var hasPhotosBySku = false;

                         
    if (swatchArgs.isSingleSku) {
        //console.log("brand.product.initSwatchSet: isSingleSku"); 
        // for now the only prods that display multi-colored sets of swatches also only display 1 sku per page
        swatchContainer = new brand.product.SwatchContainer(swatchArgs, args.node);
        skuField.value = product.skus[0].path;
        args.pageArgs.favField.value = skuField.value;
        cartConfirm.sku = product.skus[0];               
    } else {
        //console.log("brand.product.initSwatchSet: !isSingleSku"); 
        
        // store filters by finish
        if (product.product_multicolor_type !== "duo") {
            filters = brand.product.swatchMenus.getFilters(product, "color");
            swatchArgs.filters = filters;
        }

        // set up main image swapping by sku
        if (product.skus[0].sku_special_packaging_image) {
            hasPhotosBySku = brand.product.photoBySku.init(product.skus);
        }
        
        // on swatch select
        swatchArgs.onSelectCallback = function(selectedChild) {
              //console.log("swatchArgs.onSelectCallBack ");
            /** JSTEST - new 
            swatchContainer is not recognied
            if (selectedChild = swatchContainer.selectedChild) {
        return;
     }**/
     
            // tell CartConfirm which sku has been selected
            cartConfirm.sku = selectedChild.sku;
             
            // tell color play button which hex has been selected
            if (hexField) {
                hexField.value = selectedChild.hex;
            }
            // tell name menu which swatch has been selected
            brand.product.swatchMenus.updateNameMenu(selectedChild.idx);  
            
            // swap main Image
            if (hasPhotosBySku) {
                brand.product.photoBySku.onSwatchSelect(selectedChild.idx);
            }
        }
        
        //console.log("brand.product.initSwatchSet calling SC: " +swatchArgs+" / "+args.node); 
        swatchContainer = new brand.product.SwatchContainer(swatchArgs, args.node);
    }
                    
    return swatchContainer;
    
}


// sorting/filtering drop-downs
brand.product.swatchMenus = {

    _currentFilter: "all",
    
    init: function(args) {
        //console.log("brand.product.swatchMenus");  
       
        var swatchContainer = args.swatchContainer;
        this.filterMenu = this._initFiltering(swatchContainer);         
       // console.log("brand.product.swatchMenus: filterMenus"+this.filterMenu);
        this.swatchNameMenu = this._initNameMenu("menu_swatches_by_name", swatchContainer, args.product);
        
        // load with first sku selected
        var firstSel = (swatchContainer.selectedChildWidget ? swatchContainer.selectedChildWidget.idx : null);
        if (firstSel) { 
            this.updateNameMenu(firstSel);  
            if (this.filterMenu) this.filterMenu.selectedIndex = 0;
            swatchContainer.processData("filter", "all"); //JSTEST: hack
        }
    },

    _initNameMenu: function(menuid, swatchContainer, product) { 
        // set up callback for sorting menu
        var menu = $(menuid);
        if (!menu) { return; }
        
        var self = this;        
        var options = this._getNames(product); 
            
        options.each(function(opt, idx) {
            menu.addOption({ value:opt.num, label:opt.label });
        });
        
        menu.onChangeCallback(function() {  
            var value = this.getValue();  
            console.log("brand.product.swatchMenus._initNameMenu onChangeCallback "+value);
            if (typeof(value) === "undefined") { return; }
            var swatch = $("swatch_" + product.skus[value].sku_id).widget;
            if (!swatch || swatchContainer.selectedChildWidget == swatch) { return; }
           
            swatchContainer.setSwatch(swatch);
            
            //if swatch seleted is not in current filter, set filter back to "all"
            var filter = self._currentFilter;
            if (filter !== "all") { 
                var hasSwatchInFilter = self.filters[filter].any(function(swatchIdx) { 
                    return (swatchIdx === value);
                }); 
                if (!hasSwatchInFilter) {
                    self.filterMenu.selectedIndex = 0;
                    swatchContainer.processData("filter", "all");//JSTEST: event not being thrown, why?
                }
            }
        })
        
        return menu;
    },
        
    _initFiltering: function(swatchContainer) {
        //console.log("_initFiltering: "+$('menu_filter_by'));
        // populate filtering menu 
        var menu = $('menu_filter_by');
        if (!menu) { return; }
        
        var self = this;
        var filterLabels = this.filterLabels;
        var count = 0;
        
        for (var filter in this.filters) {
            menu.addOption({ value:filter, label:filterLabels[filter] });
            count++;
        }
        
        // hide menu if no prod has no finishes
        if (count == 0) {
            menu.domNode.style.display = "none";
            return;
        }
        
        // set up callback
        menu.onChangeCallback(function() {
            //console.log("brand.product.swatchMenus._initFiltering onChangeCallback");
            var value = this.getValue();     
            self._currentFilter = value;
            swatchContainer.processData("filter", value);
        })
        
        return menu;
    },

    updateNameMenu: function(idx) {
        //console.log("brand.product.updateNameMenu "+idx); 
        if (this.swatchNameMenu) {
            this.swatchNameMenu.setValue(idx);
        }
    },
    
    _getNames: function(product) {
        var names = [];
        var sortedSkus = product.sorters.names;
        for (var i=0; i<product.skus.length; i++) {
            var name = {};
            var num = sortedSkus[i];
            name.num = num.toString();
            name.label = product.skus[num].shade_name;
            names[i] = name;
        }
        return names;             
    },
 
     getFilters: function(product, sortType) {
        var filters = {};
        var filterLabels = {};
        var sortedSkus = product.sorters[sortType];
        for (var i=0; i<product.skus.length; i++) { 
            var num = sortedSkus[i];
            var finish = label = product.skus[num].finish;
            if (!finish) { continue; }
            finish = finish.replace(/ /, "");
            finish = finish.toLowerCase();
            filterLabels[finish] = label;
            if (!filters[finish]) {
                filters[finish] = [num.toString()];
            } else {
                filters[finish].push(num.toString());
            }
            this.filters = filters;
            this.filterLabels = filterLabels;
        }
        return filters;             
    }
    
}

// color play link
brand.product.colorPlayButton = {        
    url: "/flash/color_play/index.tmpl",
    param: "?colorplaysample=",
    
    init: function(field) {  
        if (!field) {
            return false;
        }
        this.field = field; 
        field.observe("click", this._onClick.bind(this));
    },
    
    _onClick: function(e) {
        var hex;
        hex = this.field.value.split("#")[1];
        hex = "0x" + hex;
        location.href = this.url + this.param + hex;
    }
}

// main image rollover
brand.product.photoRollover = {
    hasRollover: true,
    init: function(img, altImg) {
        var node = $("prod_image_rollover");
        if (!img || !altImg || !node) {
            this.hasRollover = false;
            return false;
        }
        
        this.img = img;
        this.altImg = altImg;
        var pl = new Image();
        pl.src = altImg; 
        var self = this;
        node.observe("mouseover", self.over.bind(self));
        node.observe("mouseout", self.out.bind(self));
    },
    
    over: function(e) {
        e.target.src = this.altImg;
    },
    
    out: function(e) {
        e.target.src = this.img;
    }
}

// main image swap on shade selection
brand.product.photoBySku = {
    init: function(skus) {
        this.node = $("prod_image_rollover");
        if (!this.node) {
            return false;
        }
        var imgPaths = [];
        var pl = new Image();
        
        skus.each(function(sku, idx) {
            var img = sku.sku_special_packaging_image;
            if (img) {
                imgPaths[idx] = img;
                pl.src = sku.sku_special_packaging_image;
            }
        });
        
        this.imgPaths = imgPaths;
        
        return true;
    },
    
    onSwatchSelect: function(swatchIdx) {
        if (!swatchIdx) { return; }
        var img = this.imgPaths[swatchIdx];
        if (!img) { return; }
        this.node.src = img;
        
        // if photo rollover, set off state to currently selected "special" image
        var pr = photoRollover;
        if (pr.hasRollover) {
            pr.img = img;
        }
    } 
}

brand.product.sppInventoryStatus = function(args) {
       var suppressAddToBag = brand.product.inventoryStatus.suppressAddToBag.any(function(n) { return n==args.sku.inventory_status; });
       console.log("brand.product.sppInventoryStatus suppressAddToBag: "+suppressAddToBag);
             var inv_stat_msg = args.sku.inventory_status_message;
             var prodbtn = $("add_to_bag");
             var prodbtn_top = $("add_to_bag_top_container");
             var statusnode = (args.shaded) ? $("inventory_status") : $("inventory_btn_message"); 
      
             if (suppressAddToBag) { 
                 prodbtn.style.display = "none";
                 if (prodbtn_top) prodbtn_top.style.visibility = "hidden"; 
                 statusnode.innerHTML = inv_stat_msg; 
             } else {
                 prodbtn.style.display = ""; 
                 if (prodbtn_top) prodbtn_top.style.visibility = ""; 
                 statusnode.innerHTML = (args.shaded && inv_stat_msg) ? inv_stat_msg : ""; 
             } 
             statusnode.style.display = (inv_stat_msg.length > 1) ? "block" : "none";
         
}

/* Shoppables on content pages (i.e. news, faves) */
brand.product.productPopovers = {
    cartConfirmProps: {},
    
    init: function(args) {
        console.log("brand.product.productPopovers.init");
        var self = this;
        
        var is_shaded = false; 
        var containerId = (args.containerId ? args.containerId : "main_content");
        this.cartConfirmProps = (args.cartConfirmProps ? args.cartConfirmProps : this.cartConfirmProps);
        
        if (args.positionPopup) {
            this.positionPopup = args.positionPopup;
        }
         
        args.products.each(function( product ) {
            var sku = product.skus[0];
            var hasLinkNodes = false; 
	  
            // check for link nodes as single instances (element  id) or multiple instances (css class)
            var linkNodes = [];
            linkNodes = $(containerId).select("."+sku.path);
            if (linkNodes[0]) {
                hasLinkNodes = true;
            } else {
                linkNodes[0] = $(sku.path);
                if (linkNodes[0]) {
                    hasLinkNodes = true;
                }
            }
            
            console.log("brand.product.productPopovers.init "+sku + " " + hasLinkNodes);
                        
            if (hasLinkNodes) {
                self.initPopover(product, sku, linkNodes);
            }
            
        });         
    },
    
    initPopover: function(product, sku, linkNodes) {
        console.log("brand.product.productPopovers.initPopover");
        
        var self = this;
        
        if ((sku.shade_name.length > 0) && (sku.color[0].length > 2)) {
            is_shaded = true;
        } else {
            is_shaded = false;
        }
        
        this.cartConfirmProps.type = "order";
        
        var cartConfirmMsg = new brand.product.CartConfirm({
            id: "cart_confirm-" + sku.path,
            is_shaded: false,
            prodName: product.name
        }, $("cart_confirm_placeholder-" + sku.path));
        
        cartConfirmMsg.setDisplayProperties(this.cartConfirmProps);
        
        // init quick buy popover
        var cartAddArgs = {
            id: "cart_add-"+sku.path,
            is_shaded: is_shaded,
            prodName: product.name,
            skuFieldId: "prod_sku_cart_add-" + sku.path,
            price: product.price,
            cartConfirm: cartConfirmMsg,
            sku: sku                    
        }
        
        if (is_shaded) {
            cartAddArgs.smooshId = "smooshImg_cart_add-" + sku.path // pass smooshImg id to set template to use swatch smoosh instead of product thumb
        } else {
            cartAddArgs.smooshPath = product.thumb;
        }
        
        var cartAddMsg = new brand.product.CartAdd(cartAddArgs, $("cart_add_placeholder-" + sku.path));
        
        if ($("prod_sku_cart_add-" + sku.path)) $("prod_sku_cart_add-" + sku.path).value = sku.path; 
        
        var show = function(evt) {
            self.show(evt, cartAddMsg, cartConfirmMsg);
        }
        
        // connect each link node to popover action
        linkNodes.each(function( node ) {
            node.observe("click", show );  
        });
    },
    
    show: function(evt, cartAddMsg, cartConfirmMsg) {
        if (this.positionPopup) { 
            this.positionPopup(evt, cartAddMsg, cartConfirmMsg);
        }
        cartAddMsg.show();            
    }
}