$(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<td width="180">Item Name</td>\n<td width="120">Artist</td>\n<td width="100">Price</td>\n<td width="18"></td>\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="images/checkout.jpg" width="83" height="23" border="0" alt="Clear cart icon" /></a></div>\n<div class="cart-btn"><a id="clear-cart-btn" href="#" title="Clear the carts content"><img src="images/clear-cart.jpg" width="83" height="23" border="0" alt="Clear cart icon" /></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
		
		//tell a friend handler
		$('a.rec_btn').click(function(){
			$btn = $(this);
			
			$searchNode = $btn.parent();
			
			$search_term = 'td.m_duration';
			$item_id = $searchNode.siblings($search_term).attr('id').substring(4);//remove the dur_ by starting extraction at index 4
			
			$search_term = 'span.sTrack';
			$title = $searchNode.siblings().find($search_term).text();
			
			$search_term = 'span.sArtist';
			$artist = $searchNode.siblings().find($search_term).text();
			
			recommendSong($item_id, $title, $artist);
		
			return false;
		});
		
		$('a.rec_btn1').click(function(){
			$btn = $(this);
			
			$searchNode = $btn.parent().parent().parent();
			
			$item_id = $btn.attr('id').substring(3);//remove the rc_ by starting extraction at index 3
			
			$search_term = 'span.trName';
			$title = $searchNode.find($search_term).text();
			
			$search_term = 'div.arName';
			$artist = $searchNode.find($search_term).text();
			
			recommendSong($item_id, $title, $artist);
		
			return false;
		});
		
		$('a.rec_btn2').click(function(){
			$btn = $(this);
			
			$searchNode = $btn.parent().parent();
			
			$item_id = $btn.attr('id').substring(3);//remove the rc_ by starting extraction at index 3
			
			$search_term = 'div.ttAl';
			$title = $searchNode.siblings($search_term).text();
			
			$search_term = 'div.ttAr';
			$artist = $searchNode.siblings($search_term).text();
			
			recommendSong($item_id, $title, $artist);
			//console.log($item_id+", "+$title+", "+$artist);
		
			return false;
		});
		
		var recommendSong = function($item_id, $title, $artist){
			$html = "<div id='recFriend'><h2 id='recTitle'>Recommend &quot;<span id='ms'>"+$title+"</span>&quot;&nbsp; to a friend</h2><div id='rfMsg'></div><form id='recForm' action='recommendSongHandler.php' method='post'><div style='padding: 5px 0px;' class='clearfix'><input type='hidden' id='artist' name='artist' value='"+$artist+"' /><input type='hidden' id='track' name='track' value='"+$title+"' /><input type='hidden' id='sid' name='sid' value='"+$item_id+"' /><label id='nameLb'>Your Name:</label><input type='text' size='35' id='r_name' name='r_name'/></div><div style='padding: 5px 0px;' class='clearfix'><label>Friend's Email(s):</label><input type='text' size='35' id='r_email' name='r_email'/></div><div id='recommendusers'><b>NOTE: </b>You can tell multiple friends by using a <b>comma</b> to separate their email addresses</div><div style='padding: 5px 0px;' class='clearfix'><label>Alert Type:</label><select id='alert-type' name='alert-type'><option value='0'>--- Select One ---</option><option value='A'>You've got to hear this!</option><option value='B'>This sounds interesting</option><option value='C'>Your kind of music</option><option value='D'>Sample this, you may like it</option><option value='E'>This reminds me of you</option><option value='F'>This track talks to you</option><option value='G'>Get this and tell me what you think</option><option value='H'>--Write your own comment--</option></select></div><div id='commentBox' style='padding: 5px 0px;' class='clearfix'><label>Comment:</label><textarea wrap='soft' rows='4' cols='38' id='r_comment' name='r_comment'></textarea></div><div><input type='submit' value='Submit' id='rfBtn1'/><input type='reset' value='Reset' id='rfBtn2'/></div><div style='height: 30px;'>&nbsp;</div></form></div>";
			$.facebox($html)
		}
		
		$('input#rfBtn1').live('click', function(evt){//when the recommend song form is submitted
			$msgBox = $('div#rfMsg').empty();//clear the error message if any message is there
			
			$name = $('input#r_name').val();
			if(!$name.match(/.+/)){
				$msgBox.text("You need to specify the your name").slideDown('fast');
				return false;
			}
			
			if($name.length < 3){
				$msgBox.text("You need to specify a valid name").slideDown('fast');
				return false;
			}
			
			$email = $('input#r_email').val();
			
			if(!$email.match(/.+/)){
				$msgBox.text("You need to specify your friend's email address").slideDown('fast');
				return false;
			}
			
			//first check if multiple email addresses were specified
			$emails = $email.split(",");
			for(a=0; a < $emails.length; a++){
				//trim the email first b4 validating
				$em = $emails[a].replace( /^\s+/g,'').replace(/\s+$/g,'');
				
				if(!$em.match(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/)){
					$msgBox.text("There was an error in the email address specified: '"+$emails[a]+"'").slideDown('fast');
					return false;
				}
			}
			
			/*if(!$email.match(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/)){
				$msgBox.text("You need to specify a valid email address").slideDown('fast');
				return false;
			}*/
			
			$alert = $('select#alert-type').val();
			if($alert == 0){
				$msgBox.text("You need to select the type of notification to send").slideDown('fast');
				return false;
			}
			
			if($alert == 'H'){
				$comment = $('textarea#r_comment').val();
				if(!$comment.match(/.+/)){
					$msgBox.text("You need to specify the your comment").slideDown('fast');
					return false;
				}
				
				if($comment.length < 5){
					$msgBox.text("Your comment is too short").slideDown('fast');
					return false;
				}
			}
			
				
			
			//everything seems okay, so post the data and hide the overlay
			$form = $('form#recForm');
			$form.slideUp('fast', function(){
				$msgBox.after('<div class=\'nMsg\'>Your recommendation has sucessfully been sent</div>').show();
				setTimeout(function(){
					$(document).trigger('close.facebox');
				}, 2000);
			});
			
			$.post($form.attr('action'), $form.serialize());
			
			
			return false;
		});
		
		$('select#alert-type').live('change', function(evt){
			$cb = $('div#commentBox');
			
			if($(this).val() == 'H')
				$cb.slideDown();
			else
				$cb.slideUp();
		 });
		
		
		$("#bnb").click(function(){
			$html = '<div id="sgBar">\n<span id="sgTitle">New Songs Notification</span>\n</div>\n<div id="sgForm">\n<div class="cInfo">Please specify your email address in the field below. </div>\n<div id="sgMsg"></div>\n<form id="sgForm" action="pp/nsn.php" method="post">\n<div class="clearfix">\n<label for="tr_email">Your email:</label>\n<input type="text" name="tr_email" id="tr_email" size="30"/>\n<input type="submit" class="transBtn" id="nsBtn" value="Proceed"/>\n</div>\n</form>\n</div><div id="throbber1">Processing...</div>';
					
			$.facebox($html);
			
			return false;
		});
		
		$('input#nsBtn').live('click', function(){
			$msgBox = $('div#sgMsg').css('font-size', '0.8em').slideUp('fast').empty();//empty the msg box if there's anything in it
			
			$email = $('input#tr_email').val();
			if(!$email.match(/.+/)){
				$msgBox.text("You need to specify your email address").slideDown('fast');
				return false;
			}
			
			if(!$email.match(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/)){
				$msgBox.text("You need to specify a valid email address").slideDown('fast');
				return false;
			}
			
			//disable the button so that it can't be clicked again while the form is being submitted
			$(this).attr('disabled', 'disabled');
			
			$('div.cInfo').hide();
			$('#sgForm').hide();
			$('#throbber1').show();
			
			$.post("pp/nsn.php", {em: $('#tr_email').val()}, function(data){
				$('#throbber1').after("<div id='nt-msg'>Your Email has been sucessfully registered</div>").hide();
				
				//remove the overlay after 2secs
				//setTimeout(function(){$(document).trigger('close.facebox');}, 2000);
			});
			
			return false;
		});
		
		
		//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="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.0;
			
			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
			//$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();
		}
		
		//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();
			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+", "+$title+", "+$artist+", "+$price+", "+$type+", "+$section);
				
				//console.log($id+" , "+$title+" , "+$artist+" , "+$price);
				$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');
				
				$btnEl = $('a#ac-'+$type+$section+'_'+$id);
				//console.log('disabling '+'a#ac-'+$type+$section+'_'+$id);
				disableCartBtn($btnEl, $id, $type, $section, true);
			}
			
			/*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);
					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};
				$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='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);
					
					$btnEl = $('a#ac-'+$type+$section+'_'+$btnID);
					disableCartBtn($btnEl, $btnID, $type, $section, false);
					
					$this.remove();
				});
			});
			
			for(i=0; i<$cartItems.length; i++){
				$cookie_name = "fg-"+$cartItems[i]['type']+$cartItems[i]['section']+"_"+$cartItems[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="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='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
		}
		
		//the lower panels contain the same logic, so this function handles them all
		var level2SendGift = function($item, evt){
			$item_id = $item.attr('id').substring(4);//remove the sg0_, sg1_, sg2_ or sg3_ by starting extraction at index 4
			$track_title = $item.parent().parent().parent().find('span[class=trName]').text();
			handleSendGift($item_id, $track_title, evt);
		}
		
		var level3SendGift = function($item, evt){
			$item_id = $item.attr('id').substring(4);//remove the sg2_  by starting extraction at index 4
			$track_title = $item.parent().parent().parent().find('div.ttAl').text();
			handleSendGift($item_id, $track_title, evt);
		}
		
		var handleSendGift = function($item_id, $track_title, evt){
			$html = '\n<div id="sgBar">\n<span id="sgTitle">Send \''+$track_title+'\' as a gift</span>\n</div>\n<div id="sgForm">\n<div id="sgMsg"></div>\n<form id="sgForm" action="pp/payment-handler.php?ac=gift-item&ty=singles" method="post">\n<div class="clearfix">\n<label for="sg_email">Friend\'s email:</label>\n<input type="text" name="sg_email" id="sg_email" size="30"/>\n<input type="hidden" id="sgid" name="sgid" value="'+$item_id+'" />\n<input type="submit" id="sgBtn" value="Send"/>\n</div>\n</form>\n</div>';
			
			$.facebox($html);
		}
		
		restoreState();
		
		$('#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'));
		})
		
		//restoreState();//populate the cart with any cookies found
		
		//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;
		});
		
		/*var showCart = function(evt){
			$bodyWidth = $body.width();
			
			//$cartWidth = $cart.width();
			$xLoc = ($bodyWidth - 400)/2;
			
			$overlay.css('display', 'block');
			$yLoc = evt.pageY;
			$cart.css({'left': $xLoc+'px', 'top': $yLoc+'px'}).slideDown('fast');
			
			return false;
		}*/
		
		//when the send as gift button is clicked, show the dialog for receiving
		//the friend's  email address, then validate the email to see if it's correct,
		//if it's not, report the error
		$('a[id^=sg0]').click(function(evt){
			$item = $(this);
			$item_id = $item.attr('id').substring(4);//remove the sg0_ by starting extraction at index 3
			$track_title = $item.parent().siblings().find('span[id^=tt]').text();
			handleSendGift($item_id, $track_title, evt);
			
			return false;
		});
		
		$('a[id^=sg1], a[id^=sg3]').click(function(evt){
			level2SendGift($(this), evt);
			
			return false;
		});
		
		$('a[id^=sg2]').click(function(evt){
			level3SendGift($(this), evt);
			
			return false;
		});
		
		//make sure the email field is filled in before continuing
		$('input#sgBtn').live('click', function(){
			$msgBox = $('div#sgMsg').css('font-size', '0.8em').slideUp('fast').empty();//empty the msg box if there's anything in it
			
			$email = $('input#sg_email').val();
			if(!$email.match(/.+/)){
				$msgBox.text("You need to specify the recipient's email address").slideDown('fast');
				return false;
			}
			
			if(!$email.match(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/)){
				$msgBox.text("You need to specify a valid email address").slideDown('fast');
				return false;
			}
			
			return true;
		});
		
		//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;
		});
		
		//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 = 'span[id^=tt_'+$item_id+']';
			$title = $searchNode.find($search_term).text();
			
			$search_term = 'span[id^=ar_'+$item_id+']';
			$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 = 'span[class=trName]';
			$title = $searchNode.find($search_term).text();
			
			$search_term = 'div.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;
		});
		
		//Top Tens cart buttons
		$('a[id^=ac-T4], a[id^=ac-T5], a[id^=ac-T6]').click(function(){
			$btn = $(this);
			$item_id = $btn.attr('id').substring(6);
			$searchNode = $btn.parent().parent().parent();
			
			$search_term = 'div.ttAl';
			$title = $searchNode.find($search_term).text();
			
			$search_term = 'div.ttAr';
			$artist = $searchNode.find($search_term).text();
			
			$search_term = 'div.tPrice';
			$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($section+", "+$title+", "+$artist+", "+$price);
			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
			
			$searchNode = $btn.parent().parent();
			$search_term = 'div.aln';
			$title = $searchNode.parent().find($search_term).text();
			
			$search_term = 'div.ala';
			$artist = $searchNode.parent().find($search_term).text();
			
			$search_term = 'div.alp';
			$price = $searchNode.siblings($search_term).text();
			
			$type = "A";
			$section = "1";
			addItem($item_id, $title, $artist, $price, $type, $section);
			disableCartBtn($btn, $item_id, $type, $section, true);
			//console.log($title+", "+$artist+", "+$price);
			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;
		});
		
		var handleBuyItem = function($item_id){
			$form = '<form action="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(){
			$item_id = $(this).attr('id').substring(5);//remove the ban0_ by starting extraction at index 5						   
			handleBuyAlbum($item_id);
			return false;
		});
		
		var handleBuyAlbum = function($item_id){
			$form = '<form action="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;
		});
		
		$('#c-cart1').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);
			});
		}
	}
);