/* Function for Brand Notify Me to add thank you */
window.addEvent("domready", function(){
	var form = document.getElement("#brand-notifyme .standard-form");				
	if (!form) return;
	var brandname = window.brandname || "this brand";
    var myform = new AsyncForm("#brand-notifyme .standard-form",{
        'validations':[
            {'present': ['email','Please enter your email address.']}
        ],
      
        'onError':function() {
            document.getElement('.async_error').setStyle('color','#c00');
        },

        'onSuccess':function(fields){
            var parent = $('brand-notification');
            var header = new Element('h4',{'text':"Thank You For Your Notification Request!"});
            var body = new Element('p',{'text':"We will send an email to " + fields.emailAddress + " should new styles of "+brandname.cleanASCII()+" become available."});
            parent.empty();
            parent.grab(header);
            parent.grab(body);
            parent.setStyle('width','100%');
        }
    });
});

window.addEvent('domready', function(){
    if (!document.getElement('#zappme'))
        return;
    
    document.getElement('#zappme').addEvent('click', function(event){
      this.select();
      this.focus();
    });
    var zappmeHover = new HoverPop("#zappmeHov", "#zappmeHov", {'position': 'right', 'close':false, 'href':'/popovers/zappmePop.zml'});    
    document.getElement('#zappmeHov').addEvent('click', function(event){
      return false;
      });
});

window.addEvent('domready', function(){
    if (!document.getElement('#shipping-options'))
        return;
				var element1 = $$('#shipping-options a')[0].get('href');
    var zappmeHover = new ClickPop("#shipping-options a", "#shipping-options a", {'position':'top', 'close':false, 'popoverId':'shipping-options-popover', 'href':element1});    
});

window.addEvent('domready', function() {
    if($('back-to-browsing')) {
        $('back-to-browsing').addEvent('click', function(e) {
            e.preventDefault();
            window.history.go(-1);
        });
    }
});

window.addEvent('domready', function(){
    if (!document.getElement('#blog-this'))
        return;
    
    new HoverPop("#blog-this-pop", "#blog-this-pop", {'position': 'right', 'close':false, 'href':'/popovers/blogThis.zml'});
    
    document.getElement('#blog-this-code-snippet').addEvent('click', function(e){
        this.select();
        this.focus();
    });
    
    document.getElement('#blog-this-do-preview').addEvent('click', function(e) {
        e.preventDefault();
        $(e.target);
        
        var preview = $('blog-this-preview');
        if(preview.getStyle('display') == 'none') {
            e.target.set('text','Hide Preview');
            preview.setStyle('display','block');
        } else {
            e.target.set('text','Preview Badge');
            preview.setStyle('display','none');
        }
    });
});

window.addEvent("domready", function(){
  var linkPop = $$('a.popWindow');
  if (!linkPop) return;
  var popWindowDefaults = 'location=0, statusbar=0, menubar=0, width=450, height=475';
  if (linkPop.hasClass('tell-a friend')){
    var popWindowDefaults = 'location=0, statusbar=0, menubar=0, width=446, height=666, scrollbars=1';
    }
  if (linkPop.hasClass('report-an-error')){
    var popWindowDefaults = 'location=0, statusbar=0, menubar=0, width=450, height=475, scrollbars=1';
    }
  var PopUp= function(url, name) {
    window.open(url,name,popWindowDefaults);
  }
  linkPop.addEvent('click', function() {
    PopUp(this.href, 'newWindow');
    return false;
  });
});

/* Size Chart Popup */
window.addEvent('domready', function() {
 $$('.productsize-ruler').addEvent('click', function(event) {
 event.preventDefault();
 window.open('/cs/mmf-popop.zml', 'shoesizes', 'status=0,toolbar=0,location=0,menubar=0,directories=0,resizeable=1,scrollbars=1,height=600,width=790');
 })
});

