var loader_image = document.createElement('img');
loader_image.src = "images/loading_medium.gif";

function include_dom(script_filename) 
{
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
    return false;
}

include_dom('../classes/xlibrary/x/x_core.js');
include_dom('../classes/xlibrary/x/x_event.js');
include_dom('../classes/xlibrary/x/lib/xenabledrag2.js');
include_dom('../classes/xlibrary/x/lib/xdisabledrag.js');
include_dom('../classes/xlibrary/x/lib/xenabledrag.js');;
include_dom('../classes/xlibrary/x/lib/xshow.js');
include_dom('../classes/xlibrary/x/lib/xvisibility.js');


function initializeXMLHTTP()
{
	
	if(typeof xmlhttp=="undefined")var xmlhttp=false; 
	
	/* running locally on IE6,IE7 */                      ;/*Gotta love IE's support for Conditional Compilation*/; /*@cc_on 
	  if(location.protocol=="file:"){ 
	   if(!xmlhttp)try{ xmlhttp=new ActiveXObject("MSXML2.XMLHTTP"); }catch(e){xmlhttp=false;} 
	   if(!xmlhttp)try{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){xmlhttp=false;} 
	  }                                                                                                             @cc_off @*/ 
	
	/* IE7, Firefox, Safari, Konqueror, Opera... the conventional/standard way */ 
	//Yes, standard: http://www.w3.org/TR/XMLHttpRequest/ 
	  if(!xmlhttp)try{ xmlhttp=new XMLHttpRequest(); }catch(e){xmlhttp=false;} 
	
	/* IE5, IE6 */ 
	  if(typeof ActiveXObject != "undefined"){ 
	   if(!xmlhttp)try{ xmlhttp=new ActiveXObject("MSXML2.XMLHTTP"); }catch(e){xmlhttp=false;} 
	   if(!xmlhttp)try{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){xmlhttp=false;} 
	  } 
	
	/* IceBrowser */ 
	  if(!xmlhttp)try{ xmlhttp=createRequest(); }catch(e){xmlhttp=false;} 
// Note IceBrowser does not support responseXML

	return xmlhttp;
}

/* Used to retrieve the text from an XML tag. Validates empty tags */
function getXMLvalue(tagname,i,response)
{
	var tag = response.getElementsByTagName(tagname)[i];
	
	if(tag.hasChildNodes())
	{
		return tag.firstChild.nodeValue;
	}
	else
	{
		return "";	
	}
}


function getformdata(formname)
{
	var theform = document.getElementById(formname);
	var getstr = "";
	
	for (i=0; i<theform.elements.length; i++) 
	{
		if(theform.elements[i] != null)
		{		
		 if (theform.elements[i].tagName == "INPUT") 
		 {			   
			if (theform.elements[i].type == "checkbox") 
			{
			   if (theform.elements[i].checked) 
			   {
				  getstr += theform.elements[i].id + "=" + encodeURIComponent(theform.elements[i].value) + "&";
			   } else {
				  getstr += theform.elements[i].id + "=&";
			   }
			}
			else if (theform.elements[i].type == "radio") 
			{
			   if (theform.elements[i].checked) 
			   {
				  getstr += theform.elements[i].id + "=" + encodeURIComponent(theform.elements[i].value) + "&";
			   }
			}
			else
			{
				getstr += theform.elements[i].id + "=" + encodeURIComponent(theform.elements[i].value) + "&";	
			}
		 }   
		 else if (theform.elements[i].tagName == "SELECT") 
		 {
			var sel = theform.elements[i];
			getstr += sel.name + "=" + encodeURIComponent(sel.options[sel.selectedIndex].value) + "&";
		 } 
		 else
		 {
			 getstr += theform.elements[i].id + "=" + encodeURIComponent(theform.elements[i].value) + "&";	
		 }
      }
	}
	   
	return getstr;			
}

function emptydivcontents(container)
{
	while (container.firstChild) 
	{
		container.removeChild(container.firstChild);
	}	
}

