/**
 * Codes for new login panel
 * 2009-9-23 14:35:15
 * @author bruce
 * */
String.prototype.trim = function(){
    return this.replace(/(^\s*)|(\s*$)/g, '');
}

/*
 * It's more efficient than string concat
 */
function StringBuffer(){
    this.arr = new Array();
    this.append = function(str){
        this.arr.push(str);
    };
    this.toString = function(){
        return this.arr.join("");
    };
}

/**
 * Defined the Error Message box
 * @param {Object} errorMsg
 */
function ErrorDiv(errorMsg){
    this.show = function(){
        var errorDiv = document.getElementById("error_div");
        var sb = new StringBuffer();
        sb.append('<div id="error_div">');
        sb.append('<div align="center"><div class="z_t"><img src="images/login/table_t.gif" /></div>');
        sb.append('<table width="286" height="113" border="0" cellpadding="0" cellspacing="0" background="images/login/errorer_bg.gif" class="login-table" style="border-left:solid 1px #9BB3CF;border-right:solid 1px #9BB3CF;">');
        sb.append('<tr><td width="15%" height="78" align="right" valign="middle"><img src="images/login/error.gif" width="27" height="28" /></td><td colspan="2" align="left" valign="middle"><b style="padding-left:8px;">' + errorMsg + '</b></td></tr>');
        sb.append('<tr><td height="35" align="right">&nbsp;</td><td width="67%" align="center" valign="top"><input class="login-button" type="submit" name="Submit" value="OK" onclick="javascript:ERROR_DIV_OBJECT.remove();"/></td><td width="26%" align="left" valign="top">&nbsp;</td></tr>');
        sb.append('</table><div class="z_t"><img src="images/login/table_b.gif" /></div></div>');
        var loginDiv = document.getElementById("login_panel_div");
        document.getElementById("error_div").innerHTML = sb.toString();
        loginDiv.style.display = "none";
    };
    this.remove = function(){
        var loginDiv = document.getElementById("login_panel_div");
        loginDiv.style.display = "block";
        var errorDiv = document.getElementById("error_div");
        errorDiv.innerHTML = "";
        setLoginStatus(1, LOGIN_WELCOME_MESSAGE);
    }
}

