var SF = {};
SF.num_images = 0;

// Use long way so $ doesn't conflict with BC's usage of prototype
jQuery(document).ready(function($) {

  // Carousel\
  var carousel = $('#carousel');
  if (carousel.length) {
    // Generate nav items for all the items in the scrollable
    $('#carousel .items > div').each(function () {
      var name = $(this).find('h2').text();
      var url = $(this).find('a').attr('href');
      var edition = $(this).attr('class');
      
      var navItem = $('<li/>').attr('class',edition).append(
        $('<a/>').attr('href',url).text(name)
      );
      navItem.appendTo('#navi');
    });
  
    carousel.scrollable({
      circular:true
    }).autoscroll({
      interval:5000
    }).navigator({
      navi:'#navi'
    });
  }
  
  // Hopefully more reliable than using the carousel in case the
  // carousel is removed or added to pages other than homepages
  var isHome = $('#is-home').length == 1;
  
  // Article list hover states
  var articles = $('.article');
  
  // Articles anywhere
  if (articles.length) {
  
    // Here we adjust the layout (ahhggg) and parse out the preview image
    var width = 230;
    if (!isHome) {
      var width = 350;
    }
    $(articles).each(function () {
      var body = $(this).children('div');
      
      // Parse out the first sentence
      var headline = body.text().split('.',1) + '.';
      $(this).children('p').text(headline);
      
      // Grab the first image from the gallery so we can use it to display
      var images = body.find('.photogalleryItem a');
      
      if (images.length) {
        var image = $(images[0]).attr('href');
        $(images).remove(); // Maybe we can remove them before they all load?
        var params = {
          action  : 'thumbnail',
          width   : width,
          height  : 9999
        }
        var image = image + '?' + $.param(params);
        
        $(this).children('img').attr('src',image).load(function () {
          var delay = Math.ceil(Math.random()*2000);
          if (isHome) {
            $(this).delay(delay).fadeIn();
          }
          else {
            // Weird selectors to get the siblings and current item at the same time
            $(this).parent().delay(Math.ceil(Math.random()*2000)).children('h2,a,img').fadeIn();
          }
        }).each(function(){
          if(this.complete) $(this).trigger('load');
        });
      }
    });
  }
  
  // Articles on the homepage
  if (articles.length && isHome) {
    articles.hover(function() {
      $(this).find('h2').stop(true, true).fadeIn();
    },function() {
      $(this).find('h2').stop(true, true).fadeOut();
    });
  }
  // Articles not on the homepage
  else if (articles.length) {
    $(articles).find('h2').show();
    $(articles).addClass('span-9').removeClass('span-6').css('height',192).children().hide();
  
    articles.hover(function () {
    
      $(this).find('h2').stop(true, true).animate({
        backgroundColor:'black'
      }).find('a').stop(true, true).animate({color:'white'});
      
      $(this).find('p').stop(true, true).fadeIn();
      
    },function () {
    
      $(this).find('h2').stop(true, true).animate({
        backgroundColor:'#e6e6e6'
      }).find('a').stop(true, true).animate({color:'black'});
      
      $(this).find('p').stop(true, true).fadeOut();
    });
  }
  
  // If we're on a post page
  if(!isHome && $('#details').length) {
    // Set the CSS to that of the referring page
    var referrer = document.referrer.split('/',4)[3];
    if (referrer == 'melbourne' || referrer == 'sydney') {
    
      // Set the css to the referring page
      $('<link/>').attr({
        rel   :'stylesheet',
        media :'screen,projection',
        type  :'text/css',
        href  :'/stylesheets/' + referrer + '.css'
      }).appendTo('head');
      
      // Change twitter icon
      $('.twitter').addClass(referrer);
      
      // change the facebook thing
      if (referrer == 'sydney') {
        $('#fbpage').attr('src','http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fpages%2FSydney-Street-Fashion%2F124488070948271&amp;width=220&amp;colorscheme=light&amp;connections=0&amp;stream=false&amp;header=false&amp;height=72').height(72);
      }
      else if (referrer == 'melbourne') {
        $('#fbpage').attr('src','http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fmelbstreetfash&amp;width=220&amp;colorscheme=light&amp;connections=0&amp;stream=false&amp;header=false&amp;height=85').height(85);
        
      }
      
      // fix the home/nav links
      $('#header h2 a').attr('href','/' + referrer);
      
      $('#nav a').each(function () {
        var link = '/' + referrer + $(this).attr('href');
        $(this).attr('href',link);
      });
    }
  }
  
  /* 
   * Newsletter form
   */
  var inputs = $('.newsletter-form input,#directory-box input,#reply input,#reply textarea');
  
  $('.newsletter-form form').submit(function(e) {
    if ( $(this).find('input:checked').length == 0 ) {
      e.preventDefault();
      alert('You must select one or more newsletters to subscribe to.');
    }
  });
  
  if (inputs.length) {
  
    inputs.focus(function () {
      //$(this).prev('label').fadeOut(200);
      $(this).prev('label').animate({ opacity:.4 },100);
      $(this).parent().siblings('div').slideDown();
    });

  
    // Hide the label on edit, or show it if the user removes all text
    inputs.keyup(function () {
      if ($(this).val().length > 0){
        $(this).prev('label').fadeOut(200);
      }
      else {
        $(this).prev('label').fadeIn(200);
      }
    });
    
    // Show label if field empty
    inputs.blur(function () {
      if ($(this).val().length == 0){
        $(this).prev('label').fadeIn(200).animate({ opacity:1 },100);
      }
    });
    
    // Clear labels on page load if necessary
    inputs.each(function () {
      if ($(this).val().length != 0){
        $(this).prev('label').hide();
      }
    });
    
    /** Attempt to account for browser's autofill changing the fields
      * Browser support may vary */
    inputs.change(function () {
      if ($(this).val().length != 0){
        $(this).prev('label').hide();
      }
    });
  }
  

  /**
    * The BC template system sucks so we need to fix the html with javascript ... */
  var items = $('.article,.listing')
  if (items.length) {
    var columns = 3;
    if (!isHome && !$('.directory.container').length) {
      columns = 2
    }
    
    $('.article,.listing').each(function(i) {
      // Add blueprint css last class to the last items
      if((i + 1) % columns == 0) {
        $(this).addClass('last');
      }
    });
  }


  /**
    * Blog post page */
  
  // Move the gallery images to the details thing
  
  var images = $('.photogalleryItem a');
  
  // If there are images available and we are not on an article list page
  if (images.length && !articles.length) {
  
    var params = {
      action  : 'thumbnail',
      width   : 710,
      height  : 1200
    }
  
    var url = $(images[0]).attr('href') + '?' + $.param(params);
    $('.page').append($('<img>').attr('alt','').attr('src',url).hide().load(function () {
      $(this).css('opacity',0).slideDown('slow').animate({opacity:1},'slow');
    })).each(function(){
      if(this.complete) $(this).trigger('load');
    });

    delete images[0];
    
    var details = $('#details div.span-3').html('');
    
    // We want the last one to end up on the left
    var i=0;
    images.each(function() {
      if (!this.nodeName) {
        return;
      }
      $(this).appendTo(details[i]);
      i == 0 ? i = 1 : i = 0;
    });
    
    $('#details .span-3 img').hide().load(function () {
      $(this).fadeIn('slow');
      
      // Adjust the size based on landscape or portrait
      if ($(this).width() > $(this).height()) {
        $(this).css('width','auto');
        $(this).height(110);
      }
    }).each(function(){
      // If they're already loaded (cached) trigger the load event
      if(this.complete) $(this).trigger('load');
    });
    
    $('.photogalleryTable').remove();
  }
  
  var sidebar = $('#sidebar');
  if (sidebar.length && !$('#directory-detail').length) {
    sidebar.after($('#related,#comments,#reply'));
  }
  
  
  /* Shop */
  var products = $('.shop-item');
  if (products.length) {
    $(products).each(function (i) {
      if ((i + 1) % 2 == 0) {
        $(this).addClass('last');
      }
    });
    
    products.hover(function() {
      $(this).find('ul').stop(true, true).fadeIn();
	  $(this).find('h2').stop(true, true).animate({
        backgroundColor:'black'
      }).find('a').stop(true, true).animate({color:'white'});
	   $(this).find('p').stop(true, true).fadeIn();
	  
    },function() {
		
      $(this).find('ul').stop(true, true).fadeOut();
      $(this).find('h2').stop(true, true).animate({
        backgroundColor:'#e6e6e6'
      }).find('a').stop(true, true).animate({color:'black'});
      
      $(this).find('p').stop(true, true).fadeOut();
    });
  }
  
  
  // Shop thumbnails
  var details = $('.shop-product-large .thumbs');
  var thumbs = $('.shop-product-large .productPopletsItem a');
  if (thumbs.length) {
    // We want the last one to end up on the left
    var i=0;
    thumbs.each(function() {
      if (!this.nodeName) {
        return;
      }
      $(this).appendTo(details[i]);
      
      var params = {
        action  : 'thumbnail',
        width   : 110,
        height  : 999
      }
      var url = $(this).attr('href') + '?' + $.param(params);
      
      $(this).find('img').attr('src',url);
      
      i == 0 ? i = 1 : i = 0;
    });
  }
  
});
