brand.product.SwatchContainer = Class.create(Widget, 
{
    //MK: huh? does exist.
    templatePath : "/js/brand/product/templates/SwatchContainer.html", //doesn't exist but used as key
    templateString: '<div id="#{id}" class="swatch_by_color"></div>',
    
    sortType: "",    
    isContainer: true,
    isActive: false,
    _started: false,
    _loaded: null,
    _dataMethod: "sort",
    _dataParam: "",
    _activeSet: "",
    _initialized: 0,
    
    // _swatchSelected: Boolean
    // flag true when first hex has been selected & large swatch is visible
    _swatchSelected: false,
    
    // initDefault: Boolean
    // start with first swatch selected by default
    initDefault: false,
    shadedType: "solo",
    isDiscontinued: false,
    selectedSkuPath: "",
    
    // skuField: DOM node
    // input field for storing selected sku
    skuField: null,

    // productType: String (optional)
    // additional identifier to distinguish btwn products appearing more than once on page.
    // ex: cross-sell vs. main product
    productType: "",
    
    skus: "",
    product: "",
    smooshImg: "",

    sorters: {},
    filters: {},

    // arrays for multiple values associated w/ each sku (ex: multi-colored skus)
    smooshes: null,
    shadeDescriptions: null,
    
    initialize: function($super, arguments, node) {
        //console.log("brand.product.SwatchContainer.initialize "+node.id + "/"+arguments.product.video_prod);
        //this.inherited(arguments);
       /**
        for (prop in arguments[0]) { 
    	   	this[prop] = arguments[0][prop];
        }**/

        this.setProperties(arguments);
        this.id = node.id; 
        var self = this;
        this._loaded = {};
        this.skus = this.product.skus; 
 
        this.sortType = (this.sortType !== "" ? this.sortType : "color");
        this._dataParam = this.sortType;
        
        if (this.isSingleSku) {
            //console.log("brand.product.SwatchContainer.initialize: isSingleSku");
            var sku = this.skus[0];
        
            // check for multiple values (arrays) in single sku
            if (Object.isArray(sku.smoosh) && sku.smoosh.length > 0) {
                this.smooshes = {};        
            }
            if (Object.isArray(sku.shade_description) && sku.shade_description.length > 0) {
                this.shadeDescriptions = {};        
            } 
            // save shade info (alternate to sku.smoosh, etc...)
            var idbase = this.product.product_id + "_" + this.productType;
            for (var i = 0; i < sku.color.length; i++) {
                var id = "swatch_" + idbase + i.toString();
                if (this.smooshes) {
                    this.smooshes[id] = sku.smoosh[i];        
                }
                if (this.shadeDescriptions) {
                    this.shadeDescriptions[id] = sku.shade_description[i];        
                }           
            }
            
        } else {
            //console.log("brand.product.SwatchContainer.initialize: !isSingleSku");
            // template has a sort order
            if (this.product.sorters) {
                this.sorters = this.product.sorters;
            } else {
                // creates default sort order from order of skus in page_data
                var set = []; 
                
                this.skus.each(function(sku, idx) { 
                    set[idx] = [idx];
                });
                this.sorters[this._dataParam] = set;
            }
        }
         
        $super();
    },  

    postCreate: function() {
        //console.log("brand.product.SwatchContainer.postCreate "+this.id); 
        var idbase = this.product.product_id + "_" + this.productType;
                
        if (this.isSingleSku) {
            var sku = this.skus[0];

            for (var i = 0; i < sku.color.length; i++) { 
                var cid = "swatch_" + idbase + i.toString();
                var name = (sku.shade_name[i] ? sku.shade_name[i] : "");
                var hex = sku.color[i].toString();
                var swatch = new brand.product._Swatch({
                    id: cid,
                    sku: sku,
                    hex: hex,
                    name: name,
                    parentId: this.id
                });                
                this.loadSwatch(swatch);
            }
            
        } else {
	  //console.log("brand.product.SwatchContainer.postCreate !isSingleSku "+this.id);
            for (var i = 0; i < this.skus.length; i++) { 
                var sku = this.skus[i];
                var cid = "swatch_" + sku.sku_id; 
                if (this.product.video_prod) {
                    this.video_prod = true;
                    cid = "video_" + cid;
                }
                
                var idx = i.toString();
                var hex = (sku.color[0] ? sku.color[0].toString() : null);   
                var swatch = new brand.product._Swatch({
                    id: cid,
                    sku: sku,
                    hex: hex,
                    name: sku.shade_name,
                    containerId: this.id,
                    idx: idx,
                    parentId: this.id
                });                
                this._loaded[i] = swatch;
                
            }
            
            this.processData(this._dataMethod, this._dataParam);
        }
        
        if (this.initDefault) {
            this.isActive = true;
        }

    },
    
    setSwatch: function(child, event) { 
        //console.log("brand.product.SwatchContainer.setSwatch: "+child.id+" / sku path = "+child.sku.path);
        
        if (!child || this.selectedChildWidget == child) { 
            this.onSelectCallback(child);
            return;
        }
        var sku = child.sku;
        
        // if there is a large swatch to show
        if (this.smooshNode) {
            this._swatchDance({
                childid: child.id,
                name: child.name,
                sku: child.sku,
                hex: child.hex             
            });
        }
        
        this._updateSelected(child, this.selectedChildWidget);
        this.selectedChildWidget = child; 
        if (!this.isSingleSku) {
            this.skuField.value = child.sku.path;
        }
        this.onSelectCallback(child);
        this._swatchSelected = true;       

        /**JSTEST discontinued
        if ( this.isDiscontinued ) {
            this._setDiscontinued(sku);
        }**/
            
        // on user click event
        if (event !== "load") {
           // fire coremetrics event
           generic.events.fire({event:"swatch:click", msg:{ name: child.name, product: child.parent.product}});
        }
    },
    
    onSelectCallback: function(child) {
        // for external callback use
    },

    _swatchDance: function(args) {
        this.smooshNode.style.backgroundColor = args.hex;
        var sku = args.sku;
        
        // swatch args: get from sku or from alternate objs for multi-colored
        var desc = (this.shadeDescriptions ? this.shadeDescriptions[args.childid] : sku.shade_description);
        var smoosh = (this.smooshes ? this.smooshes[args.childid] : sku.smoosh);
                
        if (args.name) {
            this.swatchTitle.innerHTML = args.name;
        }
        if (desc) {
            this.swatchDesc.innerHTML = desc;
        }
        this.smooshImg.src = smoosh;
        
        brand.product.sppInventoryStatus({
            sku: sku,
            shaded: true
        });
    },

    processData: function(method, param) {
        if ((this._dataMethod === method && this._dataParam === param) && this._started) { return; }
        //console.log("brand.product.SwatchContainer.processData");  
        this._dataMethod = method;
        this._dataParam = param;

        var set;
        if (method === "sort") {
            if (param === "status") {
                var sorters = this.sorters[param];
                for (var i = 1; i <= 4; i++) {
                    var sub = sorters[i.toString()];
                    if (!set) {
                        set = sub;
                    } else {
                        set.concat(sub);
                    }
                }
            } else {
                set = this.sorters[param];
            }
        } else {
            if (param === "all") {
                this._dataMethod = "sort";
                set = this.sorters[this.sortType];
            } else {
                var filters = this.filters;
                if (filters[param]) {
                    set = filters[param];
                }
            }
        }
        
        this._activeSet = set;
        this._updateSet();
    },

    _updateSet: function() { 
        var children = this.children;
        if (children && this._initialized > 0) {
            for (var i = 0; i < children.length; i++) {
                var child = children[i];
                //console.log("removeChild: "+child.id+" / " + this.id); 
                $(child.id).style.display = "none";
            }
        }
        
        this._initialized++;
        var ids = this._activeSet;
        //console.log("brand.product.SwatchContainer._updateSet "+ids.length);
        if (!ids) return;
        
            for (var i = 0; i < ids.length; i++) {
                var idx = ids[i];
                var swatch = this._loaded[idx];
                //console.log("addChild: "+swatch.id+" / " + ids[i]);
                $(swatch.id).style.display = "block";
                $(this.id).appendChild($(swatch.id));
                this.loadSwatch(swatch);
            }
              
    },
    
    loadSwatch: function(swatch) {
        //JSTest this.addChild(swatch);
        //console.log("SwatchContainer.loadSwatch");
        if (!this.selectedChildWidget && this.initDefault) {
            
            if ( this.selectedSkuPath ) {
                //select a different default sku
                if (this.selectedSkuPath == swatch.sku.path ) {
                    //this.selectChild(swatch); // TODO: needed?
                    this.setSwatch(swatch, "load");
                }
            } else {
                //this.selectChild(swatch); // TODO: needed?
                this.setSwatch(swatch, "load");
            }
        }
    },

    _updateSelected: function(newChild, oldChild) {        
        if (oldChild) {
            oldChild.selected = false;
            oldChild.toggleSelectedState(false);
        }
        newChild.selected = true;
        newChild.toggleSelectedState(true);
    },
    
    _setDiscontinued: function(sku) {
       /**JSTEST: untested 
        //remove add to bag buttons
        $("prod_sku").style.display = "none"; // TODO
        $("add_to_bag_top").style.display = "none"; // TODO
        var path = sku.path;
        var sku_replacements = page_data.sku_replacements;
        var xs_container = $('discontinued_xs_container');
        xs_container.innerHTML = "";
        // check if there are replacements
        //var num_of_replacements = sku_replacements[path].replacements[0];
        if ( sku_replacements[path].replacements.length == 0 || sku_replacements[path].replacements[0].length == 0 ) {
           xs_container.style.display = "none";
           $("artist_recommendations").style.display = "none";
        } else {
            xs_container.style.display = "block";  
            $("artist_recommendations").style.display = "block";          
            sku_replacements[path].replacements.each(function(replacements) {
                var time = (new Date()).getTime(); // TODO: only create new widgets if they don't already exist.  if they do, show them & hide the others that have been created instead of creating a new instance
                //one replacement
                if ( replacements.length == 1 ) {
                    var sku = replacements[0];
                    var product = new brand.product.ReplacementProduct({
                        product_name: sku.product_name,
                        category_id: sku.category_id,
                        product_id: sku.product_id,
                        path: sku.path,
                        shade_name: sku.shade_name,
                        description: sku.description,
                        price: sku.price,
                        thumb: sku.thumb,
                        hex: sku.hex,
                        header: sku.header,
                        is_shaded: sku.is_shaded,
                        sku: sku,
                        time: time
                    });
                    
                    xs_container.appendChild(product.domNode);
                    product.initButton();
                    
                } else { //two replacements
                    var mixable_container = new brand.product.MixableReplacements({
                        path: path,
                        time: time
                    });
                    
                    var skus = [];
	          var allReplacements = [].concat(replacements[0], replacements[1]);
					
                    allReplacements.each(function(replacement) {
                        var product = new brand.product.MixableProduct({
                            product_name: replacement.product_name,
                            category_id: replacement.category_id,
                            product_id: replacement.product_id,
                            path: replacement.path,
                            shade_name: replacement.shade_name,
                            description: replacement.description,
                            price: replacement.price,
                            thumb: replacement.thumb,
                            hex: replacement.hex,
                            header: replacement.header
                        });
                        
                        mixable_container.addItem(product); 
                        skus.push( replacement.path );  
                    });
                    
                    xs_container.appendChild(mixable_container.domNode);
                    mixable_container.addPrices();
                    mixable_container.initButton(skus);
                }                
            });
        }**/
    }
});


