
$(document).ready(
	function(){
		var $cartItems = new Array();
		
		var $cartLimit = 15;//the maximum number of items that a cart can take
		
		$body = $('body');
		$body.append('<div id="overlay"></div>');
		
		$cart_content = $('<div id="view-cart-box"><div id="view-cart-content"><div id="chd">Here are your cart items:</div>\n<table id="cart-table" width="500" cellpadding="0" cellspacing="1" border="0">\n<tr id="vch" class="view-cart-header">\n<th width="180">Item Name</th>\n<th width="120">Artist</th>\n<th width="100">Price</th>\n<th width="18"></th>\n</tr>\n<tr id="row-marker"><td colspan="4"></td></tr>\n</table>\n</div><div id="cart-btn-panel">\n<div class="cart-btn"><a id="checkout-btn" href="#" title="Checkout to Paypal"><img src="http://fusiongreen.com/images/checkout-home.png" width="88" height="19" border="0" alt="Checkout" /></a></div>\n<div class="cart-btn"><a id="clear-cart-btn" href="#" title="Clear the carts content"><img src="http://fusiongreen.com/images/clear-cart.png" width="88" height="19" border="0" alt="Clear cart" /></a></div>\n</div></div>').insertAfter('div#cart-marker');
		
		$cart = $('#view-cart-box');//a reference to the cart box
		
		$overlay = $('#overlay');
		
		//$marker = $('tr#row-marker');//the marker/indicator to know where to insert content
		
		$('<tr id="row-total"><td><b>Total: </b></td><td></td><td id="row-tVal"></td><td></td></tr>').insertAfter($('tr#row-marker')).hide();//insert the row that holds the total
		
		//adds a new row with the specified arguments to the grid
		//and it returns a reference to the added row
		var addRow = function(id, title, artist, price, type, section){
			$data = '<tr id="rw-'+type+section+'_'+id+'"><td>'+title+'</td><td>'+
						artist+'</td><td class="view-cart-price">'+
						price+'</td><td><a id="dct-'+type+section+'_'+id+'" href="#" title="Delete '+title+'"><img src="http://fusiongreen.com/images/del-item.gif" width="16" height="16" border="0" alt="Delete '+title+'" /></a></td></tr>';
			
			$a = $($data).insertBefore($('tr#row-marker'));
			updateTotal();
			bindDeleteHandler($a);
		
			return $a;
			//$marker.before($data);
		}
		
		//any time an item is added to the cart, ensure that the total is updated accordingly
		var updateTotal = function(){
			$tRow = $('#row-tVal');
			
			tot = 0.00;
			
			/*if($cartItems.length > 0)
				sym = $cartItems[0]['price'].substring(0, 1);*/
				
			for(var index=0; index < $cartItems.length; index++){
				val = $cartItems[index]['price'];
				val = val.substring(1);//remove the dollar sign
				tot += parseFloat(val);
			}
			//tot = Math.round((tot) * 100)/100;//round off to 2d.p
			tot = tot.toFixed(2);
			//$tRow.html("<b>$"+tot+"</b>");
			$tRow.html("<b>$"+tot+"</b>");
			
			//check if the cart is empty, if yes, hide the total
			if($cartItems.length == 0)
				$('#row-total').hide();
			else
				$('#row-total').show();
		}
		
		var updateAlbumBtn = function($id, $section, $action){
			$btn = $('a[id^=ac-A'+$section+'_'+$id+']');
			
			if($action == 'add'){
				$btn.text('Add to cart');
			}else if($action == 'remove'){
				$btn.text('Remove from cart');
			}
		}
		
		var updateSingleAlbumBtn = function($id, $action){
			$btn = $('a[id^=ac-A0'+'_'+$id+']');
			
			if($action == 'add'){
				$btn.text('Add album to cart');
			}else if($action == 'remove'){
				$btn.text('Remove album from cart');
			}
		}
		
		var updateAlbumTrackBtn = function($id, $action){
			$btn = $('a[id=ac-s0'+'_'+$id+']');
			
			if($action == 'add'){
				$btn.text('Add to cart');
			}else if($action == 'remove'){
				$btn.text('Remove from cart');
			}
		}
		
		//in case there are any cookies available that corresponds to this cart,
		//populate the grid with it
		var restoreState = function(){
			//console.log('restoreState called');
			$tracks = getTracks();
			//console.log('restoreState(): Found '+$tracks.length+' items in the cart on page reload');
			for(i=0; i<$tracks.length; i++){
				$id = decodeURIComponent($tracks[i]['id']);//revert the String back to human readable form instead of an encoded form
				$title = decodeURIComponent($tracks[i]['title']);
				$artist = decodeURIComponent($tracks[i]['artist']);
				$price = decodeURIComponent($tracks[i]['price']);
				$type = decodeURIComponent($tracks[i]['type']);
				$section = decodeURIComponent($tracks[i]['section']);
				
				//console.log('restoring: id - '+$id+", title - "+$title+", artist - "+$artist+", price - "+$price+", type - "+$type+", section - "+$section);
				
				$cartItems.push({'id': $id, 'title': $title, 'artist': $artist, 'price': $price, 'type': $type, 'section': $section});
				$row = addRow($id, $title, $artist, $price, $type, $section);
				
				if(($cartItems.length % 2) === 0)
					$row.addClass('r2');
					
				if($type == 'T'){//track
					$btnEl = $('a#ac-'+$type+$section+'_'+$id);
					
					if($section == '0'){//handling of the single tracks section is different from that of regular tracks
						$btnEl.removeClass('a2c').addClass('rfc').text('Remove from cart');
					}else{
						//console.log('disabling '+'a#ac-'+$type+$section+'_'+$id);
						disableCartBtn($btnEl, $id, $type, $section, true);
					}
				}else if($type == 'A'){//album
					if($section == '0'){
						updateSingleAlbumBtn($id, 'remove');
					}else{
						updateAlbumBtn($id, $section, 'remove');
					}
				}else if($type == 's'){
					if($section == '0'){
						updateAlbumTrackBtn($id, 'remove');
					}
				}
			}
			
			/*for($field in $obj){
				$val = $obj[$field];
				console.log($field+" : "+$val);
			}*/
		}
		
		var bindDeleteHandler = function(scope){
			//delete this item from the grid, and its associated cookie and also enable its button
			//the scope argument is used to avoid binding the click event multiple times
			$('a[id^=dct-]').live('click', function(){
				$item = $(this);
				$id = $item.attr('id');
				$type = $id.substr(4, 1);
				$section = $id.substr(5, 1);
				$item_id = $id.substring(7);//remove the dct_A_s1_ by starting extraction at index 9
				removeItem($item_id, $type, $section);
				
				return false;
			});
		}
		
		//removes the item with the specified id from the array
		var removeItem = function(id, t, s){
			for(var index=0; index < $cartItems.length; index++){
				if($cartItems[index]['id'] == id){
					$cartItems.splice(index, 1);
					deleteCookie('fg-'+t+s+'_'+id);
					
					//remove the associated row from the grid
					$rowID = 'tr#rw-'+t+s+'_'+id;
					$($rowID).fadeOut('slow').remove();
					
					updateTotal();
					
					$btnEl = $('a#ac-'+t+s+'_'+id);
					
					if(t == 'T' && s == '0')
						$btnEl.removeClass('rfc').addClass('a2c').text('Add to cart');
					else if(t == 'A' && s == '0')//remove this singular album from the cart
						updateSingleAlbumBtn(id, 'add');
					else if(t == 'A' && s == '1')//remove this particular album
						updateAlbumBtn(id, s, 'add')
					else if(t == 's' && s == '0')//remove the track within an album from the cart
						updateAlbumTrackBtn(id, 'add');
					else
						disableCartBtn($btnEl, id, t, s, false);
					break;
				}
			}	
		}
		
		//a function to close the dialog
		var closeDialog = function(){
			$cart.slideUp('fast', function(){
				//$overlay.fadeOut('fast');
				$overlay.css('display', 'none');
			});
		}
		
		//adds a new item into the cart array and to the cookie
		var addItem = function(id, title, artist, price, type, section){//T=track, A=Album
			$cookie_name = "fg-"+type+section+"_"+id;
			
			$cookieExists = getCookie($cookie_name);
			if(!$cookieExists){//only add the item if it doesn't already exist as a cookie
				var item = {'id': id, 'title': title, 'artist': artist, 'price': price, 'type': type, 'section': section};
				//console.log("addItem(): "+item);
				$cartItems.push(item);
				setCookie($cookie_name, object2String(item));
				$row = addRow(id, title, artist, price, type, section);
				
				if(($cartItems.length % 2) === 0)
					$row.addClass('r2');
			}else{
				//console.log($cookie_name+' already exists');
			}
			
		}
		
		//disables the button with the specified id by removing the <a> tag and the image tag and replacing it by another image
		var disableCartBtn = function($el, btn_id, $t, $s, disable){
			$parentTag = $el.parent();
			
			if(disable){
				if($parentTag.is('td')){
					$el.fadeOut('fast', function(){
						$("<div id='dcb_"+$t+$s+"_"+btn_id+"' class='disabled-cart-btn'></div>").insertAfter($el).fadeIn('fast');
					});//end fadeOut
				}else if($parentTag.is('li')){
					$el.fadeOut('fast', function(){
						$nb = $("<div id='dcb_"+$t+$s+"_"+btn_id+"' class='disabled-cart-btn'><img src='http://fusiongreen.com/images/dot.gif' border='0' /></div>").insertAfter($el).fadeIn('fast');
						//if($s == 2 || s == 3)
						//	$nb.css('margin-left', '3px');//only the top music downloads/fusiongreen recommends section require this margin
					});//end fadeOut
				}
				
			}else{//if the button should be enabled, remove the disabled icon, then add the enabled one
				$genID = 'div#dcb_'+$t+$s+"_"+btn_id;
					$($genID).fadeOut('fast', function(){
						$el.fadeIn('fast');
						$(this).remove();
					});
			}//end else/if
		}//end disableCartBtn
		
		//clears the cart by removing all cookies and clearing the grid
		var clearCart = function(){
			/**
				The selector expression 'tr#rw_'+$itemID doesn't remove
				the rows that have the class 'r2', so the alternative was
				just to look for all the rows that start with 'rw'
				
				So fadeout the rows and then remove them when done
			*/
			$sel = 'tr[id^=rw-]';
			$($sel).each(function(index){
				$row = $(this);
				$row.fadeOut('slow', function(){
					$this = $(this);
					$id = $this.attr('id');
					$btnID = $id.substring(6);//remove the rw-T1_ID by starting extraction at index 6
					$type = $id.substr(3, 1);
					$section = $id.substr(4, 1);
					
					if($type == 'T'){//disable the icon if the item is a track
						$btnEl = $('a#ac-'+$type+$section+'_'+$btnID);
						
						if($section == '0'){
							$btn.removeClass('rfc').addClass('a2c').text('Add to cart');
						}else{
							disableCartBtn($btnEl, $btnID, $type, $section, false);
						}
					}else if ($type == 'A'){//update the button if the item is an album
						if($section == '0'){
							updateSingleAlbumBtn($btnID, 'add');
						}else{
							updateAlbumBtn($btnID, $section, 'add');
						}
					}else if($type == 's'){
						if($section == '0'){
							updateAlbumTrackBtn($btnID, 'add');
						}
					}
					
					$this.remove();
				});
			});
			
			$tracks = getTracks();
			//console.log("Clearing the following cart items.");
			//console.log($tracks);
			for(i=0; i<$tracks.length; i++){
				$cookie_name = "fg-"+$tracks[i]['type']+$tracks[i]['section']+"_"+$tracks[i]['id'];
				
				//$cartItems.splice(i, 1);
				deleteCookie($cookie_name);
			}
			
			//splicing the cart items with $cartItems.splice(i, 1) makes
			//the program buggy, so just create a new array
			$cartItems = new Array();//a way of clearing the array is recreating it
			//clear the grid
			//$tr.siblings().remove();
			//hide the total
			$('#row-total').hide();
		}
		
		//checks out to paypal
		/*var checkout = function(){
			$preForm = '<form action="pp/payment-handler.php?ac=upload" method="post">';
			$size = $cartItems.length;
			
			if($size > 0){
				$preForm += '\n   <input type="hidden" id="size" name="size" value="'+$size+'" />';
				
				for(i=0; i<$size; i++){
					$id = $cartItems[i]['id'];
					$type = $cartItems[i]['type'];
					$preForm += '\n   <input type="hidden" id="music_'+i+'" name="music_'+i+'" value="'+$id+'" />';
					$preForm += '\n   <input type="hidden" id="ty_'+i+'" name="ty_'+i+'" value="'+$type+'" />';
				}
				$preForm += '\n</form>';
				//alert($preForm);
				$theForm = $($preForm).appendTo($body).submit();
			}
		}*/
		
		var checkout = function(){
			$size = $cartItems.length;
			
			if($size > 0){
				//count the number of items available in the cart before procedding
				
				$numWindows = Math.ceil($cartItems.length/$cartLimit) - 1;//the number of windows to create (minus the current window)
				if($numWindows > 0){//create windows to handle the other transactions, though you have to notify the user first about this
					$content = "<div id='chd'>Checkout Notice</div>Dear customer, to ensure that all the items you have in the cart are successfully sent to Paypal, additional windows will be opened to handle all the items you have in the cart as the cart can only accommodate "+$cartLimit+" items at once without opening additional windows.<div id='cart_cont' style='text-align: center; margin: 10px 0 3px 0;'><input id='cwBtn' type='button' value='Click here to continue' /><div></div>";
					
					$.facebox($content);
				}else{//proceed with normal checkout, since all the items are manageable at once
					$preForm = '<form action="http://fusiongreen.com/pp/payment-handler.php?ac=upload" method="post">';
					$preForm += '\n   <input type="hidden" id="size" name="size" value="'+$size+'" />';
				
					for(i=0; i<$size; i++){
						$id = $cartItems[i]['id'];
						$type = $cartItems[i]['type'];
						$preForm += '\n   <input type="hidden" id="music_'+i+'" name="music_'+i+'" value="'+$id+'" />';
						$preForm += '\n   <input type="hidden" id="ty_'+i+'" name="ty_'+i+'" value="'+$type+'" />';
					}
					$preForm += '\n</form>';
					//alert($preForm);
					$theForm = $($preForm).appendTo($body).submit();
				}
			}
		}
		
		
		//creates external windows that handles the splitted checkout process
		var extWinCheckout = function(){
			$docHeight = $(document).height();
			$docWidth = $(document).width();
			$cartSize = 15;//the size of the cart items to be put in the window to be created
			
			$size = $cartItems.length;
			//console.log("The number of cart items is: "+$size);
			if($size > $cartLimit){
				$numWindows = Math.ceil($cartItems.length/$cartLimit);//the number of windows to create
				//console.log("numWindows: "+$numWindows);
				if($numWindows > 0){
					for($currentWin = 2; $currentWin <= $numWindows; $currentWin++){//current window starts from window 2 since the first is handled by the main window itself
						if(($currentWin * $cartLimit) < $size)
							$currentCartSize = $cartLimit;
						else
							$currentCartSize = $size - ($cartLimit * ($currentWin - 1));
							
						//console.log("current cart size: "+$currentCartSize);
						
						//create the window and add the form fields to it
						$preForm = "<html xmlns='http://www.w3.org/1999/xhtml'>\n<head>\n<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1' />\n<title>FusionGreen Checkout &raquo; Processing Payment...</title>\n<style type='text/css'>\nbody{ margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px; font-family: Verdana, Tahoma, sans-serif; font-size: 13px; background: #ffffff;}\n	.box1{background-color: #006600; height: 20px; width: 100%; margin-bottom: 0px;}\n.top_b{border-top: 2px solid #FFFFCC ;}\n	.btm_b{border-bottom: 2px solid #FFFFCC ;}\n</style>\n</head>\n<body onLoad='document.forms[\"paypal_form\"].submit();'>\n<div class='box1 btm_b'></div>\n<div><img src='http://fusiongreen.com/images/new-banner.jpg' style='margin-left:0px; margin-top: 0px; margin-bottom:0px;' width='669' height='113' border='0' /></div>\n<div class='box1 top_b'></div>\n<div>\n<h2 style='text-align: center; font-family: Georgia, \"Times New Roman\", Times, serif;'>Please wait, your order is being processed and you will be redirected to the Paypal website.</h2>\n<p>&nbsp;</p>\n<form action='pp/payment-handler.php?ac=upload' method='post'>";

						$preForm += "\n   <input type='hidden' id='size' name='size' value='"+$currentCartSize+"' />";
							
						for($j = 0; $j < $cartLimit; $j++){
							
							if($j < $currentCartSize){
								//console.log("j: "+$j);
								$ind = (($currentWin-1) * $cartLimit) + $j;
								//console.log("ind: "+$ind);
								$id = $cartItems[$ind]['id'];
								$type = $cartItems[$ind]['type'];
								$preForm += "\n   <input type='hidden' id='music_"+$j+"' name='music_"+$j+"' value='"+$id+"' />";
								$preForm += "\n   <input type='hidden' id='ty_"+$j+"' name='ty_"+$j+"' value='"+$type+"' />";
							}else{
								break;	
							}
						}
						$preForm += "\n	<p style='text-align: center;'>If you are not automatically redirected to Paypal within 10 seconds...</p>\n	<p style='text-align: center;'><input type='submit' value='Click Here' /></p>\n	</form>\n</body>\n</html>";
						
						//open a window for the newly created form and add the form content to it
						$top = $currentWin * 5;
						$left = $currentWin * 10;
						var winObj = window.open("win"+$currentWin, "status,left="+$left+",top="+$top+",screenX="+$left+",screenY="+$top+",height=640,width=480");
						winObj.document.write($preForm);
						winObj.document.close();
						
						//console.log($preForm);
					}
					
					//then submit the first batch in the main window
					$preForm = '<form action="pp/payment-handler.php?ac=upload" method="post">';
					$preForm += '\n   <input type="hidden" id="size" name="size" value="'+$cartLimit+'" />';
				
					for(i=0; i<$cartLimit; i++){
						$id = $cartItems[i]['id'];
						$type = $cartItems[i]['type'];
						$preForm += '\n   <input type="hidden" id="music_'+i+'" name="music_'+i+'" value="'+$id+'" />';
						$preForm += '\n   <input type="hidden" id="ty_'+i+'" name="ty_'+i+'" value="'+$type+'" />';
					}
					$preForm += '\n</form>';
					//alert($preForm);
					$theForm = $($preForm).appendTo($body).submit();
				}
					
			}
		}
		
		
		var showCart = function(){
			//$.facebox($cart_content);
			$cb = $("#view-cart-box");
			$content = $cb.html();
			//empty the cart-box so as to ensure that there is only one available cart per unit time,
			//whoch can either be invisible on the main page, or moved to the facebox
			$cb.empty();
			
			$.facebox($content);//ensure u move the content back to the cart box when the facebox is closed
		}
		
		restoreState();//populate the cart with any cookies found
		
		$('#cwBtn').live('click', function(){
			extWinCheckout();
		});
		
		//when the facebox is closed, return the cart to the dom
		$(document).bind('close.facebox', function() {
			$('#view-cart-box').append($('#view-cart-content')).append($('#cart-btn-panel'));
		});
		
		//when the SHOW CART link is clicked, populate with cart table with the cart array, and then display it
		$('a#show-cart').click(function(evt){
			//return showCart(evt);
			showCart();
			return false;
		});
		
		//close the dialog if the ESC key is pressed
		$(document).keydown(function(evt){
			var ESC = 27;
			if(evt.keyCode && evt.keyCode == ESC)
				closeDialog();
		});
		
		
		$('a#closeX').click(function(evt){
			evt.stopPropagation();
			closeDialog();
			return false;
		});
		
		$('#sgXBtn a').click(function(evt){
			evt.stopPropagation();
			$('#sgWin').fadeOut('fast', function(){
				$overlay.css('display', 'none');
			});
			return false;
		});
		
		//Single Track handling
		$('a[id^=ac-T0]').click(function(){
			$btn = $(this);
			
			//you need to determine if the click was a add to cart or remove from cart
			$action = $btn.text().substring(0, 3);
			$item_id = $btn.attr('id').substring(6);//remove the ac-T0_ by starting extraction at index 4
			$searchNode = $btn.parent().parent().parent();
			$search_term = 'div.info h2';
			$title = $searchNode.find($search_term).text();

			$search_term = 'div.info p.meta span.artiste a';
			$artist = $searchNode.find($search_term).text();

			$price = $btn.data('price');

			$type = "T";
			$section = "0";
			
			if($action == 'Add'){//add this track to cart
				addItem($item_id, $title, $artist, $price, $type, $section);
				$btn.removeClass('a2c').addClass('rfc').text('Remove from cart');
				//console.log($title+", "+$artist+", "+$price);
			}else{//remove this track from cart
				removeItem($item_id, $type, $section);
			}
			
			return false;
		});
		
		//Music section & New songs cart buttons handling
		$('a[id^=ac-T1]').click(function(){
			$btn = $(this);
			$item_id = $btn.attr('id').substring(6);//remove the ac-T1_ by starting extraction at index 4
			$searchNode = $btn.parent().siblings();
			$search_term = 'h3[id^=tt_'+$item_id+'] a';
			$title = $searchNode.find($search_term).text();
			
			$search_term = 'h4 a[class=sArtist]';
			$artist = $searchNode.find($search_term).text();
			
			$search_term = 'span[id^=pr_'+$item_id+']';
			$price = $searchNode.find($search_term).text();
			
			$type = "T";
			$section = "1";
			addItem($item_id, $title, $artist, $price, $type, $section);
			disableCartBtn($btn, $item_id, $type, $section, true);
			//console.log($title+", "+$artist+", "+$price);
			return false;
		});
		
		//Top Music Downloads/ Fusiongreen Recommends cart buttons
		$('a[id^=ac-T2], a[id^=ac-T3]').click(function(){
			$btn = $(this);
			$item_id = $btn.attr('id').substring(6);
			$searchNode = $btn.parent().parent().parent();
			
			$search_term = 'h3 a[class=trName]';
			$title = $searchNode.find($search_term).text();
			
			$search_term = 'h4.arName';
			$artist = $searchNode.find($search_term).text();
			
			$search_term = 'div[class=gPrice]';
			$price = $searchNode.find($search_term).text();
			
			$type = "T";
			$section = $btn.attr('id').substr(4, 1);;
			addItem($item_id, $title, $artist, $price, $type, $section);
			disableCartBtn($btn, $item_id, $type, $section, true);
			//console.log($title+", "+$artist+", "+$price);
			return false;
		});
		
		//Single Album handling
		$('a[id^=ac-A0]').click(function(){
			$btn = $(this);
			$item_id = $btn.attr('id').substring(6);//remove the ac-A0_ by starting extraction at index 4
			
			//determine the action to perform if it is to add the album
			//to cart or remove it from cart
			$action = $btn.text().substring(0, 3);
			$searchNode = $btn.parent().parent().parent();
			$search_term = 'h2.aln a';
			$title = $searchNode.find($search_term).text();
			
			$search_term = 'h3.ala';
			$artist = $searchNode.find($search_term).text();
			//remove the 'by ' preceeding the artiste name
			$artist = $artist.substring(3);
			
			$price = $btn.data('price');
			
			$type = "A";
			$section = "0";
			
			if($action == 'Add'){//Add to cart
				addItem($item_id, $title, $artist, $price, $type, $section);
				updateSingleAlbumBtn($item_id, 'remove');
			}else if($action == 'Rem'){//Remove from cart
				deleteCookie('fg-'+$type+$section+'_'+$item_id);
				updateSingleAlbumBtn($item_id, 'add');
			}
			
			return false;
		});
		
		//Album cart buttons handling
		$('a[id^=ac-A1]').click(function(){
			$btn = $(this);
			$item_id = $btn.attr('id').substring(6);//remove the ac-A1_ by starting extraction at index 4
			
			//determine the action to perform if it is to add the album
			//to cart or remove it from cart
			$action = $btn.text().substring(0, 3);
			$searchNode = $btn.parent();
			$search_term = 'h3 a';
			$title = $searchNode.find($search_term).text();
			
			$search_term = 'h4 a';
			$artist = $searchNode.find($search_term).text();
			
			$price = $searchNode.data('price');
			
			$type = "A";
			$section = "1";
			
			if($action == 'Add'){//Add to cart
				addItem($item_id, $title, $artist, $price, $type, $section);
				//$btn.text('Remove from cart');
				updateAlbumBtn($item_id, $section, 'remove');
			}else if($action == 'Rem'){//Remove from cart
				deleteCookie('fg-'+$type+$section+'_'+$item_id);
				//$btn.text('Add to cart');
				updateAlbumBtn($item_id, $section, 'add');
			}
			
			return false;
		});
		
		
		var handleBuyItem = function($item_id){
			$form = '<form action="http://fusiongreen.com/pp/payment-handler.php?ac=buy&ty=singles" method="post">\n   <input type="hidden" id="sid" name="sid" value="'+$item_id+'" />\n</form>';
			//console.log($preForm);
			$($form).appendTo($body).submit();
		}
		
		//whenever the buy now button for an album is clicked, generate a form with the value of the button clicked and then submit the form to paypal
		$("a[id^=ban0]").click(function(){
			$link = $(this);
			$item_id = $link.attr('id').substring(5);//remove the ban0_ by starting extraction at index 5						   
			handleBuyAlbum($item_id);
			return false;
		});
		
		//whenever the buy now button is clicked, generate a form with the value of the button clicked and then submit the form to paypal
		$("a[id^=bn0], a[id^=bn1], a[id^=tp]").click(function(){
			$item_id = $(this).attr('id').substring(4);//remove the bn0_ by starting extraction at index 4						   
			handleBuyItem($item_id);
			return false;
		});
		
		$('div.al-info a.bn').click(function(){
			$btn = $(this);
			$item_id = $btn.data('sid');
			handleBuyItem($item_id);
			return false;
		});
		
		$('div.al-info a.a2c').click(function(){
			$btn = $(this);
			$item_id = $btn.data('sid');
			$artist = $btn.data('artist');
			$price = $btn.data('price');
			$title = $btn.data('sname');
			
			$type = 's';
			$section = '0';
			addItem($item_id, $title, $artist, $price, $type, $section);
			updateAlbumTrackBtn($item_id, 'remove');
			
			return false;
		});
		
		var handleBuyAlbum = function($item_id){
			$form = '<form action="http://fusiongreen.com/pp/payment-handler.php?ac=buy&ty=album" method="post">\n   <input type="hidden" id="sid" name="sid" value="'+$item_id+'" />\n</form>';
			//console.log($preForm);
			$($form).appendTo($body).submit();
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		$('#clear-cart-btn').live('click', function(){
			clearCart();
			
			return false;
		});
		
		$('#c-cart').click(function(){
			checkout();
			
			return false;
		});
		
		$('#checkout-btn').live('click', function(){
			checkout();
			
			return false;
		});
		
		$('#newsForm').submit(function(){
			newsletterSignup($(this));
			
			return false;
		});
		
		var newsletterSignup = function($el){
			$msgHolder = "<div id='resBox' style='padding: 1px; border: 1px solid #CCC; background: #FFC; display: none; color: #000; font-size: 9px; font-weight: bold; margin-top: 2px; margin-bottom: 2px;'></div>";
			$msgHolder = $($msgHolder).insertBefore('#newsForm');
			
			$email = $('#e').val();
			var reg = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
			if (!$email.match(reg)) {
				$msgHolder.html("The email entered is invalid.").css('color', '#E00').fadeIn('fast');
				
				//fade out the message after 5 secs
				setTimeout(function(){$msgHolder.empty().fadeOut('fast');}, 2000);
				
				return false;
			}
			
			$msgHolder.html('Subscribing...').css('color', '#060').fadeIn('fast');
			
			//$url = "newsletter/signup_user.php";
			$.getJSON($el.attr('action'), $el.serialize(), function(data){
				$code = data.c;
				$res = data.msg;
				if($code == 0)
					$msgHolder.empty().html($res).css('color', '#060').fadeIn('fast');
				else
					$msgHolder.empty().html($res).css('color', '#E00').fadeIn('fast');
				
				setTimeout(function(){$msgHolder.remove();}, 2000);
			});
		}
	}
);
