	//these variables are populated by the AJAX functions
	var phones=new Array();
	var tariffs=new Array();
	var gifts=new Array();
	var errors=new Array();
	var tariff=new Array();
	var phone=new Array();
	var gift=new Array();
	var price=0;
	var step=1;
	var checkOutUrl="";
	
	
	var _forms=new Array();
	var tariffPaganations=Array();
	var tariffNetPaganation=new Array();
	var currentTariffNetwork=0;
	var networkLinks=null;
	var tarList=null;
	var doFade = true;
	var lastTarInfo=0;	
	
	var waitingObject = "";
	

	
	//The fade slows IE down considerably.
	jQuery.each(jQuery.browser, function(i, val) {
  	if(i=="msie") {
  		doFade = (!val);
  	}
  	});
	
	/**
		displays the loading icon where it's been clicked.
	**/
	
	function resetDealCreator(){
		var i=0;
		while(i<document.forms.length){
			document.forms[i].reset();
			i++;
		}
	}
	
	function pleaseWait(obj) {
		
		$("#dcLoading").css("left", $(obj).offset().left + (($(obj).width() - $("#dcLoading").width()) / 2));
		$("#dcLoading").css("top", $(obj).offset().top + (($(obj).height() - $("#dcLoading").height())/ 2));
		
			
		$("#dcLoading").show();
		
		$(obj).fadeTo(100,0.4);
		
		waitingObject = obj;
	}
	
	
	function disableForm(frm,what){
	return;
	
	str="setting "+frm + " to " + what+ "\n\n";
		/*
		if(_forms[frm]==null)_forms[frm]=document.forms[frm];
		i=0;
		while (el = _forms[frm][i++]){
		
		
		
			str+=el.type+" "+el.name+" "+el.id+"\n";
			el.disabled=what;	
		}*/
		
		//make sure the correct sections are disabled
		if (!what) {
			if ((getElephantById("emptyChoosePhones").className=="notDisplay"
			&&getElephantById("emptyChooseTariffs").className=="notDisplay")) {
					
					$("#giftType1").removeAttr("disabled");
					$("#giftType2").removeAttr("disabled");
					$("#giftType1lbl").removeAttr("title");
					$("#giftType1lb2").removeAttr("title");
					//$("#giftType1").attr("checked","checked");	
					//$("input[@name='giftType']").val("Cashback");	
				}
				else {
					$("#giftType1").attr("disabled","disabled");
					$("#giftType2").attr("disabled","disabled");
					
			}
		
		}
		//alert(str);
	}
	
	var currentTab = "";
	var tabTransition = false;
	
	function getElephantById(el){
		return document.getElementById(el);
	}
	

	
	function dealCreatorAjaxOk(request)
	{
		
		var Tabs=new Array("Phones","Tariffs","Gifts","Checkout");
		var handsetPrice=0;
		if (request.readyState != 4) {
			return 1;
		}
		
		if (request.status != 200) {
			enableSelects(1);
			return 0;  
		}

		//try it out, maybe the thing made an error.  who knows eh?
		
		try{
			eval(request.responseText);
			}
		catch(e){
			//alert(e);
		}
		
		if(errors.length>0) {
			showError(errors.join("<br />"));
		}
		
		if (price>0) {
			handsetPrice = "&pound;" + price;
		}
		else {
			handsetPrice = "FREE";
		}
		
		change("#dealPrice", handsetPrice);
		
		//enable/disable certain objects.
		if ((tariff['network_name'])&&(phone['product_name'])) {
			
			$("#giftType1").removeAttr("disabled");
			$("#giftType2").removeAttr("disabled");
			
		}
		else {
			$("#giftType1").attr("disabled","disabled");
			$("#giftType2").attr("disabled","disabled");
		}
		
		if(tariff['network_name']){
			change("#monthlyCost","&pound;" + tariff['price'] + " per month") ;
			getElephantById("emptyChooseTariffs").className="notDisplay";
			getElephantById("selectedChooseTariffs").className="display";
			
			tprice=tariff['price'];

			if(tprice==null) {
				tprice="";
			}
			else {
				if(tprice==0) {
					tprice="FREE";
				}
				else {
					 tprice="&pound;"+tprice;
				}
			}
			
			changeImg("selectedTariffNetwork","/images/www/deal_creator/"+tariff['network_name'].toLowerCase()+".png");
			$("#rowTariff").show();
			change("#selectedTariffMinutes", tariff['minutes']);
			change("#selectedTariffTexts", tariff['texts']);
			change("#selectedTariffPrice", tprice);
			change("#selectedTariffPrice1", tprice);
			change("#selectedTariffLength", tariff['contract_length']);
			change("#selectedTariffName", (tariff['name']!=null)?tariff['name']:"");
			change("#tariffName", tariff['name']);
			$("#tariffInfoLink").attr("href","/tariff-info?tariff=" + tariff['plu']);
			MakeRequest(null, "/deal-creator?ajaxrequest=1&ajaxfunc=getListOfCashbacks", requestCashbackListOk);	
		}
		else{
			$("#rowTariff").hide();
			getElephantById("emptyChooseTariffs").className="display";
			getElephantById("selectedChooseTariffs").className="notDisplay";
		}	
		
		if(phone['product_name']){
			$("#rowPhone").show();
			getElephantById("emptyChoosePhones").className="notDisplay";
			getElephantById("selectedChoosePhones").className="display";
			change("#handsetPrice", handsetPrice)
			//getElephantById("phoneImage").src=(phone['image_url']);
			change("#selectedPhoneName",(phone['product_name']!=null)?phone['make']+ ' ' + phone['product_name']:"");
			changeImg("phoneImage",phone['image_url']);
			$("#phoneInfoLink").attr("href","/phone-info?phone=" + phone['plu']);
			change("#handsetName",phone['make'] + ' ' + phone['product_name']);
		}
		else{
			$("#rowPhone").hide();
			document.getElementById("emptyChoosePhones").className="display";
			document.getElementById("selectedChoosePhones").className="notDisplay";
		}
	
		if(gift['type']=="cashback" || gift['type']=="autocashback"){
			$("#rowGift").show();
			changeImg("giftImage",gift['image']);
			change("#selectedGiftName", gift["name"]);
			change("#giftName", gift["name"]);
			change("#giftCost", "");
							
			$("#giftInfoLink").attr("href","/gift-info?gift=" + gift['type'].toUpperCase());
			
			document.getElementById("emptyChooseGifts").className="notDisplay";
			document.getElementById("selectedChooseGifts").className="display";
		}
		else if(gift['variantName']){
			$("#rowGift").show();
			change("#giftName", gift['variantName']);
			change("#giftCost", handsetPrice!="FREE"?"-":"FREE");
			changeImg("giftImage",gift['image_url']);
			change("#selectedGiftName",gift["variantName"]);
			
			$("#giftInfoLink").attr("href","/gift-info?gift=" + gift['plu']);
			document.getElementById("emptyChooseGifts").className="notDisplay";
			document.getElementById("selectedChooseGifts").className="display";
		}
		else{
			$("#rowGift").hide();
			document.getElementById("emptyChooseGifts").className="display";
			document.getElementById("selectedChooseGifts").className="notDisplay";
		}
		
		if(checkOutUrl!=""){
			changeImg("checkOutButton","/images/www/deal_creator/checkout_on.png");
			$("#checkOutLink").attr("href",checkOutUrl);
		}
		else{
			changeImg("checkOutButton","/images/www/deal_creator/checkout_off.png");
			$("#checkOutLink").attr("href","#");
		}
		
		if(step!=null){
			switchTab(Tabs[step-1]);
			}
		lurl="dchistory.html";//document.location.href.split("#")[0];
		//alert(gift["type"]);
		if(gift["type"]!=null){
			lastURL=lurl+"?*"+phone["plu"]+"*"+tariff["plu"]+"*"+gift["type"]+"*"+gift["id"];
			}
		else{
			lastURL=lurl+"?*"+phone["plu"]+"*"+tariff["plu"]+"*"+gift["type"]+"*"+gift["plu"];	
		}
		//document.location.href=lastURL;
	//	if(window.historyFrame==null)window.historyFrame=document.getElementById("historyIframe");
		
		//document.getElementById("historyIframe").document.location.href=lastURL;
		//alert("set iframe srec to "+lastURL);
		
	//	document.getElementById("historyIframe").location=lastURL;
	//	document.getElementById("historyIframe").src=lastURL;
		frames["history_iframe"].location.href=lastURL;
		if(document.all){
			document.getElementById("historyIframe").src=lastURL;
		}
		//turn off waiting icons
		if (waitingObject) {
			$(waitingObject).fadeTo(1,1);
			$("#dcLoading").hide();
			waitingObject = "";
		}
	//	document.getElementById("historyIframe").onload = checkIfPageHasChanged;
		
		
	}
	function effect_giftsOut(){
		$("#giftList").fadeOut("slow");	
	}
	function effect_giftsIn(){
		$("#giftList").fadeIn("slow");	
	}
	
	function effect_phonesOut(){
		$("#phoneList").fadeOut("slow");
	}
	function effect_phonesIn(){
		$("#phoneList").fadeIn("slow");
	}
	function effect_tariffsOut(){
		$("#tariffTableContainer").slideUp("slow");
	}
	function effect_tariffsIn(){
		$("#tariffTableContainer").slideDown("slow");
	}
	function effect_tariffsPageChange(){
		$("#tariffTableContainer").fadeOut("normal");
		
	}
	function effect_tariffsPageChanged(){
		$("#tariffTableContainer").fadeIn("normal");
		
	}
	
	function changeImg(target,changeTo){	
		var newImg = $("#"+target+"cf");
		var target = $("#"+target);
		
		
		
		if(target.attr("src")==changeTo){
			return;
		}
		if(target.attr("src")=="")target.attr("src",changeTo);
		if(newImg.attr("src")=="")newImg.attr("src",changeTo);
			
		
		
		newImg.fadeOut(1,function(){
				newImg.attr("src",changeTo);
				target.fadeOut(1500);
				newImg.fadeIn(1500,function(){
				target.attr("src",changeTo);
				target.fadeIn(10);
			});
		});
	}
	
	function populateGifts(){
		var i=0;
		var str="";
		if (gifts.length > 0) {
			while(i<gifts.length){
				str+="<div class=\"dcPhoneBox\"><a class=\"infoButton\" href=\"/gift-info?gift="+gifts[i]["plu"]+"\"  onclick=\"return pop(this,600, 400,1);\"><img src=\"/images/www/info.png\" /></a><a onclick='dcRequest(null, this.href+\"?ajaxrequest=1\", dealCreatorAjaxOk, this.parentNode);return false' href=\"/deal-creator/-/-/"+gifts[i]["plu"]+"\"><img src=\""+gifts[i]["image_url"]+"\" /></a>";
				str+="<div class=\"dcGiftModel\">"+gifts[i]["variantName"]+"</span></div>";
				str+="<p><a onclick='dcRequest(null, this.href+\"?ajaxrequest=1\", dealCreatorAjaxOk, this.parentNode);return false' href=\"/deal-creator/-/-/"+gifts[i]["plu"]+"\"><img src=\"/images/www/select_butt.png\" /></a></p></div>"
				i++;
			}
			$("#giftList").width(112 * gifts.length);
		}
		else
		{
			str = "<div class=\"dcNotice\">There are no matching gifts.</div>";
			$("'giftList").width=(500);
		}
		
		document.getElementById("giftList").innerHTML=str;
		performScroll(-10,"gift");
		effect_giftsIn();
	}
	
	function populatePhones(){
		var i=0;
		var str="";
		
		if (phones.length > 0) {
			while(i<phones.length){
	
	
				if(phones[i]["display_status"]=="1"){
					vis="class='dcPhoneImgSelected'";
				}
				else{
					vis=(phones[i]["display_status"]=="-1")?"class=\"dcPhoneImgUnavailable\" onmouseover=\"showInlineNotice('This phone is not available on this tariff. If you select it you will have to choose another tariff','#dcHandsetNotice');\" onmouseout=\"hideInlineNotice('#dcHandsetNotice');\"":"";
					
				}
	
				str+="<div class=\"dcPhoneBox\"><a class=\"infoButton\" href=\"/phone-info?phone="+phones[i]["plu"]+"\"  onclick=\"return pop(this,600, 400,1);\"><img src=\"/images/www/info.png\" /></a><a onclick='dcRequest(null, this.href+\"?ajaxrequest=1\", dealCreatorAjaxOk, this.parentNode);return false' href=\"/deal-creator/"+phones[i]["plu"]+"/-/-\" >";
	
				str+="<img "+vis+" src=\""+phones[i]["image_url"]+"\" /></a><p>";
				str+=phones[i]["make"]+"<br/>";
				str+="<div class=\"dcModel\">"+phones[i]["name"]+"</div></p>";
				str+="<p><a onclick='dcRequest(null, this.href+\"?ajaxrequest=1\", dealCreatorAjaxOk, this.parentNode);return false' href=\"/deal-creator/"+phones[i]["plu"]+"/-/-\"><img src=\"/images/www/select_butt.png\" /></a></p></div>"
				
				i++;
			}
			
			
			//102 = width of dcPhoneBox.
			$("#phoneList").width(112 * phones.length);
		}
		else
		{
			str = "<div class=\"dcNotice\">There are no matching phones.</div>";
			$("#phoneList").width(700);
		}
		performScroll(-10,"phone");
		document.getElementById("phoneList").innerHTML=str;
		effect_phonesIn();
	}
	
	function pageTariffs(start){

		$("#tariffList").scrollTo(start*parseInt($("#tariffList").css("height")),0,{duration:1000});
	
	}
	
	function pageTariffsNet(start){
	
		args=new Array();
		args["top"]="0px";
		w=parseInt($("#tariffList").css("width"));
		if(document.all)w=765;
		args["left"]=(start* w) + "px";
		
		$("#tariffList").scrollTo(args,0,{duration:1000,axis:'xy'});

		change2("#tariffPagenation",tariffPaganations[start]);
	}
	
	function bindPageTariffsNet(n)
	{
	  return function () { pageTariffsNet(n);return false };
	}

	
		function populateTariffs(viewAll){
			var pageLen=8;
			var i=0;
			var str="";
			var strx="<tr>";
			var tariffsF=new Array();
			var numTariffs=0;
			
			
			//return if the data is the same as it was last time.. dumbn
			if(lastTarInfo==tariffs.length){
			pageTariffsNet(0);
			effect_tariffsIn();	
				return;
				}
			lastTarInfo=tariffs.length;
			//get the network link icons
			if(networkLinks==null)networkLinks=document.getElementById('dcNetworkLinks').getElementsByTagName('a');
			if(tarList==null)tarList=document.getElementById("tariffList");
			tariffPaganations=new Array();
			
			i=0;
			while(i<networkLinks.length){
				//gray out the network links 
				$("#"+networkLinks[i].id).css({"opacity": 0.3}); 
				$("#"+networkLinks[i].id).click(function(){return false;});
				i++;
			}
			tariffsF["_tar_view_all"]=new Array();
			
			
							//alert("should do tariff list "+tariffs.length);
			
			if (tariffs.length) {		
				i=0;
				while(i<tariffs.length){
					if(tariffsF[tariffs[i]["network_name"]]==null){
						tariffsF[tariffs[i]["network_name"]]=new Array();
						numTariffs++;
					}
					tariffsF[tariffs[i]["network_name"]].push(tariffs[i]);
					tariffsF["_tar_view_all"].push(tariffs[i]);
					i++;
				}
				
				
				
				tariffLength=0;
				i=0;
				for(network in tariffsF){
					if(tariffsF[network].length>tariffLength)tariffLength=tariffsF[network].length;
					//str+="<a href='#' onclick='pageTariffsNet("+i+");return false'>"+network+"</a> | ";
					if($("#networkButton_"+network)){
						$("#networkButton_"+network).fadeTo("normal",0.99);						
						
						$("#networkButton_"+network).unbind("click");
						$("#networkButton_"+network).click(bindPageTariffsNet(i));
						
					}
					
					x=0;
					strx+="<td valign='top' style='width:800px'><table class='tarTableInd'>";
					var thisTariff=null;
					while(x<tariffsF[network].length){
						thisTariff=tariffsF[network][x];
						if(parseInt(thisTariff["handset_price"])=="0"){
							thisTariff["handset_price"]="FREE";
						}
						else thisTariff["handset_price"]="&pound;"+thisTariff["handset_price"];
						
						col=((x&1)?"dark":"light");
						
						
						
						strx+="<tr><td class=\""+col+" tarTableNetwork\"><a href='#"+network+"'></a><img src=\"/images/www/"+thisTariff["network_name"].toLowerCase()+"_fortab.png\" title=\""+thisTariff["network_name"]+"\" alt=\""+thisTariff["network_name"]+"\" /></td>";
						
						strx+="<td class=\""+col+" tarTableCost\">"+thisTariff["handset_price"]+"</td>";
						
						strx+="<td class=\""+col+" tarTableContract\">"+thisTariff["contract_length"]+"</td>";
						strx+="<td class=\""+col+" tarTableCost\">&pound;"+thisTariff["price"]+"</td>";
						strx+="<td class=\""+col+" tarTableMinutes\">"+thisTariff["minutes"]+"</td>";
						strx+="<td class=\""+col+" tarTableTexts\">"+thisTariff["texts"]+"</td>";
						strx+="<td class=\""+col+" tarTableSelect\">";
						strx+="<a onclick='dcRequest(null, this.href+\"?ajaxrequest=1\", dealCreatorAjaxOk, this.parentNode);return false' href=\"/deal-creator/-/"+thisTariff["plu"]+"/-\" >Select</a><br /></td></tr>";
						x++;
					}
					strx+="</table></td>";
					tariffPaganations[i]=" ";
					if(tariffsF[network].length>pageLen){
						tariffPaganations[i]+="<a href='#' onclick='pageTariffs(0);return false'>1</a> |";
						
						pages=parseInt((tariffsF[network].length-1)/pageLen);
						x=0;
						while(x<pages){
							tariffPaganations[i]+="<a href='#' onclick='pageTariffs("+(x+1)+");return false'>"+(x+2)+"</a> | ";
							x++;
						}
					}
					i++;
				}
				strx+="</tr>";
				change("#tariffPagenation",tariffPaganations[0]);			
			}
			else {
				strx = "<tr><td colspan=\"6\"><div class=\"dcNotice\"><p>Sorry, there are no available tariffs that match your selection.</p></div></td></tr>";
			}
			tarList.innerHTML="<Table id='tariff-table-container' cellpadding=0 cellspacing=0>"+strx+"</table>";
			
			//MakeRequest(null, "/deal-creator?ajaxrequest=1&ajaxfunc=getListOfCashbacks", requestCashbackListOk);		
			pageTariffsNet(0);
			effect_tariffsIn();	
		}
		
		/**
			SWITCHTAB
		**/
		
		function switchTab(newTab) {
			//Hide any status boxes
			
				
			if ((!tabTransition)||(currentTab=="Checkout")) {
				setLeft = $("#choose" + newTab).offset().left;
				setTop = $("#tabSelectors").offset().top + 1;	
				
				currentTab = newTab;
					
			
				if ($(".dcSelectedChoicesBox").length > 0) {
				//Create floaty box
					if (doFade) {
						if (!document.getElementById('dcFloatySelectedChoicesBox')) {
							moveBox = document.createElement("div");
							moveBox.id = "dcFloatySelectedChoicesBox";
							
							document.getElementById('dcContainer').appendChild(moveBox);
							
							moveBox.style.left = setLeft + "px";
							moveBox.style.top  = setTop + "px";
							
						}
				
						moveBox.style.display = "block";
						moveBox.style.zIndex = "1";				
										
						if ($("#dcFloatySelectedChoicesBox").css("left") !="-1px") {
						
							
							$("#dcFloatySelectedChoicesBox").animate({ 
						        left:setLeft + "px"
						     }, 300, function() {
						     		
						     		//When floaty box has finished, hide it and select the new tab
						     		moveBox.style.display = "none";
						     		document.getElementById('choose' + newTab).className = "dcSelectedChoicesBox";
						     		document.getElementById('space' + newTab).className = "dcSelectedChoicesBox";
						     		
						     } );
					     }
					     else {
					     	$("#dcFloatySelectedChoicesBox").css("left",setLeft + "px");
					     	moveBox.style.display = "none";
					     	document.getElementById('choose' + newTab).className = "dcSelectedChoicesBox";
					     	document.getElementById('space' + newTab).className = "dcSelectedChoicesBox";
					     }
				     }
				     else 
				     {
				     		document.getElementById('choose' + newTab).className = "dcSelectedChoicesBox";
					     	document.getElementById('space' + newTab).className = "dcSelectedChoicesBox";
				
				     }
					
				}
			
				
				
				//Stop if from repeating until the animation is over
				tabTransition = true;
				
				if (doFade) {
				//Fade out all visible tabs except the one selected
					tabs = $(".dcTab:visible").not("#tab" + newTab).fadeOut("slow", function() {
						//...then fade that one in
						$("#tab" + newTab).fadeIn("slow", function() {
								//Animation is over, enable tabs again.
								tabTransition = false;
								
								//Hide the tab if it's no longer the current tab
								// (This is to stop their being two tabs showing if 
								// the user clicks 2 tabs in quick succession somehow)
								
								if (newTab!=currentTab) {
									$("#tab" + newTab).fadeOut("slow");
								}
							}
						);
					}); 
					
					//The callback above only runs if any tabs are visible
					//so if none are visible we need to tell it to fade in
					//and hide anything else (which may be mid-fade)
					if (!tabs.length) {
						tabTransition = false;
						$(".dcTab:visible").not("#tab" + newTab).css("display","none");
						$("#tab" + newTab).fadeIn(500);
					}
				}
				else {
					//No fade effect for poor browsers
					$(".dcTab").hide();
					$("#tab" + newTab).show();
					tabTransition = false;
				}
				
				//Clear all tab styles		
				tabs = document.getElementById('tabSelectors').childNodes;
				
				for (x=0; x<tabs.length; x++) {
					if ((tabs[x].className)&&(tabs[x].className!="currentDeal")&&(tabs[x].className!="finalBox")) {
						tabs[x].className="dcChoicesBox";
					}
				}
				
				/*
				* The bit of the selected tabs that's outside the main div */
				tabs = document.getElementById("SpaceBox").childNodes;
				
				for (x=0; x<tabs.length; x++) {
					if ((tabs[x].className)&&(tabs[x].className!="currentDeal")&&(tabs[x].className!="finalBox")) {
						tabs[x].className="dcChoicesBox";
					}
				}
				
				//If the floaty thing doesn't exist for some reason
				//then we need to add the selection anyway
				if (!document.getElementById("dcFloatySelectedChoicesBox")) {
					tabTransition = false;
					document.getElementById('choose' + newTab).className = "dcSelectedChoicesBox";
					document.getElementById('space'  + newTab).className = "dcSelectedChoicesBox";
				}
			
			}		
			
			if(newTab=="Phones" && phones!=null)populatePhones();
				else if(newTab=="Tariffs" && tariffs!=null){
					populateTariffs();
				}
			return false;
		}	
		
	
	var bespokeScroll = 0;
	$(document).ready(function(){
	 $("#rightGift").click(function(){
	 performScroll(-1, "gift")
	 });
	 $("#leftGift").click(function(){
	 performScroll(1, "gift")
	 });
	 $("#rightPhone").click(function(){
	 performScroll(-1, "phone")
	 });
	 $("#leftPhone").click(function(){
	 performScroll(1, "phone")
	 });
	 
	 /*
	 	Show/hide gift scroller
	 */
	 $("input[name='giftType']").click(function() {
		 effect_giftsOut();
	 	if(this.id=="giftType1") {
	 		$("#giftScroller").css("display","none");
	 		$("#giftTariffTable").css("display","block");
		disableForm("giftSelectForm",true);
	 		MakeRequest(null, "/deal-creator?ajaxrequest=1&ajaxfunc=getListOfCashbacks", requestCashbackListOk);	
	 		
	 	}
	 	else if(this.id=="giftType2"){
	 		$("#giftScroller").css("display","none");
	 		$("#giftTariffTable").css("display","block");
		disableForm("giftSelectForm",true);
	 		MakeRequest(null, "/deal-creator?ajaxrequest=1&ajaxfunc=getListOfCashbacks&autocashback=1", requestCashbackListOk);	
	 	}
		else{
	 		$("#giftScroller").css("display","block");
	 		$("#giftTariffTable").css("display","none");
	 		change2("#giftTariffList","");
	 		
	 		requestGiftList();
	 	}
	 	
	 });
	});

