var highlightcolor="#ff9900"
var ns6=document.getElementById&&!document.all
var previous=''
var eventobj
var intended=/INPUT|TEXTAREA|SELECT|OPTION|SUBMIT/

function competitionPopup() {
}

function eventHover(event){ //makes form buttons highlight on rollover
	element = getElementFromEvent(event);
	element.className += ' hover';
}
function eventUnHover(event){
	element = getElementFromEvent(event);
	element.className = element.className.replace(/\bhover\b/gi, '');
}
function getElement(id){
	if (document.getElementById)
		return document.getElementById(id);
	if (document.all)
		return document.all[id];
	
	return null;
}
function getElementFromEvent(event) {
	if (event.srcElement)
		return event.srcElement;
	if (event.currentTarget)
		return event.currentTarget;
	return null;
}
function addEventHandler(element, eventName, functionName){
	if (element.attachEvent)
		element.attachEvent('on' + eventName, functionName);
	if (element.addEventListener)
		element.addEventListener(eventName, functionName, false);
}
function arbitraryHoverHandlers(){
	if (document.body.getElementsByTagName)
	bodyElements = document.body.getElementsByTagName("*" );
	
	for(i = 0; i < bodyElements.length; i++){
		if (bodyElements[i].type == "submit" || bodyElements[i].type == "button")
		{
			addEventHandler(bodyElements[i], "mouseover", eventHover);
			addEventHandler(bodyElements[i], "mouseout", eventUnHover);
		}
	}
}
window.onload = arbitraryHoverHandlers;

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_swapImgRestore() { //v3.0 for rollover images
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function changeDisplay( elementId, setTo ) {
//Changes display of any element such as paragraph visibility show and hide
    if( document.getElementById ) {
        //DOM
        var theElement = document.getElementById( elementId );
    } else {
        if( document.all ) {
            //Proprietary DOM
            var theElement = document.all[ elementId ];
        } else {
            //Create an object to prevent errors further on
            var theElement = new Object();
        }
    }
    
    if( !theElement ) {
        //The page has not loaded or the browser claims to support
        //document.getElementById or document.all but cannot actually
        //use either
        return;
    }

    //Reference the style ...
    if( theElement.style ) { theElement = theElement.style; }
    if( typeof( theElement.display ) == 'undefined' &&
    !( window.ScriptEngine && ScriptEngine().indexOf('InScript') + 1 ) ) {
      //The browser does not allow us to change the display style
      //Alert something sensible (not what I have here ...)
      window.alert( 'Your browser does not support this' );
      return;
    }

    //Change the display style
    theElement.display = setTo;
}

function clearSelectControl(selectControl)
{
	for (i = selectControl.options.length; i >= 0; i--) {
		selectControl.options[i] = null; 
	}
}

function getStockCodeControl()
{
	return document.getElementById('stockcode');
}

function getEmployeesControl()
{
	return document.getElementById('employees');
}

function getTypeControl()
{
	return document.getElementById('type');
}

function getBoxTypeControl()
{
	return document.getElementById('boxtype');
}

function getQuantityControl()
{
	return document.getElementById('quantity');
}

function getCompaniesControl()
{
	return document.getElementById('companies');
}

function getTotalControl()
{
	return document.getElementById('configTotal');
}

function getTotalExVATControl()
{
	return document.getElementById('configTotalExVAT');
}

function getUnitPriceControl()
{
	return document.getElementById('unitprice');
}

function getVoucherTypeControl()
{
	return document.getElementById('vouchertype');
}

function getVoucherTypeColour()
{
	return document.getElementById('vouchercolour');
}

function getVoucherCodeControl()
{
	return document.getElementById('vouchercode');
}
		 
function getVoucherPrintReverseTextControl()
{
	return document.getElementById('voucherprintreversetext');
}

function getVoucherCompanyTextControl()
{
	return document.getElementById('vouchercompanytext');
}

function getVoucherDenom1Control()
{
	return document.getElementById('voucherDenom1');
}

function getVoucherDenom5Control()
{
	return document.getElementById('voucherDenom5');
}

function getVoucherDenom10Control()
{
	return document.getElementById('voucherDenom10');
}

function getVoucherDenom20Control()
{
	return document.getElementById('voucherDenom20');
}

function getVoucherDenom50Control()
{
	return document.getElementById('voucherDenom50');
}

function getVoucherTotalControl()
{	
	return document.getElementById('lblVouchersTotal');
}

function getTradeBoxControl()
{	
	return document.getElementById('tradebox');
}

function getConnectLine50Control()
{	
	return document.getElementById('connectline50');
}

function getDeliveryControl()
{	
	return document.getElementById('delivery');
}

function formatTotal(total)
{	
	var result = '';
	var addPoint = true;
	var zeros = 0;
	var count;
	
	if (total == 0)
	{
		result = "FREE";
	}
	else
	{
	
	
		result = total.toString();
		
		for (count = 0; count < result.length; count++)
		{
			if (result.charAt(count) == ".")
			{
				addPoint = false;
				zeros = result.length - count - 1;
				if (zeros >= 2)
				{
					zeros = 0;
				}
				
				break;
			}
		}

		if (addPoint)
		{
			result += '.00';
		}
		else
		{
			for (count = 0; count < zeros; count++)
			{
				result += '0';
			}
		}
			
		//get the cookie
		var currencySymbol = '&pound;';
		var currency=getCookie('Currency');
		var currencyRate = getCookie('CurrencyRate');		
		if (currency!=null && currency == 'EUR' && currencyRate!=null)
			{
			currencySymbol = '&#8364;';
			currencyRate = currencyRate;
			
			}
		else 
		{		
			currencyRate = 1;		
		}
	
		var calculatedCurrencyResult = currencyRate * result;
				
		result = currencySymbol + calculatedCurrencyResult.toFixed(2);
	}
	
	return result;
}

function getVatRate()
{
	var result = 17.5;
	var stockCode = getStockCodeControl().value;
	
	switch (stockCode)
	{
		case "013614" :
		case "023614" :
			result = 0;
			break;

		case "219025" :
		case "219026" :
		case "219027" :
		case "219028" :
			result = 1.75;
			break;
		
		default :
			result = 17.5;
			break;
	}
	
	return result;
}

function updateTotalPrice()
{
	var totalPrice = '';
	var totalPriceExVAT = '';
	var productPriceControl = getProductPriceControl();
	var productPrice = productPriceControl.value;
	
	if (productPrice.length > 0)
	{
		var total = parseFloat(productPrice);
		var contractPriceControl = getContractPriceControl();
		var contractPrice = contractPriceControl.value;
		
		if (contractPrice.length > 0)
		{
			total += parseFloat(contractPrice);
		}
		
		var temp = total;
		var tempVAT = total;
		
		if (total > 0)
		{
			var quantityControl = getQuantityControl();
			var quantity = quantityControl != null ? quantityControl.value : 1;
		
			temp = quantity * total;
			
			var vatCalc = (temp / 100) * getVatRate();
			tempVAT = temp + vatCalc;
			
			temp = temp.toFixed(2);
		}
			
		totalPrice = formatTotal(tempVAT);
		totalPriceExVAT = formatTotal(temp);
	}
	
	var totalControl = getTotalControl();
	var totalExVATControl = getTotalExVATControl();
	
	if (totalPrice.length > 0 && totalPrice != "FREE")
	{
		totalPriceExVAT = totalPriceExVAT + " ex VAT";	
		totalPrice = totalPrice + " inc VAT";	
	}
	
	totalControl.innerHTML = totalPrice;
	totalExVATControl.innerHTML = totalPriceExVAT;
}

function getProductPriceControl()
{
	return document.getElementById('productprice');
}

function getProductControl()
{
	return document.getElementById('product');
}

function updateProductPriceControl(productPrice)
{
	var control = getProductPriceControl();
	
	if (control != null)
	{
		control.value = productPrice;
		updateTotalPrice();
	}
}

function getContractPriceControl()
{
	return document.getElementById('contractprice');
}

function updateContractPriceControl(value)
{
	var control = getContractPriceControl();
	control.value = value;
	updateTotalPrice();
}

function getContractControl()
{
	return document.getElementById('contract');
}

function getSelectedCompaniesControl()
{
	return document.getElementById('selectedcompanies');
}

function getSelectedUsersControl()
{
	return document.getElementById('selectedusers');
}

function getUsersControl()
{
	return document.getElementById('users');
}

function getVersionControl()
{
	return document.getElementById('version');
}

function getStageControl()
{
	return document.getElementById('stage');
}

function getDayControl()
{
	return document.getElementById('day');
}

function getLevelControl()
{
	return document.getElementById('level');
}

function getWorkstationsControl()
{
	return document.getElementById('workstations');
}

function getPayrollBureauControl()
{
	return document.getElementById('payrollbureau');
}

function setSelectedCompanies()
{
	var companiesControl = getCompaniesControl();
	var selectedCompaniesControl = getSelectedCompaniesControl();
	
	selectedCompaniesControl.value = companiesControl.options[companiesControl.selectedIndex].value;
}

function getLicenseTypeControl()
{
	return document.getElementById('licensetype');
}

function validateConfiguration()
{
//Must complete all selections before continuing.
	var result = false;
	var controls = document.getElementsByTagName("select");
	var selected = 0;
	var error = "Please complete your selections\n\n";
	
	for (i = 0; i < controls.length; i++) 
	{
		if (controls[i].options.length == 1)
		{
			//If there is only one item in the 
			//drop down it will be selected and valid.
			selected++;
		}
		else
		{
			selected += controls[i].selectedIndex > 0 ? 1 : 0;
		}
	}			
	
	if (selected < controls.length)
	{
		//alert('Please complete your selections.');
		result=false;
	}
	else
	{
		result = true;
	}
	
	//Check if it the vouchers page
	var voucherCodeControl = document.getElementById('vouchercode');
	
	if (voucherCodeControl != null)
	{	
		result = validateVouchersConfiguration();					
		
		if(result != true)
		{
			error += result;
			result = false
		}
	}
	
	var licenseTypeControl = document.getElementById('licensetype');
	
	if (licenseTypeControl != null)
	{	
		result = validateSage50OnlineDemoConfiguration();					
		
		if(result != true)
		{			
			result = false
		}
	}
	
	
	if(result==false)
	{
		alert(error);
	}
	
	return result;
}

function openRemote(url, winwidth, winheight) {
	var counter = 0

	if (navigator.appName == "Netscape")
	{
		counter++;
		newWin = "win" + counter;
		var newNavWin = window.open(url, newWin, "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=" + winwidth + ",height=" + winheight);
	}
	if (navigator.appName == "Microsoft Internet Explorer")
	{
		counter++;
		newWin = "win" + counter;
		var image_win = window.open(url, newWin, "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=" + winwidth + ",height=" + winheight);
	}
}

function showPrintableVersion(basketID)
{
	var url = "printable.aspx?BasketID=" + basketID;
	openRemote(url, 750, 500);
	return false;
}

function printPage() {
	if (window.print) {
    	window.print() ;  
	} else {
		var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
		document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
		WebBrowser1.ExecWB(6, 2);//Use a 1 vs. a 2 for a prompting dialog box    WebBrowser1.outerHTML = "";  
	}
}

var popup;

function openPopup(url, width, height, scrollbars)
{
	if (popup && !popup.closed && popup.location)
	{
		popup.location.href = url;
	}
	else
	{
		var parameters = "resizable=1,toolbar=0,status=0,menubar=0,height=" + height + ",width=" + width + ",scrollbars=" + scrollbars;
		popup = window.open(url, "popup", parameters);
		if (popup && !popup.opener) popup.opener = self;
	}
	
	if (popup)
	{
		if (window.focus) {popup.focus()}
	}
}

function onchangeQuantity()
{
	setProductPrice();
}

function displayProcessing() {
	MM_showHideLayers('processingsection', '', 'show')
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    } 
  }
