// firebugx
if (!window.console || (!console.firebug && !$.browser.webkit))
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}

/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);


// lazyload
(function($){$.fn.lazyload=function(options){var settings={threshold:0,failurelimit:0,event:"scroll",effect:"show",container:window};if(options){$.extend(settings,options);}
var elements=this;if("scroll"==settings.event){$(settings.container).bind("scroll",function(event){var counter=0;elements.each(function(){if($.abovethetop(this,settings)||$.leftofbegin(this,settings)){}else if(!$.belowthefold(this,settings)&&!$.rightoffold(this,settings)){$(this).trigger("appear");}else{if(counter++>settings.failurelimit){return false;}}});var temp=$.grep(elements,function(element){return!element.loaded;});elements=$(temp);});}
this.each(function(){var self=this;if(undefined==$(self).attr("original")){$(self).attr("original",$(self).attr("src"));}
if("scroll"!=settings.event||undefined==$(self).attr("src")||settings.placeholder==$(self).attr("src")||($.abovethetop(self,settings)||$.leftofbegin(self,settings)||$.belowthefold(self,settings)||$.rightoffold(self,settings))){if(settings.placeholder){$(self).attr("src",settings.placeholder);}else{$(self).removeAttr("src");}
self.loaded=false;}else{self.loaded=true;}
$(self).one("appear",function(){if(!this.loaded){$("<img />").bind("load",function(){$(self).hide().attr("src",$(self).attr("original"))
[settings.effect](settings.effectspeed);self.loaded=true;}).attr("src",$(self).attr("original"));};});if("scroll"!=settings.event){$(self).bind(settings.event,function(event){if(!self.loaded){$(self).trigger("appear");}});}});$(settings.container).trigger(settings.event);return this;};$.belowthefold=function(element,settings){if(settings.container===undefined||settings.container===window){var fold=$(window).height()+$(window).scrollTop();}else{var fold=$(settings.container).offset().top+$(settings.container).height();}
return fold<=$(element).offset().top-settings.threshold;};$.rightoffold=function(element,settings){if(settings.container===undefined||settings.container===window){var fold=$(window).width()+$(window).scrollLeft();}else{var fold=$(settings.container).offset().left+$(settings.container).width();}
return fold<=$(element).offset().left-settings.threshold;};$.abovethetop=function(element,settings){if(settings.container===undefined||settings.container===window){var fold=$(window).scrollTop();}else{var fold=$(settings.container).offset().top;}
return fold>=$(element).offset().top+settings.threshold+$(element).height();};$.leftofbegin=function(element,settings){if(settings.container===undefined||settings.container===window){var fold=$(window).scrollLeft();}else{var fold=$(settings.container).offset().left;}
return fold>=$(element).offset().left+settings.threshold+$(element).width();};$.extend($.expr[':'],{"below-the-fold":"$.belowthefold(a, {threshold : 0, container: window})","above-the-fold":"!$.belowthefold(a, {threshold : 0, container: window})","right-of-fold":"$.rightoffold(a, {threshold : 0, container: window})","left-of-fold":"!$.rightoffold(a, {threshold : 0, container: window})"});})(jQuery);

jQuery.fn.eachDelay = function(callback, speed){
  return jQuery.eachDelay( this, callback, speed)
}

jQuery.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
};

$.fn.highlight = function(backgroundColor)

{
    var color = backgroundColor ? backgroundColor : "#f7f53d";
    var currentColor = $(this).css('background-color');

    $(this).animate({ backgroundColor: color }, 800).animate({ backgroundColor: currentColor });
}

jQuery.easing.def = "easeInOutExpo";

jQuery.extend({
  eachDelay: function(object,callback, speed){
    var name, i = -1, length = object.length, $div = $('<div>'), id;
    if (length === undefined) { //not an array process as object
      var arr = [], x = -1;
      for (name in object) arr[++x] = name;
      id = window.setInterval(function(){
       if( ++i === arr.length || callback.call(object[ arr[i] ], arr[i], object[ arr[i] ]) === false)
          clearInterval(id);
      }, speed);
    }
    else { //array-compatible element ie. [], jQuery Object
      id = window.setInterval(function(){
        if (++i === object.length || callback.call(object[i], i, object[i]) === false)
          clearInterval(id);
      }, speed);
    }
    return object;
  }
});

