/*global $, jQuery, document, window */ 




(function() {
  var i = document.createElement('input');
  jQuery.support.placeholder = 'placeholder' in i;
})(); 
(function($) {
  // Overlabel
  $.fn.overlabel = function() {
      this.each(function(index) {
          var label = $(this),
              field,
              id = this.htmlFor || label.attr('for'),
              control;
          if (id && (field = document.getElementById(id))) {
              control = $(field);
              label.addClass("overlabel-apply");
              if (field.value !== '') {
                  label.not('.readonly').css("display", "none");
              }
              control.focus(function () {label.not('.readonly').css("display", "none");}).blur(function () {
                  if (this.value === '') {
                      label.css("display", "block");
                  }
              });
              label.click(function() {
                  var label = $(this), 
                      field,
                      id = this.htmlFor || label.attr('for');
                  if (id && (field = document.getElementById(id))) {
                      field.focus();
                  }
              });
          }
      });
  };
})(jQuery); 

function sizeCart(e, unit) {
  var widths = [],
      totalWidth = 0,
      visible = $(e).parent().width(),
      offsets = [],
      i;
  
  $(unit).removeClass('pageStart').each(function(){
    var x = $(this).width() + 20;
    widths.push(x);
  });
  
  for(i = 0; i < widths.length; i++){
   totalWidth += widths[i];
  }
  
  $(e).animate({
    'height' : 70, 
    'width': totalWidth
  }, 0, function(){
    $(unit).each(function(){
      var offset = $(this).offset();
      offsets.push(offset.left);
    }); 
  });
    
  if(totalWidth > visible) {
    $('.itemsNav').show();
  } else {
    $('.itemsNav').hide();
  }
}

