// date stuff used in cached pages
var dayofweek= new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var dayofmonth= new Array("","1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th","11th","12th","13th","14th","15th","16th","17th","18th","19th","20th","21st","22nd","23rd","24th","25th","26th","27th","28th","29th","30th","31st");
var months= new Array("January","February","March","April","May","June","July","August","September","October","November","December");

// returns todays date as a formated string
function theDate(){
	var mydate=new Date();
	var year=mydate.getYear();
	if (year < 1000) year+=1900;
	var day=mydate.getDay();
	var month=mydate.getMonth();
	var daym=mydate.getDate();
	var todaysDate="  "+dayofweek[day]+" "+dayofmonth[daym]+" "+months[month]+" "+year;
	return todaysDate;
}

// Search box validation used for both the search box and the main search page
function searchpagevalidate(ref) {
	if (ref.keyword.value != '')
		{
		return true;
		}
	else
		{
		alert('Need a keyword to \nsearch on!');
		return false;
		}		
}
function gotoarticle(sel)
	{
		artID=sel.options[sel.selectedIndex].value;
		if (artID.length > 0){
			aURL="index.cfm?articleid="+artID;
			window.location.href = aURL;
		}
	}
	
//scripts used in the forum template
// check all fields have been entered.
function  _forum_checkThreadForm(_forum_this){
    if  (_forum_this.forum_topic.value.length ==0){
		alert("You must enter a Title.");
		return false;
	}
    if  (_forum_this.forum_username.value.length ==0){
		alert("You must enter your name to post to the forum.");
		return false;
	}
    if  (_forum_this.forum_body.value.length ==0){
		alert("In order to post you need to enter text into the message.");
		return false;
	}
	return true;
} 
//variables and functions used in the calendar template
var Days_in_Month = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
function monthchange(sel){
	mnth=sel.options[sel.selectedIndex].value;
	aform=sel.form;
	if(aform.aday != null){
		if (mnth =='2'){
			theYear=aform.ayear.options[aform.ayear.selectedIndex].value;
			Days_in_Month[1] = ((theYear % 400 == 0) || ((theYear % 4 == 0) && (theYear % 100 !=0))) ? 29 : 28;
		}
		for(i=27; i < Days_in_Month[mnth-1]; i++){
			aform.aday.options[i].text=i+1;
		}
		for(i=Days_in_Month[mnth-1]; i < 31; i++){
			aform.aday.options[i].text='';
		}
		checkday(aform);
	}
	changer(sel);	
}

function checkday(aform){
	if (aform.aday.options[aform.aday.selectedIndex].text==''){
		aform.aday.options[eval(Days_in_Month[aform.amonth.selectedIndex]-1)].selected=true;
		aform.aday.focus();
	}
}

function changer(sel)
{
	aform=sel.form;
	dy=(aform.aday != null)?aform.aday.options[aform.aday.selectedIndex].value:1;
	mnth=aform.amonth.options[aform.amonth.selectedIndex].value;
	yer=aform.ayear.options[aform.ayear.selectedIndex].value;
	aid=aform.articleid.value;
	aURL="index.cfm?articleid="+aid+"&ayear="+yer+"&amonth="+mnth+"&aday="+dy;
	window.location.href = aURL;
}

//Functions Used by the commerce templates
function checkNum(id){	// Check that the quantity is a positive integer --->
	var checkstr = /^[1-9][0-9]*$/;
	if  ( checkstr.test(id.value) ){ 
		id.value = id.value;	
	}else{
		alert ('You must specify a valid quantity');	
		id.value = 1;
	}
}

function showProductStatus(f,itemAttribs,ProductStatus){//<!--- Search the stock array for  an itemAttribs and get it's price/availability info to the form --->
	qty = f.Quantity.value;
	if( (qty == '') || (isNaN(parseInt(qty))) ){
		qty = 0;  
	}else{
		qty = parseInt(qty);
		if (isNaN(qty)){
			qty = 1;
		}else if (qty < 0){
			qty = 0-qty;
		}
		f.Quantity.value = qty;
	}
	selectAttribs=""; //<!--- Variable to hold Attributes selected by the user in a CSV string --->
	for(i = 0; i < f.length; i++)//<!--- Scan the form and get product ProductStatus into PID --->
	{
		e = f.elements[i];
		if(e.name !=null && e.name.substr(0,7) == "Attrib_"){//<!--- Get the selection from the form's DROP DOWN lists --->
			if(e.type == "select-one") selectAttribs=selectAttribs+e.options[e.selectedIndex].value+",";
			if(e.type == "hidden") selectAttribs=selectAttribs+e.value+",";
		}
	}
	selectAttribs = selectAttribs.substr(0,selectAttribs.length-1); 		//<!--- Loose that final comma! --->
	for(i = 1; i < itemAttribs.length-1; i++){ 	//<!--- Search the itemAttribs array for the Selected Attributes --->
		if(itemAttribs[i] == selectAttribs){break;}
	}//<!--- If we get to here without a 'break' it's Out of Stock in that config. --->
	//<!--- Put the details on to the form display ---> 
	if(ProductStatus[i].STK == 0 || ProductStatus[i].STK == -1){
		Avail = 'Unavailable';
	}else{
		Avail = ProductStatus[i].STK ;
	}
	f.Availability.value = Avail;
	if (Avail != 'Unavailable'){
		// the following may or may not exist
		if (f.PriceIncVAT != null)f.PriceIncVAT.value = formatNum(ProductStatus[i].PRCinc);
		if (f.PriceExVAT != null)f.PriceExVAT.value = formatNum(ProductStatus[i].PRCex);
		if (f.VAT != null)f.VAT.value = formatNum(ProductStatus[i].VAT);
		if (f.TotalIncVAT != null)f.TotalIncVAT.value = formatNum(f.PriceIncVAT.value * qty);
		f.BasketAction.style.display='block';
		//these always exist
		f.Code.value = ProductStatus[i].CID;
		f.ProductOptionID.value = ProductStatus[i].PID;
	}else{
		// the following may or may not exist
		if (f.PriceIncVAT != null)f.PriceIncVAT.value = "N/A";
		if (f.PriceExVAT != null)f.PriceExVAT.value = "N/A";
		if (f.VAT != null)f.VAT.value = "N/A";
		if (f.TotalIncVAT != null)f.TotalIncVAT.value = "N/A";
		f.BasketAction.style.display='none';
		//these always exist
		f.Code.value = "N/A"; 
		f.ProductOptionID.value = "N/A";
	}
} 	

