function getXmlReqObj() {
    var httpRequest;

    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
        httpRequest = new XMLHttpRequest();
        if (httpRequest.overrideMimeType) {
            httpRequest.overrideMimeType('text/xml');
            // See note below about this line
        }
    }
    else if (window.ActiveXObject) { // IE
        try {
            httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!httpRequest) {
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }

    return httpRequest;
}

function doCaptchaLogin(getParams) {
   var httpRequest = getXmlReqObj();
   var param = getParams() + "&" + getCaptchaQueryString();
   httpRequest.open('POST', '/captcha/login_rcp.php', true);
   httpRequest.onreadystatechange = function() { postKuberaLogin(httpRequest); };
   httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   httpRequest.setRequestHeader("Content-length", param.length);
   httpRequest.setRequestHeader("Connection", "close");
   if (param.length == 0) return;
   httpRequest.send(param);
}

function doKuberaLogin(getParams, httpRequest, require_captcha) {
    var param = getParams();
    httpRequest.open('POST', '/KuberaVault/kv', true);
    httpRequest.onreadystatechange = function() { postKuberaLogin(httpRequest); };
    httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    httpRequest.setRequestHeader("Content-length", param.length);
    httpRequest.setRequestHeader("Connection", "close");
    if (param.length == 0) return;
    httpRequest.send(param);
}

function showProcessing() {
    // Clear showMsg
    document.getElementById('showMsg2').innerHTML="";
    document.getElementById('showMsg').innerHTML="Processing...Please wait";
    document.appLogin.login.disabled=true;
}

function validate(addressField) {
    if (!validateEmail(addressField)) {
        document.appLogin.email.focus();
        return false;
    }
    if (document.appLogin.passwd.value == "") {
        document.getElementById('showMsg').innerHTML="";
        document.getElementById('showMsg2').innerHTML="";
        document.getElementById('showMsg').innerHTML="Enter your password";
        document.appLogin.passwd.focus();
        return false;
    }
    return true;
}

function performLogin(getParams) {
    var addressField = document.getElementById("email");
    if (validate(addressField) == false) {
        return false;
    }
    setSecurity();
    showProcessing();
    doKuberaLogin(getParams, getXmlReqObj(), false);
    return false;
}

function performLoginIncludingCaptcha(getParams) {
    var addressField = document.getElementById("email");
    if (validate(addressField) == false) {
        return false;
    }
    setSecurity();
    showProcessing();
    doCaptchaLogin(getParams);
    return false;
}

function postKuberaLogin(httpRequest) {
    if (httpRequest.readyState == 4) {
        if (httpRequest.status == 200) {
            var responseXml = httpRequest.responseXML;
            var status = responseXml.getElementsByTagName('Status').item(0).firstChild.data;

            var tempMessage = responseXml.getElementsByTagName('Message').item(0);
            var message;
            if (tempMessage != null) {
                message = tempMessage.firstChild.data;
            }

            var tempVer = responseXml.getElementsByTagName('Version').item(0);
            var ver;
            if (tempVer != null) {
                ver = tempVer.firstChild.data;
            }

            if (ver == null) ver = "";
            if (status == "yes") {
                document.getElementById("showMsg").innerHTML = message;
                document.getElementById("showMsg2").innerHTML = '';
                postLogin(httpRequest, ver);
            } else if (status == "no") {
                document.getElementById("showMsg").innerHTML = '';
                document.getElementById("showMsg2").innerHTML = message;
                document.getElementById('loginButton').value = 'Login';
                document.appLogin.force.value = 'no';
                document.appLogin.passwd.focus();
                document.appLogin.login.disabled = false;
            } else if (status == "maybe") {
                document.appLogin.login.disabled = false;
                document.getElementById("showMsg").innerHTML = '';
                alert(message);
                //document.getElementById("showMsg2").innerHTML = "Click Login to Log him out and login";
                document.appLogin.login.value = "Login";
                document.appLogin.force.value = 'yes';
            } else if (status == "email_mismatch") {
                document.appLogin.login.disabled = false;
                document.getElementById("showMsg").innerHTML = '';
                alert(message);
                document.appLogin.login.value = "Login";
            } else if (status == "require_captcha") {
                window.location = "/login_rcp.html";
            } else if (status == "err_passwd_captcha") {
                createCookie("kpasserr", message, 0);
                window.location = "/login_rcp.html";
            }
        } else if (httpRequest.status >= 500) {
            //alert('Unable to login. Service may be temporarily unavailable.');
            document.getElementById('loginButton').value = 'Login';
            document.appLogin.force.value = 'no';
            document.appLogin.login.disabled = false;

            window.location = "/err500.html";
        } else if (httpRequest.status >= 400) {
            //alert('Unable to login. Service may be temporarily unavailable.');
            document.getElementById('loginButton').value = 'Login';
            document.appLogin.force.value = 'no';
            document.appLogin.login.disabled = false;

            window.location = "/err400.html";
        }
    }
}

