var ShopMenu = {};
ShopMenu.init = function() {
  if ($('#shop-overlay').length > 0) {
    var timeout = null;
  
    function show() {
      clearTimeout(timeout);
      $('li.nav-shop').addClass('hover');
      $('#main').hide();
      $('.popup').hide();
      $('#shop-overlay').show();
    }
  
    function hide() {
      timeout = setTimeout(function() {
        $('li.nav-shop').removeClass('hover');
        $('#main').show();
        $('.popup').show();
        $('#shop-overlay').hide();
      }, 200);
    }
  
    $('li.nav-shop, #shop-overlay').hover(
      function() { show(); },
      function() { hide(); }
    );
  }
};



var Popup = function(tabs, options) {
  this.options = options;
  this.container = $(options.appendTo || 'body');
  this.tabs = tabs;
  this.current = null;
  
  var self = this;
  
  $('a', tabs).click(function() {
    $('li', tabs).removeClass('current');
    $('> .popup', self.container).remove();
  
    if (options.onHide) options.onHide();
    
    var url = $(this).attr('href');
    
    if (self.current == url) {
      self.current = null;
    } else {
      self.current = url;
      
      $(this).parent().addClass('current');
      
      if (options.onShow) options.onShow();
      
      if (Popup.cache[url]) {
        self.container.append(Popup.cache[url]);
        self.afterShow();
      } else {
        var popup = $('<div class="popup loading"><div class="frame" /><div class="right" /><div class="bottom" /></div>').appendTo(self.container);
        
        if ($('body').hasClass('stretch')) {
          $('.frame', popup).height($('#content').height() - 172);
        }
        
        $('.right', popup).css('height', popup.height());
        
        $.get(url, {}, function(data) {
          Popup.cache[url] = data;
          popup.replaceWith(data);
          
          self.afterShow();
        });
      }
      
      popup = $('> .popup', self.container);
    }
    
    return false;
  });
  
  this.afterShow();
};
Popup.init = function(tabs, options) { return new Popup(tabs, options); };
Popup.cache = {};
Popup.prototype.afterShow = function() {
  var self = this;
  var popup = $('> .popup', this.container);
  var frame = $('.frame', popup);
  var scroll = $('.scroll', popup);
  
  $('img:first', scroll).appendTo(frame);
  
  scroll.jScrollPane({ scrollbarMargin: 20, scrollbarWidth: 6 });
  $('input:visible:first', popup).focus();
  $('table tbody tr:even', popup).addClass('odd');
  
  if ($('body').hasClass('stretch')) {
    frame.css('padding-top', $('#content').height() - 445);
  }
  
  $('.right', popup).css('height', popup.height());
  
  $('form', popup).submit(function() {
    var url = $(this).attr('action');
    
    popup.html('<div class="frame" /><div class="right" /><div class="bottom" />');
    
    if ($('body').hasClass('stretch')) {
      $('.frame', popup).height($('#content').height() - 172);
    }
    
    $('.right', popup).css('height', popup.height());
    popup.addClass('loading');
    
    $.post(url, $(this).serialize(), function(data) {
      popup.replaceWith(data);
      self.afterShow();
    });
    
    return false;
  });
  
  var close = $('<a href="#" class="close">Close</a>').appendTo(popup);
  close.click(function() {
    $('li', self.tabs).removeClass('current');
    $('> .popup', self.container).remove();
    $('#main').removeClass('hidden');
    self.current = null;
    
    return false;
  });
};


var Gallery = {};
Gallery.init = function() {
  var large = $('#gallery img#large-image');
  
  $('#gallery #thumbnails a').click(function() {
    large.hide();
    
    large.attr('src', $(this).attr('href'));
    large.attr('alt', $(this).attr('alt'));
    
    large.one('load', function() { large.show(); });
    
    return false;
  });
};


var Timeline = {};
Timeline.init = function() {
  var timeline = $('#timeline');
  var previousButton = $('a.previous', timeline);
  var nextButton = $('a.next', timeline);
  
  previousButton.hide();
  
  nextButton.click(function() {
    var current = $('li:visible', timeline);
    var next = current.next('li');
    
    nextButton.hide();
    previousButton.hide();
    
    next.css({ left: 873 }).show().animate({ left: 0 });
    current.animate({ left: -873 }, function() {
      $(this).hide();
      
      if (!next.is(':first-child')) previousButton.show();
      if (!next.is(':last-child')) nextButton.show();
    });
    
    return false;
  });
  
  previousButton.click(function() {
    var current = $('li:visible', timeline);
    var next = current.prev('li');
    
    nextButton.hide();
    previousButton.hide();
    
    next.css({ left: -873 }).show().animate({ left: 0 });
    current.animate({ left: 873 }, function() {
      $(this).hide();
      
      if (!next.is(':first-child')) previousButton.show();
      if (!next.is(':last-child')) nextButton.show();
    });
    
    return false;
  });
};