var Coal = Coal || {};

var lazyloadOptions = {
    placeholder: "/img/grey.gif",
    effect : "fadeIn",
    theshold: 300,
    failurelimit: 5
}

$(function() {
    $("input, textarea, select, button").uniform();

    if (!$.browser.msie) {
        $('.content .gallery img').lazyload(lazyloadOptions);
    }

    $('.top').click(function() {
        $(window).scrollTo(0, 500);
        return false;
    })

    if ($('.product .colors').length) {

        $('.product .color').live('click', function(e) {
            Coal.Products.activateColors($(this).find('a'));
            console.log('activatedColor');

            e.preventDefault();
            e.stopPropagation();
            return false;
        });

        $('.product .colors .color').each(function(index, color) {
            if ($(color).index() == 0) {
                Coal.Products.activateColors($(color).find('a'));
            };
        });

        $('span.addBag').live('click', function(e) {
            Coal.Products.activateSizingSkus($(this));
        });
    };

    $('.productNav .products a').live('click', function(e) {
         e.preventDefault();
         var slug = $(this).attr('href').split('/').pop();

         var historySlug = $(this).attr('href').replace(Coal.Products.naturalSlug, '');

         // $.history.load(historySlug);

         var top = $('#product_' + slug).position().top;

         // var offset = 0;
         var offset = $('.productNav').height() - $('#cartTrackerWrapper').height();

         $('.productNav .products li').removeClass('active');
         $(this).parent().addClass('active');

         var currentPos = $(window).scrollTop();
         var duration = Math.log(Math.abs((top - offset) - currentPos)) * 200;

         $(window).scrollTo(top - offset, duration, { axis: 'y'});

    });

    $('.gallery_image').css('cursor', 'pointer').live('click', function() {
      var $product = $(this).closest('.product');
      $product.find('.embiggen.active').trigger('click');
    });

        if ($('.productNav').length) {
            var productScrollTops = new Object();
            $('.product').each(function(index, item) {
                 productScrollTops[$(item).position().top] = $(item).attr('id');
            });

            function positionProductNavObject(){
                var productNavTopOffset = $('#cartTrackerWrapper').height() + $('#header').height();
                if ($(window).scrollTop() <= productNavTopOffset) {
                   $(".productNav").css({position: 'relative', top:0+"px"});
                   $('.productNav .productNavCart').fadeOut();
                   $('.content').css('marginTop', 0+"px");
                } else {
                    var calculatedTopValue = ($(window).scrollTop()); ;
                    //$(".productNav").css({width: '960px', position: 'absolute', top:calculatedTopValue+"px"});

                 $('.productNav').css({width: '880px'});

                 $(".productNav").css({position: 'fixed', top:0+"px"});
                 if ($('#cartTracker:visible').length) {
                     $('.productNav .productNavCart').fadeIn();
                 };

                 $('.content').css('marginTop', $('.productNav').height()+"px");
                };

         }
         positionProductNavObject();
         $(window)
             .scroll(positionProductNavObject)
             .resize(positionProductNavObject);

             //if we are on a product page, we should start set
            // the anchor of the page to where in the category its in
            var url = window.location.pathname;
            var urlChunks = url.split('/');
            //we know we're at a product URL by the scheme /:productId/:productslug
            var productSlug = urlChunks.pop();
            var productId = urlChunks.pop();

            var currentProduct = productSlug;

            if ($('#'+productSlug).length) {
                var top = $('#'+productSlug).position().top - $('.productNav').height();

                $(window).scrollTo(top);
            };
        };

});