function postLogin(httpRequest, ver) {
    if (httpRequest.readyState == 4) {
        if (httpRequest.status == 200) {
            var app = "MyFinanceApp";
            if (navigator.userAgent.indexOf("Linux") != -1) {
                app += "_s";
            }
            createCookie("perfios_version", ver, 0);
            var cmks = readCookie("_cmks");
            if (typeof(cmks) != "undefined" && cmks != null) {
                eraseCookie("_cmks");
            }
            window.location = app + ".html";
        }
    }
    document.appLogin.login.disabled = false;
}

function launchKuberaWindow() {
    var dimensions='toolbar=0,location=1,directories=0,status=1,menubar=0,scrollbars=1,resizable=0,top=0,left=0,width='+screen.width+',height='+0.85*screen.height;
    var mainwin=window.open('/login.html', '', dimensions);
}

function isSecurity() {
    // if "on public computer checkbox cookie is present in the browser, then check the checkbox
    var secure = readCookie("ksecure");
    if (secure == "no") {
        document.getElementById("secure").checked = true;
    }
}

function firstlogin() {
    isSecurity();
    tabPasswdFocus();
}

function tabPasswdFocus() {
    var passwd = document.getElementById("passwd");
    if (passwd.value == null || passwd.value == "") {
        passwd.focus();
    }
}

function setUpCaptchaPage() {
    setup();
    var message = readCookie("kpasserr");
    if (message != "") {
        document.getElementById("showMsg").innerHTML = '';
        document.getElementById("showMsg2").innerHTML = message;
        eraseCookie("kpasserr");
    }
}

function setup() {
    isSecurity();
}

function tabFocus() {
    var email = document.getElementById("email");
    if (email.value == null || email.value == "") {
        email.focus();
    }
}

function getEmailFromURL() {
    var url = decodeURIComponent(window.location);
    var usremail = url.split("email=")[1];
    return usremail;
}

function setEmailCookie() {
    var usremail = getEmailFromURL();
    createCookie("kemail", usremail, 0);
}

function switchLoginMode() {
    if (isCookieEnabled()) {
        var kemail = readCookie("kemail");
        if (typeof(kemail) == "undefined" || kemail == null) {
            setup();
            jQuery("#dialog").dialog({ autoOpen: false });
        } else {
            document.getElementById("email").value = kemail;
            jQuery("#dialog").dialog(
                    {
                        autoOpen: true,
                        width: 600,
                        closeOnEscape: true,
                        buttons: { "OK": function() { jQuery(this).dialog("close"); } }
                    });
            firstlogin();
            eraseCookie("kemail");
        }
    }
}

function checkRegisterEmail() {
    var addressField = document.getElementById("email");
    if (!validateEmail(addressField)) {
        document.interested.email.focus();
        return false;
    }
    return true;
}

function writeErrorMessage(message) {
    document.getElementById('showMsg2').innerHTML = message;
    return;
}

function registerUser() {

    if (cookieWasDisabled) {
        if (isCookieEnabled()) {
            writeErrorMessage("Refresh the page now to proceed.");
            return false;
        } else {
            writeErrorMessage("Please enable cookies and refresh page.");
            return false;
        }
    }

    var addressField = document.getElementById("email");
    var confirmAddressField = document.getElementById("confirm_email");

    // First: check if either email field is empty.
    if (stringEmpty(addressField.value) || stringEmpty(confirmAddressField.value)) {
        writeErrorMessage("Email address cannot be empty.");
        return false;
    }

    // Second: check if email addresses match.
    if (addressField.value != confirmAddressField.value) {
        writeErrorMessage("Email addresses do not match.");
        return false;
    }

    // Third: check if both email IDs are valid.
    if (!validateEmail(addressField)) {
        document.register.email.focus();
        return false;
    }

    if (!validateEmail(confirmAddressField)) {
        document.register.confirm_email.focus();
        return false;
    }

    // Fourth: Check if captcha is entered
    document.getElementById('showMsg2').innerHTML='';
    var cap = document.getElementById("code");
    if (cap.value == "") {
        document.getElementById('showMsg4').innerHTML="<br/>";
        document.getElementById('showMsg3').innerHTML="Please enter the verification code.";
        document.register.code.focus();
        return false;
    }

    // Fifth: check if Terms of Use and the Privacy Policy.
    if (document.register.tac.checked == false) {
        document.getElementById('showMsg3').innerHTML="";
        showAcceptTAC();
        return false;
    }

    return true;
}

