

var cart = {	
	cartUrl: '/cart/cart.php',
	checkoutUrl: 'http://www.do2learn.com/order/order_address.php',
	products: {},
	currentRequest: null,
	
	addProduct: function(product_code) {
		cart.open(function(){
			cart.request('add', {product_code: product_code}, function(product){
				cart.createItem(product);
				cart.updateTotal();				
			});
		});		
	},
	
	createItem: function(product) {
		cart.removeItem(product.code);
		
		product.html = $('<li />').attr('id', 'cart-product-' + product.code);
		product.html.append(	
			$('<a />').addClass('del').html('&nbsp;').click(function() {cart.removeProduct(product.code)}),	
			$('<div class="title" />').text(product.name + ' - $' + product.price),
			$('<input />').attr({
				name: 'product_qty[' + product.code + ']',
				value: product.qty
			}).blur(function() {cart.updateQty(product.code)}),
			$('<div class="clear" />')
		);
		
				
		cart.html.itemsList.append(product.html);	
		product.html.hide().fadeIn('fast');	
		
		cart.products[product.code] = product;
	},
	
	
	removeItem: function(product_code) {
		if (typeof(cart.products[product_code]) == 'undefined') return;
		cart.products[product_code].html.fadeOut('fast', function() {$(this).remove(); })
		delete cart.products[product_code];
	},
	
	removeProduct: function(product_code) {
		cart.request('delete', {product_code: product_code}, function() {
			cart.removeItem(product_code);
			cart.updateTotal();
		});
	},
	
	updateQty: function(product_code) {
		var $input = cart.products[product_code].html.find('input');
		var qty = parseInt($input.val());
		
		if (qty == 0) {
			cart.removeProduct(product_code);
			return;
		}
		
		cart.request('change_qty', {product_code: product_code, qty: qty}, function(response) {
			cart.products[product_code].qty = response.qty;
			$input.val(qty);
			cart.updateTotal();
		});
	},
	
	loadProducts: function() {
		cart.request('load_products', {}, function(response) {
			for (i in response) {
				cart.createItem(response[i]);
			}
			cart.updateTotal();
		});
	},
	
	open: function(callback) {
		cart.html.content.slideDown('slow', function() {
			cart.html.slidingTrigger.addClass('up').text('Hide Basket');
			
			if (typeof(callback) != 'undefined') callback();
		});
	},
	
	close: function(callback) {
		cart.html.content.slideUp('slow', function() {
			cart.html.slidingTrigger.removeClass('up').text('Show Basket');
			
			if (typeof(callback) != 'undefined') callback();
		});
	},
	
	
	toggle: function() {
		cart.html.content.is(':visible') ? cart.close() : cart.open();
	},
	
	isEmpty: function() {
		for (var i in cart.products) return false;
		
		return true;
	},
	
	updateTotal: function() {
		if (cart.isEmpty()) cart.html.bottom.hide();
		else {
			cart.html.total.text(cart.total());			
			cart.html.bottom.show();
		}
		
		cart.html.productsCount.text(cart.totalItems());
	},
	
	total: function() {
		var total = 0;
		
		for (var i in cart.products) {
			total += cart.products[i].price * cart.products[i].qty;
		}
		
		return total.toFixed(2);
	},
	
	totalItems: function() {
		var items = 0;
		
		for (var i in cart.products) {
			items += cart.products[i].qty;
		}
		
		return items;
	},
		
	checkout: function() {
		if (cart.isEmpty()) return;
		
		var $form = $('<form />').attr({
			action: cart.checkoutUrl,
			method: 'post'
		}).append($('<input />').attr({type: 'hidden', name: 'productCategory', value: 'all'}));
		
		var incart = '';
		
		for (var i in cart.products) {
			var product = cart.products[i];
			
			incart += product.code + ':';
			$form.append(
				$('<input />').attr({type: 'hidden', name: product.code, value: product.qty}),
				$('<input />').attr({type: 'hidden', name: product.code + 'price', value: product.price})
			);
		}
		
		$form.append($('<input />').attr({type: 'hidden', name: 'incart', value: incart}));
		
		//~ cart.request('empty', {}, function() {
			//~ $form.appendTo('body').hide().submit();
		//~ });
		
		$form.appendTo('body').hide().submit();
	},
			
	
	initialize: function() {
		cart.html = {
			wrapper: $('#slidingTopWrap'),
			content: $('#slidingTopContent'),
			slidingTrigger: $('#slidingTopTrigger'),
			itemsWrapper: $('#basketItemsWrap'),
			itemsList: $('#basketItemsWrap ul'),
			loader: $('#notificationsLoader'),
			bottom: $('#basketBottom'),
			total: $('#basketTotal'),
			checkoutBtn: $('#basketSubmitBtn'),
			productsCount: $('#navCartCount')
		}
		
		
		cart.html.slidingTrigger.click(cart.toggle);
		cart.html.checkoutBtn.click(function() {
			if (cart.currentRequest) {
				cart.currentRequest.success(function() {
					cart.checkout();
				});
			}
			else cart.checkout();
		});
		
		cart.loadProducts();
	},
	
	request: function(action, data, callback) {
		if (typeof(data) == 'undefined') data = {};
		data['action'] = action;
		
		cart.html.loader.show();
		
		cart.currentRequest = $.ajax({
			url: cart.cartUrl,
			type: 'POST',
			data: data,
			success: function(response) {
				cart.html.loader.hide();
				
				if (typeof(callback) != 'undefined') callback(response);
			},
			error: function(jqXHR, textStatus, errorThrown) {
				console.log(textStatus);
				console.log(errorThrown);
			}
		});
	}
};

$(document).ready(function(){ 
	cart.initialize();
	
	$('.product .buy-btn').click(function() {
		var $product = $(this).parents('.product');
		var code = $product.attr('id').replace('product-', '');
		
		$('img.product-img', $product).flyToCart(function() {
			cart.addProduct(code);
		});
	});
		
	$.fn.flyToCart = function(callback){
		var $img = $(this);
		
		var basket_x = cart.html.wrapper.offset().left;
		var basket_y = cart.html.wrapper.offset().top;

		var img_position_x = $img.offset().left;
		var img_position_y = $img.offset().top;
		var win_scroll_y = $(window).scrollTop();
		
		var $new_img = $img.clone();
		$new_img.css({
			'position': 'fixed',
			'top': img_position_y - win_scroll_y,
			'left': img_position_x
		})
		$('body').append($new_img);
		
		$new_img.animate({
			'top': basket_y - win_scroll_y,
			'left': basket_x,
			'width': 10,
			'height': 10,
			'opacity': 0
		},1000, function() {
			if (typeof(callback) != 'undefined') callback();
			$(this).remove();
		});
	};


});

function to_cart(product_code, element) {
	if($(element).length > 0) {
		$(element).parents('tr:first').find('img:first').flyToCart();
	}
	
}