Coal.Products = {
    initialProduct: '',
    naturalSlug: '',
    only_once: false,
    fancyboxOptions: {
      'titleShow'    : false,
      'transitionIn'  : 'fade',
      'transitionOut'  : 'fade',
      'autoDimensions' : true,
      'width' : 'auto',
      'height' : 'auto',
      'padding' : 0,
      'cyclic' : true
    },
    init: function() {
        $('.removeBag, a.addBag, .size').live('click', Coal.Products.addToCart);

        // Product Lightbox
        $("a.embiggen").fancybox(Coal.Products.fancyboxOptions);

        $('#product-list a.share').live('click', Coal.Products.activateShare);

        $('.productNav .categories a').live('click', Coal.Products.ajaxCatalog);


        // hide the collection list and make the categories list look like collections does normally
        if ($('.productNav .collections a').length == 1) {
            $('.productNav .collections').hide();
            $('.productNav .categories').addClass('collections');
        };

        Coal.Products.reformatProductNav($(".productNav ul.products"));

    },
    activateColors: function(link) {


        var root = link.closest('.color');
        var $product = root.closest('.product');
        var a = link;
        var selectedImageSelector = '#'+a.attr('rel');



        // hide all others, show selected item
        if (!$.browser.msie) {
            $product.find('.gallery_image').fadeOut();
            $product.find(selectedImageSelector).fadeIn({
                complete: function() {

                   $(selectedImageSelector).lazyload(lazyloadOptions);

                }
            });
        } else {
            $product.find('.gallery_image').hide();
            $product.find(selectedImageSelector).show();
        }

        // remove active class on other colors, then make current active
        root.closest('.colors').find('.color').removeClass('active');
        root.addClass('active');
        var index = root.index();
        // copies skuInfo markup to the "Add to shopping bag button";
        var skuInfo = root.find('.skuInfo').html();

        $product.find('.enlargeImage .embiggen').removeClass('active').eq(index).addClass('active');
        $product.find('.buyNow').hide(0, function() {
            $(this).show();
            $(this).html(skuInfo);

        });
    },
    activateSizingSkus: function(root) {
        var $product = root.closest('.product');

        $product.find('.buyNow li').eachDelay(function() {
            $(this).fadeIn();
        }, 200);
    },
    activateShare: function(e) {
       e.preventDefault();
       e.stopPropagation();

       var $product = $(this).closest('.product');
       var $share = $product.find('.sharePanel');
       var buttonPos = $(this).offset();

       $('#mainSharePanel').click(function(event) {
         event.stopPropagation();
       }).html($share.html()).css({
         top: buttonPos.top-177,
         left: buttonPos.left-40
       }).fadeIn();

       $('input', '#mainSharePanel').click(function(event) {
         $(this).select();
       });

       $('a.copyUrl', '#mainSharePanel').click(function(event) {
         $('input', '#mainSharePanel').select();
         $('<p>use Cmd+C on a Mac, CTRL+C in Windows</p>').insertAfter($(this));
       });

       $(window).click(function(event) {
         $('#mainSharePanel').fadeOut();
       });

       return false;
    },
    reformatProductNav: function(list) {
        //console.log('reformatProductNav');
        //console.info(list.html());
        list.each(function() {
          var listItem = $(this);
          var size = $('body').hasClass('considered') ? 5 : 8;
          var current_size = 0;
          if (listItem.children().length > size) {
              listItem.children().each(function() {
                if (++current_size > size) {
                  var new_list = $("<ul class=\"col3 products\"></ul>").insertAfter(listItem);
                  listItem = new_list;
                  current_size = 1;
                }
                listItem.append(this);
              });
          };

        });
    },
    ajaxCatalog: function(e) {
        e.preventDefault();
        e.stopPropagation();

        if ($('#fader').length == 0) {
            var fader = $('<div id="fader"></div>').css({
                display: 'none',
                position: 'absolute',
                width: '100%',
                height: '100%',
                backgroundPosition: '50% 0'
            }).prependTo('body');
        };

        $('#loader').fadeIn();
        $(window).scrollTo(0, 500, { axis: 'y'});
        var $link = $(this);
        var href = $link.attr('href');

        var slug = href.replace(Coal.Products.naturalSlug, '');

        $.history.load(slug);

        var type = $link.closest('ul').attr('class').replace('col3 ', '').replace('col4', '');
        //console.log(type);

        $link.closest('ul').find('li').removeClass('active');
        $link.parent().addClass('active');

        $.getJSON(href, function(json) {
            products = json.products;
            $('#product-list').animate({paddingTop: '1000px'}, {
                duration: 500,
                complete: function() {
                    $('.product').remove();
                    // load in new products
                    for (var i = 0; i < products.length; i++){
                      $('#product-list').append(products[i]);
                    };

                    $('#product-list').attr('class', 'bg-' + href.split('/').slice(2, 5).join('-'));

                    if ('url('+json.background+')' != $('body').css('background-image')) {

                       $(new Image()).load(function() {
                           // alert('image loaded');
                           $('#fader').css({
                               backgroundImage: 'url('+json.background+')'
                           }).fadeIn({
                               duration: 700,
                               complete: function() {
                                   // alert('fadeIn complete!');
                                   $('body').css('background-image', 'url('+json.background+')');
                                   $('#fader').fadeOut(700);
                               }
                           });
                       }).attr('src', json.background);
                    };

                    $('#product-list').animate({paddingTop: '0px'}, {
                      duration: 700,
                      complete: function() {
                          if (!$.browser.msie) {
                              $('#product-list .gallery img').lazyload(lazyloadOptions);
                          }
                          $("a.embiggen").fancybox(Coal.Products.fancyboxOptions);

                          $('.product .colors .color').each(function(index, color) {
                              if ($(color).index() == 0) {
                                  Coal.Products.activateColors($(color).find('a'));
                              };
                          });
                      }
                    });
                }
            });

            //navigation
            $('<div id="tempNav">').html(json.nav).hide().appendTo('body');
            var navCount = $('.productNav').find('ul.products').length;
            $('.productNav').find('ul.products').reverse().eachDelay(function() {
                $(this).fadeOut(400, function() {
                    navCount--;

                    if (navCount == 0) {

                        Coal.Products.reformatProductNav($('#tempNav ul.products'));
                        var productNav = $('#tempNav').find('ul.products');

                        productNav.eachDelay(function() {
                            $(this).hide().appendTo('.productNav').fadeIn(300);
                        }, 300);

                        $('#tempNav').remove();
                    };

                    $(this).remove();
                });

            }, 200);

            $('#loader').fadeOut();

        });

    },
    addToCart: function(e) {
         e.preventDefault();
         var href = '';
         var $link = null;
         var sizing = false;
         var $buyNow = $(this).closest('.buyNow');
         var img = '<img src="/img/addBag.png" />';
         if ($(this).hasClass('size')) {
             href = $(this).attr('href');
             $link = $buyNow.find('.addBag');
             sizing = true;
         } else {
             $link = $(this);
             href = $link.attr('href');
         }

         if (sizing) {
             $buyNow.find('ul').fadeOut().remove();
         }

         $link.html(img+' adding to cart...')

         $.ajax({
             type: 'get',
             url: href,
             dataType: 'json',
             success: function(json) {
                 if (json.status == 'error') {
                     $link.parent().html(img+' '+json.error);
                     return;
                 };

                 var cartHtml = $('#cartTracker');

                 cartHtml.find('.cartCount strong').text(json.cartCount);
                 cartHtml.find('.cartCount span').text($(json.cartHtml).find('.cartCount span').text());
                 $('.productNav .productNavCart a').text('VIEW BAG ('+json.cartCount+')');

                 if (json.cartCount == 0) {
                     cartHtml.fadeOut();
                     $('.productNav .productNavCart').fadeOut();
                 } else {
                     cartHtml.fadeIn();
                     $('.productNav .productNavCart').fadeIn();
                 }

                 if (json.status == 'added') {
                     $link.removeClass('addBag').html(Coal.Products.cancelImg(json.item.sku)+' ' + json.item.title+' '+json.item.color +(json.item.size != 'OSFM' ? ' ' + json.item.size : ''));
                 } else {
                     $link.parent().html(img+' item removed');
                     return;
                 }

             },
             error: function(json) {
                 $link.html(img+' error: '+json.error);
             }
         });

         return false;
    },
    cancelImg: function(sku) {
        return '<a class="removeBag" href="/checkout/remove/sku/'+sku+'"><img src="/img/cancelBag.png" /></a> ';
    },
    positionCartTracker: function() {
        var cartTopOffset = $('header').height() + $('.productNav').height();

        function positionCartObject(){
            if ($(window).scrollTop() > cartTopOffset) {
                var calculatedTopValue = ($(window).scrollTop());
                leftPos = $('#cartTracker').offset().left

              $("#cartTracker").css({position: 'fixed', top:"0px", left: leftPos+"px"});
            } else {
                var calculatedTopValue = cartTopOffset;
              $("#cartTracker").css({position: 'absolute', top:calculatedTopValue+"px", left: '100%'});
            };
      }
      positionCartObject();
      $(window)
        .scroll(positionCartObject)
        .resize(positionCartObject);
    },
    getCartCount: function() {
        $.getJSON('/checkout/cart-count', function(json) {
            var cartHtml = $(json.cartHtml);

            cartHtml.hide().appendTo('#cartTrackerWrapper');


            if (parseInt(json.cartCount) > 0) {
                cartHtml.fadeIn();
                $('.productNav .productNavCart a').text('VIEW BAG ('+json.cartCount+')');
            };
        });
    },
    seasonsTimeout: null,
    initSeasonsNav: function() {
        $('<img id="dropdownArrow" src="/img/top.png">').appendTo('#menu-catalogNav');

        $('#menu-catalogNav').mouseenter(function() {
            clearTimeout(Coal.Products.seasonsTimeout);
            Coal.Products.openCollectionsNav();
        });
        $('#menu-catalogNav').mouseleave(Coal.Products.closeCollectionsNav);
        $('#collectionsNav').mouseenter(function() {
            clearTimeout(Coal.Products.seasonsTimeout);
        });
        $('#collectionsNav').mouseleave(Coal.Products.closeCollectionsNav);

    },
    openCollectionsNav: function() {
        $('#menu-catalogNav').addClass('active');
        $('#collectionsNav').slideDown('fast');
    },
    closeCollectionsNav: function() {
         Coal.Products.seasonsTimeout = setTimeout(function() {
             $('#menu-catalogNav').removeClass('active');
             $('#collectionsNav').slideUp('fast');
         }, 500);
     }
}