var News = {};
News.init = function() {
  var news = $('#news');
  var previousButton = $('a.previous', news);
  var nextButton = $('a.next', news);
  
  $('.post img').each(function() {
    var li = $(this).parents('li');
    $(this).appendTo(li);
  });
  
  $('.post p:empty').remove();
  
  previousButton.hide();
  
  nextButton.click(function() {
    var current = $('li:visible', news);
    var next = current.next('li');
    
    nextButton.hide();
    previousButton.hide();
    
    next.css({ left: 873 }).show().animate({ left: 0 });
    current.animate({ left: -873 }, function() {
      $(this).hide();
      
      if (!next.is(':first-child')) previousButton.show();
      if (!next.is(':last-child')) nextButton.show();
    });
    
    return false;
  });
  
  previousButton.click(function() {
    var current = $('li:visible', news);
    var next = current.prev('li');
    
    nextButton.hide();
    previousButton.hide();
    
    next.css({ left: -873 }).show().animate({ left: 0 });
    current.animate({ left: 873 }, function() {
      $(this).hide();
      
      if (!next.is(':first-child')) previousButton.show();
      if (!next.is(':last-child')) nextButton.show();
    });
    
    return false;
  });
  
  $('#news a[href="/newsletter"]').click(function() { $('#footer .nav-newsletter a').click(); return false; })
};


jQuery.fn.disable = function() {
  $(this).each(function() {
    $(this).attr('disabled', 'disabled');
  });
};
jQuery.fn.enable = function() {
  $(this).each(function() {
    $(this).removeAttr('disabled');
  });
};
jQuery.fn.input = function(handler) {
  $(this).bind('input', handler);
  $(this).bind('blur', handler);
  $(this).bind('change', handler);
  
  if (jQuery.browser.msie) {
    function triggerInput() { $(this).trigger('input'); }
    $(this).keydown(triggerInput).keyup(triggerInput);
  }
};