function dcRequest(req, url_str, func, obj) {
	if (!waitingObject) {	
		pleaseWait(obj);
		MakeRequest(req, url_str, func);
	}
}

function escapeHTML (str)
{
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   div.appendChild(text);
   return div.innerHTML;
}; 

/**
	Change the innerHTML of an object, but also does a stylish effect.
**/
	
function change(jQuerySelector, newValue) {

	if(newValue==undefined)newValue="";
	//Stoopid javascript turns &pound; into £.
	var oldVal = ($(jQuerySelector).html()).replace("£","&pound;");
	
		
	if (newValue!=oldVal ) {
	
		$(jQuerySelector).html(newValue);
		
		if ($(jQuerySelector).html().length<1000) {
			$(jQuerySelector).effect("highlight",{color:"#59b9df"},1000);
		}
	}
}	

function change2(jQuerySelector,newValue){
	if(newValue==undefined)newValue="";
	var oldVal = ($(jQuerySelector).html()).replace("£","&pound;");
	if (newValue!= oldVal) {
		//alert($(jQuerySelector).html());
		if(newValue.length==1){
			$(jQuerySelector).slideUp("slow",function(){
			$(jQuerySelector).html(newValue);
			});
		}
		else if($(jQuerySelector).html().length==1){
			$(jQuerySelector).html(newValue);
			$(jQuerySelector).slideDown("slow");
		}
		else{
			$(jQuerySelector).fadeOut("slow",function(){
					$(jQuerySelector).html(newValue);
					$(jQuerySelector).fadeIn("slow");
				});
		}
	}
}
/**
	Pops up pretty error box!
**/
var timer;
function showError(errString) {
	newBox = getNoticePopUp();

	clearTimeout(timer);
	//parse errString!
	
	firstWord = errString.substring(0,errString.indexOf(" "));
	newBox.innerHTML = errString.substring(errString.indexOf(" "));
	
	//Set position based on position of tab select
	offsetPos = $("#choose" + firstWord).offset();
	
	newBox.style.top = (offsetPos.top + $("#choose" + firstWord).height() - 15 ) + "px";
	newBox.style.left = (offsetPos.left + 20) + "px";
	
	//Start timer - 8 seconds.
	timer = setTimeout('$(newBox).fadeOut("slow")',8000);	
	
}