$(document).ready(function(){

  // External Links in New Window
  $('a[rel*=external]').click(function(){
   window.open(this.href);
   return false;
  });
  
  // Mini Cart Toggle
  $('#miniCart .toggle').click(function() {
    if(!$(this).hasClass('cart_empty')) {
      $('header').toggleClass('open');
    }
    return false;
  }); 
  $('#miniCart .close').click(function() {
    $('#miniCart .toggle').trigger('click');
    return false; 
  });
  
  // Cart Item Hovers
  $('#miniCart .items a').hover(function(e) {
    var $container = $('#miniCart .items'),
        containerX = $container.width(),
        offset = $container.offset(),    
        unitX = $(this).width(),
        text = $(this).attr('title'),
        html = '<div class="tooltip"><h5>'+text+'</h5>Click to Remove</div>',
        style,
        ttX;
    if(Math.round(e.pageX - offset.left) > (containerX/2)) { // On Left side
      style = {
        'right' : unitX + 10
      };
    } else {
      style = {
        'left' : unitX + 10
      };
    }   
    // Position Tip
    ttX =  $(this).parent().append(html).find('.tooltip').outerHeight();
    style.top = Math.round(35 - (ttX / 2));
    $(this).parent().append(html).find('.tooltip').css(style);
  }, function() {
    $('.tooltip').remove();
  });
  
  // Cart Item Click

  $('#miniCart .items a').click(function() {
     var $this = $(this),
         href = $this.attr('href');
     $.getJSON(href+'&json_encode', function(data){
       var data = data[0];
       $('#miniCart .toggle').text('Your Cart ('+ data.count +')');
       $('#miniCart .total span').text(data.price);
       $this.parent().fadeOut(500, function() {
           $(this).remove();
           sizeCart('#miniCart .items ul', '#miniCart .items li img');
        });
     });
     return false;
  });
  $('#miniCart .clearCart').click(function() {
     var href = $(this).attr('href');
     $.getJSON(href+'&json_encode', function(data){
       var data = data[0];
       $('#miniCart .toggle').text('Your Cart ('+ data.count +')');
       $('#miniCart .items ul').empty();
     });
     return false;
  });     

  
  // Cart Item Hover
  $('#miniCart .itemsNav a').hover(function() {
      var action = $(this).parent().attr('class'),
          dir;
      if(action === 'prev') {
        dir = 'first';
      } else {
        dir = 'last';
      }
      $('#miniCart .items').scrollTo('li:'+dir, 4000);      
  }, function() {
     $('#miniCart .items').stop();
  });

  // Feature Slideshow
  $('#featureSlide').cycle({
    slideExpr: '.slide',
    timeout: 4000,
    prev: '.slideNav .prev',
    next: '.slideNav .next'
  });
  
  // Over Label
  if($.support.placeholder === false) {
    $('input.text').each(function() {
       if($(this).attr('placeholder') !== '') {
         var text = $(this).attr('placeholder'),
             id = $(this).attr('id');
         $(this).before('<label for="'+id+'">'+text+'</label>');
         $(this).parent().find('label').overlabel();  
       }
    });
  }
  
  // Blog Hovers
  $('#blogFeed .feed li').hover(function() {
    $(this).addClass('hover');
  }, function(){
    $(this).removeClass('hover');
  });
  $('#blogFeed .feed li').click(function() {
    var href = $(this).find('h3 a').attr('href');
    window.location = href;
  }); 
  
  // Grid List Hovers
  $('.gridList li').hover(function() {
    $(this).addClass('hover');
  }, function(){
    $(this).removeClass('hover');      
  });

  // Collab Hovers
  $('#collabList li').hover(function() {
    $(this)
      .find('img.hover')
      .stop()
      .fadeTo(250, 1)
    .end()
      .find('img:not(.hover)')
      .stop()
      .fadeTo(250, 0);
  }, function(){
    $(this)
      .find('img.hover')
      .stop()
      .fadeTo(250, 0)
    .end()
      .find('img:not(.hover)')
      .stop()
      .fadeTo(250, 1);     
  });
  // Collab LIst Li Click
  $('#collabList li').click(function(){
     var href = $(this).find('a').attr('href');
     window.location = href;
     return false;
  });
  
  // Collab Slide
  $('#collabSlide .slides').cycle({
    timeout: 0,
    prev: '.slideNav .prev',
    next: '.slideNav .next'
  });
  
  // Options (Collab, Product)
  $('#options li a').bind('click', function() {
    var $this = $(this),
        val = $this.attr('title'),
        opt = $this.attr('rel');
     
    $this
    .addClass('selected')
      .parent()
        .siblings()
          .find('a')
          .removeClass('selected')
        .end()
      .end()
    .end() // $this
      .parents('#options')
        .find('input[name='+opt+']')
        .val(val)
      .end() // Options Container
        .find('.error')
        .remove();
    
    return false;
  });
  
  // Validate Opts Form
  $('#options input[type=submit]').live('click', function() {
    var val = $(this).parents('form').find('input.required').val();
    if (val === ''){ 
      if($('span.error').length) {
        return false;
      } else {
        $(this)
          .parents('#options')
            .find('h3')
            .after('<span class="error">Please Select an Option</span>');
      }
    } else { 
      $(this)
        .parents('form')
        .submit();
    }
    return false;
  });
  
  // Overlay Slideshows (Used only if Ajax Fails)
  $('.overlayView .slides').cycle({
    slideExpr: 'img',
    timeout: 0,
    pager:  '.thumbs ul', 
    pagerAnchorBuilder: function(idx, slide) { 
        return '.thumbs ul li:eq(' + idx + ') a'; 
    } 
  });
  
  // Fancybox
  if(jQuery.fn.fancybox) {
    $('a.box').fancybox({
      centerOnScroll : true,
      overlayColor: '#000',
      padding: 0,
      titleShow : false
    });
  }
  
});

$(window).bind('load', function(){
  if($('#miniCart .items li').length) {
    sizeCart('#miniCart .items ul', '#miniCart .items li img');
  }
});