return null
}

function openFile(sFile){
// Opens a file for download.
// Parameters:
// - name of file to open.  All these files should be
// in the public folder of the CMS application. 
  var sUrl;
  
  sUrl = "http://www.sage.co.uk/downloads/downloadcentre.aspx?DownloadShortcut=" + sFile;
  document.location.href = sUrl;
}

function doClickOnEnter(buttonName, e) {
//the purpose of this function is to allow the enter key to 
//point to the correct button to click.
	var	key;

	if (window.event)
		key	= window.event.keyCode;		//IE
	else
		key	= e.which;	   //firefox

	if (key	== 13)
	{
		//Get the button the user wants	to have	clicked
		var	btn	= document.getElementById(buttonName);
		if (btn	!= null)
		{ //If we find the button click	it
			btn.click();
			event.keyCode =	0
		}
	}
}

// WEBABACUS CLIENT ENVIRONMENT VERSION 1.0, (c)2007 Foviance Ltd ALL RIGHTS RESERVED. 
var cookieLife = 730;
var cookieDomain = ".sage.co.uk";
var fromt = new Date();
var clifems = cookieLife * 86400000;
var cexp = new Date(fromt.getTime() + clifems);

var wa_je = navigator.javaEnabled() ? "Y" : "N";
var wa_sc = Math.pow(2, screen.colorDepth);
var wa_sp = screen.pixelDepth;
var wa_sw = screen.width;
var wa_sh = screen.height;