function LoginDiv(){
    this.oLoginUserNameInput;
    this.oLoginPasswordInput;
    this.oLoginTypeInput;
    this.oLoginGenderInput;
    this.onResize = function(){
    
        if (document.getElementById('login_panel_div') != null && document.getElementById('login_panel_div').style.display != 'none') {
            var top = 0;
            var right = 0;
            top = (document.documentElement.clientHeight - 250) / 2;
            right = (document.documentElement.clientWidth - 325) / 2;
            document.getElementById('login_panel_div').style.top = top + "px";
            document.getElementById('login_panel_div').style.right = right + "px";
        }
    };
    
    this.load = function(display){
        var style = new StringBuffer();
        style.append('style="');
        if (!display) {
            style.append('display:none;');
        }
        if (isMobile()) {
            style.append('top:10%;');
        }
        else {
            var top = (document.body.clientHeight - 250) / 2;
            var right = (document.body.clientWidth - 325) / 2;
            style.append('top:' + top + 'px;right:' + right + 'px;');
        }
        style.append('"');
        var stringBuffer = new StringBuffer();
        stringBuffer.append('<div id="login_panel_div" ' + style.toString() + '>');
        stringBuffer.append('<div class="login-top"><img src="images/login/t_l.gif" /><span>Login</span><img src="images/login/t_r.gif" /></div>');
        stringBuffer.append('<div id="main">');
        stringBuffer.append('<div align="center">');
        stringBuffer.append('<div class="c_t"><img src="images/login/c_t.gif" /><!-- space end--></div>');
        stringBuffer.append('<div class="c_c"><div class="logo"><img src="images/login/logo.gif" width="140" height="59" /></div>');
        stringBuffer.append('<div align="center">');
        stringBuffer.append('<div class="z_t"><img src="images/login/table_t.gif" /></div>');
        stringBuffer.append('<table width="286" border="0" cellspacing="0" cellpadding="0" class="login-table" style="border-left:solid 1px #9BB3CF;border-right:solid 1px #9BB3CF;">');
        stringBuffer.append('<tr><td width="81" height="25">&nbsp;</td><td width="20" align="left" valign="middle"><input name="checkbox" type="checkbox" id="loginType"  onclick="javascript:onGuestLoginTypeChanged();"/></td><td width="183" colspan="2" align="left" valign="middle">Guest login</td></tr>');
        stringBuffer.append('<tr><td height="30" align="right" valign="middle">Username:</td><td colspan="3" align="left" valign="middle"><input name="text" type="text" id="loginUsername" onkeypress="javascript:onLoginPressed(event);" class="input" /></td></tr>');
        stringBuffer.append('<tr id="loginPassword_tr"><td height="30" align="right" valign="middle">Password:</td><td colspan="3" align="left" valign="middle"><input name="password" type="password" id="loginPassword" onkeypress="javascript:onLoginPressed(event);" class="input"  /></td></tr>');
        stringBuffer.append('<tr id="loginGender_tr"><td height="30" align="right" valign="middle">Gender:</td><td colspan="3" align="left" valign="middle"><select name="select" id="loginGender" class="input2" ><option selected="selected" value="0">Couple</option><option value="1">Male</option><option value="2">Female</option></select></td></tr>');
        stringBuffer.append('</table>');
        stringBuffer.append('<div class="z_t"><img src="images/login/table_b.gif" /></div>');
        stringBuffer.append('<table width="286" border="0" cellspacing="0" cellpadding="0">');
        stringBuffer.append('<tr><td width="81" height="38">&nbsp;</td><td align="left" valign="middle"><input class="login-button" name="login-button2" type="button" id="loginButton" onclick="javascript:LOGIN_DIV_OBJECT.onLoginClicked();" value="Login"/><input class="login-button2" name="login-button2" type="button" id="registerButton" onclick="javascript:LOGIN_DIV_OBJECT.onRegisterClicked();" value="Register"/></td></tr>');
        stringBuffer.append('</table>');
        stringBuffer.append('<div id="loginStatus">');
        stringBuffer.append(LOGIN_WELCOME_MESSAGE);
        stringBuffer.append('</div></div></div><div class="c_t"><img src="images/login/c_b.gif" /><!-- space end--></div></div></div>');
        stringBuffer.append('<div class="bot"><img src="images/login/bot-l.gif" width="2" height="4" /><span><!-- space end--></span><img src="images/login/bot-r.gif" width="2" height="4" /></div>');
        stringBuffer.append('');
        stringBuffer.append('</div>');
        document.write(stringBuffer.toString());
        if (display) {
            document.getElementById("loginUsername").focus();
        }
        document.getElementById("loginType").checked = false;
		document.getElementById("loginType").disabled = true;
        onGuestLoginTypeChanged();
        this.oLoginUserNameInput = document.getElementById("loginUsername");
        this.oLoginPasswordInput = document.getElementById("loginPassword");
        this.oLoginGenderInput = document.getElementById("loginGender");
        this.oLoginTypeInput = document.getElementById("loginType");
        document.getElementById("registerButton").disabled = true;
        window.onresize = this.onResize;
    };
    this.onLoginClicked = function(){
        var loginUsername = this.oLoginUserNameInput.value;
        var loginPassword = this.oLoginPasswordInput.value;
        var loginGender = this.oLoginGenderInput.value;
        var errorMsg = "";
        var loginStatusDIV = document.getElementById("loginStatus");
        var check = true;
        loginStatusDIV.innerHTML = "";
        if (loginUsername.trim().length == 0) {
            errorMsg = "User name should not be empty!";
            check = false;
        }
        else 
            if (loginPassword.trim().length == 0 && !document.getElementById("loginType").checked) {
                errorMsg = "Password should not be empty!";
                check = false;
            }
            else {
            
                if (gwtInit) {
                    // If gwt init finished
                    if (cacheErrorMessage.length != 0) {
                        loginStatusDIV.innerHTML = cacheErrorMessage;
                    }
                    else {
                        login();
                        loginStatusDIV.innerHTML = "Login...";
                        loginButtonClicked = true;
                        this._disableInput();
                    }
                }
                else {
                    /*If gwt init has not finished yet: 
                 * Set the flag loginButtonClicked true
                 * When gwt finished init, and get loginButtonClicked vairable is true, gwt will auto login
                 */
                    loginButtonClicked = true;
                    loginStatusDIV.innerHTML = "Login...";
                    this._disableInput();
                }
            }
        if (!check) {
            ERROR_DIV_OBJECT = new ErrorDiv(errorMsg);
            ERROR_DIV_OBJECT.show();
        }
    }
    this.setLoginStatusLabel = function(result, message){
        var loginStatusDIV = document.getElementById("loginStatus");
        var loginButton = document.getElementById("loginButton");
        if (result == -1) {
            //connection failed
            cacheErrorMessage = message;
            this._enableInput();
			loginStatusDIV.innerHTML = message;
        }
        else if (result != 0) {
            //login failed
           this._enableInput();
           loginStatusDIV.innerHTML = message;
        }
    };
    this.onRegisterClicked = function(){
        var loginStatusDIV = document.getElementById("loginStatus");
        registerButtonClicked = true;
        document.getElementById("registerButton").disabled = true;
        if (gwtInit) {
            document.getElementById("login_panel_div").style.display = "none";
            //this function is defined in GWT
            onRegister();
        }
        else {
            var loginButton = document.getElementById("loginButton");
            loginButton.disabled = true;
            loginStatusDIV.innerHTML = "Initializing the register panel...";
        }
    };
    this.enableRegisterButton = function enableRegisterButton(){
        var loginStatusDIV = document.getElementById("loginStatus");
        document.getElementById("registerButton").disabled = false;
        loginStatusDIV.innerHTML = LOGIN_WELCOME_MESSAGE;
        var loginButton = document.getElementById("loginButton");
        loginButton.disabled = false;
    }
    this._disableInput = function(){
        var loginButton = document.getElementById("loginButton");
        var registerButton = document.getElementById("registerButton");
        loginButton.disabled = true;
        registerButton.disabled = true;
        this.oLoginUserNameInput.disabled = true;
        this.oLoginPasswordInput.disabled = true;
        this.oLoginGenderInput.disabled = true;
        this.oLoginTypeInput.disabled = true;
    }
    this._enableInput = function(){
        var loginButton = document.getElementById("loginButton");
        var registerButton = document.getElementById("registerButton");
        loginButton.disabled = false;
        registerButton.disabled = false;
        this.oLoginUserNameInput.disabled = false;
        this.oLoginPasswordInput.disabled = false;
        this.oLoginGenderInput.disabled = false;
        this.oLoginTypeInput.disabled = false;
    }
    
}