/**
	Pretty much as above, only it displays
	the popup near a jquery div as specified.
**/

function showPopupNotice(notice, div) {
	newBox = getNoticePopUp();
	
	if ($(newBox).css("display")!="block") {
		clearTimeout(timer);
		
		$(newBox).html(notice);
		
		offsetPos = $(div).offset();
		
		$(newBox).css("left", offsetPos.left);
		$(newBox).css("top", offsetPos.top); 
		
		timer = setTimeout('$(newBox).fadeOut("slow")',8000);
	}
}

function showInlineNotice(notice, div) {
	$(div).html(notice);
	$(div).show();
	
}

function hideInlineNotice(div) {
	$(div).hide(100);
}

function getNoticePopUp() {
	if (!document.getElementById("dcPopUpBox")) {
		newBox = document.createElement("div");
		newBox.title = "Click to close";
		newBox.id = "dcPopUpBox";
		newBox.onclick = function () {
				$(this).fadeOut("slow");
				//newBox.style.display = "none";			
			}
		newBox.style.display = "block";
		document.getElementById('dcContainer').appendChild(newBox);
	}
	else	
	{
		newBox = document.getElementById("dcPopUpBox");
		newBox.style.display = "block";
	}
	
	return newBox;

}

function performScroll(scrollAmount, name) {

	 bespokeScroll += $('#'+name+'hold').attr('offsetWidth') * scrollAmount;
	 
	 var bespokeMax = $('#'+name+'hold').attr('offsetWidth') - $('#'+name+'List').attr('offsetWidth');
	 
	 if (bespokeScroll < bespokeMax) {
	 	bespokeScroll = bespokeMax;
	 }
	 if (bespokeScroll > 0) {
	 bespokeScroll = 0;
	 }
	 $('#'+name+'List').animate({left: bespokeScroll}, 'slow');
	
}

	MakeRequest(null, "/deal-creator?ajaxrequest=1", dealCreatorAjaxOk);