function buildpopupdiv(divid,divclass,divtitle,error_div_id)
{
	
	var divitem = document.getElementById(divid);
	
	if(divitem == null) //if pop up window not created yet, create it
	{
		divitem = document.createElement('div');
	}
	else
	{
		emptydivcontents(divitem);
		showdiv(divid);
	}
				
	divitem.id = divid;
		
	if(divclass != '') 
	{
		divitem.className = divclass; 
	}
	else
	{
		divitem.className = "popupdiv";  			
	}
		
	divitem.onmouseover = function() {var e = xGetElementById(divid); e.xDragEnabled = false;};

	var docbody = document.getElementsByTagName('body');		
	docbody[0].appendChild(divitem);

	tablebody = buildtable(divitem);
	
	var headerrow = document.createElement('tr');
	var errorrow = document.createElement('tr');
	var bodyrow = document.createElement('tr');
	tablebody.appendChild(headerrow);
	tablebody.appendChild(errorrow);
	tablebody.appendChild(bodyrow);	
	
	var headercell = document.createElement('td');
	headercell.className = "divheader";
	var bodycell = document.createElement('td');
	var errorcell = document.createElement('td');
	headerrow.appendChild(headercell);
	errorrow.appendChild(errorcell);
	bodyrow.appendChild(bodycell);		

	createHeader(divtitle,divid,headercell); //Create header for the pop up div
	
	var errordiv = document.createElement('div');
	errordiv.id = error_div_id;
	errorcell.appendChild(errordiv);	

	//Set position of div on screen
	posY = getScreenCenterY();
	posX = getScreenCenterX();
	divitem.style.top = posY+90+"px";
	divitem.style.left = posX-(divitem.offsetWidth/2)+"px";
		
	return bodycell;
}

function buildimgpreviewdiv()
{
	var divid = "img-preview";
	var divitem = document.getElementById('img-preview');
	
	if(divitem == null) //if pop up window not created yet, create it
	{
		divitem = document.createElement('div');
	}
	else
	{
		emptydivcontents(divitem);
		showdiv(divid);
	}
				
	divitem.id = 'img-preview';

	var docbody = document.getElementsByTagName('body');		
	docbody[0].appendChild(divitem);	
		
	return divitem;
}

//Customer alert window
function bdalert(message)
{
	
	var divid = "bd_alert";
	
	var divitem = document.createElement('div');		
			
	divitem.id = divid;
	divitem.className = "bd_alert";  						
	divitem.onmouseover = function() {var e = xGetElementById(divid); e.xDragEnabled = false;};

	var docbody = document.getElementsByTagName('body');		
	docbody[0].appendChild(divitem);

	tablebody = buildtable(divitem);
	
	var headerrow = document.createElement('tr');
	var bodyrow = document.createElement('tr');
	tablebody.appendChild(headerrow);
	tablebody.appendChild(bodyrow);	
	
	var headercell = document.createElement('td');
	headercell.className = "divheader";
	var bodycell = document.createElement('td');
	headerrow.appendChild(headercell);
	bodyrow.appendChild(bodycell);		

	createHeader('System Alert','bd_alert',headercell); //Create header for the pop up div

	//Set position of div on screen
	posY = getScreenCenterY();
	posX = getScreenCenterX();
	divitem.style.top = posY+90+"px";
	divitem.style.left = posX-(divitem.offsetWidth/2)+"px";
	
	var para = document.createElement('p');
	var messagetext = document.createTextNode(message);
	para.appendChild(messagetext);
	bodycell.appendChild(para);
	
	var okbutton = document.createElement('input');
	okbutton.type = "button";
	okbutton.value = "OK";
	okbutton.onclick = function() { removediv('bd_alert'); };
	bodycell.appendChild(okbutton);
			
}

//Progress indicator used when waiting for server. Used in containers
function buildloader(container)
{
	var randomnumber=Math.floor(Math.random()*1000001);
	
	var newdiv = document.createElement('div');
	var loaderdivid = "loaderdiv" + randomnumber;
	newdiv.id = loaderdivid;
	newdiv.className = "loaderdiv";
	newdiv.style.textAlign = "center";
	container.appendChild(newdiv);
	var loading_icon = document.createElement('img');
	loading_icon.src = "global/images/loading.gif";
	newdiv.appendChild(loading_icon);
	var brk = document.createElement('br');
	newdiv.appendChild(brk);
	var loadingtext = document.createTextNode('Please Wait...');
	newdiv.appendChild(loadingtext);
	
	setTimeout("loadertimeout('" + loaderdivid + "','')",15000);
	
}

