$(document).ready(function(){
	$('#products .addtocart').bind('click',function() { //make 'add to cart' link add items to cart when clicked
		$(this.parentNode).TransferTo( {
			to:addProductToCart(this.parentNode),
			className:'transferProduct',
			duration: 400
		});
		return false;
	});
	
	if ($.browser.msie == false) {
		$('div.product').Draggable(
			{
				revert: true, 
				fx: 300, 
				ghosting: true, 
				opacity: 0.4, 
				snapDistance: 15
			}
		);

		$('#cart').Droppable(
			{
				accept :		'product', 
				activeclass:	'activeCart', 
				hoverclass:		'hoverCart',
				tolerance:		'intersect',
				onDrop:	addProductToCart
			}
		);
	}
	//make the products invisible and insert loading indicator
	$('#products').css('opacity', '0.0').before('<div id="loading"><img src="'+wrd+'/images/ajaxIndicator.gif"/><p>...loading store...</p></div>');

	//promo code
	$('#enterPromo').click(function() {
		$(this).after('<input type="text" name="promoCode" /><button id="submitPromo">Submit</button>');
		$(this).remove();
		$('#submitPromo').click(function() {
			code = $('input[name=promoCode]').attr('value');
			$.get(wrd+'/CMS/plugins/storefront/promocode.php?id='+objectId+'&code='+code, function(data) {
				if (data == 'error') { 
					alert('The Promo Code you entered was not valid.'); 
				} else {
					$('input[name=promoCode]').before('<p id="promo">Discount: <span id="discountPercent">'+data+'</span>%</p>');

					discountTotal();
				
					$('input[name=promoCode]').remove();
					$('#submitPromo').remove();
					document.getElementById('cart').promo = 1;
				}
			});
			
			return false;
		});
		
		return false;
	});
	
	$('#paypal').hide();//keep paypal button hidden until each cart item's hidden inputs are added when the user clicks Checkout.
});

$('#products').ready(function() {
	finalizeProducts();
});

function finalizeProducts () {
	h = 0;
	$('.product').each(function() {
		if ($(this).height() > h) {h = $(this).height();}
	});

	$('.product').each(function() {
		$(this).css('height', h);
	});

	setTimeout("$('#loading').fadeOut(200, function() {$('#products').fadeTo(300, 1.0);});", 500);
}


function discountTotal() {
		discount = $('#discountPercent').html();
		total = $('#cartTotal').html();
		discount = discount / 100;
		discountPercentage = discount;
		discount = discount * total;
		discountedTotal = total - discount;
		discount = Number(discount).toFixed(2);
		discountedTotal = Number(discountedTotal).toFixed(2);
		$('#discountInfo').replaceWith('<p id="discountInfo" style="font-weight:bold;">Discounted Total: $<span id="discountedTotal">'+discountedTotal+'</span><br/>Savings: $<span id="discount">'+discount+'</span></p>');
		document.getElementById('discountInfo').set = true;
		document.getElementById('discountInfo').discount = discount;
		document.getElementById('discountInfo').discountPercent = discountPercentage;
}