var Item = {};
Item.variations = {};
Item.init = function() {  
  Popup.init('#item-tabs', { appendTo: '#item' });
  
  $('#zoom').zoom();
  
  $('#thumbnails a').click(function() {
    Item.focusImage(this);
    
    var ref = $(this).attr('class').replace(/\s*current\s*/, '');
    if (ref != '') { Item.selectVariation(ref); }
    
    return false;
  });
  
  $('ul.variations div').click(function() { $(this).prev('a').click(); });
  
  $('ul.variations li').hover(function() {
      $('ul.variations li a').hide();
      $('a', this).show();
    }, function() {
      $('ul.variations li a').hide();
      $('ul.variations li.current a').show();
    });
    
  $('#size').change(function() {
    // Update quantities for selected size
    var max = parseInt($(this).find('option:selected').attr('data-max')) || 5;
    $('#quantity').html(Item.quantityOptions(max));
  });
  
  $('ul.variations a').click(function() {
    var variation = $(this).attr('href').match(/#(.*)/)[1];
    Item.selectVariation(variation);
  });
  
  $('#thumbnails a:first').addClass('current');
  $('ul.variations a:first').click();
};
Item.focusImage = function(link) {
  $('#zoom').zoom('out', { animate: false });
  $('#zoom').zoom('src', $(link).attr('href'));
  
  $(link).parent().siblings().find('a').removeClass('current');
  $(link).addClass('current');
};
Item.selectVariation = function(variation) {
  var details = Item.variations[variation];
  
  $('.variation').hide();
  $('.' + variation).show();
  
  $('ul.variations li').removeClass('current');
  $('ul.variations a[href="#' + variation + '"]').parent('li').addClass('current');
  
  $('#variation_id').val(details.id);
  
  if (details.sizes.length > 0) {
    // Available sizes
    $('#size').html(Item.sizeOptions(details.sizes));
    $('#size').change();
    $('.options').show();
    $('#submit').show();
    $('#sold-out').hide();
  } else {
    // Sold out
    $('.options').hide();
    $('#submit').hide();
    $('#sold-out').show();
  }
  
  // Change image if current image is not for this variation
  var currentThumbnail = $('#thumbnails a.current');
  if (!currentThumbnail.hasClass(variation) && currentThumbnail.attr('class').replace(/\s*/, '') != '') {
    var img = $('#thumbnails a.' + variation + ':first');
    if (img.get(0)) { Item.focusImage(img); }
  }
  
  $('ul.variations li a').hide();
  $('ul.variations li.current a').show();
};
Item.sizeOptions = function(sizes) {
  return $.map(sizes, function(size) {
    return '<option value="' + size.id + '" data-max="' + size.max + '">' + size.label + '</option>';
  }).join();
};
Item.quantityOptions = function(max) {
  var result = [];
  
  for (var i = 1; i <= max; ++i) {
    result = result.concat('<option value="' + i + '">' + i + '</option>');
  }
  
  return result.join();
};


var Cart = {};
Cart.init = function() {
  var cart = $('#shopping-cart');
  var form = cart.parents('form');
  
  function updateTotals() {
    var subtotal = 0;
    
    $('tbody tr', cart).each(function() {
      var quantity = parseInt($('select.quantity', this).val());
      var price = parseFloat($('td.price', this).text().slice(1));
      var total = quantity * price;
      
      $('td.total', this).text('$' + total.toFixed(2));
      
      subtotal += total;
    });
    
    $('tfoot tr td:last', cart).text('$' + subtotal.toFixed(2));
  }
  
  $('select.quantity', cart).change(function() {
    var url = form.attr('action');
    $.post(url, form.serialize() + '&update=true');
    updateTotals();
  });
  
  $('td.remove a').click(function() {
    var row = $(this).parents('tr');
    var select = row.find('select.quantity')
    
    select.val(0);
    select.change();
    row.remove();
    
    return false;
  });
};


var Checkout = {};
Checkout.init = function() {
  $('#order_billing_same_as_shipping').click(Checkout.updateBilling);
  Checkout.updateBilling();
  
  $('#ccv-tooltip').appendTo('body');
  $('a.open-tooltip').hover(function() {
    var tooltip = $($(this).attr('href'));
    var offset = $(this).offset();
    tooltip.show();
    tooltip.css({ top: offset.top - 125, left: offset.left - 108 });
  }, function() {
    var tooltip = $($(this).attr('href'));
    tooltip.hide();
  }).click(function() { return false; });
  
  $('a.return-policy').click(function() { $('li.nav-terms a').click(); return false; });
  
  $('.left .field input, .left .field select').input(function() {
    var field = $('#' + this.id.replace(/_shipping_/, '_billing_'));
    if (field.is(':disabled')) {
      var value = $(this).val();
      field.val(value);
    }
  });
  
  $('.left .country select').change(function() {
    var right = $('.right');
    
    if (right.hasClass('disabled')) {
      if ($(this).val() == 'United States') {
        right.find('.international').hide();
        right.find('.us').show();
      } else {
        right.find('.us').hide();
        right.find('.international').show();
      }
    }
  });
  
  $('.column').each(function() {
    var country = $(this).find('.country select').val();
    if (country == 'United States') {
      $(this).find('.international').hide();
    } else {
      $(this).find('.us').hide();
    }
  });
  
  $('.country select').change(function() {
    var country = $(this).val();
    var column = $(this).parents('.column');
    
    if (country == 'United States') {
      column.find('.international').hide();
      column.find('.us').show();
    } else {
      column.find('.us').hide();
      column.find('.international').show();
    }
  });
};
Checkout.updateBilling = function() {
  var checkbox = $('#order_billing_same_as_shipping');
  var column = checkbox.parents('.column');
  var fields = $('.field input, .field select', column);
  
  if (checkbox.is(':checked')) {
    column.addClass('disabled');
    fields.disable();
    
    fields.each(function() {
      var field = $('#' + this.id.replace(/_billing_/, '_shipping_'));
      var value = field.val();
      $(this).val(value);
    });
    
    var country = column.find('.country select').val();
    if (country == 'United States') {
      column.find('.international').hide();
      column.find('.us').show();
    } else {
      column.find('.us').hide();
      column.find('.international').show();
    }
  } else {
    column.removeClass('disabled');
    fields.enable();
  }
};


$(function() {
  $('#navigation > li').hover(function() {
    $(this).find('> a').andSelf().addClass('hover');
  }, function() {
    $(this).find('> a').andSelf().removeClass('hover');
  });
  
  var cartSize = $.cookie('shopping_cart_size');
  var cartTotal = $.cookie('shopping_cart_total');
  if (parseInt(cartSize) > 0 && cartTotal) {
    $('p#cart-header').html(function() {
      return '<a href="/shop/cart">Your Cart</a>: ' +
             cartSize + " Item(s), " + cartTotal + " / " +
             '<a href="/shop/checkout">Checkout</a>';
    });
  }
  
  ShopMenu.init();
  
  Popup.init('#footer-nav', {
    appendTo: '#content',
    onShow: function() { $('#main').addClass('hidden'); },
    onHide: function() { $('#main').removeClass('hidden'); }
  });
  
  Item.init();
  Gallery.init();
  Timeline.init();
  News.init();
  Checkout.init();
  Cart.init();
  
  $('input.disable-on-click').click(function() {
    $(this).attr('disabled', 'disabled');
  });
});