//Popup indicator used when there is no logic or space for a built in loader
function showpopuploader(functioncall)
{
	
	var randomnumber=Math.floor(Math.random()*1000001);
	
	//Build and add pop up div
	var divitem = document.createElement('div');			
	var popupid = "popuploader" + randomnumber;
	divitem.id = popupid;
	divitem.className = "popuploader";
	var docbody = document.getElementsByTagName('body');		
	docbody[0].appendChild(divitem);

	var loading_icon = document.createElement('img');
	loading_icon.src = "../images/loading.gif";
	divitem.appendChild(loading_icon);
	var para = document.createElement('p');
	var loadingtext = document.createTextNode('Please Wait...');
	para.appendChild(loadingtext);
	divitem.appendChild(para);

	//Set position of div on screen
	posY = getScreenCenterY();
	posX = getScreenCenterX();
	divitem.style.top = posY+150+"px";
	divitem.style.left = posX-(divitem.offsetWidth/2)+"px";
	
	setTimeout("loadertimeout('" + popupid + "','" + functioncall + "')",15000);
	
	return popupid;
	
}

//When server responds, hide the loader icon
function hidepopuploader(popupid)
{
	if(document.getElementById(popupid) != null)
	{
		removediv(popupid);
	}
}

//If server does not respond in a set time, inform the user and give them the option to try the functioncall again
//If no functioncall is provided, then only a refresh window option is provided. Otherwise user can just cancel the operation
function loadertimeout(id,functioncall)
{
	var container = document.getElementById(id);
	
	if(container != null)
	{
		emptydivcontents(container);
		
		var para = bd_insertelement(container,'p');
		para.appendChild(document.createTextNode('The operation timed out.'));		
		
		var para = bd_insertelement(container,'p');		
		
		if(functioncall != "undefined")
		{
			var retrylink = bd_insertelement(para,'a');
			retrylink.href = "javascript:removediv('" + id + "');" + functioncall + ";";
			bd_inserttext(retrylink,'Retry Operation');
			bd_inserttext(para,' | ');
		}
		
		var refreshlink = bd_insertelement(para,'a');	
		refreshlink.href = "javascript:location.reload(true)";
		bd_inserttext(refreshlink,'Refresh Page');
		
		var para = bd_insertelement(container,'p');	
		var closebutton = document.createElement('input');
		closebutton.type = "button";
		closebutton.value = "Cancel";
		closebutton.lang = id;
		closebutton.onclick = function() { removediv(id); };
		para.appendChild(closebutton);
		
	}
	
}


//Build a DOM Table and returns the body of the table so that rows and columns can be added
function buildtable(container)
{
	//Create table to store list
	var newtable = document.createElement('table');
	newtable.width = "100%";
	newtable.cellSpacing = "0";
	newtable.cellPadding = "0";
	container.appendChild(newtable);
	
	newtablebody = document.createElement('tbody');
	newtable.appendChild(newtablebody);	
	
	return newtablebody;
}

function bd_insertelement(container,type)
{
	var newelement = document.createElement(type);
	container.appendChild(newelement);
	return newelement;
}

function bd_inserttext(container,text)
{
	container.appendChild(document.createTextNode(text));
}

//Insert a row into a given table. The number of columns is equivalent to length of provided array
//items: ARRAY Contains list of strings,each will be contained in a column
//container: Table body Object, the new row will be added to this item
function insertrow(items,styles, container, colspan)
{
	var newrow = document.createElement('tr');
	container.appendChild(newrow);
	
	for(var i=0; i<items.length;i++)
	{
		var newcell = document.createElement('td');
		newrow.appendChild(newcell);
		newcell.appendChild(document.createTextNode(items[i]));
		if(styles[i] != "") { newcell.className = styles[i]; }
		if(colspan != "") { newcell.colSpan = colspan; }
		
	}
}

//Insert items from an array as columns in a table(container) and applies a style to the row
function insertheaderrow(items,rowstyle, container)
{
	var newrow = document.createElement('tr');
	newrow.className = rowstyle;
	container.appendChild(newrow);
	
	for(var i=0; i<items.length;i++)
	{
		var newcell = document.createElement('td');
		newrow.appendChild(newcell);
		newcell.appendChild(document.createTextNode(items[i]));
		
	}	
}

/* Sets a div visibility to hidden */
function hidediv(divname)
{
	var obj = document.getElementById(divname);
	if(obj != null) { obj.style.display = 'none'; }
}

function removediv(divname)
{
	var obj = document.getElementById(divname);	
	obj.parentNode.removeChild(obj);
}

/* Sets a div visibility to visible */
function showdiv(divname)
{
	var obj = document.getElementById(divname);
	if(obj != null) { obj.style.display = 'block'; }
}

