
/* 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.email + " 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 zappmeHover = new ClickPop("#shipping-options a", "#shipping-options a", {'position':'top', 'close':false, 'popoverId':'shipping-options-popover', 'href':'/popovers/shippingOptions.zml'});    
});

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=450';
  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});

            }
          }
        }
    };
    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 availabilityError = new Popover({'position':'bottom', 'title':'Item Out of Stock', 'popoverId': 'avaPop'});
    var availabilityPopover = function(available) {
        console.log('avPopFunc');
        if (!available) {
            var errorElement = new Element('p');
            var brElement = new Element('br');
            
            var notifyElement = noSizeNotify ? new Element('p'):
                                               new Element('a', {'href':'http://www.zappos.com/bin/notifyme?p='+ productId + 
                                                 '&size_id=' + this.get("sizeId") +
                                                 '&width_id='+ this.get('widthId') +
                                                 '&color_id='+ this.get('colorId'),
                                                 'text':'Notify Me When This Combination Becomes Available.'});
            var popWindowDefaults = 'location=0, statusbar=0, menubar=0, width=450, height=450';
            var PopUp= function(url, name) {
              window.open(url,name,popWindowDefaults);
            }
            notifyElement.addEvent('click', function() {
              PopUp(this.href, 'newWindow');
              return false;
            });
            var htmlString = "We're sorry, this item is currently unavailable in <br/>Size: ";
            htmlString += stockSizes.get(this.get('sizeId'));
            htmlString += "<br/>Color: ";
            htmlString += stockColors.get(this.get('colorId'));
            htmlString += "<br/>Width: ";
            htmlString += stockWidths.get(this.get('widthId'));
            errorElement.set('html', htmlString);
            errorElement.grab(brElement);
            errorElement.grab(notifyElement);

            availabilityError.popover.empty();
            availabilityError.options.html = errorElement;
            availabilityError.display(document.getElement(size_pop_to));
        } else {
            availabilityError.hide();
        }
    };
    productObserver.addCallback('available', availabilityPopover);
    
    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.'});
                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);
    
    if(document.getElement('#sharing .add-to-favorites')){
      document.getElement('#sharing .add-to-favorites').addEvent('click', function(e){
        var currStock = getCurrentStock();
        e.preventDefault();
        var noAdd = new Popover({'position':'top', 'title':'OOOPS!'});      
        if (currStock.length > 0) {
          var href = this.get('href');
          href= href.split('?')[0];
          document.location = href + '?stockId=' + currStock[0]['stockId'];
        } else if (document.getElement('#size').value != "")  {
          noAdd.options.html = new Element('p', {'text':'We\'re sorry! This product combination is out of stock right now and we can\'t add it to your Favorites.'});
          noAdd.display(document.getElement('#sharing'));
        } else {
          noAdd.options.html = new Element('p', {'text':'Please make sure that a size, color, and width are selected so we can add this product to your Favorites!'});
          noAdd.display(document.getElement('#sharing'));
        }
      });
    }  

    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 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 });
                  };
                  
          };
      });
})();
