/* 
 * @Author: Me
 * @Dependencies: jQuery 1.2.6 and chunky bacon
 * @Notes: Actions for Adding / Removing DVDs to the shopping cart...matey!
 */

jQuery.preloadImages = function() {
  for(var i = 0; i<arguments.length; i++){
    jQuery('<img>').attr('src', arguments[i]);
  }
}
	
// preload the buttons
$.preloadImages('images/remove_from_cart.gif','images/add_cart.gif');

$(document).ready(function() {
	
	// add / remove a dvd to cart
	$('.addtocart').click(function() {
		var rel_id = $(this).attr('rel').split('_');
		var action = rel_id[0];
		var id     = rel_id[1];
		var add_rel = 'add_' + id;
		var rem_rel = 'remove_' + id;
		var login = $(this).hasClass('login');
		
		if(!login) {
			if(action=='add') {
				$(this).attr({src:'images/remove_from_cart.png',rel: rem_rel,title: 'Remove from Cart'});
				$.post("addtocart.php", { vid: id });
				
			} else if(action=='remove') {
				$(this).attr({src:'images/add_cart.png',rel: add_rel,title: 'Add to Cart'});
				$.post("removefromcart.php", { vid: id });
			}
		} else {
			alert('Please log in to use this function.');
		}
	});
	
	// add / remove a dvd set to cart
	$('.buyset').click(function() {
		var login = $(this).hasClass('login');
		var rel_id = $(this).attr('rel').split('_');
		var action = rel_id[0];
		var cidx    = rel_id[1];
		var buy_rel = 'buyset_' + cidx;
		var unbuy_rel = 'unbuyset_' + cidx;
		
		if(login) {
			alert('Please log in to use this function.');
		} else {
			if(action == 'buyset') {
				$(this).attr({src:'images/remove_set_btn.gif',rel: unbuy_rel,title: 'Remove from Cart'});
				$.post("addtocart.php", { cid: cidx });
				
			} else if (action == 'unbuyset') {
				$(this).attr({src:'images/buy_set_btn.gif',rel: buy_rel,title: 'Buy Set'});
				$.post("removefromcart.php", { cid: cidx });
			}
		}
	});
	
	// add / remove entire dvd series to cart
	$('.entire').click(function() {
		var login = $(this).hasClass('login');
		var rel_id = $(this).attr('rel').split('_');
		var action = rel_id[0];
		var items    = rel_id[1];
		var entire_rel = 'buyentire_' + items;

		if(login) {
			alert('Please log in to use this function.');
		} else {
			if(action == 'buyentire') {
				if(items > 57) items = 57;
				$.post("addtocart.php", { p: 'entire', qty: items }, function(response) {
					var unbuyentire_rel = 'unbuyentire_' + response;
					$('.entire').attr({src:'images/remove_set_btn.gif',rel: unbuyentire_rel,title: 'Remove from Cart'});
				});
				
			} else if (action == 'unbuyentire') {
				$(this).attr({src:'images/buy_set_btn.gif',rel: entire_rel,title: 'Buy Set'});
				$.post("removefromcart.php", { e: items });
				
			}
		}
	});	
	
});