var ajaxObject;
var DT_showAlerts;
var DT_overrideReturnURL = "";

function addEvent(elm, evType, fn, useCapture){
	if(elm.addEventListener){
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent){
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	}
	else{
		elm['on' + evType] = fn;
	}
}

function initPage(){

	DT_showAlerts = window.location.href.indexOf('dom=y') > 0 ? true : false;
	
	
	var f=document.getElementsByTagName("a"); // we're going to reprogram the links
	
	for(i=0;i<f.length;i++)
	{
		if(f[i].title.indexOf("Go to page ")==0) // this is a navigation page
		{
			// add an onclick event
			eval("addEvent(f[i],'click',function(){gotoPage('"+f[i].title.substring(11)+"');},false);");
		}
		if(f[i].rel=="DTPopup")
		{
			eval("addEvent(f[i],'click',function(){createPopUp('"+f[i].href+"');},false);");
			f[i].href="javascript:void(0)";
		}
		if(f[i].rel=="clearSearchBox")
		{
			f[i].href="show_whole_shop_clear_search.php";
		}
	}
	


	// now put text into any textareas or inputs with a title
	var f=document.getElementsByTagName("input"); // do input type text to start with
	for(i=0;i<f.length;i++)
	{
		if(DT_showAlerts)
		{
			alert("Searching through text boxes");
		}
		if(f[i].title!="" && f[i].type=="text")
		{
			if(DT_showAlerts)
			{
				alert("Found an input type text with a title");
			}
			eval("addEvent(f[i],'click',function(){DT_selectFormElement('"+f[i].id+"','"+f[i].title+"');},false);");
			eval("addEvent(f[i],'blur',function(){DT_deselectFormElement('"+f[i].id+"','"+f[i].title+"');},false);");
			eval("addEvent(f[i],'change',function(){DT_changedFormElement('"+f[i].id+"','"+f[i].title+"');},false);");
			eval("addEvent(f[i],'keyup',function(){DT_changedFormElement('"+f[i].id+"','"+f[i].title+"');},false);");
			eval("addEvent(f[i],'keydown',function(){DT_changedFormElement('"+f[i].id+"','"+f[i].title+"');},false);");
			
			if(f[i].value == "")
			{
				f[i].value = f[i].title;
				v = "";
			}
			else
			{
				v = f[i].value;
			}
			
			// now we need to create a hidden field with EXACTLY the same ID and name, then change the ID and name of the visible one
			// this is so that the javascript routines can put 'search' or whatever in the visible box, but the form processing will be done on the invisible one which can be empty
			
			if(DT_showAlerts)
			{
				alert("Name is "+f[i].name+", and ID is "+f[i].id);
			}
			t = document.createElement("input");
			t.setAttribute('id',f[i].id);
			t.setAttribute('name',f[i].name);
			t.setAttribute('type','hidden');
			t.setAttribute('value',v);
			
			n = "DT_"+f[i].name;
			id = "DT_"+f[i].id;
			
			f[i].setAttribute('name',n);
			f[i].setAttribute('id',id);
			f[i].setAttribute('title','');
			
			f[i].parentNode.appendChild(t);
		}
	}
	
	
	var f=document.getElementsByTagName("textarea"); // now do textareas
	for(i=0;i<f.length;i++)
	{
		if(f[i].title!="")
		{
			eval("addEvent(f[i],'click',function(){DT_selectFormElement('"+f[i].id+"','"+f[i].title+"');},false);");
			eval("addEvent(f[i],'blur',function(){DT_deselectFormElement('"+f[i].id+"','"+f[i].title+"');},false);");
			eval("addEvent(f[i],'change',function(){DT_changedFormElement('"+f[i].id+"','"+f[i].title+"');},false);");
			eval("addEvent(f[i],'keyup',function(){DT_changedFormElement('"+f[i].id+"','"+f[i].title+"');},false);");
			eval("addEvent(f[i],'keydown',function(){DT_changedFormElement('"+f[i].id+"','"+f[i].title+"');},false);");
			
			if(f[i].value == "")
			{
				f[i].value = f[i].title;
				v = "";
			}
			else
			{
				v = f[i].value;
			}
			
			// now we need to create a hidden field with EXACTLY the same ID and name, then change the ID and name of the visible one
			// this is so that the javascript routines can put 'search' or whatever in the visible box, but the form processing will be done on the invisible one which can be empty
			
			t = document.createElement("input");
			t.setAttribute('id',f[i].id);
			t.setAttribute('name',f[i].name);
			t.setAttribute('type','hidden');
			t.setAttribute('value',v);
			
			n = "DT_"+f[i].name;
			id = "DT_"+f[i].id;
			
			f[i].setAttribute('name',n);
			f[i].setAttribute('id',id);
			f[i].setAttribute('title','');
			
			f[i].parentNode.appendChild(t);
		}
	}





	
	// now set up any 'add to cart' and 'buy now' links
	
	// forms first
	
	
	if(DT_showAlerts)
	{
		alert("Testing mode enabled.");
	}

	ajaxObject = startAjax();



	if(ajaxObject != null)
	{
		if(DT_showAlerts)
			alert("Ajax On");
			
		f = document.getElementsByTagName("form");
		
		if(DT_showAlerts)
			alert("f contains "+f.length+" elements");
		
		for(i=0;i<f.length;i++)
		{
			if(DT_showAlerts)
				alert("Testing element "+i+"\n"+f[i]);
			
			//if(f[i].name)
			//{	
				if(f[i].name.indexOf("addToCart") == 0)
				{
					if(DT_showAlerts)
						alert("Element "+i+" is an add to cart.");
					
					if(DT_showAlerts)
						alert("Adding submit behaviour");
					
					// add an onsubmit event
					eval("addEvent(f[i],'submit',function(){return addToCart('"+f[i].id+"');},false);");
				}
			//}
		}
		
		// now 'a' links
		f = document.getElementsByTagName("a");
		
		for(i=0;i<f.length;i++)
		{
			if(f[i].title.indexOf("Add To Basket") == 0)
			{
				// add an onclick event
				eval("addEvent(f[i],'click',function(){openLinkWithAjax('"+f[i].href+"');},false);");
			}
			else if(f[i].title.indexOf("Buy Now") == 0)
			{
				eval("addEvent(f[i],'click',function(){openLinkWithAjax('"+f[i].href+"');},false);");
			}
		}
	}
	
	// check to see if a local page wants to initialise anything too
	if(typeof localInitPage == 'function')
	{
		localInitPage();
	}
	
}