window.addEvent('domready', function() {
    $$('.multiview-link').each(function(link) {
        link.store('color', startColor);
        link.addEvent('click', function() {
            var title = ("multiview" + this["title"].split("-sku")[1] + "color" + this.retrieve("color"));
            var height;
            if (imageSize.height > imageSize.width)
                height = 688;
            else
                height = 520;
            console.debug("title: ", title, "; href: ", this["href"]);
            var multiview = window.open(this["href"], title, "menubar=no,width=580,height=" + height + ",toolbar=no");
            multiview.focus();
            return false;
        });
    });
});


window.addEvent('domready', function() {
    console.time("Adding Product Events");
    // If product is unavailable, the rest of the JS will not work.
    if(document.getElement('.outostock')) {
      return;
    }

    var productForm = document.getElement('#product-form');
    var stocks = $H({
        'all': stock,
        'sizes': stockSizes,
        'widths': stockWidths,
        'colors': stockColors,
        'color-price': stockColorPrice
    });
    
    var productObserver = new ModelObserver({
        'colorId': ['#product-form #color', '#color-side', '#swatches', '#thumbnails'],
        'widthId': ['#product-form #width'],
        'sizeId':  ['#product-form #size'],
        'available': []
    });
    
    window.productModel = new Model({
        'colorId': window.startColor,
        'widthId': document.getElement('#width').get('value'),
        'sizeId': document.getElement('#size').get('value'),
        'available': true,
        'sizeError': false,
        'submitError': false
    }, productObserver);
    
    var getCurrentStock = function(){
      return stocks.get('all').filter(function(stockItem){
        return (
          (stockItem['size']['id'] == productModel.get('sizeId')) &&
          (stockItem['color']['id'] == productModel.get('colorId')) &&
          (stockItem['width']['id'] == productModel.get('widthId'))
        )
      });
     };

    var checkAvailability = function() {
        if (productModel.get('sizeId') <= 0 || 
            !productModel.get('sizeId')) return true;
        available = stocks.get('all').some(function(stockItem) {
            return (
              (stockItem['size']['id'] == productModel.get('sizeId')) &&
              (stockItem['color']['id'] == productModel.get('colorId')) &&
              (stockItem['width']['id'] == productModel.get('widthId'))
            )
        });
        console.log("available", available);
        productModel.set('available', available);
    };
    productObserver.addCallback('colorId', checkAvailability);
    productObserver.addCallback('sizeId',  checkAvailability);
    productObserver.addCallback('widthId', checkAvailability);
    
    var checkOnHand = function() {
        if(document.getElement('#low-stock-message')) {
            document.getElement('#low-stock-message').dispose();
        }
        
        if (!productModel.get('sizeId') || !productModel.get('widthId')) return;
        var onHand = getCurrentStock() ;
                
        if(onHand[0] && onHand[0]['onHand'] <= 3) {
            console.log(onHand[0]['onHand']);
            var mySpan = new Element('span',{'id':'low-stock-message','text':'Only ' + onHand[0]['onHand'] + ' left in this size/color combination!'});
            console.log(mySpan);
            document.getElement('#product-form fieldset').grab(mySpan, 'top');
        }
    };
    productObserver.addCallback('colorId', checkOnHand);
    productObserver.addCallback('sizeId',  checkOnHand);
    productObserver.addCallback('widthId', checkOnHand);
   
    var showIcons = function() {
      if (document.getElement('#iconicDesc')) {
        document.getElement('#iconicDesc').empty();
        var currStock = getCurrentStock();
        if (currStock.length < 1){
          callIcon(stock);
        } else {
          callIcon(currStock);
        }
			}
        function callIcon(stockItem){
          for (var i=0; i < stockItem[0]['listSize']; i++) {
            var attr = "iconDesc" + i;						
            if (stockItem[0][attr]['url'] ){
              var icoImg = new Element('img',{'src':stockItem[0][attr]['url'], 'alt':stockItem[0][attr]['name'] + ': ' + stockItem[0][attr]['value'],'height':'30px','width':'30px','id':attr}); 
              document.getElement('#iconicDesc').grab(icoImg);
              var popMsg2 = new Element('p',{'html':stockItem[0][attr]['value']});
              var myIconPop = new HoverPop('#'+attr,'#'+attr,{'popoverId':'icopop','position':'bottom','close':false, 'title':stockItem[0][attr]['name'], 'html':popMsg2},0);

            }
          }
        }
    };
    productObserver.addCallback('colorId', showIcons);
    productObserver.addCallback('sizeId', showIcons);
    productObserver.addCallback('widthId', showIcons);

    var changeProductImage = function(colorId) {
        var productImage = document.getElement('#detail-image');
        var img = detailImages[colorId];
        if (productImage && img){
            img.set('id', 'detail-image');
            img.replaces(productImage);
        }
    };
    productObserver.addCallback('colorId', changeProductImage);
    
    var changeMultiviewLinks = function(colorId) {
        $$('.multiview-link').each(function(multiviewLink) {
            multiviewLink.store('color', colorId);
            multiviewLink.set('href', 
                multiviewLink.get('href').replace(/\/\d*$/, "/" + colorId));
        });
    };
    productObserver.addCallback('colorId', changeMultiviewLinks);
    
    var changePriceOnStyleChange = function(colorId) {
        if (stocks['color-price'][colorId]['was'] != "$0.00"
            && stocks['color-price'][colorId]['was'] != stocks['color-price'][colorId]['now']) {
            var contents = priceChangeView ? priceChangeView(stocks['color-price'][colorId]) : 
                                             "<span class=\"old-price\">" +
                                                addCommas(stocks['color-price'][colorId]['was']) + 
                                             "</span>" +
                                             "<span class=\"sale\">SALE!</span>" +
                                                addCommas(stocks['color-price'][colorId]['now']);
            document.getElement('#product-form .header .price').set('html', contents);
            document.getElement('#product-form .header').addClass("on-sale");  
        } else {
            document.getElement('#product-form .header .price').set('html', stocks['color-price'][colorId]['now']);
            document.getElement('#product-form .header').removeClass("on-sale");
        }
    };

    productObserver.addCallback('colorId', changePriceOnStyleChange);
    
    var outOfStockMessaging = function(available) {
        if(document.getElement('#oos-message')) {
            document.getElement('#oos-message').destroy();
        }
        
        if (!available) {
            if(!document.getElement('#oos-message')) {
                var styleId;
                var self = this;
                stock.each(function(item) {
                    if(self.get("colorId") == item.color.id) {
                        styleId = item.styleId;
                        return;
                    } else {
                        return;
                    }
                });
            
                var oosMessage = new Element('div', { 'html' : 
                    '<p>Sorry, but that Combination is Not Currently Available</p>' +
                    '<a id="oos-notify-me" href="/NotifyMe.action?productId=' + productId + '&colorId=' + styleId + '&sizeId=' + this.get('sizeId') + '&widthId=' + this.get('widthId') + '">Notify Me When It\'s Available</a>' +
                    '<a href="#" id="other-combinations">See Similar Available Combinations</a>',
                    'id' : 'oos-message'});
                document.getElement('#product-form fieldset').grab(oosMessage, 'top');
            }
            oosEvents(this.get('sizeId'), this.get('widthId'), this.get('colorId'));
        }
    };
    productObserver.addCallback('available', outOfStockMessaging);
    
    var removeColorError = function() {
        productModel.set('colorError', false);
    };
    productObserver.addCallback('colorId', removeColorError);
    
    var colorErrorChanged = function(value) {
        if (value) {
            if (!productForm.getElement('#sizes').hasClass('errors'))
                productForm.getElement('#sizes').addClass('errors')
        } else {
            productForm.getElement('#sizes').removeClass('errors')
        }
    };
    productObserver.addCallback('colorError', colorErrorChanged);
    
    var removeSubmitError = function() {
        productModel.set('submitError', false);
    };
    productObserver.addCallback('colorId', removeSubmitError);
    productObserver.addCallback('widthId', removeSubmitError);
    productObserver.addCallback('sizeId', removeSubmitError);
    
    var submitError = new Popover({'position':'top', 'title':'Item Out of Stock'});
    var submitErrorPopover = function(value) {
        console.log('subE');
        if (value) {
            console.log('in val ' + productModel.get('sizeId'));
           // var button = document.getElement('#submit a');
          //  var submit = document.getElement('#submit');
            var errorMsg = "";
            var title = "";
            
            if(productModel.get('sizeId') == "" || !productModel.get('sizeId')) {
                console.log('heresadfhkfsdh');
                errorMsg = new Element('p', {'text':'Please select a size before adding this product to your shopping cart.'});
                title = "Select a Size";
            } else {
                errorMsg = new Element('p', {'text':'We are sorry but this combination of size, width and color is not currently available. '});
                errorLink = new Element('a', {
                    'href':'#', 
                    'events' : { 
                        'click': function(e) {
                            document.getElement('#other-combinations').fireEvent('click', e);
                        }
                    },
                    'text' : 'See Similar Available Combinations.'
                });
                errorMsg.grab(errorLink);
                title = "We're Sorry!"
            }
            
            submitError.hide();
            submitError.options.html = errorMsg;
            submitError.display(productForm.getElement('.add-to-cart, .sc-button'));
        } else {
            submitError.hide();
        }
    };
    productObserver.addCallback('submitError', submitErrorPopover);
   
    productModel.set('colorId', window.startColor);
    productModel.set('widthId', document.getElement('#width').get('value'));
    productModel.set('sizeId', document.getElement('#size').get('value'));

    var submitForm; 
    submitForm = function() {
        console.log(window.productModel.get('available'));
        var av = window.productModel.get('available');
        var size = window.productModel.get('sizeId');
        if (av && size != ""){
            submitForm = function(){ return false; };
            return productForm.submit();
        }
        if (productModel.get('size') == "")
            productModel.set("sizeError", true)
        productModel.set('submitError', true);
        return false;
    };
    productForm.addEvent('submit', submitForm);
    
		//------------FAVORITES 
		if(document.getElement('#sharing .add-to-favorites')){
    	document.getElement('#sharing .add-to-favorites').addEvent('click', function(e){
				//Check to see if Currstock is filled, If not, then assume that they want to add an out of stock item or are lazy.	
	      var currStock = getCurrentStock();
	      e.preventDefault();
	      var noAdd = new Popover({'position':'centerScreen', 'title':'Add To Favorites'});      
	      if (currStock.length > 0) {
	        var href = this.get('href');
	        href= href.split('?')[0];
	        document.location = href + '?stockId=' + currStock[0]['stockId'];
	      } else {
					//assemble the url for the call
					var thisUrl = '/product/' + productId + '?json=ohyeah';
					var thisColor = productModel.get('colorId');
								
					//make the call
					var jsonRequest = new Request.JSON({url: thisUrl, onSuccess: function(allStock){
					
						//Make the lazy button be the first listed item, the smallest size
						var lbstockId = allStock[0].stockId;					
						var lbUrl = '/ViewFavorites.action?stockId=' + lbstockId + '&auto=1';
						var lbLink = new Element('a', {'href':lbUrl, 'text':'Just Add It Already!'});
						var lbNote = new Element('p', {'text':'- OR -'});
						var lbDiv = new Element('div', {'class':'lbDiv'});
						var lbHTML = lbDiv.adopt(lbNote, lbLink);
						var thisProductName = allStock[0].productName;
						var thisProdType = allStock[0].productType;
						//Create the size table
						poverTable = new Element('table');
						poverTbody = new Element('tbody');
						for (var k in stockWidths){
							if (stockWidths.hasOwnProperty(k)){							
								var poverTableRow = new Element('tr');
								var poverTableHead = new Element('th', {'scope':'row', 'axis':'width', 'text':stockWidths[k]});
								poverTableHead.inject(poverTableRow);
								var poverTableCell = new Element('td');
								var temp = 0;
								for (var l in stockSizes){
									if (stockSizes.hasOwnProperty(l)){
										for (i=0; i<allStock.length; i++){
											if (allStock[i].color.id == thisColor && allStock[i].width == stockWidths[k] && allStock[i].sizeId == l){
												var validStock = allStock[i].stockId;
												var validSize = allStock[i].sizeName;
												var validWidth = allStock[i].width;
												var poverCellContent = new Element('a', {'href':'/ViewFavorites.action?stockId=' + validStock, 'class':'favAmUndo', 'text':validSize});
												poverTableCell.adopt(poverCellContent)
												var thisColorName = allStock[i].color.name;
												var temp = 1;
											}
										};
									}
								};
								if (temp == 0){
									var poverCellContent = new Element('p', {'text':'There are no sizes available for this Width.'});
									poverTableCell.adopt(poverCellContent)
								}
								poverTableCell.inject(poverTableRow, 'bottom');
								poverTableRow.inject(poverTbody, 'bottom');
							}
						};
						poverTbody.inject(poverTable);
					
						//Make the General Info					
						var poverDiv = new Element('div', {'id':'lazyFavs'});
						var poverBlurb = new Element('p', {'html':'<strong>Product:</strong> ' + thisProductName + ' | <strong>Color: </strong>' + thisColorName });
						var poverInstr = new Element('p', {'html':'<strong>Please select from the sizes/widths that we carry</strong> (not all sizes/widths may be currently available).'})

						//Make Width Key/Legend in for shoes only and assemble all info in the popover
						if (thisProdType == 'Shoes'){
							//Size Key Table
							poverkTable = new Element('table');
							poverkTbody = new Element('tbody');
							poverkTrow = new Element('tr');
							sizeKey = new Element('th', {'text':'Men\'s Standard (Medium) width: \'D\' -- Women\'s Standard (Medium) width: \'B\''});
							sizeKey.inject(poverkTrow);
							poverkTrow.inject(poverkTbody);
							poverkTbody.inject(poverkTable);
					
							// -- THIS IS THE LAZY BUTTON SWITCH -- PART 1
							// SWAP THE FOLLOWING TWO LINES TO TURN ON THE LAZY SWITCH
							//var favConstruct = poverDiv.adopt(poverInstr, poverBlurb, poverTable, poverkTable, lbHTML);
							var favConstruct = poverDiv.adopt(poverInstr, poverBlurb, poverTable, poverkTable);
						} else {
						
							// -- THIS IS THE LAZY BUTTON SWITCH -- PART 2
							// SWAP THE FOLLOWING TWO LINES TO TURN ON THE LAZY SWITCH
							//var favConstruct = poverDiv.adopt(poverInstr, poverBlurb, poverTable, lbHTML);
							var favConstruct = poverDiv.adopt(poverInstr, poverBlurb, poverTable);
						}
					
						noAdd.options.html = favConstruct;
						noAdd.display(document.getElement('#sharing'));
				
					}}).get();
		    }
	    });
		}
	
    var updateTellAFriend = function(value) {
        if (document.getElement("#sharing .tell-a-friend")) {
            var e_tellAFriend = document.getElement("#sharing .tell-a-friend");
            e_tellAFriend.set('href', e_tellAFriend.get('href').replace(/colorId=\d*/, "colorId=" + value));
            e_tellAFriend.set('href', e_tellAFriend.get('href').replace(/color=[^&]*/, "color=" + stockColors.get(value)));
        } else {
            return false;
        }
    };
    productObserver.addCallback('colorId', updateTellAFriend);
    
    console.timeEnd("Adding Product Events");
});