var wa_sr = wa_sw + "x" + wa_sh;

document.cookie = "WA_CE=SR"+wa_sr+"|SC="+wa_sc+"|JE="+wa_je+"; expires=" + cexp.toUTCString() + "; path=/" + (cookieDomain == "" ? "" : "; domain=" + cookieDomain);
//WEBABACUS CLIENT ENVIRONMENT VERSION 1.0 END

function grayOut(vis, options) {  
// Pass true to gray out screen, false to ungray  
// options are optional.  This is a JSON object with the following (optional) properties  
// opacity:0-100         
// Lower number = less grayout higher = more of a blackout   
// zindex: #             
// HTML elements with a higher zindex appear on top of the gray out  
// bgcolor: (#xxxxxx)    
// Standard RGB Hex color code  
// grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});  
// Because options is JSON opacity/zindex/bgcolor are all optional and can appear  
// in any order.  Pass only the properties you need to set.  
var options = options || {};   
var zindex = options.zindex || 50;  
var opacity = options.opacity || 70;  
var opaque = (opacity / 100);  
var bgcolor = options.bgcolor || '#000000';  
var dark=document.getElementById('darkenScreenObject');  
if (!dark) {    
// The dark layer doesn't exist, it's never been created.  So we'll    
// create it here and apply some basic styles.    
// If you are getting errors in IE see: http:
//support.microsoft.com/default.aspx/kb/927917    
var tbody = document.getElementsByTagName("body")[0];    
var tnode = document.createElement('div');           
// Create the layer.        
tnode.style.position='absolute';                 
// Position absolutely        
tnode.style.top='0px';                          
 // In the top        
 tnode.style.left='0px';                          
 // Left corner of the page        
 tnode.style.overflow='hidden';                   
 // Try to avoid making scroll bars                    
 tnode.style.display='none';         
 // Start out Hidden        
 tnode.id='darkenScreenObject';                   
 // Name it so we can find it later    
 tbody.appendChild(tnode);                            
 // Add it to the web page    
 dark=document.getElementById('darkenScreenObject');  
 // Get the object.  
 }  
 if (vis) {    
 // Calculate the page width and height     
 if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {        
 var pageWidth = document.body.scrollWidth+'px';        
 var pageHeight = document.body.scrollHeight+'px';    } 
 else if( document.body.offsetWidth ) {      
 var pageWidth = document.body.offsetWidth+'px';      
 var pageHeight = document.body.offsetHeight+'px';    } 
 else {       
 var pageWidth='100%';       
 var pageHeight='100%';    }       
 //set the shader to cover the entire page and make it visible.    
 dark.style.opacity=opaque;                          
 dark.style.MozOpacity=opaque;                       
 dark.style.filter='alpha(opacity='+opacity+')';     
 dark.style.zIndex=zindex;            
 dark.style.backgroundColor=bgcolor;      
 dark.style.width= pageWidth;    
 dark.style.height= pageHeight;  
 dark.style.display='block';                            
 } else {     
 dark.style.display='none';  }}