/**
 * Coal.Checkout
 */
Coal.Checkout = {
    init: function() {
        if ($('#use_same').length) {
            if($('#use_same').is(':checked')) {
                $('#shipping_address').hide();
            }

            $('#use_same').click(this.copyBillingAddressData);
        };

        $('#loginForm').live('submit', this.handleLoginDuringCheckout)

        $('#couponCodeForm').live('submit', this.handleCouponCodeInput);
    },
    copyBillingAddressData: function() {
        if (!$(this).is(':checked')) {
            $('#billing_address input, #billing_address select').each(function(index, item) {
                var name = $(item).attr('name');
                var value = $(item).val();

                if (value != '') {
                    var matchingElement = $('#shipping_address').find('input[name="'+name+'"], select[name="'+name+'"]');
                    matchingElement.val(value);
                    $.uniform.update(matchingElement);
                };

            });

            $('#shipping_address').slideDown();


        } else {
            $('#shipping_address').slideUp();
        }
    },
    handleCouponCodeInput: function(e) {
        var form = $(this).closest('form');
        var box = $(this).closest('div');
        var url = form.attr('action');

        $.ajax({
            type: 'post',
            data: form.serialize(),
            url: url,
            dataType: 'json',
            success: function(data) {
                if (data.success == true) {
                    box.slideUp();

                    if ($('.discount_title').text() == '') {
                       $('.discount_title').html('Discount:<br />');
                    };

                    $('.discount').html(data.coupon_savings+'<br />').highlight();
                    $('.sub_total').html(data.sub_total+'<br />').highlight();
                    $('.grand_total').text(data.grand_total).highlight();

                } else {
                    var form = $('#couponCodeForm');
                    //console.log('reset height');
                    form.find('dd ul').hide();
                    var message = $('<ul class="errors"><li>'+data.error+'</li></ul>').appendTo(form.find('#coupon_code-element'));
                }
            },
            error: function(data) {
                var form = $('#couponCodeForm');
                //console.log('reset height');
                form.find('dd ul').hide();
                var message = $('<ul class="errors"><li>'+data.error+'</li></ul>').appendTo(form.find('#coupon_code-element'));
            }
        });

        e.preventDefault();
    },
    handleLoginDuringCheckout: function(e) {
        form = $(this).closest('form');
        box = $('.existingUsers');
        var url = form.attr('action');

        $.ajax({
            type: 'post',
            data: form.serialize(),
            url: url,
            dataType: 'json',
            beforeSend: function(data) {
               //console.log('beforeSend!');
               height = form.height();

               form.find('dl').fadeOut(400);

               var message = $('<h2 class="middle">Logging In...</h2>').hide();
               console.log('setting height to '+height+'px');
               form.css('height', height+'px');

               message.prependTo(form).fadeIn().show();
            },
            success: function(data) {
                if (data.success == true) {
                    var name = '';

                    $('#contact_information').find('input, select').each(function(index, item) {
                        name = $(item).attr('id').replace('contact_information-', '');
                        $(item).val(data.form.contact_information[name]);
                        $.uniform.update(item);
                    });

                    $('#billing_address').find('input, select').each(function(index, item) {
                        name = $(item).attr('id').replace('billing_address-', '');
                        $(item).val(data.form.billing_address[name]);
                        $.uniform.update(item);
                    });

                    $('#shipping_address').find('input, select').each(function(index, item) {
                        name = $(item).attr('id').replace('shipping_address-', '');
                        $(item).val(data.form.shipping_address[name]);
                        $.uniform.update(item);
                    });

                    box.slideUp();
                    $('#shipping_address').show();
                    $('#use_same').closest('div.element').hide();
                    $('#new_account').hide();

                    var firstName = data.form.contact_information['name'].split(' ')[0];
                    $('.newCustomers').find('h2').text('Welcome back, '+firstName);
                    $('.newCustomers').find('p:first').text('We missed you.')
                } else {
                    //console.log('success false');
                    // access the queue and stop any in process animation

                    var form = $('#loginForm');
                    //console.log('reset height');
                    form.clearQueue();
                    form.css('height', '');
                    form.find('dd ul').hide();
                    var message = $('<ul class="errors"><li>'+data.errors+'</li></ul>').appendTo(form.find('#email-element'));

                    form.find('h2').hide().remove();
                    form.find('dl').fadeIn();
                }
            },
            error: function(data) {
                //console.log('error!');
                var form = $('#loginForm');
                form.clearQueue().css('height', '');
                form.find('h2').remove();
                form.find('dl').show();
            }
        });

        e.preventDefault();
    }
}