//this defined the error message box object
var ERROR_DIV_OBJECT;
var LOGIN_DIV_OBJECT = new LoginDiv();
var LOGIN_WELCOME_MESSAGE = "Welcome to use 123 Flash Chat";
var registerButtonClicked = false;

function getURLParameter(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];
}

var gwtInit = false;
var loginButtonClicked = false;
var parameters = "";
var urlLink;
var cacheErrorMessage = "";

try {
    urlLink = window.location.href;
} 
catch (e) {
    try {
        urlLink = document.URL;
    } 
    catch (e) {
        urlLink = "";
    }
}

if (urlLink.indexOf("?") != -1) {
    parameters = urlLink.substring(urlLink.indexOf("?") + 1);
    if (parameters.indexOf("init_user") != -1) {
        loginButtonClicked = true;
        addAutoConnectionDIV(getURLParameter("init_user"));
        LOGIN_DIV_OBJECT.load(false);
    }
    else {
        LOGIN_DIV_OBJECT.load(true);
    }
}
else {
    LOGIN_DIV_OBJECT.load(true);
}

function gwtInitSuccess(){
    gwtInit = true;
}

function addAutoConnectionDIV(name){
    var sb = new StringBuffer();
    sb.append('<div id="auto_login_div" style="top: 50%; position: absolute; right: 40%;">');
    sb.append('<div align="center">');
    sb.append('<div class="ts"><span>');
    sb.append(name);
    sb.append(' is connecting...');
    sb.append('</span></div></div></div>');
    document.write(sb.toString());
}

function onGuestLoginTypeChanged(){
    var loginPassword_tr = document.getElementById("loginPassword_tr");
    var loginGender_tr = document.getElementById("loginGender_tr");
    var loginPassword = document.getElementById("loginPassword");
    if (document.getElementById("loginType").checked) {
        loginPassword_tr.style.display = 'none';
        loginGender_tr.style.display = '';
        loginPassword.value = "";
    }
    else {
        loginPassword_tr.style.display = '';
        loginGender_tr.style.display = 'none';
    }
    try {
        document.getElementById("loginUsername").focus();
    } 
    catch (ex) {
        //ignored exception
    }
}

function onLoginPressed(evt){
    if (evt.keyCode == 13) {
        LOGIN_DIV_OBJECT.onLoginClicked();
    }
}

function login(){
    onLogin(); //this function is defined in GWT
}


