//---EVENT HANDERS -----------------------------------------
function isUndefined(v) {
    var undef;
    return v===undef;
}

function format (expr, decplaces) {
   var str = "" + Math.round (eval(expr) * Math.pow(10,decplaces))
   while (str.length <= decplaces) {str = "0" + str }
   // establish location of decimal point
   var decpoint = str.length - decplaces
   return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
}

function decimalize (expr) {
   return "£" + format(expr,2)
}
// JavaScript Document
function addEvent(obj, evType, fn){
   if (obj.addEventListener){
      obj.addEventListener(evType, fn, true);
      return true;
   } else if (obj.attachEvent){
      var r = obj.attachEvent("on"+evType, fn);
      return r;
   } else {
      return false;
   }
  }


  function getEventSrc(e) {
   /* Cookie-cutter code to find the source of the event */
    if (typeof e == 'undefined') {
      var e = window.event;
    }
    var source;
    if (typeof e.target != 'undefined') {
       source = e.target;
    } else if (typeof e.srcElement != 'undefined') {
       source = e.srcElement;
    }
    return source;
    /* End cookie-cutter code */
  }
  
  var domLoadedFunctionList=new Array();
  var domLoaded=false;
  
  function callWhenDOMLoaded(func) {
	  if (domLoaded) {
		  func();
	  } else {
		domLoadedFunctionList[domLoadedFunctionList.length]=func;
	  }
  }
  
  function domLoadedEvent() {
	  domLoaded=true;
	  // quit if this function has already been called
       if (arguments.callee.done) return;

       // flag this function so we don't do the same thing twice
       arguments.callee.done = true;
	   
	   for (var i=0;i<domLoadedFunctionList.length;i++) {
		   domLoadedFunctionList[i]();
	   }
  }
  
   /* for Mozilla */
   if (document.addEventListener) {
       document.addEventListener("DOMContentLoaded", domLoadedEvent, null);
   }

	// this doesnt work the event doesnt fire reliably at the end of the DOM Load
   /* for Internet Explorer */
   /*@cc_on @*/
   /*@if (@_win32)
       document.write();//"<script defer src="+baseurl+"/js/ie_onload.js><"+"/script>");
   /*@end @*/

   /* for other browsers */
   window.onload = domLoadedEvent;
   
   //---END EVENT HANDERS -----------------------------------------
   
// JavaScript Document
function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name)
{
	createCookie(name,"",-1);
}


function CookieStore_storeArray(array) {
	var datastring="";
	for (var i=0;i<array.length;i++) {
		if (i>0) {
			datastring+="|";
		}
		datastring+=array[i].join("{");
		if (datastring.length>2048) {
			break;
		}
	}
	createCookie(this.name,datastring,365);
	return datastring;
	
}
function CookieStore_readArray() {
	var rawdata=readCookie(this.name);
	var data=[];
	if (rawdata != null) {
		var datalist=rawdata.split("|");
		for (var i=0;i<datalist.length;i++) {
			var datarow=datalist[i].split("{");
			data[data.length]=datarow;
		}
	}
	return data;
}
function CookieStore_readHashtable() {
	var data=this.readArray();
	
	var hashTable={};
	if (data.length>=1) {
		for (var i=0;i<data[0].length;i+=2) {
			hashTable[data[0][i]]=data[0][i+1];
		}
	}
	return hashTable;
}
function CookieStore_writeHashtable(hashTable) {
	var data=new Array();
	var c=0;
	for (var item in hashTable) {
		data[c]=item;
		data[c+1]=hashTable[item];
		c+=2;
	}
	this.storeArray([data])
}
function CookieStore(name) {
	this.name=name;
}

CookieStore.prototype.storeArray=CookieStore_storeArray;
CookieStore.prototype.readArray=CookieStore_readArray;
CookieStore.prototype.writeHashtable=CookieStore_writeHashtable;
CookieStore.prototype.readHashtable=CookieStore_readHashtable;
	
function HistoryPage() {
	this.name='';
	this.url='';
	this.pageid='';
	this.valid=true;
}

function HistoryPage_initfromArray(dataArray){
	this.name=dataArray[1];
	this.url=dataArray[2];
	this.pageid=dataArray[3];
	if (this.description=='') {
		this.description=this.name;
	}
	var checksum=dataArray[0];
	if (checksum != this.calculateChecksum()) {
		this.valid=false;
	}
}
function HistoryPage_calculateChecksum() {
	// when the page is stored as a cookie there is a chance
	// that the data will become corrupted
	// the greatest risk is from shortening of the cookie if it grows over 4k in length
	// this simple checksum is used to abort the use of the page if this has happend
	return this.name.length+this.url.length+this.pageid.length;
}
function HistoryPage_toArray(){
	var checksum=this.calculateChecksum();
	return [checksum,this.name,this.url,this.pageid];
}