/**
 * Coal.Homepage
 */
Coal.Homepage = {
  speed: 1750,
  current: null,
  slideshow: {
    id: null,
    reset: null,
    timeout: null,
    speed: 15000
  },
  init: function () {
      if ($('.slide').length > 1) {
          $('.carousel li.next a').click(this.nextLinkListener);
        $('.carousel li.back a').click(this.backLinkListener);

        this.startSlideshow();
      } else {
          $('.carousel li.next a').hide();
        $('.carousel li.back a').hide();
      };

        // this.__adjustBackground(); // Need to resize the initial image
        var activeImg = $('img', '.slide_bg.active');
        if(activeImg.get(0).complete) {
            Coal.Homepage.__adjustBackground();
            activeImg.animate({
                opacity: 1
            });
        } else {
            activeImg.load(function () {
                Coal.Homepage.__adjustBackground();
                activeImg.animate({
                    opacity: 1
                });
            });
        }

        // 1337 HACK
        // setTimeout(function () {
        //     var correct = $('.slide_bg:eq(1)');
        //     $('.slide_bg:eq(0) img').css({
        //         width: parseInt(correct.css('width')),
        //         height: parseInt(correct.css('height')),
        //         top: correct.css('top')
        //     });
        // }, 10);
        $(window).resize(this.__adjustBackground);
        setTimeout(function () {
            $(window).resize();
        }, 10);
  },
  startSlideshow: function () {
    if (this.slideshow.id !== null) {
      window.clearInterval(this.slideshow.id);
    }

    this.slideshow.id = setInterval(function () {
      Coal.Homepage.switchSlides('next');
    }, this.slideshow.speed);
  },
  /**
   * nextLinkListener -> (Event)
   * it's in jQuery context so you must use Coal.Homepage
   */
  nextLinkListener: function (e) {
    e.preventDefault();

    Coal.Homepage.switchSlides('next');
  },
  /**
   * backLinkListener -> (Event)
   * it's in jQuery context so you must use Coal.Homepage
   */
  backLinkListener: function (e) {
    e.preventDefault();

    Coal.Homepage.switchSlides('back');
  },
  /**
   * We need to find the next or previous slide, if it's the
   * last one, loop all the way back to the next one so it's
   * infinite.
   */
  findNextSlide: function (direction) {
    var total   = $('.slide', '.carousel').length,
      current = $('.slide.active', '.carousel'),
      selected;

    if (direction == 'next') {
      selected = (current.next('.slide').length == 0) ? $('.slide:eq(0)', '.carousel') : current.next('.slide');
    } else {
      selected = (current.prev('.slide').length == 0) ? $('.slide:eq('+ (total-1) +')', '.carousel') : current.prev('.slide');
    }

    return selected;
  },
  switchSlides: function (direction) {
        var self    = this,
            el      = this.findNextSlide(direction),
            nextId       = this.current = el.attr('id').substr(6),
            wHeight     = $(window).height(),
            text     = el.attr('data-subtitle');

    var activeSlide = $('.slide_bg.active');
    activeSlide.removeClass('active');

        $('.slide_bg').removeClass('reset');

    var nextSlide = $('#slide_bg_'+ nextId);
    nextSlide.addClass('active');
    this.__adjustBackground();

    // If they support css, let the browser do the animation.
    if (this.__supportsCSS3()) {
        if(direction == 'next') {
            activeSlide.css({
                height: wHeight,
                marginTop: -wHeight
            }, this.speed, 'linear');
                nextSlide.css({
                    height: wHeight,
                    marginTop: 0
                }, this.speed, 'linear');
            } else {
                nextSlide.removeClass('active').addClass('reset').css({
                    marginTop: -wHeight,
                    height: wHeight
                })

                setTimeout(function () {
                    nextSlide.removeClass('reset').addClass('active').css({
                        marginTop: 0
                    });
                activeSlide.css({
                    height: wHeight,
                    marginTop: wHeight
                });
                }, 1);
            }
    } else {
        $('.slide_bg').css('z-index', '1');
      nextSlide.css('z-index', '2').animate({
        marginTop: 0
      }, this.speed, 'linear');
    }

        // Need to reset the backgrounds because CSS doesn't have callbacks
        if (this.slideshow.reset !== null) {
            window.clearTimeout(this.slideshow.reset);
        }
        this.slideshow.reset = window.setTimeout(this.__resetBackgrounds, this.speed);

        // Resets page text
        if (this.slideshow.timeout !== null) {
            window.clearTimeout(this.slideshow.timeout);
        }
        this.slideshow.timeout = window.setTimeout(function () {
            self.switchSlideText(el, text, direction);
        }, this.speed/2);
  },
  switchSlideText: function (el, text, direction) {
    $('.carousel ul .subtitle').fadeOut(function () {
      $(this).text(text).fadeIn();
    });

    $('.slide.active', '.carousel').fadeOut(function () {
      $(this).removeClass('active');

      el.fadeIn(function () {
        $(this).addClass('active');
      });
    });
  },
  fadeInContent: function () {
      var wrap = $('#wrap'),
          preloader = $('#preloader'),
          loader = $('#loader'),
          cart = $('#cartTrackerWrapper'),
          cartHidden = $('#cartTrackerWrapper').css('display') == 'none',
          wrapHidden = $('#wrap').css('display') == 'none',
          image = preloader.attr('data-load-image');

      $(new Image()).load(function () {
          preloader.css({
              backgroundRepeat: 'no-repeat',
              backgroundImage: 'url(' + image + ')',
              backgroundAttachment: 'fixed'
          });
          setTimeout(function () {
              preloader.fadeOut();
              loader.fadeOut();
              wrap.fadeIn(500, function() {
                      if (Coal.Products.initialProduct != '') {
                          var offset = $('.productNav').height() - $('header').height();

                          var position = ($(Coal.Products.initialProduct).offset().top || 0) - offset;
                          $(window).scrollTo(position, 500);
                      };
                  });
              cart.fadeIn();
              if (!$.browser.msie) {
                  $('.content .gallery img').lazyload(lazyloadOptions);
              }
          }, 2000);
        }).error(function () {
            // die?
        }).attr('src', image);
  },
  __resetBackgrounds: function () {
    // Starting the new interval after full transition is complete.
    Coal.Homepage.startSlideshow();

    $('.slide_bg:not(.active)').addClass('reset').css({
      marginTop: '100%',
      zIndex: 1
    });
  },
  __adjustBackground: function () {
    var image = $('img', '.slide_bg.active'),
      imgRatio = image.width() / image.height(),
      bgWidth = $(document).width(),
      bgHeight = bgWidth / imgRatio,
      windowHeight = $(document).height();
        // alert(imgRatio);
        // alert(bgHeight + " < " + windowHeight);
    if(bgHeight < windowHeight && !isNaN(bgHeight)) {
      bgHeight = windowHeight;
      bgWidth = bgHeight * imgRatio;
    }
        // alert(bgHeight);
        // if(isNaN(bgHeight)) bgHeight = windowHeight;

    var bgOffsetW = Math.round((bgWidth - windowHeight) / 2);
    var bgOffsetH = Math.round((bgHeight - windowHeight) / 2);

        // console.log('==============');
        // console.log("bgOffsetW:", bgOffsetW);
        // console.log("bgOffsetH:", bgOffsetH);
        // console.log("bgHeight:", bgHeight);
        // console.log("bgWidth:", bgWidth);

    image.width(bgWidth).height(bgHeight)
         .css({ position: 'absolute', top: '-' + bgOffsetH + 'px', right: '0px' });
  },
  __supportsCSS3: function () {
        return ($.browser.webkit && parseFloat($.browser.version) > 400);// || ($.browser.mozilla && parseFloat($.browser.version) >= 2);
        // return false;
  }
}