function startAjax(){
	// returns an ajax object if possible
	var xmlHttp=null;
	try
  	{
  		// Firefox, Opera 8.0+, Safari
  		xmlHttp=new XMLHttpRequest();
  	}
	catch (e)
  	{
  		// Internet Explorer
  		try
    	{
    		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    	}
  		catch (e)
    	{
    		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    	}
  	}
	return xmlHttp;
}

addEvent(window, 'load', initPage, false);



// functions
function submitListOptionsForm()
{
	if(DT_showAlerts)
	{
		alert("submitting form");
		
	}
	// putting this here to maximize backwards compatibility across the site
	d = document.createElement("input");
	d.setAttribute("type","hidden");
	d.setAttribute("name","returnURL");
	d.setAttribute("id","returnURL");
	
	l = self.location.href;

	
	if(DT_overrideReturnURL != "")
	{
		l = DT_overrideReturnURL;
	}
	
	if(DT_showAlerts)
	{
		alert("Setting returnURL to "+l);
	}
	
	d.setAttribute("value",l);
	document.getElementById("listOptions").appendChild(d);
	
	document.getElementById("listOptions").action="submit-options-form.php";
	document.getElementById("listOptions").submit();
}
function submitListOptionsFormTop()
{
	document.getElementById("listOptions").sortOrder.selectedIndex = document.getElementById("listOptionsTop").sortOrder.selectedIndex;
	submitListOptionsForm();
	return false;
}
function gotoPage(p)
{
	// just set the form and submit it
	document.getElementById("page").value = p - 1;
	
	// create a new hidden field in the form
	// putting this here to maximize backwards compatibility across the site
	d = document.createElement("input");
	d.setAttribute("type","hidden");
	d.setAttribute("name","returnURL");
	d.setAttribute("id","returnURL");
	
	l = self.location.href;

	
	if(DT_overrideReturnURL != "")
	{
		l = DT_overrideReturnURL;
	}
	
	if(DT_showAlerts)
	{
		alert("Setting returnURL to "+l);
	}
	
	d.setAttribute("value",l);
	document.getElementById("navigationForm").appendChild(d);
	
	document.getElementById("navigationForm").action="submit-navigation-form.php";
	document.getElementById("navigationForm").submit();
}
function setOverride(n)
{
	if(DT_showAlerts)
	{
		alert("Setting override to "+n);
	}
	DT_overrideReturnURL = n;
}

function gotoPageOld(p)
{
	// just set the form and submit it
	document.getElementById("page").value = p - 1;
	document.getElementById("navigationForm").action=self.location.href;
	document.getElementById("navigationForm").submit();
}