function HistoryPage_toHTML(){
	return '<a href="'+this.url+'" title="'+this.name+'">'+this.name+'</a>';
}
function HistoryPage_equals(page) {
	return (page.pageid==this.pageid);
}
HistoryPage.prototype.initfromArray=HistoryPage_initfromArray;
HistoryPage.prototype.toArray=HistoryPage_toArray;
HistoryPage.prototype.equals=HistoryPage_equals;
HistoryPage.prototype.toHTML=HistoryPage_toHTML;
HistoryPage.prototype.calculateChecksum=HistoryPage_calculateChecksum;


function SitePageHistory(maxPages,targetDivID) {
	this.maxPages=maxPages;
	this.targetDivID=targetDivID;
	this.cookieStore=new CookieStore("h");
	this.pageArray=[];
	var dataArray=this.cookieStore.readArray();
	this.numPages=dataArray.length;
	if (this.numPages>this.maxPages) {
		this.numPages=this.maxPages;
	}
	for (var i=0;i<this.numPages;i++) {
		var page=new HistoryPage();
		page.initfromArray(dataArray[i]);
		if (page.valid) {
			this.pageArray[this.pageArray.length]=page;
		}
	}
}

function SitePageHistory_store() {
	var dataArray=[];
	for (var i=0;i<this.numPages;i++) {
		var page=this.pageArray[i];
		dataArray[dataArray.length]=page.toArray();
	}
	this.cookieStore.storeArray(dataArray);
}

function SitePageHistory_addPage(name,url,pageid) {
	var newpage=new HistoryPage();
	newpage.name=name;
	newpage.url=url;
	newpage.pageid=pageid;
	// check if the page is already recorded 
	var pagePositionInList=-1;
	for (var i=0;i<this.numPages;i++) {
		var testpage=this.pageArray[i];
		if (testpage != null) {
			if (testpage.equals(newpage)) {
				pagePositionInList=i;
				break;
			}
		}
	}
	if (pagePositionInList>-1) {
		// remove it from the list
		this.pageArray.splice(pagePositionInList,1);
		this.numPages--;
	}
	// add the page to the top of the list
	this.pageArray.unshift(newpage);
	// if the list grows too big remove the last one.
	this.numPages=this.pageArray.length;
	while (this.numPages>this.maxPages) {
		this.pageArray.pop();
		this.numPages=this.pageArray.length;
	}
	this.store();
	this.render();
}
function SitePageHistory_addCurrentPage() {
	this.addPage(document.title,document.location.href,document.location.href);
}
function SitePageHistory_removeURL(url) {
	for (var i=this.pageArray.length-1;i>=0;i--) {
	
		if (testpage != null) {
			var testpage=this.pageArray[i];
			if (testpage.url==url) {
				this.pageArray.splice(i,1);
			}
		}
	}
	this.numPages=this.pageArray.length;
	this.store();
	this.render();
}
function SitePageHistory_toHTML() {
	var s='<ul>';
	for (var i=0;i<this.numPages;i++) {
		var page=this.pageArray[i];
		
		if (page != null) {
			s+='<li>';
			s+=page.toHTML();
			s+='</li>';
		}
	}
	s+='</ul>';
	return s;
}
function SitePageHistory_render() {
	if (document.getElementById && document.getElementById(this.targetDivID) ) {
		document.getElementById(this.targetDivID).innerHTML=this.toHTML();
	}
}
SitePageHistory.prototype.store=SitePageHistory_store;
SitePageHistory.prototype.addPage=SitePageHistory_addPage;
SitePageHistory.prototype.toHTML=SitePageHistory_toHTML;
SitePageHistory.prototype.render=SitePageHistory_render;
SitePageHistory.prototype.removeURL=SitePageHistory_removeURL;
SitePageHistory.prototype.addCurrentPage=SitePageHistory_addCurrentPage;


 
var itemsInHistory=6;
var historyDivID="recentlyvisitedlist";
var sitePageHistory=new SitePageHistory(itemsInHistory,historyDivID);

	var numItems=0;
	var basketTotal=0;
	var AccessorizedProductTotals = {};
	var AccessoryTotals = {};
	