brand.product._Swatch = Class.create(Widget,
{
    _swatchPath: "/js/brand/product/templates/_Swatch.html",
    _swatchDarkPath: "/js/brand/product/templates/_SwatchDark.html",
    
    _swatchString: ''+
        '<div id="#{id}" class="swatch_hex_container" attachPoint="shadeContainerNode" attachEvent="click:_onClick">'+
            '<div class="swatch_hex" attachPoint="shadeNode" attachEvent="mouseover:_onMouseOver,mouseout:_onMouseOut" style="background-color: #{hex};"><br /></div>'+
            '<div class="swatch_tooltip" attachPoint="tooltipNode" style="background-color: #{hex};">#{name} #{inventory_status}</div>'+
        '</div>',
        
    _swatchDarkString: ''+
        '<div id="#{id}" class="swatch_hex_container" attachPoint="shadeContainerNode" attachEvent="click:_onClick">'+
            '<div class="swatch_hex swatch_hex_smoosh" attachPoint="shadeNode" attachEvent="mouseover:_onMouseOver,mouseout:_onMouseOut" style="background-color: #{hex};"><img src="#{smooshThumb}" width="12" height="12" alt=""></div>'+
            '<div class="swatch_tooltip" attachPoint="tooltipNode" style="background-color: #{hex};">#{name} #{inventory_status}</div>'+
        '</div>',
      
    sku: null,
    hex: "",
    rgb: "",
    name: null,
    type: "solo", 
    idx: null, // sku index 
    selected: false,
    
    // smooshImg: String
    // for prods that use images for swatch/hex thumb
    smooshThumb: null,
    
    swatchContainerSelectedClass: "swatch_hex_container_selected",
    swatchSelectedClass: "swatch_hex_selected", 
     
    initialize: function($super, arguments) { 
        this.setProperties(arguments); 
        //console.log("brand.product._Swatch: "+this.hex);
        this.templateString = this._swatchString;        
        this.templatePath = this._swatchPath;        
        this.smooshThumb = this.sku.smoosh_thumb;     
        this.rgb = generic.hexToRGB(this.hex);
        
        if ( this.sku.sku_multicolor_type ) { 
           this.type = this.sku.sku_multicolor_type;
        }
        if ( this.type === "duo" || ( this.type === "solo" && this._isDark(this.rgb) ) ) {
            this.templateString = this._swatchDarkString;
            this.templatePath = "this._swatchDarkPath";
        }
        var self = this;
        var msg = brand.product.inventoryStatus.suppressAddToBag.any(function(n) { return n==self.sku.inventory_status; });
        if (msg) {
            this.inventory_status = "(" + this.sku.inventory_status_message + ")";
        } else {
            this.inventory_status = "";
        }
        
        $super();
    },

    postCreate: function() {        
        if ( this.rgb ) { 
            this._setTextColor(this.rgb);
        }
         if ( this.type === "duo" || ( this.type === "solo" && this._isDark(this.rgb) ) ) {
             
        }
    },
    
    _onClick: function(e) {
        this.parent.setSwatch(this);
    },

    _onMouseOver: function(e) {
        if (this.name) {
            this.tooltipNode.style.visibility = "visible";
            this.shadeContainerNode.style.zIndex = "10"; // fix for IE position+layering bug
        }
    },

    _onMouseOut: function(e) {
        if (this.name) {
            this.tooltipNode.style.visibility = "hidden";
            this.shadeContainerNode.style.zIndex = "1";
        }
    },

    toggleSelectedState: function(/* Boolean */state) {     
        if (state) {
            if (this.shadeContainerNode) {
                this.shadeContainerNode.addClassName(this.swatchContainerSelectedClass);
            }
            this.shadeNode.addClassName(this.swatchSelectedClass);
        } else {
            if (this.shadeContainerNode) {
                this.shadeContainerNode.removeClassName(this.swatchContainerSelectedClass);
            }
            this.shadeNode.removeClassName(this.swatchSelectedClass);
        }
    },
    
    _setTextColor: function(rgb) {
        if (!rgb) { return; }
        // if color is light, set text to black for appropriate contrast
        if (this._isBright(rgb)) {
            this.tooltipNode.style.color = "#000";
        }
    },
    
    _getBrightness: function(rgb) {
        if (!rgb) { return; }
        var total = rgb[0] + rgb[1] + rgb[2];
        return total;
    },

    _isBright: function(rgb) {
        if (!rgb) { return; }
        var isBright = this._getBrightness(rgb) > 450;
        return isBright;
    },

    _isDark: function(rgb) {
        if (!rgb) { return; }
        var isDark = this._getBrightness(rgb) < 100;
        return isDark;
    }
});
