var Famark = Famark || {};
var Resources = Resources || {};

Famark.pageLoad = function () {
    Famark._frmAuth = document.getElementById('frmAuth');
    Famark._messageLabel = document.getElementById('MessageLabel');
    Famark._txtDomainName = document.getElementById('txtDomainName');
    Famark._txtUserName = document.getElementById('txtUserName');
    Famark._txtPassword = document.getElementById('txtPassword');
    Famark._btnSubmit = document.getElementById('btnSubmit');
    var passFrame = document.getElementById('passFrame');

    var tokenKey = '#deviceToken=';
    var hrefVal = window.location.href;
    var tokenPos = hrefVal.indexOf(tokenKey);
    var tokenValue = (tokenPos < 0) ? null : window.decodeURIComponent(hrefVal.substr(tokenPos + tokenKey.length));

    Famark.addHandler(passFrame, 'load', function () {
        Famark._btnSubmit.className = '';
        Famark._btnSubmit.disabled = false;
        var frameDoc = passFrame.contentDocument || passFrame.contentWindow.document;
        var result = Famark.parseJSON(frameDoc.body.innerHTML);
        if (result.ErrorMessage == null || result.ErrorMessage == '') {
            var loc = window.top.location.href;
            if (loc.toLowerCase().indexOf('/gate.ashx') > 0) {
                var redPos = loc.toLowerCase().indexOf('&redirect=');
                if (redPos > 0)
                    window.top.location = window.decodeURIComponent(loc.substring(redPos + 10));
                else
                    window.top.location = loc.substring(0, loc.lastIndexOf('/') + 1);
            } else {
                if (tokenValue != null)
                    window.location.hash = '';
                window.location.reload(true);
            }
        } else {
            var errorMessage = result.ErrorMessage;
            if (errorMessage.length > 45) {
                var cutPos = errorMessage.lastIndexOf(' ', 45);
                cutPos = (cutPos < 30) ? 45 : cutPos + 1;
                var alertMessage = errorMessage.replace(/'/g, "\"").replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
                errorMessage = errorMessage.substr(0, cutPos) + "<input type='button' value='...' onclick='alert(\"" + alertMessage + "\");' />";
            } else if (Resources.hasOwnProperty(errorMessage)) {
                errorMessage = Resources[errorMessage];
            }
            Famark._messageLabel.innerHTML = errorMessage;
        }
    });

    if (tokenValue != null) {
        var elToken = document.createElement('input');
        elToken.type = 'hidden';
        elToken.name = 'DeviceToken';
        elToken.value = tokenValue;
        Famark._frmAuth.appendChild(elToken);
    }

    var hdnIdentityProvider = document.getElementById('hdnIdentityProvider');
    if (hdnIdentityProvider == null) {
        Famark._txtPassword.onkeyup = function (e) {
            e = e || window.event;
            if (Famark._txtPassword.value != '' && e.keyCode == 13)
                Famark.performLogin();
        };
    } else {
        var txtEmail = document.getElementById('txtEmail');
        txtEmail.onkeyup = function (e) {
            e = e || window.event;
            if (txtEmail.value != '' && e.keyCode == 13)
                Famark.registerUser();
        };
    }

    Famark.addHandler(window, 'resize', Famark.screenLoad);
    Famark.screenLoad();
};

Famark.performLogin = function () {
    var firstField = null;
    var reqFields = '';

    if (Famark._txtDomainName.value == '') {
        reqFields = Resources.LabelDomainName + ', ';
        Famark._txtDomainName.className = 'elError';
        firstField = Famark._txtDomainName;
    } else {
        Famark._txtDomainName.className = '';
    }

    if (Famark._txtUserName.value == '') {
        reqFields += Resources.LabelUserName + ', ';
        Famark._txtUserName.className = 'elError';
        firstField = firstField || Famark._txtUserName;
    } else {
        Famark._txtUserName.className = '';
    }

    if (Famark._txtPassword.value == '') {
        reqFields += Resources.LabelPassword + ', ';
        Famark._txtPassword.className = 'elError';
        firstField = firstField || Famark._txtPassword;
    } else {
        Famark._txtPassword.className = '';
    }

    if (reqFields.length > 1 && firstField != null) {
        Famark._messageLabel.innerHTML = Resources.RequiredFieldPrefix + reqFields.substring(0, reqFields.length - 2);
        firstField.readOnly = false;
        firstField.focus();
    }
    else {
        Famark._messageLabel.innerHTML = '';
        Famark._btnSubmit.className = 'loading';
        Famark._btnSubmit.disabled = true;
        Famark._frmAuth.action = 'Pass.ashx';
        Famark._frmAuth.target = 'passFrame';
        Famark._frmAuth.submit();
    }
};

Famark.registerUser = function() {
    var firstField = null;
    var reqFields = '';
    var invFields = '';
    var password = null;

    if (Famark._txtDomainName.value == '') {
        reqFields = Resources.LabelDomainName + ', ';
        Famark._txtDomainName.className = 'elError';
        firstField = Famark._txtDomainName;
    } else {
        Famark._txtDomainName.className = '';
    }

    if (Famark._txtUserName.value == '') {
        reqFields += Resources.LabelUserName + ', ';
        Famark._txtUserName.className = 'elError';
        firstField = firstField || Famark._txtUserName;
    } else {
        Famark._txtUserName.className = '';
    }

    if (Famark._txtPassword != null) {
        if (Famark._txtPassword.value == '') {
            reqFields += Resources.LabelPassword + ', ';
            Famark._txtPassword.className = 'elError';
            firstField = firstField || Famark._txtPassword;
        } else {
            var txtConfirmPassword = document.getElementById('txtConfirmPassword');
            if (txtConfirmPassword.value != Famark._txtPassword.value) {
                invFields += Resources.LabelConfirmPassword + ', ';
                txtConfirmPassword.className = 'elError';
                firstField = firstField || txtConfirmPassword;
            } else {
                txtConfirmPassword.className = '';
                password = txtConfirmPassword.value;
            }
        }
    } else {
        password = document.getElementById('hdnPassword').value;
    }

    var txtDisplayName = document.getElementById('txtDisplayName');

    if (txtDisplayName.value == '') {
        reqFields += Resources.LabelDisplayName + ', ';
        txtDisplayName.className = 'elError';
        firstField = firstField || txtDisplayName;
    } else {
        txtDisplayName.className = '';
    }

    var txtEmail = document.getElementById('txtEmail');

    if (txtEmail.value == '') {
        reqFields += Resources.LabelEmail + ', ';
        txtEmail.className = 'elError';
        firstField = firstField || txtEmail;
    } else {
        var emailMatch = txtEmail.value.match(/^([a-zA-Z0-9_\.\-])+@([a-zA-Z0-9_\.\-])+\.([a-zA-Z])+([a-zA-Z])+/);
        if (emailMatch == null) {
            invFields += Resources.LabelEmail + ', ';
            txtEmail.className = 'elError';
            firstField = firstField || txtEmail;
        } else {
            txtEmail.className = '';
        }
    }

    if (reqFields.length > 1 && firstField != null) {
        Famark._messageLabel.innerHTML = Resources.RequiredFieldPrefix + reqFields.substring(0, reqFields.length - 2);
        firstField.readOnly = false;
        firstField.focus();
        return;
    }

    if (invFields.length > 1 && firstField != null) {
        Famark._messageLabel.innerHTML = Resources.InvalidFieldPrefix + invFields.substring(0, invFields.length - 2);
        firstField.readOnly = false;
        firstField.focus();
        return;
    }

    Famark._messageLabel.innerHTML = '';
    var provider = document.getElementById('hdnIdentityProvider').value;

    var data = 'SystemName=' + Famark._txtUserName.value + '&DisplayName=' + txtDisplayName.value + '&Email=' + txtEmail.value + '&IdentityProvider=' + provider;
    var stateVal = provider.toLowerCase();

    var hdnIdentityName = document.getElementById('hdnIdentityName');
    var hdnIdentityToken = document.getElementById('hdnIdentityToken');

    if (hdnIdentityName == null) {
        data += '&Password=' + password;
    } else {
        data += '&Password=' + hdnIdentityToken.value + '&IdentityName=' + hdnIdentityName.value + '&IdentitySubject=' + document.getElementById('hdnIdentitySubject').value;
        var providerUrl = document.getElementById('hdnIdentityProviderUrl').value;
        if (providerUrl != null && providerUrl != '')
            stateVal += '-' + providerUrl;
    }

    data = 'entity=System_User&work=CreateRecord&data=' + window.encodeURIComponent(data);
    var http = new XMLHttpRequest();
    http.open('POST', 'Work.ashx', false);
    http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    http.send(data);
    var result = Famark.parseJSON(http.responseText);
    if (result.ErrorMessage == null || result.ErrorMessage == '') {
        if (hdnIdentityName == null) {
            var loc = window.top.location.href;
            window.top.location = loc.substring(0, loc.lastIndexOf('/') + 1);
            return;
        }
        var form = document.createElement('form');
        form.action = 'Gate.ashx';
        form.method = 'POST';
        document.body.appendChild(form);
        var accessToken = document.createElement('input');
        accessToken.type = 'hidden';
        accessToken.name = 'access_token';
        accessToken.value = password;
        form.appendChild(accessToken);
        var idToken = document.createElement('input');
        idToken.type = 'hidden';
        idToken.name = 'id_token';
        idToken.value = hdnIdentityToken.value;
        form.appendChild(idToken);
        var state = document.createElement('input');
        state.type = 'hidden';
        state.name = 'state';
        state.value = stateVal;
        form.appendChild(state);
        var user = document.createElement('input');
        user.type = 'hidden';
        user.name = 'user';
        user.value = hdnIdentityName.value;
        form.appendChild(user);
        form.submit();
        return;
    }
    
    if (result.ErrorMessage.indexOf('NotUnique: System_User.Email') == 0)
        result.ErrorMessage = Resources.EmailAlreadyRegistered;
    else if (result.ErrorMessage.indexOf('NotUnique: System_User.SystemName') == 0) {
        Famark._txtUserName.value = Famark._txtUserName.value + '_' + Math.floor(Math.random() * 100);
        result.ErrorMessage = Resources.UserNameAlreadyRegistered + ' ' + Resources.TryUsingPrefix + '"' + Famark._txtUserName.value + '"';
    }
    Famark._messageLabel.innerHTML = result.ErrorMessage;
};

Famark._resizeTimeout = null;
Famark.screenLoad = function () {
    if (Famark._resizeTimeout)
        window.clearTimeout(Famark._resizeTimeout);
    Famark._resizeTimeout = window.setTimeout(function () {
        Famark._frmAuth.style.position = 'absolute';
        Famark._frmAuth.style.left = ((document.body.clientWidth - Famark._frmAuth.offsetWidth) / 2) + 'px';
        Famark._frmAuth.style.top = ((document.body.clientHeight - Famark._frmAuth.offsetHeight) / 4) + 'px';
        Famark._resizeTimeout = null;
        Famark._frmAuth.style.visibility = 'visible';
        if (Famark._txtDomainName.value != '') {
            Famark._txtDomainName.readOnly = true;
            if (Famark._txtUserName.value == '')
                Famark._txtUserName.focus();
        } else {
            Famark._txtDomainName.focus();
        }
        Famark.fadeIn(Famark._frmAuth);
    }, 100);
};

Famark.fadeIn = function (el) {
    var op = 0.1;
    var timer = setInterval(function () {
        if (op >= 1) {
            clearInterval(timer);
        }
        el.style.opacity = op;
        el.style.filter = 'alpha(opacity=' + op * 100 + ")";
        op += op * 0.1;
    }, 10);
};

Famark.addHandler = function (el, ev, fn) {
    if (el.addEventListener)
        el.addEventListener(ev, fn, false);
    else if (el.attachEvent)
        el.attachEvent('on' + ev, fn);
    else
        el[ev] = fn;
};

Famark.parseJSON = function (data) {
    if (data == null || typeof data !== 'string')
        return null;

    data = (data.trim) ? data.trim() : data.replace(/^\s+|\s+$/g, '');

    if (window.JSON && window.JSON.parse)
        return window.JSON.parse(data);

    var valData = data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
    valData = valData.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
    valData = valData.replace(/(?:^|:|,)(?:\s*\[)+/g, '');

    var valExp = /^[\],:{}\s]*$/;

    if (valExp.test(valData))
        return (new Function('return ' + data))();

    alert('Invalid JSON: ' + data);
    return null;
};

window.onrendercomplete = function () {
    Famark._frmAuth.style.width = '280px';
    Famark.screenLoad();
};