//Creates a styled div with an error message in it
function createError(error,containername)
{
	
	var container = document.getElementById(containername);
	//Create error message if relevant
	if(error != null)
	{
		var errordiv = document.createElement('div');
		errordiv.className = "errordiv";
		errordiv.appendChild(document.createTextNode(error));
		container.appendChild(errordiv);	
	}		
}

/* Creates the header component of a pop up div */
function createHeader(title,divname,headercontainer)
{
	xEnableDrag2(divname, null,null,null, document.getElementsByTagName('body'));	
	var headerdiv = document.createElement('div');
	headercontainer.appendChild(headerdiv);
	headercontainer.onmousedown = function() {var e = xGetElementById(divname); e.xDragEnabled = true;};
	headercontainer.onmouseup = function() {var e = xGetElementById(divname); e.xDragEnabled = false;};	
			
	var headersubtable = document.createElement('table');
	headersubtable.width = "100%";
	headersubtable.cellspacing = "0";
	headersubtable.cellpadding = "0";
	headersubtable.border = "0";
	headerdiv.appendChild(headersubtable);		
	
	headersubbody = document.createElement('tbody');
	headersubtable.appendChild(headersubbody);	
	
	var headersubrow = document.createElement('tr');
	headersubbody.appendChild(headersubrow);
	var headersubcell1 = document.createElement('td');
	headersubrow.appendChild(headersubcell1);
	var headersubcell2 = document.createElement('td');
	headersubcell2.width = "18";
	headersubrow.appendChild(headersubcell2);
	
	var titletext = document.createElement('strong');
	titletext.appendChild(document.createTextNode(title));
	
	//Close Window Pic (x in top right)
	var closewindowpic = document.createElement('img');
	closewindowpic.id = "moreinfoclosewindowpic";
	closewindowpic.src = "../images/closebutton.gif";
	closewindowpic.width = 18;
	closewindowpic.height = 18;
	closewindowpic.alt = "Close this window";
	closewindowpic.style.cursor = "pointer";
	closewindowpic.onclick = function () { removediv(divname); }

	headersubcell1.appendChild(titletext);
	headersubcell2.appendChild(closewindowpic);
	
}

function get_updated_price(package_id)
{	

	var formname = "computer_builder_form";
	var url = "functions.php";
	var formdata = getformdata(formname);
	formdata += "date=" + Date() + "&action=get_updated_price&package_id=" + package_id;

	var request = initializeXMLHTTP(); //initialize the request object 
	request.open("POST",url,true); 
	request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); 
	request.send(formdata);
	
	request.onreadystatechange = function () {	
	if (request.readyState == 4) 
	{				
		var response = request.responseText; //Retrieve message from php function
		
		var price_div = document.getElementById('item_price_div');
		var price_div_lower = document.getElementById('item_price_div_lower');
		
		emptydivcontents(price_div);
		emptydivcontents(price_div_lower);
		
		price_div.appendChild(document.createTextNode("$" + response));
		price_div_lower.appendChild(document.createTextNode("$" + response));		
	}};
}

function update_item_image(item_id,category_id)
{
	var container = document.getElementById(category_id + "_img");
	container.src = "images/loading_medium.gif";
	var url = "functions.php";
	var formdata = "date=" + Date() + "&action=get_image&item_id=" + item_id;

	var request = initializeXMLHTTP(); //initialize the request object 
	request.open("POST",url,true); 
	request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); 
	request.send(formdata);
	
	request.onreadystatechange = function () {
	if (request.readyState == 4) 
	{				
		var response = request.responseText;
		
		if(response == "")
		{
			container.src = "images/photo_not_available_mini.gif";
			container.onmouseover = function() { imagePreview(this,"images/photo_not_available.gif"); };
			container.onmouseout = function() { closeImagePreview(); };			
		}
		else
		{
			container.src = "images/items/thumb" + response;
			container.onmouseover = function() { imagePreview(this,"images/items/" + response); };
			container.onmouseout = function() { closeImagePreview(); };
		}
	}};	
	
}

function move_step(which_step)
{	

	var url = "functions.php";
	var formdata = "date=" + Date() + "&action=" + which_step;

	var request = initializeXMLHTTP(); //initialize the request object 
	request.open("POST",url,true); 
	request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); 
	request.send(formdata);
	
	request.onreadystatechange = function () {	
	if (request.readyState == 4) 
	{				
		window.location.reload();
	}};
}