function forgotPasswd() {
    var addressField = document.getElementById("forgotemail");
    if (!validateEmail(addressField)) {
        document.forgotpasswd.forgotemail.focus();
        return false;
    }

    /* User defined token should have a minimum length of 6 characters
     * and a maximum length of 64 characters. */
    var userDefinedToken = document.getElementById("token");
    if (!validateUserDefinedToken(userDefinedToken)) {
        document.forgotpasswd.token.focus();
        return false;
    }

    return true;
}

function validateUserDefinedToken(userDefinedToken) {
    var token = trim(userDefinedToken.value);
    var isValid = false;

    if (stringEmpty(token)) {
        setTokenError("Security word cannot be blank.");
    } else if (token.length < 6) {
        setTokenError("Security word should be atleast 6 characters long.");
    } else if (token.length > 64) {
        setTokenError("Security word should not be more than 64 characters long.");
    } else {
        isValid = true;
    }

    return isValid;
}

/* Removes leading whitespaces */
function LTrim( value ) {
    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");
}

/* Removes ending whitespaces */
function RTrim( value ) {
    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1");
}

/* Removes leading and ending whitespaces */
function trim( value ) {
    return LTrim(RTrim(value));
}

function setTokenError(message) {
    document.getElementById("tokenError").innerHTML = message;
    return true;
}

function validateEmail (addressField) {
    if ( stringEmpty ( addressField.value ) || noAtSign ( addressField.value ) || nothingBeforeAt ( addressField.value ) || noValidPeriod ( addressField.value ) || noValidSuffix ( addressField.value ) || noValidPrefix ( addressField.value ) || hasComma( addressField.value ))
        document.getElementById('showMsg2').innerHTML="Invalid email address. Try again.";
    else
        return (true);

    return ( false );
}

function stringEmpty ( address ) {
    if ( address.length < 1 ) {
        return ( true );
    } else {
        return ( false );
    }
}

function noAtSign ( address ) {
    if ( address.indexOf ( '@', 0 ) == -1 ) {
        return ( true )
    } else {
        return ( false );
    }
}

function nothingBeforeAt ( address ) {
    if ( address.indexOf ( '@', 0 ) < 1 ) {
        return ( true )
    } else {
        return ( false );
    }
}

function noValidPeriod ( address ) {
    // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN WE ARE NOT INTERESTED
    if ( address.indexOf ( '@', 0 ) > 1 && address.charAt ( address.length - 1 ) == ']' )
        return ( false );

    // CHECK THAT THERE IS AT LEAST ONE PERIOD IN THE STRING
    if ( address.indexOf ( '.', 0 ) == -1 )
        return ( true );

    return ( false );
}

function noValidPrefix ( address ) {
    var atSignIndex = address.indexOf ( '@', 0 );
    var firstDotIndex = address.indexOf ( '.', atSignIndex );
    if ( (firstDotIndex - atSignIndex ) == 1 ) {
        return ( true );
    } else {
        return ( false );
    }
}

function noValidSuffix ( address ) {
    // IF EMAIL ADDRESS IN FORM 'user@[255,255,255,0]', THEN WE ARE NOT INTERESTED
    if ( address.indexOf ( '@', 0 ) > 1 && address.charAt ( address.length - 1 ) == ']' )
        return ( false );

    // CHECK THAT THERE IS A TWO OR THREE CHARACTER SUFFIX AFTER THE LAST PERIOD
    var len = address.length;
    var pos = address.lastIndexOf ( '.', len - 1 ) + 1;
    if ( ( len - pos ) < 2 || ( len - pos ) > 4 ) {
        return ( true );
    } else {
        return ( false );
    }
}

function hasComma ( address ) {
    if ( address.indexOf ( ',', 0 ) == -1 )
        return ( false );

    return ( true );
}

function setSecurity() {
    if (document.getElementById("secure").checked) {
        createCookie("ksecure","no",0);
    } else if (!document.getElementById("secure").checked) {
        eraseCookie("ksecure");
    }
}

function isCaptchaFine() {
    var url = decodeURIComponent(window.location);
    var userEmail = unescape(readCookie("kemail"));
    if (typeof(userEmail) == "undefined" || userEmail == null || userEmail == "null" || userEmail == "") {
        return true;
    } else {
        document.getElementById("email").value = userEmail;
        document.getElementById("confirm_email").value = userEmail;
        document.register.code.focus();
        writeErrorMessage("Code mismatch. Please re-enter.");
        eraseCookie("kemail");
        return false;
    }
}

