/*
function maxImageHeight(){

  var maxDimension = 0;
  var maxImage = null;
  // Iterate through all the images.
  var imgElements = $('#product_gallery img');
  imgElements.each(function(index, elem){
      if (parseInt(elem.height)  > maxDimension){
       maxDimension = elem.height;
    }
  });
  $('#product_gallery #images').css({height: maxDimension+"px"})
}
*/


function add_to_list(productID, items, subtotal, newquantity, deleted, basketitemid){
	$.ajax({
        url: "/products/ajax_get_product_info",
        glabal: false,
        type: "POST",
        data: "id="+productID,
        dadaType: "html",
        async: false,
        success: function(content){
            var product = $.parseJSON(content);
			
			var prefix;
			if(items == 1)
			{
				prefix = "item";
			}
			else if(items > 1)
			{
				prefix = "items";
			}
			else if(items == 0)
			{
				prefix = "items";
			}
			
			if($('.basket_rightbar').length > 0){
				
				if(subtotal == 'undefined'){
				
					$('#basket_content').html('<span class="itmsCount">'+items+'</span> '+prefix+' | £<span id="basket_subtotal">0.00</span>').removeClass('open').addClass('closed');
				}
			}else{
				
            var html = '<li id="item-'+productID+'"><div class="name">'+product.name+'</div><div class="price">&pound;'+product.price+'</div><div class="weight">'+product.uom+' | '+product.weight+'g</div><form method="post" class="removeItem"><input type="submit" id="remove_button" value="Remove" /><input type="hidden" name="id_'+productID+'" value="'+productID+'"/></form><div class="qty">Qty: <img src="/images/basket_down.jpg" class="basketTakeFromQuantity qtybttn" alt="'+productID+'" /> <span class="qtyamount">'+newquantity+'</span><img src="/images/basket_up.jpg" class="basketAddToQuantity qtybttn" alt="'+productID+'" /></div></li>';
			
			}
			
			
			if($('#basket_content').hasClass('basket_rightbar')){
				
				$('#basket_content').html('<span class="itmsCount">'+items+'</span> '+prefix+' | £<span id="basket_subtotal">'+subtotal+'</span>').removeClass('open').addClass('closed');
			
			}
			
			else if($('#basket_content').hasClass('right_basket_items_only')){
				
				$('#basket_content').html('Your cart contains <span class="itmsCount largeItems">'+items+'</span> '+prefix);
			
			}
						
			else if($('#basket_content').hasClass('closed') && items > 0){
				
				if(!$('#basket_list').html()){	
					$('#basket_content').html("<ul id='basket_list'></ul><div id=\"basket_total\">Total: <strong>&pound;</strong><span id='basket_subtotal'></span> <span class=\"small_text\">(inc VAT)</span></div><div id=\"checkout_button\"><a href=\"/basket\">checkout</a></div>").removeClass('closed');
					$('#basket_content').addClass('open');
				}
				$('#basket_list').append(html);
				
			}else if(items > 0){
				if(deleted == true)
				{
					$('#item-'+productID).remove();
				}else{
					
					if($('#item-'+productID).html())
					{
					
						$('#item-'+productID+' .qtyamount').html(newquantity);
					}else{
						$('#basket_list').append(html);
					}
				}
			}
			else if($('.open').html() && items < 1){
				$('#basket_content').html('<span class="itmsCount">'+items+'</span> '+prefix+' | £<span id="basket_subtotal">'+subtotal+'</span>').removeClass('open').addClass('closed');
			}
			$('#basket_subtotal').html(subtotal);
        }
    });
	
}
function populate_basket(){
	$.ajax({
	    url: "/basket/ajax_populate_basket_list",
		global: false,
		type: "POST",
		data: "ajax=yes",
		dataType: "html",
		async:false,
		success: function(msg){
				var basket = $.parseJSON(msg);
				
				for(prodID in basket.id)
				{
					add_to_list(basket.id[prodID], basket.numberofitems, basket.subtotal, basket.quantity[prodID], false, basket.bid[prodID]);
				}
		}
	});
	
}
jQuery(document).ready(function () {
	
	// Lets attach a note to all country dropdowns
	$('select').change(function(){
	    if($(this).val() == 'Ireland' && $(this).attr('name').indexOf('country'))
	    {
		$(this).after('<div id="ireland-notice"><p><strong>If you do not have a postcode, please type \'N/A\' in the postcode field.</strong></p></div>');
	    } else if($(this).attr('name').indexOf('ountry') > 0) { //hacky hack hack
		$('#ireland-notice').remove();
	    }
	});
	
	
	$("#delivery_options").click(function(){
		updateTotalWithShipping();
	});
	$("#delivery_options").change(function(){
		updateTotalWithShipping();
	});
	$('li.subpage ul').hide();
	
	$('li.subpageheader').click( function () {
		$('li.subpage ul').hide();
		$('ul', this).show();
	});
	
    //maxImageHeight();
	populate_basket();
	// Enable the Placeholder plugin;
	$('input, textarea').placeholder();

	$.fn.animateHighlight = function(highlightColor, duration) {
	    var highlightBg = highlightColor || "#FEFFDE";
	    var animateMs = duration || 500;
	    var originalBg = this.css("backgroundColor");
	    this.stop().css("background-color", highlightBg).stop().animate({backgroundColor: originalBg}, animateMs);
	};
	
	$.fn.textFlash = function(highlightColor, duration) {
	    var highlightBg = highlightColor || "#FEFFDE";
	    var animateMs = duration || 500;
	    var originalBg = this.css("color");
	    this.stop().css("color", highlightBg).stop().animate({color: originalBg}, animateMs);
	};
	
	$('#category_picker').change(function() {
		if($(this).val() != "none")
			window.location.href = "/categories/view/"+$(this).val();
	});
	

$('.addItem').submit(function (e) {
	
    e.preventDefault();
	
    var productID = $('input[type=hidden]', this).val();
    var productQty = $('select', this).val();
    $('select', this).val('1');

    $.ajax({
        url: "/basket/ajax_add_item",
	global: false,
	type: "POST",
	data: "id="+productID+"&qty="+productQty,
	dataType: "html",
	async:false,
	success: function(msg){
            var basket = $.parseJSON(msg);
	    	$('#basket_subtotal').html(basket.subtotal);
			var prevTotal = parseInt($('.itmsCount').html());
			$('.itmsCount').html(basket.numberofitems);
			add_to_list(productID, basket.numberofitems, basket.subtotal, basket.item.quantity);
			$('#basket_subtotal').html(basket.subtotal);
	}
    });
});

//scroll
$(window).scroll(function () {      
    
        if($('div.site_wrapper').attr('nodeName'))
        {
            if($(document).scrollTop() > 322)
            {
                var boxHeight = $("#right_basket").height() + $("#site_footer").height() + 130;
            
                if($(document).scrollTop() < parseInt($(document).height() - boxHeight))
                {
                    $("#right_basket").css({ top: parseInt($(document).scrollTop() + 20 )+'px' }); 
                }
            }
            else
            {
                $("#right_basket").css({ top: 342 });
            }   
        }
        else
        {
            if($(document).scrollTop() > 142)
            {
                var boxHeight = $("#right_basket").height() + $("#site_footer").height() + 130;
            
                if($(document).scrollTop() < parseInt($(document).height() - boxHeight))
                {
                    $("#right_basket").css({ top: parseInt($(document).scrollTop() + 20 )+'px' }); 
                }
            }
            else
            {
                $("#right_basket").css({ top: 162 });
            }   
        }

    });

$('.addToQuantity').live('click',function (e) {
	
	var pID = $(this).attr('title');
	
	
	$.ajax({
	      url: "/basket/ajax_add_item",
	      global: false,
	      type: "POST",
	      data: "id="+$(this).attr('alt')+"&qty=1",
	      dataType: "html",
	      async:false,
	      success: function(msg){			
			drawCart(msg, pID);
	      }
	   });
		var current = parseInt($('#input_'+pID).val());
		var newone = current + 1;
		//$('#input_'+pID).val(newone);
});

$('.basketAddToQuantity').live('click', function (e) {
	var pID = parseInt($(this).attr('alt'));
	$.ajax({
	      url: "/basket/ajax_add_item",
	      global: false,
	      type: "POST",
	      data: "id="+pID+"&qty=1",
	      dataType: "html",
	      async:false,
	      success: function(msg){			
			
			drawCart(msg, pID);			
			
	      }
	  });
});

$('.basketTakeFromQuantity').live('click', function (e) {
		var pID = parseInt($(this).attr('alt'));
		$.ajax({
		      url: "/basket/ajax_basket_remove_item",
		      global: false,
		      type: "POST",
		      data: "id="+pID+"&qty=1",
		      dataType: "html",
		      async:false,
		      success: function(msg){
				
				//redraw totals
				drawCart(msg, pID);
		   }
		 });
});

// called when someone decriments an item quanitity
$('.takeFromQuantity').live('click', function (e) {
	
	//product ID used in AJAX call
	var pID = $(this).attr('title');
		
	//if there is zero items dont allow them to go negative
	if($('#input_'+pID).val() > 0)
	{
		$.ajax({
		      url: "/basket/ajax_remove_item",
		      global: false,
		      type: "POST",
		      data: "id="+$(this).attr('alt')+"&qty=1",
		      dataType: "html",
		      async:false,
		      success: function(msg){
				
				//redraw totals
				drawCart(msg, pID);
				var current = parseInt($('#input_'+pID).val());
				var newone = current - 1;
				//$('#input_'+pID).val(newone);
		   }
		   });
	}
});

$('.removeItem').live('submit', function(e) {

	e.preventDefault();	
	var pID = $(this).children('input[type=hidden]').val();
	$.ajax({
     	url: "/basket/ajax_delete_item",
		global: false,
		type: "POST",
		data: "id="+pID,
		dataType: "html",
		async:false,
		success: function(msg){
			//redraw totals
			drawCart(msg, pID);
		}
	});
});

//check if the cart is empty or not so we don't show the checkout button
function doEmpty(items){
		if(items == 0){
			$('#basket_table').html('<table cellspacing="0" cellpadding="10px"><tr><td colspan ="4"><p><strong>Your basket is empty at the moment</strong><br/> Why not head to our online store and checkout some of our great produce!</p></td></tr></table>');
			$('#basket_continue').fadeOut(500, function(){$('#basket_continue').remove()});
		}
}

//Put message in the shipping option if it is not default to make user refresh
function showRefreshMessage(){
		$('#delivery_options').append('<option selected diabled>Please Refresh Your Browser To Update Total With Shipping Option</option>');
		$('#delivery_options').attr('disabled','true')
}

// Redraw the basket view post ajax calls
function drawCart(msg, item_id) {
	var cart = $.parseJSON(msg);	
	add_to_list(cart.item.product_id, cart.numberofitems, cart.subtotal, cart.item.quantity, cart.deleted, cart.item.id);
	
	
	$('#subtotal').html(cart.subtotal);
	var vatSubtotal;
	
	if(cart.item.quantity == '0.00'){
		
		$('#product_row_'+item_id).fadeOut('1000', function(){$('#product_row_'+item_id).remove(); doEmpty(cart.numberofitems);});
		
	}
	else
	{
		vatSubtotal = cart.noVATsubtotal;
	}
	showRefreshMessage();
    $('#basket_subtotal').html(cart.subtotal);
	$('.itmsCount').html(cart.numberofitems);
	
	$("#input_"+item_id).val(cart.item.quantity);
	
	$("#total_price_"+item_id).html(cart.item.total);
	$('#vat_subtotal').html(cart.vat)
	var minOrder = parseInt($('#continue').attr('alt'));

	if(cart.subtotal > minOrder){
		$('#continue').html('<input type="image" src="/images/checkoutbutton.gif" name="checkout" value="Go to Checkout &raquo;" class="button" />');
	}
	else
	{
		$('#continue').html('<p><strong style="color:#A30011">Minimum order amount: &pound;'+minOrder+'</strong></p>');
	}
	
	updateTotalWithShipping();
}

function updateTotalWithShipping() {
	var no_shipping_sub_total = parseFloat($('#subtotal').html());
	
	var shipping_id = parseFloat($("select[name='delivery_option']").val());
	$.ajax({
	   	url: "/basket/ajax_upadte_cart_total_with_shipping",
		global: false,
		type: "POST",
		data: "id="+shipping_id+"&subtotal="+no_shipping_sub_total,
		dataType: "html",
		async:false,
		success: function(msg){
			//redraw totals
			var shipping_total = $.parseJSON(msg);
			if(no_shipping_sub_total > 0){
			$('#total').html(shipping_total);
			$('#total').animate({
				opacity: 0.25
				},
				100, function(){ $('#total').animate({
					opacity: 1
					},
					100); });
			}
			else
			{
				$('#total').animate({
					opacity: 0.25
					},
					100, function(){ $('#total').animate({
						opacity: 1
						},
						100); });
				$('#total').html('0.00');
			}
		}
	});
}

$('#product_gallery #images #img1').addClass('current');
$('#images_number a').first().addClass('active');


    $('#images_number a').click(function(event){
        event.preventDefault();
        var target = $(this).attr('href');
        // check to see if there is a target set
        if(target.length > 4){
            //there is one and it is more than 4 charachters long
             if($('#product_gallery '+target).hasClass('current')){
                 //the image is current
             }
             else{
                 //the images is not current
                 $('#images_number a').removeClass('active');
                 $('#product_gallery .current').fadeOut(200);
                 $('#product_gallery li').removeClass('current');
                 $('#product_gallery '+target).css('visibility', 'visible').css('display', 'none').fadeIn(200).addClass('current');
                 $(this).addClass('active');
             }
        }
    });
});