function showForm()
{
	var container = document.getElementById('client_details_div');
	var url = "functions.php";
	var formdata = "date=" + Date() + "&action=displayForm";

	var request = initializeXMLHTTP(); //initialize the request object 
	request.open("POST",url,true); 
	request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); 
	request.send(formdata);
	
	request.onreadystatechange = function () {	
	if (request.readyState == 4) 
	{				
		var response = request.responseText;
		if(response != "")
		{
			eval(response);
			container.appendChild(form_client_details);
		}
	}};		
}

function submitForm()
{
	var formname = "form_client_details";
	var formdata = getformdata(formname);
	
	var url = "functions.php";
	formdata += "date=" + Date() + "&action=submit";

	var request = initializeXMLHTTP(); //initialize the request object 
	request.open("POST",url,true); 
	request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); 
	request.send(formdata);
	
	request.onreadystatechange = function () {	
	if (request.readyState == 4) 
	{				
		var response = request.responseText;
		if(response == "true")
		{			
			//Load confirmation into div
			var container = document.getElementById('client_details_div');
			emptydivcontents(container);
			
			var para = document.createElement('p');
			var header = document.createElement('strong');
			header.appendChild(document.createTextNode('Order has been received'));
			para.appendChild(header);
			container.appendChild(para);
			
			var para = document.createElement('p');
			container.appendChild(para);
			para.appendChild(document.createTextNode('A representative will be in touch shortly to help you finalise your purchase'));
			
			var para = document.createElement('p');
			container.appendChild(para);
			var header = document.createElement('strong');
			header.appendChild(document.createTextNode('Thank you for your business'));
			para.appendChild(header);			
			
		}
		else
		{
			alert(response);
		}			
	}};			
}

//Ensure the add to cart quantity fields have maximum of 2 characters and numbers only
function validateQuantityField(evt,textbox)
{	
    var e = window.event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;

    if (charCode > 31 && (charCode < 48 || charCode > 57))
    {
		return false;
	}

    return true;
}

function validateFloatField(evt)
{
    var e = window.event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;

	if(charCode == 46)
	{
		return true;	
	}
    else if (charCode > 31 && (charCode < 48 || charCode > 57))
    {
		return false;
	}

    return true;	
}

//Returns false if any other than ( ) - 0-9 is pressed. For phone number fields.
function validatePhoneField(evt)
{
    var e = window.event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;

	if(charCode == 40 || charCode == 41 || charCode == 45)
	{
		return true;	
	}
    else if (charCode > 31 && (charCode < 48 || charCode > 57))
    {
		return false;
	}

    return true;	
}

//Returns absolute position of an element, which can be used to position other element directly under it
function findPos(who){
    var T= 0,L= 0;
    while(who){
        L+= who.offsetLeft;
        T+= who.offsetTop;
        who= who.offsetParent;
    }
    return {left:L,top:T};    
}

//Get URL Parameter value
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function getScreenCenterY() 
{
	var y = 0;     
	y = getScrollOffset();     
	return(y);
}   
  
function getScreenCenterX() 
{   
	return(document.body.clientWidth/2);   
}   
  
function getInnerHeight() 
{
	var y;   
	if (self.innerHeight) // all except Explorer   
	{
		y = self.innerHeight;   
	}   
	else if (document.documentElement && document.documentElement.clientHeight)   
	// Explorer 6 Strict Mode   
	{   
		y = document.documentElement.clientHeight;   
	}
	else if (document.body) // other Explorers   
	{
		y = document.body.clientHeight;   
	}
	return(y);   
}   
  
function getScrollOffset() 
{
	var y;   
	if (self.pageYOffset) // all except Explorer   
	{
		y = self.pageYOffset;   
	}
	else if (document.documentElement &&  document.documentElement.scrollTop)   
	// Explorer 6 Strict   
	{   
		y = document.documentElement.scrollTop;   
	}
	else if (document.body) // all other Explorers   
	{
		y = document.body.scrollTop;   
	}
	return(y);
}

function imagePreview(container,image)
{
	var imgcontainer = buildimgpreviewdiv();
	
	var containerpos = findPos(container);
	imgcontainer.style.top = containerpos['top'] + 'px';
	imgcontainer.style.left = containerpos['left'] + 60 + 'px';	
	
	var newtable = buildtable(imgcontainer);
	var newrow = bd_insertelement(newtable,'tr');
	var newcell = bd_insertelement(newrow,'td');
	
	var newimg = bd_insertelement(newcell,'img');
	newimg.src = image;
}

function closeImagePreview()
{
	hidediv('img-preview');	
}