var lastURL="";
function checkIfPageHasChanged(){
	//document.location.href=lurl+"#*"+phone["plu"]+"*"+tariff["plu"]+"*"+gift["type"]+"*"+gift["plu"];
	//<a onclick='MakeRequest(null, this.href+\"?ajaxrequest=1\", dealCreatorAjaxOk);return false' href=\"/deal-creator/"+phones[i]["plu"]+"/-/-\" >";
	//if(lastURL==document.location.href)return;
	//lurl=document.location.href.split("*");
	//alert("check if page has changed");
	//lurl=frames["history_iframe"].location.href.split("?");
	if(lastURL.split(".html")[1]==frames["history_iframe"].location.href.split(".html")[1])return;
	
	//alert(lastURL+" "+frames["history_iframe"].location.href);
	lurl=frames["history_iframe"].location.href.split("*");
	//alert(lurl);
	//frames["history_iframe"].location.href
	
	phoneget=(phone["plu"]!=lurl[1])?lurl[1]:"-";
	//alert(phone["plu"]+" "+lurl[1]+" == "+phoneget);
	
	tariffget=(tariff["plu"]!=lurl[2])?lurl[2]:"-";
	
	if(lurl[3]!="undefined"){
		giftget=lurl[3]+"?priceID="+lurl[4];
		}
	else if(lurl[4]!="undefined")giftget=lurl[4];
	else if(lurl[3]=="undefined" && lurl[4]=="undefined")giftget="undefined";
	else giftget="-";
	
	url="/deal-creator/"+phoneget+"/"+tariffget+"/"+giftget;
	MakeRequest(null, url+"?ajaxrequest=1", dealCreatorAjaxOk);
	lastURL=frames["history_iframe"].location.href;
	//alert(url);
}

