function gE(f) { return document.getElementById(f);};

function doneLoadin() {
	// Load ops complete.
	if (navigator.userAgent.indexOf("MSIE") != -1) {
		gE('loginButtonCell').style.paddingRight='3px';	// Add cell padding for IE
		with (gE('remember').style) {
			left='-4px';
			position='relative';
		}
	}
	if (expired) {
		gE('licenceExpired').style.display='';
		gE('username').disabled = true;
		gE('remember').disabled = true;
		gE('password').disabled = true;
		gE('btnRenew').focus();
	} else {
		if (readCookie('AAC30_rememberMe') != null) {
			gE('username').value = readCookie('AAC30_rememberMe');
			gE('remember').checked = true;
			gE('password').focus();
		} else {
			gE('username').focus();
		}
	}
}

function checkKey(e) {

	var keynum;

	if(window.event) // IE
		keynum = e.keyCode
	else if(e.which) // Netscape/Firefox/Opera
		keynum = e.which
		
	if (keynum==13) {
		clickLogin();
		e.keycode=0;
	}
	return false;
	
}

// ----------------------------------------------------------------------------
// Login button functions
// ----------------------------------------------------------------------------
function highLight(ctl, backgroundColor, borderColor) {
	ctl.style.backgroundColor = backgroundColor;
	ctl.style.borderColor = borderColor;	
}
function clickLogin() {
	var u = gE('username').value;
	var p = gE('password').value;
	var r = gE('remember').checked;

	// Switch to the "please wait" display	
	gE('loginButton').style.display='none';
	gE('waitForLogin').style.display='';
		
	// Fetch the login details
	loadXMLDoc('data/login.aspx?u=' + u + '&p=' + p + '&r=' + r);
	
}

// ----------------------------------------------------------------------------
// Load an XML object
// ----------------------------------------------------------------------------
var reqXML;					// XML document
function loadXMLDoc(url) {

	// Browsers with native XMLHttpRequest object    
    if (window.XMLHttpRequest) {
        reqXML = new XMLHttpRequest();
        reqXML.onreadystatechange = loadXMLDocStateChange;
        reqXML.open("GET", url, true);
        reqXML.send(null);
    // IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        reqXML = new ActiveXObject("Microsoft.XMLHTTP");
        if (reqXML) {
            reqXML.onreadystatechange = loadXMLDocStateChange;
            reqXML.open("GET", url, true);
            reqXML.send();
			
        } else {
			alert('Your browser is not capable of running Optymyse, or has activeX objects switched off.');
        }
    }
}
function loadXMLDocStateChange() {
	// Some vars
	var hasWallboard = 0, hasReport = 0;
	
   // only if reqXML shows "complete"
    if (reqXML.readyState == 4) {
        // only if "OK"
        if (reqXML.status == 200) {
            // ...processing statements go here...            
            response = reqXML.responseXML.documentElement;
            if (response == null) {
				//alert('Null response');
				// Probably the user clicking all over the shop
            } else {
				switch (response.getAttribute('docType')) {
					case 'login':
						doLogin(response);
						break
					case 'licenceUpdate':
						doUpdate(response);
						break
					case 'licenceChanges':
						doneUpdate(response);
						break;
					default:
						alert('Unknown document response...');
				}
			}
        } else {
            alert("There was a problem retrieving the XML data:\n" + reqXML.statusText);
        }
    }
}

function doLogin(xmlResponse) {
	if (xmlResponse.getAttribute('response') == 'OK') {
		if (xmlResponse.getAttribute('remember') != '')
			createCookie('AAC30_rememberMe',xmlResponse.getAttribute('remember'),30);
		createCookie('AAC30_loggedIn',xmlResponse.getAttribute('userId'),0);
		document.location.href='consoleMain.aspx';
	} else {
		alert(xmlResponse.getAttribute('response'));
		
		// Switch to the "login button" display	
		gE('loginButton').style.display='';
		gE('waitForLogin').style.display='none';
		
		gE('password').value='';
		gE('username').focus();
		
	}
}
function renewLicence() {
	// Load the licence renewal form
	if (ur.indexOf('newsn') != -1) {
		ur = ur.replace('newsn',gE('newSN').value);
	}
	loadXMLDoc(licenceSite + '/getLicence.aspx?' + ur);
}
function doUpdate(xmlResponse) {
	// Store the new licence
	var status = xmlResponse.getElementsByTagName('status')[0].getAttribute('value');
	switch (status) {
		case 'OK':
			// Retrieve the licence details & pass them to the updater
			var url = 'data/adminData.aspx?a=licence';
			var licItemHolder = xmlResponse.getElementsByTagName('licenceItems')[0];
			for(i=0;i<licItemHolder.childNodes.length;i++) {
				with (licItemHolder.childNodes[i]) {
					if (nodeType == 1) {
						// Item: Add it to the URL
						url += '&' + getAttribute('name') + '=' + escape(getAttribute('value'));
					}
				}
			}			
			loadXMLDoc(url);
			break
		case 'badLicence':
			alert('Your licence details are not valid. Please contact SJS Solutions for assistance.');
			break
		default:
			alert('An invalid response - "' + status + '" - was received from the licence system. Please contact SJS Solutions for more information');
			break
	}
}
function doneUpdate(xmlResponse) {
	// Called after a licence update
	// Don't worry about what happened, just reload the page
	alert(xmlResponse.getElementsByTagName('status')[0].getAttribute('value'));
	window.location.reload();
}
// ----------------------------------------------------------------------------
// Cookie functions
// ----------------------------------------------------------------------------
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 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=/";
}

