function DebugShowInnerHTML(id, url) {
    var el = document.getElementById(id);
    var floatDiv = document.createElement("div");
      
    floatDiv.style.position = "absolute";    
    floatDiv.style.zIndex='1000';
    floatDiv.innerHTML = "<span style='background-color:red; color:white; cursor:pointer;' onclick='this.parentNode.parentNode.removeChild(this.parentNode);'>[close]</span>";    
    floatDiv.innerHTML += "<div style='background-color:black; color:white;'>" + url + "</div><textarea rows='20' cols='80'>" + el.childNodes[0].childNodes[1].innerHTML + "</textarea>";
    el.insertBefore(floatDiv, el.childNodes[0]);
}

function SLAuthProxy(url) {
    // User Configurable Properties - these can be set at any time

    // your apiKey, this value must be set!
    this.apiKey = "ignored";

    // sniff the browser for custom behaviors
    this.__isExplorer = navigator.userAgent.toLowerCase().indexOf('msie') != -1;
    this.__isSafari = navigator.userAgent.toLowerCase().indexOf('safari') != -1;
    this.__isMac = navigator.platform.toLowerCase().indexOf('mac') != -1;
    this.__isMacIE = this.__isMac && this.__isExplorer;
    
    // if enabled, spit out debug information through alert()
    this.debug = window.location.href.indexOf("debug=true") != -1 ? true : false;
    
    this.OnDebug = function(msg){
        if (this.debug)
        alert("Debug: " + msg);
    }
    
    this.OnDebug("Created SLAuthProxy");
    
    // used to track the id of the handler expecting the results from the immediately preceeding method invocation
    // this is used only for testing purposes
    this.lastHandlerId = "";
    
    // Methods You can Overide
    //
    // OnSuccess(returnValue) - is passed the return value at the end of a successful call, default does nothing
    // OnError(msg) - is passed an error message if a problem occurs
    // OnDebug(msg) - is called when debugging is enabled
     
    this.__baseUrl = url;
    this.__sendInvokeCount = 0;
    
    this.__eventHandlers = new Object();
}

// Override this function after the Proxy is loaded and you can
// make the profile link go anywhere you want.
SLAuthProxy.prototype.generateProfileURL = function(userId) {
    // Look for any query parameters that are already using ?
    var configProfileUrl = "http://www.bestbuy.co.uk/page/custom.aspx?PageName=Best Buy Profile";
    var profileUrlResults = configProfileUrl.match(/\?/);
    if (profileUrlResults != null) {
        return "http://www.bestbuy.co.uk/page/custom.aspx?PageName=Best Buy Profile&UID=" + userId;
    }
    else {
        return "http://www.bestbuy.co.uk/page/custom.aspx?PageName=Best Buy Profile?UID=" + userId;
    }
}

SLAuthProxy.prototype.gotoProfile = function(userId) {
    document.location = this.generateProfileURL(userId);
}

// Default error handler for the proxy object, simple alert
SLAuthProxy.prototype.OnError = function(msg) {
   alert("OnError: " + msg);
}

// browser independent method to get elements by ID
SLAuthProxy.prototype.GetElement = function(id) {
    this.OnDebug("GetElement " + id);
    if (document.getElementById)
        return document.getElementById(id);
    if (document.all)
        return document.all[id];
    this.OnError("No support for GetElement() in this browser");
    return null;
}

// browser independent method to get elements by tag name
SLAuthProxy.prototype.GetTags = function(tagName) {
    this.OnDebug("GetTags " + tagName);
    if (document.getElementsByTagName)
        return document.getElementsByTagName(tagName);
    if (document.all)
       return document.tags(tagName);
    this.OnError("No support for GetTags() in this browser");
    return null;
}

SLAuthProxy.prototype.ScriptId = function() { return this.__scriptId = "_sla_script_" + this.__sendInvokeCount; }