var addProductToCart = function(dragged) {
	$('#paypal').hide();//hide the paypal button if the cart changes
	$('#checkout').fadeIn(200);//fade in teh Checkout button if something is in the cart
	var cartItem;
	var productName = $('h2', dragged).html();
	var productPrice = $('span.price', dragged).html();
	if (document.getElementById('cart').shipping == 1) {
		var productShipping = parseFloat($('span.shipping', dragged).html());
	}
	var productId = $(dragged).attr('id');
	var isInCart = $('#' + productId + '_cart');
	if (isInCart.size() == 1) {
		var quantity = parseInt(isInCart.find('span.quantity').html()) + 1;
		isInCart.find('span.quantity').html(quantity+'').end();
		cartItem = isInCart.get(0);
		//increment quantity and add options
	} else {
		$('#cartProducts')
			.append('<div class="productCart" id="' + productId + '_cart"><span class="name">' + productName + '</span><a href="#">remove</a><br />qty: <span class="quantity">1</span><br />price: <span class="price">$' + productPrice + '</span></div>')
			.find('div.productCart:last')
			.fadeIn(400)
			.find('a')
			.bind(
				'click', 
				function(){
					$('#paypal').fadeOut(400);
					$(this.parentNode).fadeOut(
						400,
						function() {
							$(this).remove();
							calculateCartTotal();
						}
					);
					return false;
				}
			);
		if (document.getElementById('cart').shipping == 1) {
			$('div.productCart:last').append('<br />shipping: $<span class="shipping">' + productShipping + '</span>');
		}

		cartItem = $('div.productCart:last').get(0);
	}
	
	if ($('select', dragged)) {
		$('#'+productId+'_cart').append('<span class="itemOptions"></span>');
			$('select', dragged).each(function() {
				$('#'+productId+'_cart > span.itemOptions:last').append('<span class="options"></span>');
				option = $(this).children('option:selected').attr('value');
				optionName = this.id;
				$('#'+productId+'_cart > span.itemOptions:last > span.options:last').append('<br/><span class="optionName">'+optionName+'</span>: <span class="option">'+option+'</span>');
			});
	}
	
	calculateCartTotal();
	if (document.getElementById('cart').promo == 1) {
		discountTotal();
	}
	return cartItem;
};
var calculateCartTotal = function()
{
	var total = 0;
	$('#cartProducts .productCart').each(
		function()
		{
			var price = $('span.price', this).html();
			price = price.substr(1, price.length);
			price = parseFloat(price);
			if (document.getElementById('cart').shipping == 1) {
				var shipping = parseFloat($('span.shipping', this).html());
				var price = price + shipping;
			}
			var quantity = parseInt($('span.quantity', this).html());
			total += price * quantity;
		}
	);
	$('#cartTotal').html(formatNr(total));
};
var formatNr = function(nr)
{
	thousands = parseInt(nr/1000);
	hundreds = parseInt(nr - thousands*1000);
	decimals = parseInt((nr - parseInt(nr)) * 100);
	return (thousands > 0 ? thousands + ' ' : '') + (nr > 1000 & hundreds < 100 ? '0' : '') + (nr > 1000 & hundreds < 10 ? '0' : '') + hundreds + '.' + (decimals > 0 ? decimals : '00');
}

function checkout() {
	//checkoutList = '';
	$('#checkoutInfo').empty();//clear all of the hidden inputs that may have already been added. For instance, if the user submits to paypal and then goes back to change the order. Or if the user clicks checkout and then changes the order
	$('.productCart').each(function(i) {
		productId = this.id;
		productId = productId.replace(/_cart/, '');
		productPrice = $('span.price', this).html();
		productPrice = productPrice.substr(1, productPrice.length);
		if (document.getElementById('discountInfo').set == true) {
			percentage = document.getElementById('discountInfo').discountPercent;
			discountPrice = productPrice * percentage;
			productPrice = Number(productPrice - discountPrice).toFixed(2);
		}
		itemName = $('span.name', this).html();
		quantity = $('span.quantity', this).html();
		i++;
		$('#checkoutInfo').append('<input type="hidden" name="item_name_'+i+'" value="'+itemName+'"><input type="hidden" name="item_number_'+i+'" value="'+productId+'"><input type="hidden" name="quantity_'+i+'" value="'+quantity+'"><input type="hidden" name="amount_'+i+'" value="'+productPrice+'">');
		//var cartData = 'item_name='+itemName+'&item_number='+productId+'&quantity='+quantity+'&mc_gross='+productPrice;
		//alert(cartData);
		var options = '';
		var optionCount = 0;
		$('span.itemOptions', this).each(function(j) {
			optionCount = j;
		});
		$('span.itemOptions', this).each(function(j) {
			if (optionCount > 0) {
				j++;
				options += '#'+j+': ';
			}
			$('span.options', this).each(function() {
				optionName = $('span.optionName', this).html();
				option = $('span.option', this).html();
				options += optionName+': '+option+', ';
			});
		});
		//options = options.substr(0, options.length-2);
		//alert(options);
		$('#checkoutInfo').append('<input type="hidden" name="on0_'+i+'" value="options"><input type="hidden" name="os0_'+i+'" value="'+options+'">');
		//checkoutList += itemName+','+quantity+','+options+';';
		if (document.getElementById('cart').shipping == 1) {
			productShipping = $('span.shipping', this).html();
			//cartData += '&mc_handling='+shipping;
			$('#checkoutInfo').append('<input type="hidden" name="shipping_'+i+'" value="'+productShipping+'">');
			//alert(cartData);
		}
		
	});
	

	$('#paypal').fadeIn(200);
}