var currencyCharacter = "&pound;";

function CommaFormatted(amount)
{
	var delimiter = ","; // replace comma if desired
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = minus + amount;
	return amount;
}

function CurrencyFormatted(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	var temp =i;
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return CommaFormatted(s);
}
function updateBasket(pnumItems,pbasketTotal) {
	numItems=pnumItems;
	basketTotal=pbasketTotal;
	var basketCookieStore=new CookieStore("b");
	basketCookieStore.storeArray([[numItems,basketTotal]]);
}

function updateProductTotals(pAccessorizedProductTotals) {
		var AccessorizedProductTotalsCookieStore=new CookieStore("apt");
		AccessorizedProductTotalsCookieStore.writeHashtable(pAccessorizedProductTotals);
		AccessorizedProductTotals=pAccessorizedProductTotals;
}
function updateAccessoryTotals(pAccessoryTotals) {
		var AccessoryTotalsCookieStore=new CookieStore("at");
		AccessoryTotalsCookieStore.writeHashtable(pAccessoryTotals);
		AccessoryTotals=pAccessoryTotals;
}

function renderBasket() {

	if (document.getElementById("basket")) {
		var basketCookieStore=new CookieStore("b");
		var dataArray=basketCookieStore.readArray();
		if (dataArray != null && dataArray[0] != null) {
		dataArray=dataArray[0];
			numItems=parseInt(dataArray[0]);
			basketTotal=parseFloat(dataArray[1]);
			if (isNaN(numItems)) {
				numItems=0;
				basketTotal=0;
			}
		}
		var baskethtml=" |";
		if (numItems==1) {
			baskethtml+=" "+numItems+" item ";
		} else {
			baskethtml+=" "+numItems+" items ";
		}
		baskethtml+="&pound;"+CurrencyFormatted(basketTotal, 2);
		document.getElementById("basket").getElementsByTagName("a")[0].innerHTML+=baskethtml;
		
		var AccessorizedProductTotalsCookieStore=new CookieStore("apt");
		AccessorizedProductTotals=AccessorizedProductTotalsCookieStore.readHashtable();
		var AccessoryTotalsCookieStore=new CookieStore("at");
		AccessoryTotals=AccessoryTotalsCookieStore.readHashtable();
	}
}
var numSampleItems=-1;

function updateSampleBasket(pnumSampleItems) {
	numSampleItems=pnumSampleItems;
	var sampleCookieStore=new CookieStore("s");
	sampleCookieStore.storeArray([[pnumSampleItems]]); 
}

function renderSampleBasket() {
	if (document.getElementById("sampletext")) {
		if (numSampleItems<0) {
			var sampleCookieStore=new CookieStore("s");
			var dataArray=sampleCookieStore.readArray(); 
			if (dataArray != null && dataArray[0] != null) {
				dataArray=dataArray[0];
				numSampleItems=parseInt(dataArray[0]);
			}
		}
		if (numSampleItems>0) {
			if (numSampleItems>1) {
				document.getElementById("sampletext").innerHTML=""+numSampleItems+" samples selected";
			} else {
				document.getElementById("sampletext").innerHTML=""+numSampleItems+" sample selected";
			}
		}
	}
}


function showItemTotal(productType, accessoryType) {
	var elementName="product_status";
	if (!document.getElementById || (document.getElementById(elementName).style.display=="block")) {
		return;
	}
	var productName=productType.toLowerCase();
	var quantity=getProductAccessoryTotal(productType, accessoryType);
	
	if (productType=="Carpet") {
		productName="carpet";
	}
	if (productType=="Laminate") {
		productName="laminate flooring";
	}
	if (productName != "") {
		document.getElementById(elementName).style.display="block";
		document.getElementById(elementName+"_total").innerHTML=quantity;
		document.getElementById(elementName+"_name").innerHTML=productName;
	}
	
}
function getProductAccessoryTotal(productType, accessoryType) {
	var quantity=0;
	if (AccessorizedProductTotals[productType] != null) {
		quantity=AccessorizedProductTotals[productType];
	}
	var accessoryTotalKey=accessoryType+"_"+productType;
	if (AccessoryTotals[accessoryTotalKey] != null) {
		quantity-=AccessoryTotals[accessoryTotalKey];
	}
	return quantity;
}
function calculateQuantityRequired(quantity,productRatio) {
	return Math.round((quantity/productRatio)+0.499999);
}
function renderAccessoryQuantity(destinationElementID,productType,accessoryType,productRatio) {
// check what type of product (laminate or carpet)
	var quantity=getProductAccessoryTotal(productType, accessoryType);
	// check the display element exists
	if (!document.getElementById) {
		return;
	}
	if (document.getElementById && (!document.getElementById(destinationElementID))) {
		//alert("Cannot find "+destinationElementID+" on the page");
		return;
	}
	var docElement=document.getElementById(destinationElementID);
	// see if the user has any quantity of this product in the basket
	if (quantity>0) {
		var totalrequired=calculateQuantityRequired(quantity,productRatio);
		docElement.value=totalrequired;
	}
}

