function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}

// Login functions used to log in to the site and update account info etc.
// Requires a DIV with id LoginFormDiv for the login form
// and for the customer information.

TexasCaller = {
    getHTTPObject : function() {
	var http = false;
	if (typeof ActiveXObject != 'undefined') {
            try {
                http = new ActiveXObject("Msxml2.XMLHTTP"); 
            } catch (e) {
    	        try {
                    http = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (E) { 
                    http = false; 
                }
    	    }
	} else if (XMLHttpRequest) {
	    try {
                http = new XMLHttpRequest();
            } catch (e) {
                http = false;
            }
	}
	return http;
    },

    post : function(data, callback, error) {
        this.http = this.getHTTPObject();
	this.callback = callback;
        this.error = error;
	var ths = this; //Closure

	this.http.open("post", "/CallBroker.ashx", true);
	this.http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	this.http.setRequestHeader("Content-length", data.length);
	this.http.setRequestHeader("Connection", "close");

	this.http.onreadystatechange = function () {
            var http = ths.http;
	    if (http.readyState == 4) {
		var result = "";
		if (http.responseText) {
                    result = http.responseText;
                }
	        //\n's in JSON string, when evaluated will create errors in IE
		result = result.replace(/[\n\r]/g,"");
		result = eval('(' + result + ')');
                if (http.status == 200) {
		    ths.callback(result);
		} else {
		    ths.error(http.status, result);
		}
            }
        }
	this.http.send(data);
    }
}

function ClearLoginInfo() {
    window.fullName = null;
    window.userPreferences = null;
    window.accoutDetails = null;
}

// The chain of functions start with either OnLogin or UpdateUserName.
// UpdateUserName can be called any time, i.e., either at page load time or
// periodically.  When logging in, there is no need to call GetPersonalDetails.

function OnLogin() {
    ClearLoginInfo();
    window.loginErrorMessage = '';
    var loginRequest = '{"serviceName":"UserService","methodName":"Login","arguments":{"username":"' 
        +  document.LoginForm.UserName.value + '","password":"' + document.LoginForm.Password.value 
        + '","IDMDLanguage":"UK"}}';
    TexasCaller.post(loginRequest, OnLoginResponse, OnLoginFailed);
}

function OnLogout() {
    ClearLoginInfo();
    window.top.name = null;
    var logoutRequest = '{"serviceName":"UserService","methodName":"Logout","arguments":{"IDMDLanguage":"UK"}}';
    TexasCaller.post(logoutRequest, OnLogoutResponse, null);
}

function OnLoginResponse(response) {
    if (response.result != null) {
	window.fullName = response.result.FullName;
	GetPreferencesAndMaybeAccountDetails();
    } else {
	window.loginErrorMessage = response.message;
	RedrawLoginInfo();
    }
}

function OnLoginFailed(status, response) {
    window.loginErrorMessage = response.message;
    RedrawLoginInfo();
}

function OnLogoutResponse(response) {
    RedrawLoginInfo();
}

// Call this when the page loads to get user name information from the server.

function UpdateUserName() {
    if (!window.loginErrorMessage) {
	window.loginErrorMessage = '';
    }
    var getPersonalDetailsRequest = '{"serviceName":"UserService","methodName":"GetPersonalDetails",' 
        + '"arguments":{"IDMDLanguage":"UK"}}';
    TexasCaller.post(getPersonalDetailsRequest, OnGetPersonalDetailsResponse, OnGetPersonalDetailsFailed);
}

function OnGetPersonalDetailsResponse(response) {
    if (response.result) {
	window.fullName = response.result.FullName;
	GetPreferencesAndMaybeAccountDetails();
    } else {
	OnGetPersonalDetailsFailed(-1, null);
    }
}

function OnGetPersonalDetailsFailed(status, response) {
    ClearLoginInfo();
    RedrawLoginInfo();
}

function GetPreferencesAndMaybeAccountDetails() {
    var getPreferencesRequest = '{"serviceName":"AccountService","methodName":"GetPreferences",' 
        + '"arguments":{"IDMDLanguage":"UK"}}';
    TexasCaller.post(getPreferencesRequest, OnGetPreferencesResponse, OnGetPreferencesFailed);
    RedrawLoginInfo();
}

function OnGetPreferencesResponse(response) {
    window.userPreferences = response.result;
    if (window.userPreferences.IsAccountBalanceConstantlyDisplayed
        || window.userPreferences.IsCallCentreAccountNumberConstantlyDisplayed) {
        var getAccountDetailsRequest = '{"serviceName":"AccountService","methodName":"GetAccountsDetails",'
            + '"arguments":{"IDMDLanguage":"UK"}}';
        TexasCaller.post(getAccountDetailsRequest, OnGetAccountDetailsResponse, null);
    } else {
        window.accoutDetails = null;
        RedrawLoginInfo();
    }
}

function OnGetPreferencesFailed(status, response) {
    window.userPreferences = null;
    window.accoutDetails = null;
    RedrawLoginInfo();
}

function OnGetAccountDetailsResponse(response) {
    window.accoutDetails = response.result;
    RedrawLoginInfo();
}

function OnKeyPress(e) {
    var keynum;
    if (window.event) {
        keynum = e.keyCode;
    } else if (e.which) {
        keynum = e.which;
    }
    if (keynum == 13) {
        document.getElementById("loginButton").click();
        return false;
    }
    else
    {
        return true;
    }
}

function RedrawLoginInfo() {
    RedrawMenu();

    if (window.fullName == null) {
	if (!window.loginFormVisible || window.shownLoginErrorMessage != window.loginErrorMessage) {
	    document.getElementById("LoginFormDiv").innerHTML =
            '<p><form name="LoginForm" onKeyPress="return OnKeyPress(event)">' +
                'Username: <input type="text" name="UserName" size="12"> ' +
		'Password: <input type="password" name="Password" size="12"> ' +
                '<input type="button" id="loginButton" value="Login" onClick="OnLogin()" class="btnS"><br/>' +
	        '<font color="red">' + window.loginErrorMessage + '</font> ' +
	        '<a href="/Areas/Accounting/Template_1_UK/index.html#action=forgotten-password">Forgot your password?</a>' +
            '</form></p>';
	    window.loginFormVisible = 1;
	    window.shownLoginErrorMessage = window.loginErrorMessage;
	}
    } else {
	window.loginFormVisible = 0;
        document.getElementById("LoginFormDiv").innerHTML = '';

        var s = "<b>" + this.fullName + "</b>" + "<br />";

        if (window.userPreferences != null && window.accoutDetails != null) {
            var accounts = window.accoutDetails;

            var accountNumber = "unknown";
            var balance = "";
            for (i = 0; i < accounts.length; i++) {
		var accountClass = accounts[i].IDMMAccountClass;
                if (accountClass == "CREDIT") {
                    accountNumber = accounts[i].AccountNumber;
                    balance += "Balance: ";
		    balance += accounts[i].TradingBalance.toFixed(2) + " ";
                } else if (accountClass == "FREE") {
		    // Do not show
                } else {
                    balance += accountClass + " balance: ";
		    balance += accounts[i].TradingBalance.toFixed(2) + " ";
		}
	    }

            if (window.userPreferences.IsCallCentreAccountNumberConstantlyDisplayed) {
                s += "Account number: " + accountNumber + "<br />";
            }
            if (window.userPreferences.IsAccountBalanceConstantlyDisplayed) {
                s += balance + "<br />";
            }
        }
        s += '<input type="button" value="Sign out" onClick="OnLogout()" class="btnS">';
        document.getElementById("LoginFormDiv").innerHTML = s;
    }
}

// Functions used to display content server data in web page

function loadTransformedXml(domElement, xmlUrl, xslUrl)
{
  // code for IE
  if (window.ActiveXObject)
  {
    var xml = new ActiveXObject("Microsoft.XMLDOM");
    xml.async = false;
    xml.load(xmlUrl);
    var xsl = new ActiveXObject("MSXML2.FreeThreadedDOMDocument");
    xsl.async = false;
    xsl.load(xslUrl);
    var template = new ActiveXObject("MSXML2.XSLTemplate");
    template.stylesheet = xsl;
    var xsltProcessor = template.createProcessor();
    xsltProcessor.input = xml;

    xsltProcessor.addParameter("remote-host", window.location.host);
    xsltProcessor.addParameter("language-code", window.languageCode);
    if (window.fullName != null) {
	xsltProcessor.addParameter("logged-in", true);
    }
    xsltProcessor.transform();
    document.getElementById(domElement).innerHTML = xsltProcessor.output;
  }
  // code for Mozilla, Firefox, Opera, etc.
  else if (document.implementation && document.implementation.createDocument)
  {
    var xml = new XMLHttpRequest();
    xml.open("GET", xmlUrl, false);
    xml.send(null);
    var xsl = new XMLHttpRequest();
    xsl.open("GET", xslUrl, false);
    xsl.send(null);

    var xsltProcessor = new XSLTProcessor();
    xsltProcessor.importStylesheet(xsl.responseXML);
    xsltProcessor.setParameter(null, "remote-host", window.location.host);
    xsltProcessor.setParameter(null, "language-code", window.languageCode);
    if (window.fullName != null) {
	xsltProcessor.setParameter(null, "logged-in", true);
    }
    resultDocument = xsltProcessor.transformToFragment(xml.responseXML, document);

    var domElement = document.getElementById(domElement);
    while (domElement.firstChild != null) {
	domElement.removeChild(domElement.firstChild);
    }
    domElement.appendChild(resultDocument);
  }
}

function RedrawMenu() {
    loadTransformedXml("menutopleft", "/Areas/Betting/Template_1_UK/components/NavigationComponent/Navigation-" + window.languageCode + ".xml", "/static/xslt/menu.xslt");
}