function checkAvail(f){
	if(f.Availability.value="" || f.Availability.value == "Unavailable"){
		alert("   Sorry, this item is not\navailable with the options\n    you have selected.");
		return false;
	}else{
		return true;
	}
}

function formatNum(value){
	// round up to nearest pence
	value = Math.round(value*100)/100;
	// ensure 2 trailing digits
	var svalue = "" +value;
	if (svalue.indexOf('.')==-1)
		svalue = svalue +".00"
	else while (svalue.indexOf('.') > svalue.length-3)
		svalue = svalue +"0";
	// padd out to 12 digits
	while (svalue.length < 9)
		svalue = " "+svalue;
	return svalue;
}
//Functions Used by the commerce templates end

//functions for importing IPSV and then updating AtoZ
/*
function importIPSV(url)
{
	sourceUrl = url;
	xmlfeed = ; //do something with url to obtain feed
	for (length of xml feed, cycle through)
	Identify IPSV details : probably heading and description?
	Translate to different xml document type
	populate new xml feed with these xml instances
	return new xmlfeed
}
*/
/*function updateAtoZ(articleId, xmlfeed)
{
	update atoz article using xmlfeed
}
*/

//-----------------------------------------------------------------------
// use newHttpObject() to return a HttpXml object regardless of browser,
// if the browser does not support the object, a warning popup is generated
// and the return valu is nil

function newHttpObject(handler)
{
  var xmlhttp = null;
  var alerted = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
  // JScript gives us Conditional compilation, we can cope with old IE versions.
  try
  {
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
		xmlhttp.onreadystatechange = handler;
  }
  catch (e)
  {
    try
    {
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
		xmlhttp.onreadystatechange = handler;
    }
    catch (E)
    {
      alert("You must have Microsofts XML parsers available");
    }
  }
@else
  alert("You must have JScript version 5 or above.")
  xmlhttp=null;
  alerted = true;
@end @*/
  if (!xmlhttp && !alerted)
  {
    // Non ECMAScript Ed. 3 will error here (IE<5 ok), nothing I can
    // realistically do about it, blame the w3c or ECMA for not
    // having a working versioning capability in  <SCRIPT> or
    // ECMAScript.
    try
    {
		xmlhttp = new XMLHttpRequest();
		xmlhttp.onload	= handler;
		xmlhttp.onerror = handler;
    }
    catch (e)
    {
      alert("You need a browser which supports an XMLHttpRequest Object.\n"
      +"Mozilla build 0.9.5 has this Object and IE5 and above");
    }
  }
  return xmlhttp;
}

function getHttpResponse(xmlhttp) 
{
	var httpObj = xmlhttp;
	
    if (httpObj.readyState == 4)
	{
        if (httpObj.status == 200) 
		{
            content = httpObj.responseText;
            div = document.getElementById("post_office");
            div.innerHTML = "";
            // insert HTML content into "post_office" <div>
            div.innerHTML = content;
        } 
		else 
		{
            alert("There was a problem with the response" + httpObj.statusText);
        }
    }
}

function getElement (id)
{
	if (document.getElementById != null) // Not IE4 or NS4
	{
		return document.getElementById(id);
	}
	if (document.all != null) // IE only
	{
		return document.all[id];
	}
	if (document.layers != null) // NS4 only
	{
		return document.layers[id];
	}
	return null; // give up
}