//TO DO: put this somewhere nicer
	//spend time with the kids
	//paint those pictures
	var giftListTimer=null;
	

	
	function requestGiftList()
	{
		clearTimeout(giftListTimer);
		giftListTimer=setTimeout("sendGiftListRequest()",350);
	}
	function sendGiftListRequest()
	{
		var giftType=getRadioValue(document.forms["giftSelectForm"]["giftType"]);
		//effect_giftsOut();
		//alert("/deal-creator?ajaxrequest=1&ajaxfunc=getListOfGifts&giftType="+giftType);
		disableForm("giftSelectForm",true);
		MakeRequest(null, "/deal-creator?ajaxrequest=1&ajaxfunc=getListOfGifts&giftType="+giftType, requestGiftListOk);
	}	
	function requestGiftListOk(request){
		if (request.readyState != 4) {
			return 1;
		}
		if (request.status != 200) {
			return 0; 
		}
		eval(request.responseText);
		
		if(errors.length>0)alert(errors.join("\n"));
		disableForm("giftSelectForm",false);
		
		populateGifts();	
	}
	
	function pageCashbacks(start){
		$("#cashbackList").scrollTo(start*parseInt($("#cashbackList").css("height")),0,{duration:1000});
	}
		
	function requestCashbackListOk(request){
		var pageLen=8;
		
		if (request.readyState != 4) {
			return 1;
		}
		if (request.status != 200) {
			return 0; 
		}

		eval(request.responseText);
	
		var rows="";
		var pag="";
		
		if (cashbacks.length) {
		
		if(cashbacks.length>pageLen){
			pag+="<a href='#' onclick='pageCashbacks(0);return false'>1</a> |";
			
			pages=parseInt((cashbacks.length-1)/pageLen);
			x=0;
			while(x<pages){
				pag+="<a href='#' onclick='pageCashbacks("+(x+1)+");return false'>"+(x+2)+"</a> | ";
				x++;
			}
		}
		change2("#giftPaganation",pag);
		for(i=0;i<cashbacks.length;i++){
			rows+="<tr>";
		
			colour=((i&1)?"light":"dark");
			
			price=(parseInt(cashbacks[i]["handset_price"])==0)?"FREE":"&pound;"+cashbacks[i]["handset_price"];
	
			rows+="<td class='giftTariffName'>"+cashbacks[i]["tariff_name"]+"</td>";
			rows+="<td class='"+colour+" giftTariffPrice'>"+price+"</td>";
			rows+="<td class='"+colour+" giftTariffContract'>&pound;"+cashbacks[i]["tariff_price"]+"</td>";
			rows+="<td class='"+colour+" giftTariffMinutes'>"+cashbacks[i]["minutes"]+" minutes / "+cashbacks[i]["texts"]+" texts</td>";
			rows+="<td class='"+colour+" giftTariffGift'>"+cashbacks[i]["gift_default_name"]+"</td>";
			rows+="<td class='"+colour+" giftTariffEffectivePrice'>&pound;"+cashbacks[i]["effective_price"]+"</td>";
			rows+="<td class='"+colour+" giftTariffSaving'>&pound;"+cashbacks[i]["saving"]+"</td>";
			
			tarriff=(cashbacks[i]['tariff_plu']!=undefined)?cashbacks[i]['tariff_plu']:"-";
			if(tariff=="")tariff="-";
			if(cashbacks[i]["autocashback"]=="1"){
				gift="autocashback";
			}
			else gift="cashback";
			rows+="<td class='"+colour+" giftTariffSelect' ><a onclick='dcRequest(null, this.href+\"&ajaxrequest=1\", dealCreatorAjaxOk, this.parentNode);return false' href=\"/deal-creator/-/"+tariff+"/"+gift+"?priceID="+cashbacks[i]["price_id"]+"\">select</a></td>";
			
			rows+="</tr>";
		}
		}
		else
		{
			rows+="<tr><td colspan=\"5\">There are no cashback deals available on this tariff</td></tr>";
		}
		disableForm("giftSelectForm",false);
		
		
		change("#giftTariffList",rows);
	}
	
