var currHomeImg = 0;
var slideshowImage = null;
var cachedOffset = null;
var zoomedImg = null;
var zoomRatio = 0;
var zoomLocked = false;
$(document).ready(function(){
    
		$('input.with-default').focus(function(){
		 if (this.value == $(this).data('default'))
		   $(this).val('').removeClass('faded');
		}).blur(function(){
		 if (this.value == '')
		   $(this).val($(this).data('default')).addClass('faded');
		}).each(function(){
		 inputWithDefault = $(this);
		 inputWithDefault
		   .data('default', inputWithDefault.val())
		   .val('')
		   .parents('form').submit(function(){
		     if (inputWithDefault.val() == 'Search for a Product...')
		       inputWithDefault.val('');
		   });
		}).blur();
  
  if ($('#home-slideshow img').length)
  {
    currHomeImg = parseInt($('#home-slideshow img').attr('src').slice(-5,-4));
    setInterval('progressSlideshow()', 7000);
  }
  
  $('li.fromthecoast').mouseover(function()
  {
    if (!$(this).hasClass('current'))
    {
	    img =  $('#fromthecoast-img');
	    img.attr('src','/images/fromthecoast_current.gif');
    }
  });
  
  $('li.fromthecoast').mouseout(function()
  {
    if (!$(this).hasClass('current'))
    {
	    img =  $('#fromthecoast-img');
	    img.attr('src','/images/fromthecoast.gif');
    }
  });
  
 $('#home-top-brands li')
    .css('opacity', 0.5)
    .mouseover(function(){ $(this).stop().animate({'opacity':1}, 200); })
    .mouseout(function(){ $(this).stop().animate({'opacity':0.5}, 400); });
  
  // EVIL browser hack
  if ($.browser.msie && $.browser.version <= 6) { $('#home-top-brands li').prepend('<span></span>') };
  
  $("a[href^='http:']").not("[href*='ocbutcher.demo.shelton.co.uk']").click(function(){ window.open(this.href); return false; });
  
  $('.share').click(share);
  $('.catalogue-popup').click(popup);
  $('.news-month').click(toggleArchive);
  
  
  $('#search-form').submit(function(){ if ($('#search-field').val() == 'Search for a Product ...') return false; });
  
  $('.product-thumbs a').click(function(){
    $('#product-picture').attr('src', this.href);
    return false;
  });
  
  $('#product-picture').mousemove(function(e){
    if (zoomLocked) return false;
    $('select').hide(); 
    zoomed = $('#product-image-zoomed');
    if (zoomed.length == 0)
    {
      zoomLocked = true;
      cachedOffset = $('#product-picture').offset();
      $('#container').append($('<div id="product-image-zoomed">Loading...</div>'));
      zoomedImg = new Image();
      zoomedImg.onload = function(){ 
        $('#product-image-zoomed').html('').append('<img src="' + this.src + '" />');
        zoomRatio = this.width / $('#product-picture').width();
        zoomLocked = false;
      };
      zoomedImg.src = $('#product-picture').attr('src').replace('_large.','_huge.');
    }
    $('#product-image-zoomed img').css({ 
      top: ((cachedOffset['top'] - e.pageY) * zoomRatio) + 150,
      left: ((cachedOffset['left'] - e.pageX) * zoomRatio) + 150
    });
  });
  $('#product-picture').mouseout(function(){ $('#product-image-zoomed').remove(); $('select').show(); });
  
  $('.basket-add').click(function(){
    qty = $(this).parent('td').find('input');
    qty.val(parseInt(qty.val()) + 1);
    return false;
  });
  
  $('.basket-subtract').click(function(){
    qty = $(this).parent('td').find('input');
    if (parseInt(qty.val()) > 0) qty.val(parseInt(qty.val()) - 1);
    return false;
  });
  
  $('.popup').click(function(){ 
    if ($(this).hasClass('terms'))
      window.open(this.href, 'terms', 'width=500,height=400,scrollbars=yes');
    else
      window.open(this.href);
    return false; 
  });

  $('.select-variety').change(function(){
    updateProductSKU($(this).parents('form').find('select[name="sales_order_item[varieties][]"]').serializeArray(), 'sku_by_varieties_json');
  });
  //if ($('#product-stock').hasClass('zero-stock'))
  //  $('#add-to-basket').addClass('inactive').click(function(){ return false; });
    
  if ($('#product-options').length > 0)
  {
    $('#product-options').hide();
    $.get('/catalogue/varieties/' + $('input[name="product_id"]').val(), function(data){
      $('#product-options').replaceWith(data);
      
      $('#product-varieties-colour-and-size li:not(.zero)').click(function(){
        $('#product-varieties-colour-and-size li.active').removeClass('active');
        $(this).addClass('active');
        updateProductSKU({ sku_id: this.id.replace('product-variety-','') }, 'sku_by_id_json');
      });
      
      if ($('#product-varieties-colour-and-size li.active').hasClass('zero'))
      {
        $('#product-varieties-colour-and-size li.active').removeClass('active');
        $('#product-varieties-colour-and-size li:not(.zero):first').addClass('active');
      }
      $('#product-varieties-colour-and-size li.active').click();
    });
  }
});