var oosEvents = function(size, width, color) {
    document.getElement('#other-combinations').addEvent('click', function(e) {
        e.preventDefault();
        var altSizes = stockSizes.getKeys();
        altSizes.some(function(item, index) {
            if(item == size) {
                altSizes = altSizes.slice(Math.max(index - 2, 0) , index + 2);
                return true;
            }
            return false;
        });
        var altWidths = stockWidths.getKeys();
        altWidths.some(function(item, index) {
            if(item == width) {
                altWidths = altWidths.slice(Math.max(index -1, 0), index + 1);
                return true;
            }
            return false;
        });
        var altSizesAndWidths = stock.filter(function(item) {
            if(altSizes.contains(item.size.id) && item.width.id == width && item.color.id == color && item.onHand > 0) {
                return true;
            }
            
            if(altWidths.contains(item.width.id) && item.size.id == size && item.color.id == color && item.onHand > 0) {
                return true;
            }
            
            if(altWidths.contains(item.width.id) && altSizes.contains(item.size.id) && item.color.id == color && item.onHand > 0) {
                return true;
            }
        });
        var altColors = stock.filter(function(item) {
            return item.size.id == size && item.width.id == width && item.onHand > 0;
        });
        
        var altCombinations = new Element('div', {'id' : 'alternative-combinations'});
        var altSizeWidthDiv = new Element('div', {'id' : 'alternative-sizes'});
        var altColorsDiv = new Element('div', {'id' : 'alternative-colors'});
        
        var altSizeWidthWrapDiv = new Element('div');
        
        altCombinations.grab(new Element('a', {
            'href':'#',
            'class' : 'close',
            'text' : 'close',
            'events' : {
                'click' : function(e) {
                    e.preventDefault();
                    $('size').setStyle('display', 'inline');
                    $('width').setStyle('display', 'inline');
                    $('color').setStyle('display', 'inline');
                    altCombinations.destroy();
                } 
            }
        }));
        
        altCombinations.grab(new Element('p', {'class':'header','text':'Similar Available Combinations in Your Size Range:'}));

        if(altSizesAndWidths.length) {
            altSizeWidthDiv.grab(new Element('p', {'html' : 'We\'ve got these sizes in the same color you selected:'}));
            if(thumbnailImages[color]) {
                altSizeWidthDiv.grab(thumbnailImages[color]);
            }
            altSizesAndWidths.each(function(item) {
                altSizeWidthWrapDiv.grab(new Element('div', {
                    'html' : '<a href="#">' + '<span>Size: <span>' + item.size.name + '</span></span>' + '<span>Width: <span>' + item.width.name + '</span></span>' + '<span class="price">' + item.price + '</span>' + '</a>',
                    'events' : {
                        'click' : function(e) {
                            e.preventDefault();
                            document.getElement('#size').set('value', item.size.id).fireEvent('change');
                            document.getElement('#width').set('value', item.width.id).fireEvent('change');
                            document.getElement('#color').set('value', item.color.id).fireEvent('change');
                            $('size').setStyle('display', 'inline');
                            $('width').setStyle('display', 'inline');
                            $('color').setStyle('display', 'inline');
                            altCombinations.destroy();
                        }
                    }
                }));
            });
            altSizeWidthDiv.grab(altSizeWidthWrapDiv);
        }
        
        if(altColors.length) {
            altColorsDiv.grab(new Element('p', {'html' : 'We\'ve got these colors in the same size you selected:'}));
            altColors.each(function(item) {
                var itemDiv = new Element('div');
                var itemLink = new Element('a', {
                    'href' : '#',
                    'events' : {
                        'click' : function(e) {
                            e.preventDefault();
                            document.getElement('#size').set('value', item.size.id).fireEvent('change');
                            document.getElement('#width').set('value', item.width.id).fireEvent('change');
                            document.getElement('#color').set('value', item.color.id).fireEvent('change');
                            $('size').setStyle('display', 'inline');
                            $('width').setStyle('display', 'inline');
                            $('color').setStyle('display', 'inline');
                            altCombinations.destroy();
                        }
                    }
                });
                itemDiv.grab(itemLink);
                if(thumbnailImages[item.color.id]) {
                    itemLink.grab(thumbnailImages[item.color.id]);
                }
                itemLink.grab(new Element('span', {'html' : '<span>' + item.color.name + '</span><span class="price">' + item.price + '</span>'}));
                altColorsDiv.grab(itemDiv);
            });
        }
        
        if(altSizesAndWidths.length) {
            altCombinations.grab(altSizeWidthDiv);
        }
        if(altColors.length) {
            altCombinations.grab(altColorsDiv);
        }
        altCombinations.setStyles({
           'left' :  window.getSize().x/2 - 300,
           'top' : 125
        });
        
        $('size').setStyle('display', 'none');
        $('width').setStyle('display', 'none');
        $('color').setStyle('display', 'none');
        
        document.getElement('body').grab(altCombinations);
    });
    
    document.getElement('#oos-notify-me').addEvent('click', function(e) {
        e.preventDefault();
        $(e.target);
        
        PopUp(e.target.href, 'notify_me', 445, 470);
    });
}