var tariffListTimer=null;
	var networkID=0;
	function requestTariffList(network){
		if(network)networkID=network;
	
		clearTimeout(tariffListTimer);
		tariffListTimer=setTimeout("sendTariffListRequest()",350);
	}
	
	function requestTariffListOk(request){
		if (request.readyState != 4) {
			return 1;
		}
		
		if (request.status != 200) {
			return 0; 
		}
		eval(request.responseText);
		disableForm("tariffSelectForm",false);
		
		populateTariffs();
	}
	function getRadioValue(radio){
	for (var i=0; i < radio.length; i++)
	   {
	   if (radio[i].checked)
	      {
	      return radio[i].value;
	      }
	   }
	   return -1;
	}
		
	function sendTariffListRequest(){
		var args="";
		var len=getRadioValue(document.forms["tariffSelectForm"]["contractLength"]);
		var cost=getRadioValue(document.forms["tariffSelectForm"]["contractCost"]);
		if(networkID!=0)args+="network_id="+networkID+"&";
		disableForm("tariffSelectForm",true);
		effect_tariffsOut();
		
		
	
		if(len>=0){
			args+="contract_length="+len+"&";
		}
		if(cost>=0){
			args+="price_range="+cost+"&";
		}
		//alert(args);
		MakeRequest(null, "/deal-creator?ajaxrequest=1&ajaxfunc=getListOfTariffs&"+args, requestTariffListOk);
	}
	var phoneListTimer=null;
	
	function requestPhoneList(){
		requeryDealCreator();
		
		clearTimeout(phoneListTimer);
		phoneListTimer=setTimeout("sendRequestPhoneList()",350);
	}
	
	function requestPhoneListOk(request){
		if (request.readyState != 4) {
			return 1;
		}
		
		if (request.status != 200) {
			return 0; 
		}
		//alert(request.responseText);
		eval(request.responseText);
		populatePhones();
		disableForm("phoneSelectForm",false);
	}
	
	function sendRequestPhoneList(){
		var args="";
		effect_phonesOut();
		disableForm("phoneSelectForm",true);
		
		args+="makeID="+document.getElementById("dealcreator_makeID").value+"&";
		args+="productVariantID="+document.getElementById("dealcreator_productVariantID").value+"&";
		args+="colour="+document.getElementById("dealcreator_colourID").value+"&";
		//alert("mk da requerst");
		MakeRequest(null, "/deal-creator?ajaxrequest=1&ajaxfunc=getListOfPhones&"+args, requestPhoneListOk);
	}