//Handle AJAX response. 
function handleAJAXResponse(xmlHttpEvent) 
{
	var xmlHttpSource	= null;
	var httpManager		= null;

	if (xmlHttpEvent != null)
	{
		//Firefox seems to pass an event object into this method which contains the original
		//XMLHTTP object. We can use this to then link back to the manager and find out
		//where we should put the response.
		xmlHttpSource	= xmlHttpEvent.target;
		httpManager		= LocateXMLHttpRequestManagerByObject(xmlHttpSource);	
	}
	else
	{
		//IE has access to an "event" object which seems to be fairly empty except for the srcElement
		//item, from which we can extract the ID and perform a lookup on that to obtain where to put
		//the response.
		if (event != null)
		{
			httpManager	= LocateXMLHttpRequestManagerByCaller(event.srcElement.id);	
			if (httpManager != null)
			{
				xmlHttpSource = httpManager.xmlObject;
			}
		}
	}

	if (xmlHttpSource != null)
	{	
		if (xmlHttpSource.readyState == 4 || xmlHttpSource.readyState == 'complete')
		{
			window.status = 'Response received';
			if (httpManager != null)
			{
				var resultsDiv = getElement(httpManager.results);
				if (resultsDiv != null)
				{
					var content					= xmlHttpSource.responseText;
					resultsDiv.innerHTML		= "";
					resultsDiv.innerHTML		= content;
					resultsDiv.style.display	= "block";
				}
				else alert('Cannot locate control to place AJAX response into');
			}
			else alert('Cannot find XML HTTP Request Manager!');
		}
	}
}

//Create XML Http Request
function createXMLHttpRequest(url, sectionId, resultsDiv)
{
	try
	{
		//Create and send the request
		var o = newHttpObject(handleAJAXResponse);
		return o;
	}
	catch(error)
	{
		var errtext = '';
		for (key in error)
		{
			errtext = key + ': ' + error[key] + '\n';
		}
		alert('Error whilst creating XML HTTP request: \n\n' + errtext);
		return null;
	}
}

//Holder for all XMLHttpRequestManager instances
var pendingXMLRequests = new Array();

//Class constructor
function XMLHttpRequestManager(baseUrl, sectionId, resultsDiv, caller)
{
	this.url		= baseUrl;
	this.xmlObject	= createXMLHttpRequest(baseUrl, sectionId, resultsDiv);
	this.results	= resultsDiv;
	this.section	= sectionId;
	this.button		= caller.id;
}

//Locate the XML HTTP Request Manager for the given sectionId, creating if necessary
function LocateXMLHttpRequestManager(baseUrl, sectionId, resultsDiv, paramnames, paramvalues, caller)
{
	//Build URL
	var newurl = baseUrl + "?section=" + sectionId;
	if (paramnames.length != paramvalues.length)
	{
		throw('Length of Parameter names and Parameter value arrays do not match!');
	}
	for (param = 0; param < paramnames.length; param++)
	{
		newurl = newurl + "&" + paramnames[param];
		newurl = newurl + "=" + paramvalues[param];
	}

	var found = false;
	var req = null;
	for (i = 0; i < pendingXMLRequests.length; i++)
	{
		req = pendingXMLRequests[i];
		if (req.section == sectionId)
		{
			found = true;
			break;
		}
	}
	
	//Create if necessary
	if (!found)
	{
		req = new XMLHttpRequestManager(newurl, sectionId, resultsDiv, caller);
		pendingXMLRequests[pendingXMLRequests.length] = req;
	}
	else
	{
		//Set URL of existing object
		req.url			= newurl;
		req.xmlObject	= createXMLHttpRequest(newurl, sectionId, resultsDiv);
	}
	
	//Send the request
	window.status = 'Opening XML HTTP Connection for ' + newurl;
	req.xmlObject.open('GET', newurl, true);
	window.status = 'Sending Request for ' + newurl;
	req.xmlObject.send(null);
}

//Locate the manager information for the XML HTTP object passed in
function LocateXMLHttpRequestManagerByCaller(callerId)
{
	var found = false;
	var req = null;
	for (i = 0; i < pendingXMLRequests.length; i++)
	{
		req = pendingXMLRequests[i];
		if (req.button == callerId)
		{
			found = true;
			break;
		}
	}
	
	if (!found)
	{
		return null;
	}
	else
	{
		return req;
	}
}
//Locate the manager information for the XML HTTP object passed in
function LocateXMLHttpRequestManagerByObject(xmlHttp)
{
	var found = false;
	var req = null;
	for (i = 0; i < pendingXMLRequests.length; i++)
	{
		req = pendingXMLRequests[i];
		if (req.xmlObject == xmlHttp)
		{
			found = true;
			break;
		}
	}
	
	if (!found)
	{
		return null;
	}
	else
	{
		return req;
	}
}

// return the browser type for the benefit of stylesheet selection
function getBrowserStyle()
{
	if (navigator.appVersion.indexOf("MSIE 5.") > -1)
		return "ie5";
  	if ((navigator.appName.indexOf("Netscape") > -1) && (navigator.appVersion.indexOf("5.") > -1) && (navigator.appVersion.indexOf("KHTML") < 0))
		return "ns5";
	if (navigator.appVersion.indexOf("MSIE 7.") > -1)
		return "ns5";
	return "";
}