var PopUp = function(url, title, width, height) {
    window.open(url, title, 'status=0,toolbar=0,location=0,menubar=0,directories=0,resizeable=1,scrollbars=1,height=' + height + ',width=' + width);
}

var addCommas = function(nStr) {
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

window.addEvent('domready', function() {
	zlib.shoppingCartButtonize('.add-to-cart', 'product-form');
});
var zlib = new Object();

zlib.buttonize = function(selector, spans) {
    $$(selector).each(function(button) {
        if (button.hasClass("button-x"))
            return;
        var begin = "";
        var end = "";
            (spans).times(function() {
                begin = begin + "<span>";
                end = end + "</span>";
            });
        button.set('html', begin + button.get('html') + end);
    });
};

zlib.shoppingCartButtonize = function(selector, form) {
    $$(selector).each(function(button) {
        var a = new Element('a', {'class': 'sc-button', 'href': '/cart'});
        a.set('html', button.get('value'));
        a.addEvent('click', function(e) {
            e.preventDefault();
            var hidden = new Element('input', {'type': 'hidden'});
            hidden.set('name', 'add-to-cart');
            hidden.set('value', 'true');
            $(form).grab(hidden, 'top');
            $(form).fireEvent('submit');
            return false;
        });
        a.replaces(button);
    });
};

zlib.actionButtonize = function(selector) {
    document.getElements(selector).each(function(button) {
        button.set('class', 'sc-button');
    });
};

zlib.createRoundedCorners = function() {
  if (Browser.Engine.webkit420) //webkit 3 has border-radius thus doesn't need to spend time doing this
    return true;
    
  console.time("Timing createRoundedCorners()");
  
  var extra = new Element('div', {'class': 'rounded'});
  extra.grab(new Element('div'));
  var clearDiv = new Element('div', {'class': 'clear', 'style': {'clear': 'both', 'font-size': '1px', 'line-height': '1px'}});
  
  $$('.round').each(function(element) {
      if (element.get('tag') == 'h3') {
          var h3Wrap = new Element('div', {'class': 'round-h3-wrap'});
          h3Wrap.grab(extra.clone(), 'top');
          h3Wrap.wraps(element);
          var newPadding = element.getStyle('padding-top').toInt()-5;
          newPadding = (newPadding < 0) ? 0 : newPadding;
          element.setStyle('padding-top', element.getStyle('padding-top').toInt()-5);

          h3Wrap.setStyle('margin', element.getStyle('margin'));
          element.setStyle('margin', 0);
      } else {
          var divWrap = new Element('div', {'class': 'round-div-wrap'});
          divWrap.wraps(element, 'top');
          if (element.hasClass('round-important')) {
              var lightExtra = extra.clone();
              lightExtra.addClass('rounded-important');
              divWrap.grab(lightExtra);
          } else {
              divWrap.grab(extra.clone());
          }
          var newPadding = element.getStyle('padding-bottom').toInt()-5;
          newPadding = (newPadding < 0) ? 0 : newPadding;
          element.setStyle('padding-bottom', newPadding);

          element.grab(clearDiv.clone());
          divWrap.setStyle('margin', element.getStyle('margin'));
          element.setStyle('margin', 0);
          element.setStyle('margin-left', 1);
      }
  });
  
  delete extra;
  delete clearDiv;
  
  console.timeEnd("Timing createRoundedCorners()");
  return true;
};

/* Function for Thumbnail Colors PopOver and Swatch Hover Thumbnails */
(function(){

  if (!$('all-colors-pop'))
          return;

    //Build Color Popover Thumbnail List
      var colorsPop;
      $('all-colors-pop').addEvent('click', function(e){

          e.preventDefault();
          if (!colorsPop){
                   
             var cpDiv = new Element('div', {'id':'colors-pop', 'class':'styles-' + prodThumbs.length});
             var cpClose = new Element('a', {'href':'/', 'class':'cp-close', 'text':'close'}).inject(cpDiv);
             var cpDiv2 = new Element('div').inject(cpDiv);
             var cpUL = $('thumbnails');
             cpUL.inject(cpDiv2);
             cpUL.setStyle('display', 'block');
             var cpThumbNum = (prodThumbs.length - (prodThumbs.length % 3) + 1);
             for (i = 0; i < prodThumbs.length; i++) {
                if ((i < cpThumbNum && i > 2) && (Math.floor( i / 3 ) == i / 3) && (i / 3 >= 1)) new Element('li', {'class':'clear'}).inject(cpUL);
                var cpLI = new Element('li').inject(cpUL);
                var cpThumbSRC = prodThumbs[i].imageSRC;
                var cpLink = new Element('a', {'href':prodThumbs[i].productURL, 'class': prodThumbs[i].thumbClass}).inject(cpLI);
                var cpThumb = new Element('img', {'src':cpThumbSRC, 'class': prodThumbs[i].thumbClass}).inject(cpLink);
                var cpBR = new Element('br').inject(cpLink);
                var cpColor = new Element('span', {'text': prodThumbs[i].colorName}).inject(cpLink);
             };

             colorsPop = new Popover(
               {'position':'right',
               'html':cpDiv,
               'close':false,
               'popoverId':'colors-popover'});

             colorsPop.display(this);

             cpUL.addEvent('click', function(){
                   colorsPop.popover.setStyle('display', 'none');
                   });
             cpClose.addEvent('click', function(e){
                   colorsPop.popover.setStyle('display', 'none');
                   e.preventDefault();
                   });
              }
          
          else{
              colorsPop.popover.setStyle('display', 'block');
          };

      });

    //Swatch hover thumbnails
      var swatchHover;
      $('swatches').addEvent('mouseover', function(e){

          e.preventDefault();
          if (!swatchHover){
                  
                  var swatches = $$('#swatches img.swatchHov');

                  swatches.addEvent('click', function(event){
                    this.focus();
                  });

                  var swatchID = swatches.get('id'); 
                  for (i = 0; i < swatches.length; i++) {
                      var thumbnailURL = prodThumbs[i].imageSRC;
                      var thumbnailHTML = new Element('img',{'src':thumbnailURL });
                      swatchHover = new HoverPop('#' + swatchID[i], '#' +swatchID[i], {'position': 'right', 'close':false, 'customClass':'swatch-hover', 'html':thumbnailHTML },0);
                  };
                  
          };
      });
})();
