// initialize some variables that are critical for keeping track of the cart. 

var cartitems = new Array();


function loadphones() {
	
	var makeid = $('make').options[$('make').selectedIndex].value;
	var target = "http://www.webuycell.com/phones.php?id="+makeid;
 
	var req = new Request({url:target, 
						  method:'get',
						  
		onSuccess: function(txt) {
			$('phonegrid').set('html', txt);
		},
		//Our request will most likely succeed, but just in case, we'll add an
		//onFailure method which will let the user know what happened.
		onFailure: function() {
			$('phonegrid').set('html', 'The request failed. Please try loading the phone make again.');
		}
	}).send();
	
}

function addphone(id) {
	
	var duplicate = 0;
	
	cartitems.each(function(item,index) {
		if(item.test('^'+id+'\:'))
		{
			if(duplicate!=1)
			{
			duplicate = 1;
			var combo = $splat(item.split(':'));
			var newqty = (combo[1]*1)+1;
			cartitems[index] = combo[0]+':'+newqty 
			}
		}
	}
	);
	
	if(duplicate == 0)
	{
	cartitems.include(id+':1');
	}
	loadcart(cartitems);
}


function removephone(id) {
	var duplicate = 0;
	cartitems.each(function(item,index) {
		if(item.test('^'+id+'\:'))
		{
			if(duplicate!=1)
			{
			duplicate = 1;
			var combo = $splat(item.split(':'));
			var newqty = (combo[1]*1)-1;
			if(newqty>0)
			{
			cartitems[index] = combo[0]+':'+newqty;
			}
			else
			{
			cartitems.erase(item);
			}
			}
		}
	}
	);
	
	cartitems.erase(id);
	
	loadcart(cartitems);
	
}


function loadcart(phones) {
	
	var query;
	var count=0;
	
	$('phonecart').set('html', '<br /><br /><br /><center><img src="/images/ajax-loader.gif"></center>');
	
	phones.each(function(item, index){
    	
		if($chk(item))
		{
			if(count>0)
			{
			query = query+','+item
			}
			else
			{
			query = item;
			}
		}
	
	count++;
	});
	
	if(!$defined(query))
	{query = '';}

	
	var target = "http://www.webuycell.com/phonecart.php?cartitems="+query;
 	
	var req = new Request({url:target, 
						  method:'get',
						  
		onSuccess: function(txt) {
			$('phonecart').set('html', txt);
			var pricedisplay = $('totalprice').innerHTML;
			$('totaldisplay').set('html',pricedisplay);
		},
		//Our request will most likely succeed, but just in case, we'll add an
		//onFailure method which will let the user know what happened.
		onFailure: function() {
			$('phonecart').set('html', 'The request failed. Please click on any phone to attempt a refresh.');
		}
	}).send();
	
	
}