function addToCart(f)
{	
	if(DT_showAlerts)
		alert("Adding to the basket");
		
	// f is the id of the form
	v = document.getElementById(f);
	
	if(v.elements['js_on'])
		v.elements['js_on'].value = "YES";
	
	product = v.elements['product'].value;
	quantity = v.elements['quantity'].value;
	type = v.elements['type'].value;
	
	s = "add_to_cart.php?product="+product+"&quantity="+quantity+"&type="+type;
	
	// check to see if it's a 'straight to checkout' one
	if(v.elements['straightToCheckout'] != null)
	{
		// yes
		s+="&straightToCheckout=yes";
	}
	
	ajaxObject.open("GET", s, true);
	ajaxObject.onreadystatechange=basketUpdated;
	ajaxObject.send(null);
    
	return false;
}

function openLinkWithAjax(l)
{
	ajaxObject.open("GET", l, true);
	ajaxObject.onreadystatechange=basketUpdated;
	ajaxObject.send(null);
	
	return false;
}

function basketUpdated()
{
	if(ajaxObject.readyState==4) // the request is complete
	{
		var data=ajaxObject.responseText;
		
		////alert(data);
		
		if(data.indexOf('Sorry, your basket could not be updated') >= 0)
		{
			//alert("Sorry, your basket could not be updated.\nIn order to prevent fraud, we only allow a maximum of 3 items per purchase.");
		}
		if(data.indexOf('That product is already in your basket') >= 0)
		{
			//alert("That product is already in your basket. To buy more than one, please open your basket and change the quantity.");
		}
		
		if(data.indexOf("CHECKOUT") == 0)
		{
			////alert("Test - please ignore");
			// self.location.href="confirm_and_pay";
			//self.location.href="show_basket";
			self.location.href="http://www.expresswatches.co.uk/show_basket";
			// self.location.href="http://panther.directrouter.co.uk/~expressw/show_basket";
		}
		else
		{
			// simply reload
			self.location.reload();
		}
	}
}

function showTheBasket()
{
	self.location.href="show_basket";
	dt = new Date();
	while((new Date()) - dt <= 1000){};
}


function ajaxOn()
{
	if(ajaxObject == null)
		return true;
	else
		return false;
}

function ajaxOnForms()
{
	if(ajaxObject == null)
		return false;
	else
		return true;
}

function compareButtonClicked(i)
{
	s = "comparisons["+document.getElementById(i).value+"]=true;";
	s+="path=/;";	
	if(document.getElementById(i).checked == false)
	{
		s+= "expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
	document.cookie= s;

}

function removeProductFromComparison(p)
{
	s = "comparisons["+p+"]='';";
	s+= "expires=Thu, 01-Jan-1970 00:00:01 GMT";
	document.cookie= s;
	
	document.cookie="removedFromComparison='yes';";

	self.location.reload();
}

function wishlistButtonClicked(i)
{
	s = "wishlist["+document.getElementById(i).value+"]=true;";
	
	if(document.getElementById(i).checked == false)
	{
		s+= "expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
	document.cookie= s;
	
	self.location.reload();

}

function wishlistAdded(i)
{
	s = "wishlist["+i+"]=true;";
	document.cookie = s;
	self.location.reload();
}

function wishlistRemoved(i)
{
	s = "wishlist["+i+"]=true;";
	s+= "expires=Thu, 01-Jan-1970 00:00:01 GMT";
	document.cookie = s;
	self.location.reload();
}

function changeSecurityImage(i)
{
	document.getElementById(i).src="php/security_image.php?r="+Math.floor(Math.random()*999999);
}


function changeSecurityImageNew(i,f)
{
	f = typeof(f) != 'undefined' ? f : "securityCode";
	document.getElementById(i).src="captcha/captcha.php?codeID="+f+"&r="+Math.floor(Math.random()*999999);
}





function DT_selectFormElement(i,t)
{
	if(document.getElementById("DT_"+i).value == t)
	{
		document.getElementById("DT_"+i).value = "";
		document.getElementById(i).value = "";
	}
	else
	{
		document.getElementById(i).value = document.getElementById("DT_"+i).value;
	}
}







function DT_deselectFormElement(i,t)
{
	if(document.getElementById("DT_"+i).value == "")
	{
		document.getElementById("DT_"+i).value = t;
		document.getElementById(i).value = "";
	}
	else
	{
		document.getElementById(i).value = document.getElementById("DT_"+i).value;
	}
}


function DT_changedFormElement(i,t)
{
	if(document.getElementById("DT_"+i).value == t)
		document.getElementById(i).value = "";
	else
		document.getElementById(i).value = document.getElementById("DT_"+i).value;
}