function initGStart() {
    isCookieEnabled();
    if (isCaptchaFine()) {
        document.register.email.focus();
    }
}

// Redirection call made from landing pages. Hence the relative path
function adRedirectToLogin() {
    setEmailCookie();
    window.location = "../../login.html";
}

function redirectToLogin() {
    setEmailCookie();
    window.location = "/login.html";
}

function submitLoginForm() {
    if (jQuery.cookie('_aphid') != null) {
        return performLogin(getRegisterAndLoginQueryString);
    } else {
        return performLogin(getLoginQueryString);
    }
}

function handleAphid() {
    var aphid = jQuery.cookie('_aphid');
    if (aphid != null) {
        jQuery('#repeatPassword').show();
        jQuery('#email').val(aphid);
        jQuery('#email').attr('disabled', 'disabled');
        jQuery('#passwd').focus();
        jQuery('#forgotpass').hide();
    }
}

function getCaptchaQueryString() {
    var options = { code: jQuery('#code').val() }

    return jQuery.param(options);
}

function getLoginQueryString() {
    var options = {
        email: jQuery('#email').val(), _p: jQuery('#passwd').val(),
        force: jQuery('#force').val(), act: "login", app: jQuery('#app').val()
    }

    return jQuery.param(options);
}

function getRegisterAndLoginQueryString() {
    var options = {
        email: jQuery('#email').val(), _p: jQuery('#passwd').val(),
        _second_p: jQuery('#_second_p').val(), force: jQuery('#force').val(),
        act: "registerandlogin"
    }

    return jQuery.param(options);
}

/* Added for Xerago */
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 "";
}

function checkCookie() {
    bid = getCookie('bid');
    if (bid != null && bid != "") {
        var zid = "";
        if (!document.phpAds_used) document.phpAds_used = ',';
        phpAds_random = new String (Math.random());
        phpAds_random = phpAds_random.substring(2,11);
        document.write("<" + "script language='JavaScript' type='text/javascript' src='");
        document.write("http://66.235.187.220/xaltadserver/www/delivery/leads.php?n=" + phpAds_random);
        document.write("&amp;bid="+bid+"&amp;zid="+zid);
        var aphid = jQuery.cookie('_aphid');
        document.write("&amp;aphid="+aphid);
        if (document.referrer)
            document.write("&amp;referer=" + escape(document.referrer));
        document.write("'><" + "/script>");
    }
}

function parseUrlQueryParams() {
    var urlParams = {};
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
       urlParams[d(e[1])] = d(e[2]);
    return urlParams;
}

function showErrorMessage() {
    var qParams = parseUrlQueryParams();
    var errorCode = qParams.errorCode;
    var element = jQuery("#" + errorCode);
    if (element.length == 0) {
        element = jQuery("#default_error");
    }
    jQuery("#errorMessage").html(element.html());
}

function replaceRetryUrl() {
    var qParams = parseUrlQueryParams();
    var retryPageUrl = qParams.retryPageUrl;
    var elements = jQuery("#retryPageUrl");

    if (elements.length != 0) {
        elements.attr("href", retryPageUrl);
    }
}

function populateXnId() {
    var qParams = parseUrlQueryParams();
    var xnId = qParams.xnid;
    if (xnId != null && xnId.length !=0) {
        var element = jQuery("#xnid");
        if (element.length != 0) element.html(xnId);
    }
}

function initPage() {
    isCookieEnabled();
    if (isCaptchaFine()) {
        tabFocus();
    }
    return true;
}

function showAcceptTAC() {
    document.getElementById('showMsg4').innerHTML="Please accept Terms of Use &amp; Privacy Policy.";
    document.register.tac.focus();
}

function isTACAccepted() {
    if (document.register.tac.checked == false) {
        showAcceptTAC();
        return false;
    } else {
        return true;
    }
}

/* Added for OpenID/OAuth */
var providers_urls = {
    google: 'https://www.google.com/accounts/o8/id',
    yahoo:  'http://me.yahoo.com/'
};

function submitOpenIdForm(formId) {
    if (isTACAccepted()) {
        var form = jQuery(formId);
        form.submit();
    }
}

function submitOpenIdForm(formId, provider) {
    if (isTACAccepted()) {
        var provider = providers_urls[provider];
        jQuery('#identifier').val(provider);
        var form = jQuery(formId);
        form.submit();
    }
}

