var Basket = {
	Add: function(id){
		var params = {'id':id,which_action:'add'};
		var bs = new BasketAdaptor(params);
		bs.DoPostAndRender();
	},
	
	Remove: function(id){
		var params = {'id':id,which_action:'remove'};
		var bs = new BasketAdaptor(params);
		bs.DoPostAndRender();
	},
	
	RemoveAll: function(){
		var params = {which_action:'remove_all'};
		var bs = new BasketAdaptor(params);
		bs.DoPostAndRender();
	},
	
	ViewBasket: function(){
		window.location.href='/job_basket.php?start='+Search.Start+'&sid='+Search.Sid;	
	}
}



function BasketAdaptor(params){
	
	BasketAdaptor.prototype.DoPostAndRender = doPost;
	
	function doPost() {
		var xmlhttp = null;
		xmlhttp = getxmlhttp();
		xmlhttp.open("POST", "/xml/basket.php", true);
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				var results = xmlhttp.responseText;
				render(results);
			}
		}
	
		xmlhttp.send(getQueryString(params));
	}
	
	function getQueryString(){
		if(params.which_action == 'add' || params.which_action == 'remove'){
			return "id="+params.id+"&which_action="+params.which_action;	
		} else if(params.which_action == 'remove_all'){
			return "which_action="+params.which_action;		
		}
	}
	
	function render(results){
		
		if(params.which_action == 'add' && results != -1){
			document.getElementById('advert_'+params.id).innerHTML = "<div onclick='Basket.Remove("+params.id+")' class='remove_from_basket'></div><div class='view_basket' onClick='Basket.ViewBasket()'></div>";	
		} else if(params.which_action == 'remove' || params.which_action == 'remove_all'){
			document.getElementById('advert_'+params.id).innerHTML = "<div onclick='Basket.Add("+params.id+")' class='add_to_basket'></div>";		
		}
		
		if(results == 0){
			mesg = 'Your basket is empty';
			document.getElementById('job_basket').innerHTML = mesg;
		} else {
			
			if(results == -1){
				alert('You can only add up to 20 Jobs in the basket');	
			}
			
			if(results != -1){
				mesg = 'You have '+results+ ' job'+((results>1)?'s':'')+' in your basket';
				document.getElementById('job_basket').innerHTML = mesg;
			}
		}
		
		
	}
}