function initialiseAddToBasketLink(destinationElementID,productType,accessoryType,productRatio,hyperlink) {
	var quantity=getProductAccessoryTotal(productType, accessoryType);
	if (quantity>0) {
		hyperlink+=calculateQuantityRequired(quantity,productRatio);
		if (!document.getElementById) {
			return;
		}
		if (document.getElementById && (!document.getElementById(destinationElementID))) {
			//alert("Cannot find "+destinationElementID+" on the page");
			return;
		}
		var docElement=document.getElementById(destinationElementID);
		docElement.style.display="block";
		var atags=docElement.getElementsByTagName("a");
		atags[0].href=hyperlink;
	}
}
function renderProductPrice(destinationElementID,unitPrice,productType,accessoryType,productRatio) {
	// check what type of product (laminate or carpet)
	var quantity=getProductAccessoryTotal(productType, accessoryType);
	// check the display element exists
	if (!document.getElementById) {
		return;
	}
	if (document.getElementById && (!document.getElementById(destinationElementID))) {
		alert("Cannot find "+destinationElementID+" on the page");
		return;
	}
	var docElement=document.getElementById(destinationElementID);
	// see if the user has any quantity of this product in the basket
	if (quantity>0) {
		// ensure that the we display at the top of the page the amount of product in the bakset
		showItemTotal(productType,accessoryType);
		// if they do calculate the cost to buy enough of this product for the whole amount
		var totalrequired=unitPrice*calculateQuantityRequired(quantity,productRatio);
		// format the cost to currency
		var totalText="&pound;"+CurrencyFormatted(totalrequired, 2);
		// find the price and  inside the displayelement and put the price details inside it
		var quantityElement=document.getElementById(destinationElementID+"_quantity");
		var totalElement=document.getElementById(destinationElementID+"_total");
		totalElement.innerHTML=totalText;
		quantityElement.innerHTML=quantity;
		// show the display element
		docElement.style.visibility="visible";
		docElement.style.display="block";
	} else {
		// if the dont make sure that the destination element is not displayed (it should be hidden by default anyway)
		docElement.style.visibility="hidden";
		docElement.style.display="none";
	}
}

function renderHistoryAndBasket() {
	if (document.getElementById && document.getElementById("recentlyvisited") ) {
		document.getElementById("recentlyvisited").style.display = 'block';
	}
	sitePageHistory.render();
	renderBasket();
	renderSampleBasket();
}

callWhenDOMLoaded(renderHistoryAndBasket);

//--------------------------------------------------------------------------------

function changeStyle(element,newStyleSuffix) 
{
	if(null != element)
	{
		if (element.originalClass==null || element.originalClass.length==0) {
			if (element.className.length>0) {
				element.originalClass=element.className;
			} else {
				element.originalClass=" ";
			}
			
		}
		if ((element.originalClass.length>0) && (element.originalClass != " ") ) {
			element.className = element.originalClass+" "+element.originalClass+newStyleSuffix;
		} else {
			element.className = newStyleSuffix;
		}
	}
}

function revertToOriginalStyle(element) {
	if (element != null && null != element.originalClass && element.originalClass.length>0) {
		element.className =element.originalClass;
	}
}