SLAuthProxy.prototype.LoadScript = function (url, callback) {
	var script = document.createElement('script');
	script.type = 'text/javascript';
	if (callback)
		script.onload = script.onreadystatechange = function() {
			if (script.readyState && script.readyState != 'loaded' && script.readyState != 'complete')
				return;
			script.onreadystatechange = script.onload = null;
			callback();
		};
	script.src = url;
	document.getElementsByTagName('head')[0].appendChild (script);
}

SLAuthProxy.prototype.__Send = function(url, scriptToUse) {
    this.OnDebug("_Send " + url);
    if (this.__isSafari) {
        this.LoadScript(url);
        return;
    } 
    
    scriptToUse = scriptToUse || this.ScriptId();
    
    //append our various parameters as necessary
    url = this.__AppendUrlValues(url);
    this.OnDebug("_Send (updated) " + url);
    // add the script node to the document
    if (document.createElement && ! this.__isMacIE) {
		var scriptNode = this.GetElement(scriptToUse);

		var head = this.GetTags('head')[0];
		if ( (scriptNode != null) && (scriptNode != undefined) && (!this.__isExplorer) && head.removeChild && (!this.__isSafari)) {
			head.removeChild(scriptNode);
			scriptNode = null;
		}
		if(scriptNode == null) {
			scriptNode = document.createElement('script');
			scriptNode.id = scriptToUse;
			scriptNode.setAttribute('type','text/javascript');
			scriptNode.setAttribute('charset', 'utf-8');
			head.appendChild(scriptNode);
        }
        scriptNode.setAttribute('src', url);

        return;
    }

    // could fall back to sync at this point, but will bust if the page is already loaded

    this.OnError("No support for async in this browser");
}

SLAuthProxy.prototype.__AppendUrlValues = function (url)
{
	time = new Date();
    url += this.__GetArgument("plckNoCache", time.getTime(), false, false);
    url += this.__GetArgument("plckApiKey", this.apiKey, true, false);
    
    return url;
}  

// validate and fetch arguments, if the argument is missing and optional, we return an empty string        
SLAuthProxy.prototype.__GetArgument = function(variableName, variableValue, isRequired, isArray) {
    this.OnDebug("__GetArgument " + variableName + "," + variableValue + "," + isRequired + "," + isArray);
    if (typeof variableValue == "undefined" || variableValue == null || variableValue == "")
    {
        if (isRequired)
        {
            this.OnError("Missing required parameter " + variableName);
            this.__isValid = false;
            return "";
        }
        else
            return "";
    }
    if (isRequired && isArray) 
    {
        if (!this.__ArrayValidation(variableValue)) 
        {
            this.OnError("Invalid array parameter " + variableName);
            this.__isValid = false;
            return "";
        }
    }
    return "&" + variableName + "=" + encodeURIComponent(variableValue);
};

// fetch a named request parameter from the page URL
SLAuthProxy.prototype.GetParameter = function(parameterName) {
    var key = parameterName + "=";
    var parameters = document.location.search.substring(1).split("&");
    for (var i = 0; i < parameters.length; i++)
    {
        if (parameters[i].indexOf(key) == 0)
            return parameters[i].substring(key.length);
    }
    return null;
};

 // determines if the provided string constitutes a valid email address
function jsValidateEmailAddress(pvEmailAddress)
{
   if (!pvEmailAddress.match(/^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$/))
   {
       return false; 
   } 
   
   return true;
}

SLAuthProxy.prototype.SubmitLoginForm = function (form){
    var emailElement = this.GetElement("plckEmail");
    var passwordElement = this.GetElement("password");
    var emailValidationControl = this.GetElement("emailValidation");
    var passwordValidationControl = this.GetElement("passwordValidation");
    
    emailValidationControl.style.display = "none";
    passwordValidationControl.style.display = "none";

    var isValid = true;
    if (!jsValidateEmailAddress(emailElement.value)){
        emailValidationControl.style.display = "inline";
        isValid = false;
    }
    
    if (passwordElement.value == ""){
        passwordValidationControl.style.display = "inline";
        isValid = false;
    }
    
    if (isValid)
        this.__SubmitForm(form);
}