/**
 * Coal.About
 */
Coal.About = {
    paused: false,
    id: null,
  init: function () {
    $('.friends_list a').click(this.toggleFriend);
    $('.friends_list a:eq(0)').attr('class', 'active');

    if ($('.friends_list a').length) {
        var count = $('.friends_list a').length;
        Coal.About.friendLoop();
        $('.friends_list a').bind('loop', this.toggleFriend);
        id = setInterval(this.friendLoop, 5000*count);
    };
  },
  friendLoop: function() {
        $('.friends_list a').eachDelay(function() {
            if (!Coal.About.paused) {
                 $(this).trigger('loop');
            };
    }, 5000);
  },
  toggleFriend: function (e) {
      if(e.type == 'click') {
          Coal.About.paused = true;
          clearInterval(Coal.About.id);
      }

    e.preventDefault();

    var id = $(this).parents('li').prevAll().size();

    // Add active class to the current link, and remove the existing
    $('.friends_list .active').removeClass('active');
    $(this).addClass('active');

    $('.content .friends .active').fadeOut(500, function () {
      $(this).removeClass('active');

      $('.friends .friend:eq('+ id +')').fadeIn(500, function () {
        $(this).addClass('active')
      });
    });
  }
}

// Form Swap Values in footer
$(function() {
  swapValues = [];
  $("#siteSearch, #location").each(function(i){
    swapValues[i] = $(this).val();
    $(this).focus(function(){
      if ($(this).val() == swapValues[i]) {
        $(this).val("");
      }
    }).blur(function(){
      if ($.trim($(this).val()) == "") {
        $(this).val(swapValues[i]);
        }
      });
  });

  $('#footerSearch').find('.button').click(function(e) {
      $(this).closest('form').submit();
  });

  Coal.Products.getCartCount();
  Coal.Products.initSeasonsNav();
    Coal.Homepage.fadeInContent();
});