//checks if back /forward buttons have been used.	
//setInterval("checkIfPageHasChanged()",50);

//TO DO: put this somewhere nicer
	//spend time with the kids
	//paint those pictures
	var giftListTimer=null;
	

	
	function requestGiftList()
	{
		clearTimeout(giftListTimer);
		giftListTimer=setTimeout("sendGiftListRequest()",350);
	}
	function sendGiftListRequest()
	{
		var giftType=getRadioValue(document.forms["giftSelectForm"]["giftType"]);
		//effect_giftsOut();
		//alert("/deal-creator?ajaxrequest=1&ajaxfunc=getListOfGifts&giftType="+giftType);
		disableForm("giftSelectForm",true);
		MakeRequest(null, "/deal-creator?ajaxrequest=1&ajaxfunc=getListOfGifts&giftType="+giftType, requestGiftListOk);
	}	
	function requestGiftListOk(request){
		if (request.readyState != 4) {
			return 1;
		}
		if (request.status != 200) {
			return 0; 
		}
		eval(request.responseText);
		
		if(errors.length>0)alert(errors.join("\n"));
		disableForm("giftSelectForm",false);
		
		populateGifts();	
	}
	
	function pageCashbacks(start){
		$("#cashbackList").scrollTo(start*parseInt($("#cashbackList").css("height")),0,{duration:1000});
	}
		
	function requestCashbackListOk(request){
		var pageLen=8;
		
		if (request.readyState != 4) {
			return 1;
		}
		if (request.status != 200) {
			return 0; 
		}

		eval(request.responseText);
	
		var rows="";
		var pag="";
		if(cashbacks.length>pageLen){
			pag+="<a href='#' onclick='pageCashbacks(0);return false'>1</a> |";
			
			pages=parseInt((cashbacks.length-1)/pageLen);
			x=0;
			while(x<pages){
				pag+="<a href='#' onclick='pageCashbacks("+(x+1)+");return false'>"+(x+2)+"</a> | ";
				x++;
			}
		}
		change2("#giftPaganation",pag);
		
		if (cashbacks.length>0) {
			for(i=0;i<cashbacks.length;i++){
				rows+="<tr>";
			
				colour=((i&1)?"light":"dark");
				
				price=(parseInt(cashbacks[i]["handset_price"])==0)?"FREE":"&pound;"+cashbacks[i]["handset_price"];
		
				rows+="<td class='giftTariffName'>"+cashbacks[i]["tariff_name"]+"</td>";
				rows+="<td class='"+colour+" giftTariffPrice'>"+price+"</td>";
				rows+="<td class='"+colour+" giftTariffContract'>&pound;"+cashbacks[i]["tariff_price"]+"</td>";
				rows+="<td class='"+colour+" giftTariffMinutes'>"+cashbacks[i]["minutes"]+" minutes / "+cashbacks[i]["texts"]+" texts</td>";
				rows+="<td class='"+colour+" giftTariffGift'>"+cashbacks[i]["gift_default_name"]+"</td>";
				rows+="<td class='"+colour+" giftTariffEffectivePrice'>&pound;"+cashbacks[i]["effective_price"]+"</td>";
				rows+="<td class='"+colour+" giftTariffSaving'>&pound;"+cashbacks[i]["saving"]+"</td>";
				
				tarriff=(cashbacks[i]['tariff_plu']!=undefined)?cashbacks[i]['tariff_plu']:"-";
				if(tariff=="")tariff="-";
				if(cashbacks[i]["autocashback"]=="1"){
					gift="autocashback";
				}
				else gift="cashback";
				rows+="<td class='"+colour+" giftTariffSelect' ><a onclick='MakeRequest(null, this.href+\"&ajaxrequest=1\", dealCreatorAjaxOk);return false' href=\"/deal-creator/-/"+tariff+"/"+gift+"?priceID="+cashbacks[i]["price_id"]+"\">select</a></td>";
				
				rows+="</tr>";
			}
		}
		else {
			rows+="<tr><td></td><td colspan=\"6\"><div class=\"dcNotice\">There are no Cashback By Redemption deals available on this tariff.</div></td></tr>";
		}
		disableForm("giftSelectForm",false);
		
		change("#giftTariffList",rows);
	}
	

	