SLAuthProxy.prototype.SubmitResetPasswordForm = function(form){
    var emailElement = this.GetElement("email");
    
    var emailRequiredElement = this.GetElement("emailRequiredValidator");
    
    if (emailElement.value == ""){
        emailRequiredElement.style.display = "inline";
        return;
    }
    
    this.__SubmitForm(form);
}

SLAuthProxy.prototype.SubmitRegistrationForm = function (form){
    var emailElement = this.GetElement("email");
    var emailConfirmElement = this.GetElement("emailConfirm");
    var displayNameElement = this.GetElement("displayName");
    var passwordElement = this.GetElement("password");
    var passwordConfirmElement = this.GetElement("passwordConfirm");
    
    var emailValidationControl = this.GetElement("emailValidation");
    var passwordValidationControl = this.GetElement("passwordValidation");
    var displayNameValidationControl = this.GetElement("displayNameValidation");
    var emailNotMatchMessage = this.GetElement("emailNotMatchMessage");
    var passwordNotMatchMessage = this.GetElement("passwordNotMatchMessage");
    
    emailValidationControl.style.display = "none";
    passwordValidationControl.style.display = "none";
    passwordNotMatchMessage.style.display = "none";
    emailNotMatchMessage.style.display = "none";
    displayNameValidationControl.style.display = "none";

    var isValid = true;
    if (!jsValidateEmailAddress(emailElement.value)){
        emailValidationControl.style.display = "inline";
        isValid = false;
    }
    
    if (displayNameElement.value == ""){
		displayNameValidationControl.style.display = "inline";
		isValid = false;
    }
    
    if (passwordElement.value == ""){
        passwordValidationControl.style.display = "inline";
        isValid = false;
    }
    
    if (emailElement.value != emailConfirmElement.value){
        emailNotMatchMessage.style.display = "inline";
        isValid = false;
    }
    
    if (passwordElement.value != passwordConfirmElement.value){
        passwordNotMatchMessage.style.display = "inline";
        isValid = false;
    }    
    
    if (passwordConfirmElement.value.length < 6){
        this.ShowInlineError("Password must be 6 characters long.");
        isValid = false;
    }    
    
    if (isValid)
        this.__SubmitForm(form);
}

SLAuthProxy.prototype.SubmitChangePasswordForm = function (form){
    this.HideInlineError();
    var oldPasswordElement = this.GetElement("oldPassword");
    var newPasswordElement = this.GetElement("newPassword");
    var newPasswordConfirmElement = this.GetElement("newPasswordConfirm");
    
    var oldPasswordRequiredElement = this.GetElement("oldPasswordRequired");
    var newPasswordRequiredElement = this.GetElement("newPasswordRequired");
    var newPasswordConfirmRequiredElement = this.GetElement("newPasswordConfirmRequired");
    
    oldPasswordRequiredElement.style.display = "none";
    newPasswordRequiredElement.style.display = "none";
    newPasswordConfirmRequiredElement.style.display = "none";
    
    isValid = true;
    
    if (oldPasswordElement.value == ""){
        oldPasswordRequiredElement.style.display = "inline";
        isValid = false;
    }
    
    if (newPasswordElement.value == ""){
        newPasswordRequiredElement.style.display = "inline";
        isValid = false;
    }    
    
    if (newPasswordConfirmElement.value == ""){
        newPasswordConfirmRequiredElement.style.display = "inline";
        isValid = false;
    }     
    
    if (newPasswordElement.value != newPasswordConfirmElement.value){
        this.ShowInlineError("Passwords do not match.");
        return;
    }
    
    if (newPasswordElement.value.length < 6){
        this.ShowInlineError("Password must be 6 characters long.");
        return;
    }
    
    if (isValid)
        this.__SubmitForm(form);
}

SLAuthProxy.prototype.ShowInlineError = function(message){
    var messageElement = this.GetElement("slaErrorMessage");
    messageElement.style.display = "inline";    
    messageElement.innerHTML = message;
    return;
}

SLAuthProxy.prototype.HideInlineError = function(){ var messageElement = this.GetElement("slaErrorMessage"); if (messageElement) { messageElement.style.display="none";}}