function getParentDiv(linkDivElement) {
	
	while ( (linkDivElement != null) && 
			(linkDivElement.clickhref==null)
		) { 
		linkDivElement=linkDivElement.parentNode;
	}
	return linkDivElement;
}
function linkPanels_click(eventObj) {
	var linkDivElement=getEventSrc(eventObj);
	
	while ( (linkDivElement != null) 
		&& (linkDivElement.clickhref==null)
		&& (linkDivElement.tagName.toLowerCase() !='a')  ) 
	 {
		linkDivElement=linkDivElement.parentNode;
	}
	if ( (linkDivElement != null) && (linkDivElement.tagName.toLowerCase() =='div') ) {
		window.location.href=linkDivElement.clickhref;
	} /*else {
		if ( linkDivElement && (linkDivElement.tagName.toLowerCase() =='a')) {
			//window.location.href=linkDivElement.href;
		}
	}*/
}
function linkPanels_rollover(eventObj) {
	var linkDivElement=getParentDiv(getEventSrc(eventObj));
	changeStyle(linkDivElement,"Hover");
	
}
function linkPanels_rollout(eventObj) {
	var linkDivElement=getParentDiv(getEventSrc(eventObj));
	revertToOriginalStyle(linkDivElement);
	
}

function initialiseLinkPanels() {
	var divList=document.getElementsByTagName("div");
	for (var i=0;i<divList.length;i++) {
		var divElement=divList[i];
		if (divElement.className.indexOf("linkpanel")>=0) {
			var atags=divElement.getElementsByTagName("a");
			if (atags.length>0) {
				divElement.clickhref=atags[0].getAttribute('href');
				addEvent(divElement, "click", linkPanels_click);
				addEvent(divElement, "mouseover", linkPanels_rollover);
				addEvent(divElement, "mouseout", linkPanels_rollout);
			}
		}
	}
}
callWhenDOMLoaded(initialiseLinkPanels);

//-------------------------------------------------------------------------


// default popup set of features
var _POPUP_FEATURES = "location=0,statusbar=0,menubar=0,width=550,height=335";
var _SCROLL_FEATURES = "scrollbars=1,location=0,statusbar=0,menubar=0,width=550,height=335";
var _ZOOM_FEATURES = "location=0,statusbar=0,menubar=0,width=790,height=630";

function raw_popup(url, target, features) {
  if (isUndefined(features)) {
    features = _POPUP_FEATURES;
  }
  if (isUndefined(target)) {
    target = '_blank';
  }
  var theWindow =
    window.open(url, target, features);
  theWindow.focus();
  return theWindow;
}

function link_popup(src, features) {
  var href=src.getAttribute('href');
  if (src.className.indexOf("zoompopuplink") != -1) {
	features=_ZOOM_FEATURES
  }
  if (src.className.indexOf("scrollingpopuplink") != -1) {
	features=_SCROLL_FEATURES
  }
  
  return raw_popup(href, src.getAttribute('target') || '_blank',features);
}
function closepopuplink_click(eventObj) {
	if (window.opener != null) {
		window.opener.focus();
		window.close();
		return false;
	}
}
function popuplink_click(eventObj) {
			//alert("popuplink_click");
	var srcElement=getEventSrc(eventObj);
	while( (srcElement!=undefined) && (srcElement.tagName.toLowerCase() !='a')) {
		srcElement=srcElement.parentNode;
	}
	  if (!isUndefined(window.event)) {
		eventObj.returnValue = false;
	  } else {
		eventObj.preventDefault();
	  }
	  link_popup(srcElement);
	return false;//
}

function createPopUpLink(element) {
			//alert("createPopUpLink");
	addEvent(element, "click", popuplink_click);
	element.title+=" [opens in a popup window]";
}
function initPopupLinks() {
	var aTags=document.getElementsByTagName('a');
	for (var i=0;i<aTags.length;i++) {
		if (aTags[i].className.indexOf("popuplink")!=-1) {
			//alert("Popup found");
			createPopUpLink(aTags[i]);
		}
		if (aTags[i].className.indexOf("popupclose")!=-1) {
			if (window.opener != null) {
				aTags[i].innerHTML="Close Window";
				addEvent(aTags[i], "click", closepopuplink_click);
			}
		}
		//alert(aTags[i].className+" "+aTags[i].href);
	}
}


callWhenDOMLoaded(initPopupLinks);

//-------------------------------------------------------------------------------

var preload = new Array();

function addPreloadImage(imgsrc) {
	preload[preload.length]=imgsrc;
}
function preLoadButtons()
{
  if(document.images)
  {
    var preloadLen = preload.length;
    for(var i = 0; i < preloadLen; i++)
    {
           var img = preload[i];
           self[img] = new Image();
           self[img].src = img;
    }
  }
}
addPreloadImage(baseurl+'/images/header/searchbg.gif');
addPreloadImage(baseurl+'/images/header/topnav_bgfullroll.jpg');

callWhenDOMLoaded(preLoadButtons);
//---------------------------------------------------------------------------