function updateProductSKU(params, action)
{
  $.getJSON('/catalogue/' + action, params, function(sku){
    $('#product-form').find('input[name="sales_order_item[sku_id]"]').val(sku.id);
    $('#product-form').find('.price').html(sku.price);
    //if (sku.stock == 'zero')
    //  stockDescriptor = 'Out of Stock';
    //else if (sku.stock == 'low')
    //  stockDescriptor = 'Limited Stock';
    //else if (sku.stock == 'high')
    //  stockDescriptor = 'In Stock';
    //$('#product-stock').removeClass('zero-stock low-stock high-stock').addClass(sku.stock + '-stock').html(stockDescriptor);
    if (sku.stock == 'zero')
      $('#add-to-basket').addClass('inactive').click(function(){ return false; });
    else
      $('#add-to-basket').removeClass('inactive').unbind('click');
  });
}

function handleCheckoutAddress()
{
  $(document).ready(function(){
    if (!$('.checkout-address').hasClass('enabled'))
      $('.checkout-address').css({ display: 'none', opacity: 0});
  });
  $('input[type="radio"]').click(function(){
    if (this.id == 'new-address' && this.checked)
      $('.checkout-address').animate({ height:"show", opacity: 1});
    else
      $('.checkout-address').animate({ height:"hide", opacity: 0});
  });
}

function share()
{
  $('<div id="overlay"></div>').css({ opacity: 0.5 }).appendTo('body');
  $('<div id="share"></div>').appendTo('body');
  $.get(this.href,function(d){ $('#share').html(d); });
  $(window).resize(function(e){
    $('#overlay').css({ height: (($(window).height() > $(document.body).height()) ? $(window).height() : $(document.body).height()) + 'px', width: $(document.body).width() + 'px' });
    $('#share').css({ left: ($(window).width() / 2) - 165, top: ($(window).height() / 2) - 235 + (($(window).attr('scrollY')) ? $(window).attr('scrollY') : document.body.parentNode.scrollTop) });
  }).scroll(function(e){
    $('#share').css({ top: ($(window).height() / 2) - 235 + (($(window).attr('scrollY')) ? $(window).attr('scrollY') : document.body.parentNode.scrollTop) });
  }).resize();
  return false;
}
function closeShare()
{
  $('body').css({ overflow: 'auto' });
  $(window).unbind('resize').unbind('scroll');
  $('#overlay').remove();
  $('#share').remove();
}

function toggleArchive()
{
   $(this).next('ul').toggle("slow");
   return false;
}

function popup()
{
  $('<div id="overlay"></div>').css({ opacity: 0.5 }).appendTo('body');
  $('<div id="popup"></div>').appendTo('body');
  $.get(this.href,function(d){ $('#popup').html(d).prepend('<a href="#" onclick="closePopup(); return false;" class="fright"><img src="/images/close.gif" alt="Close Window" /></a>'); });
  $(window).resize(function(e){
    $('#overlay').css({ height: $(document.body).height() + 'px' });
    $('#popup').css({ left: ($(window).width() / 2) - 265, top: ($(window).height() / 2) - 265 + (($(window).attr('scrollY')) ? $(window).attr('scrollY') : document.body.parentNode.scrollTop) });
  }).scroll(function(e){
    $('#popup').css({ top: ($(window).height() / 2) - 265 + (($(window).attr('scrollY')) ? $(window).attr('scrollY') : document.body.parentNode.scrollTop) });
  }).resize();
  return false;
}
function closePopup()
{
  $('body').css({ overflow: 'auto' });
  $(window).unbind('resize').unbind('scroll');
  $('#overlay').remove();
  $('#popup').remove();
}