SLAuthProxy.prototype.WriteDiv = function(id, divClass, styleString) {
    if (this.GetElement(id) == null){
        document.write('<div id="'+id+'" class="'+divClass+'" style="' + styleString + '"></div>'); 
    }
    return id;
}

SLAuthProxy.prototype.__CapturePersistentParams = function(url){
    var redirUrl = this.GetParameter("url");
    if (redirUrl != null)
        url += '&url=' + escape(redirUrl);
        
    // the url of the window hosting the call to the proxy
    var hostingUrl = document.location.href;
    if ( hostingUrl != null && typeof(hostingUrl) != 'undefined')
		url += '&hostingUrl=' + escape(hostingUrl);
		
    return url
}

SLAuthProxy.prototype.WriteDefaultDiv = function(){
    this.WriteDiv("slRenderDiv");
    // hidden div used for test automation
    this.WriteDiv("slRenderDiv_vn", "", "display:none;");
}

SLAuthProxy.prototype.Show = function(){
    this.WriteDefaultDiv();
    var url = this.__baseUrl + '/Authentication/Index.rails?slaElementId=slRenderDiv&slaDivLayout=1';
    this.__Send(this.__CapturePersistentParams(url), "renderLogin");
}

SLAuthProxy.prototype.ShowLogin = function(){
    this.WriteDefaultDiv();
    var url = this.__baseUrl + '/Authentication/Login.rails?slaElementId=slRenderDiv&slaDivLayout=1';
    this.__Send(this.__CapturePersistentParams(url), "renderLogin");
}

SLAuthProxy.prototype.ShowLoginFull = function(){
    this.WriteDefaultDiv();
    var url = this.__baseUrl + '/Authentication/LoginFull.rails?slaElementId=slRenderDiv&slaDivLayout=1';
    this.__Send(this.__CapturePersistentParams(url), "renderLogin");
}

SLAuthProxy.prototype.ShowChangePasswordFull = function(){
    this.WriteDefaultDiv();
    var url = this.__baseUrl + '/Authentication/ChangePasswordFormFull.rails?slaElementId=slRenderDiv&slaDivLayout=1';
    this.__Send(this.__CapturePersistentParams(url), "renderLogin");
}

SLAuthProxy.prototype.ShowRegistration = function(){
    this.WriteDefaultDiv();
    var url = this.__baseUrl + '/Authentication/DisplayRegistration.rails?slaElementId=slRenderDiv&slaDivLayout=1';
    this.__Send(this.__CapturePersistentParams(url), "renderLogin");
}

SLAuthProxy.prototype.__Render = function(path){
    var url = this.__baseUrl + path + "?slaElementId=slRenderDiv&slaDivLayout=1";
    this.__Send(this.__CapturePersistentParams(url), "renderHere" + escape(path));
}

SLAuthProxy.prototype.__SubmitForm = function(form){
    var elementData = "";
    for(var x=0;x<form.elements.length;x++)
    {	
        if(form.elements[x].type == "checkbox"){
		if(form.elements[x].checked == true){
			elementData += form.elements[x].name + "=" + escape(form.elements[x].value) + "&";	
		}else{
			elementData += form.elements[x].name + "=null&";
		}
	}else{
		elementData += form.elements[x].name + "=" + escape(form.elements[x].value) + "&";
    	}
    }
    elementData += "slaElementId=slRenderDiv&slaDivLayout=1";
    var actionDest = form.action + "?" + elementData;
    this.__Send(this.__CapturePersistentParams(actionDest), "submitForm");
}


gSLAuthProxy = new SLAuthProxy('http://community.bestbuy.co.uk/slauth');



SLAuthProxy.prototype.DisplayUpdateAdmin = function(){
    this.WriteDefaultDiv();
    var url = this.__baseUrl + '/Authentication/DisplayUpdateAdmin.rails?slaElementId=slRenderDiv&slaDivLayout=1';
    this.__Send(this.__CapturePersistentParams(url), "renderLogin");
}

SLAuthProxy.prototype.SubmitUpdateForm = function (form){
	this.__SubmitForm(form);
}

