jQuery(document).ready(function() {
  // html5 feature detection
  //input placeholder fallback
  if (!Modernizr.input.placeholder){
    jQuery('input[placeholder]').each(function(){
      if(jQuery(this).val() == ''){
        jQuery(this).val(jQuery(this).attr('placeholder'));
      }
    });
    jQuery('input[placeholder]').focus(function(){
      if(jQuery(this).val() == jQuery(this).attr('placeholder')){
        jQuery(this).val('');
      }
    });
    jQuery('input[placeholder]').blur(function(){
      if(jQuery(this).val() == ''){
        jQuery(this).val(jQuery(this).attr('placeholder'));
      }
    });
  }
  
  // shop by department or size dropdowns
  jQuery('#fat_footer .departments>div').clone().appendTo('#by_department');
  jQuery('.shop_by .filters a').click(function(){
    jQuery('.shop_by_options:visible').slideUp();
    var which_shop_by = jQuery(this).attr('href');
    if(jQuery(which_shop_by).filter(':visible').length > 0){
      jQuery(which_shop_by).slideUp();
      jQuery(this).removeClass('active');
    }else{
      jQuery(which_shop_by).slideDown();
      jQuery('.shop_by .filters a').removeClass('active');
      jQuery(this).addClass('active');
    }
    return false;
  });
  // close dropdowns
  jQuery('html').click(function(){
    jQuery('.shop_by_options').slideUp();
    jQuery('.shop_by .filters a').removeClass('active');
  });
   jQuery('.shop_by_options').click(function(event){
     event.stopPropagation();
   });
  
  // format item price
  var price_parts = jQuery('aside[role=complementary] .item_meta .item_price').text().split('.');
  jQuery('aside[role=complementary] .item_meta .item_price').html(price_parts[0] + '<span>.' + price_parts[1] + '</span>');
  
  jQuery('.items_list .price span').each(function(){
    var list_price_parts = jQuery(this).text().split('.');
    jQuery(this).text(list_price_parts[0]);
  });
  
  // tweets
  if(jQuery('.tweets').length > 0){
    jQuery.getJSON('http://twitter.com/status/user_timeline/bethanylouise.json?count=10&callback=?', function(data){
      jQuery('aside[role=complementary] .tweets ul').empty();
      var j = 0;
      jQuery.each(data, function(i, item){
        if(item.text.charAt(0) != '@'){
          jQuery('aside[role=complementary] .tweets ul').append('<li>' + item.text.linkify() + ' <time class="created_at">&mdash; <a href="http://twitter.com/bethanylouise/status/' + item.id_str + '">' + relative_time(item.created_at) + '</a></time></li>');
          j++;
          if(j == 3){
            return false;
          }
        }
      });
    });
  }
  
  // etsy
  if(jQuery('.etsy').length > 0){
    jQuery.getJSON('http://openapi.etsy.com/v2/shops/rewarevintage/listings/active.js?api_key=1a91d6ti65xjhhzigpoq4794&limit=9&includes=Images(url_75x75):1:0&callback=?', function(data){
      jQuery('#fat_footer .etsy ul').empty();
      jQuery.each(data.results, function(i, item){
         jQuery('#fat_footer .etsy ul').append('<li><a href="' + item.url + '" title="' + item.title + '"><img src="' + item.Images[0].url_75x75 + '" alt="' + item.title + '" /></a></li>');
      });
    });
  }
  
  // flickr
  if(jQuery('.flickr').length > 0){
    jQuery.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=7809637@N03&lang=en-us&format=json&jsoncallback=?", function(data){
      jQuery('aside[role=complementary] .flickr ul').empty();
      jQuery.each(data.items, function(i,item){
        var medium = item.media.m;
        var thumbnail = medium.replace('_m.jpg', '_s.jpg');
        jQuery('aside[role=complementary] .flickr ul').append('<li><a href="' + item.link + '" title="' + item.title + '"><img src="' + thumbnail + '" alt="' + item.title + '" /></a></li>');
        if(i == 8){
          return false;
        }
      });
    });
  }
  
  // homepage slideshow
  if(jQuery('#home_featured').length > 0){
    jQuery('#home_featured').carousel({
       slider: '#items',
       slide: 'li',
       addNav : true,
       speed: 1500
     });
     jQuery('ol', this).show();
  }
  
  // item detail galleries
  jQuery('.item_details #shopp .item_gallery .full li:gt(0)').hide();
  jQuery('.item_details #shopp .item_gallery .thumbs a').click(function(){
    jQuery('.item_details #shopp .item_gallery .full li:visible').hide();
    jQuery(jQuery(this).attr('href')).show();
    return false;
  });
  
  // update form on shipping estimate
  jQuery('#shipping-postcode').blur(function(){
    jQuery(this).closest('form').submit();
  });
  jQuery('#needs_shipping').click(function(){
    jQuery('#shipping-postcode').addClass('error');
    alert('Please enter a valid postcode to estimate tax and shipping before proceeding to checkout.');
    return false;
  });
  
  jQuery('.hentry img').removeAttr('height').removeAttr('width');
  
  jQuery('.advertise a').bind('click', function(event){
    recordOutboundLink(this, 'ADVERTISEMENT', $(this).attr('href'));
    return false;
  });
  jQuery('a.track').bind('click', function(event){
    recordOutboundLink(this, 'TRACK', $(this).attr('href'));
    return false;
  });
  
});

function recordOutboundLink(link, category, action) {
  _gat._getTrackerByName()._trackEvent(category, action);
  setTimeout('document.location = "' + link.href + '"', 100);
}

String.prototype.linkify = function() {
  return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
    return m.link(m);
  });
};
function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);
  var r = '';
  if (delta < 60) {
    r = 'a minute ago';
  } else if(delta < 120) {
    r = 'couple of minutes ago';
  } else if(delta < (45*60)) {
    r = (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (90*60)) {
    r = 'an hour ago';
  } else if(delta < (24*60*60)) {
    r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    r = '1 day ago';
  } else {
    r = (parseInt(delta / 86400)).toString() + ' days ago';
  }
  return r;
}

