var Famark = Famark || {};

var _pageLoaded = false;
var _lnkSignIn = null;
var _lblMessage = null;
var _inputElement = null;

function pageLoad() {
    if (!_pageLoaded) {
        showDialog('divUserDialog', null);
        _lnkSignIn = document.getElementById('lnkSignIn');
        _lblMessage = document.getElementById('lblMessage');
        setEventHandler(_lnkSignIn, 'click', signInDomain);
        _pageLoaded = true;
    }
}

function signInDomain() {
    if (_inputElement != null) {
        validateAndProceed();
        return;
    }

    var wrapper = document.createElement('span');
    wrapper.className = 'txtWrapper';
    _inputElement = document.createElement('input');
    _inputElement.type = 'text';
    _inputElement.className = 'txtInput';
    wrapper.appendChild(_inputElement);
    _lnkSignIn.parentNode.insertBefore(wrapper, _lnkSignIn);
    document.getElementById('lnkWelcome').style.display = 'none';
    _lblMessage.className = 'message';
    _lblMessage.innerHTML = Resources.LabelDomainName;

    var registeredDomains = Famark.getCookie('RegisteredDomains');
    if (registeredDomains != null && registeredDomains != '') {
        var savedDomains = registeredDomains.split('|');
        var listDomains = document.createElement('datalist');
        for (var i = 0; i < savedDomains.length; i++) {
            var option = document.createElement("option");
            option.value = savedDomains[i];
            listDomains.appendChild(option);
        }
        listDomains.id = 'listDomains';
        wrapper.appendChild(listDomains);
        _inputElement.setAttribute('list', 'listDomains');
    }

    setEventHandler(_inputElement, 'keydown', inputKeyDown);
    _inputElement.focus();
}

Famark.getCookie = function (key) {
    if (document.cookie.length > 0) {
        var sPos = document.cookie.indexOf(key + '=');
        if (sPos != -1) {
            sPos = sPos + key.length + 1;
            var ePos = document.cookie.indexOf(';', sPos);
            if (ePos == -1)
                ePos = document.cookie.length;
            return decodeURIComponent(document.cookie.substring(sPos, ePos));
        }
    }
    return null;
};

Famark.setCookie = function (key, value, minutes) {
    value = encodeURIComponent(value);
    if (minutes != null) {
        var now = new Date();
        now.setMinutes(now.getMinutes() + minutes);
        value += '; expires=' + now.toUTCString();
    }
    document.cookie = key + '=' + value;
};

function inputKeyDown(e) {
    if (e.key === 'Enter') {
        e.preventDefault();
        validateAndProceed();
    } else if ((e.key === 'Escape') || ((e.key === 'Backspace' || e.key === 'Delete') && _inputElement.value === '')) {
        resetWelcome();
    }
}

function resetWelcome() {
    var wrapper = _inputElement.parentNode;
    wrapper.parentNode.removeChild(wrapper);
    _inputElement = null;
    _lblMessage.innerHTML = '';
    document.getElementById('lnkWelcome').style.display = 'block';
}

function validateAndProceed() {
    if (_inputElement.value == '') {
        _lblMessage.className = 'error';
        _lblMessage.innerHTML = Resources.LabelDomainName + Resources.InvalidCannotBeBlank;
        _inputElement.focus();
    } else if (_inputElement.value.match(/^[a-zA-Z0-9]+$/) == null) {
        _lblMessage.className = 'error';
        _lblMessage.innerHTML = Resources.LabelDomainName + Resources.InvalidMustBeAlphanumeric;
        _inputElement.focus();
    } else {
        var url = window.location.href;
        url = url.substring(url.lastIndexOf('/') + 1);
        var http = new XMLHttpRequest();
        http.open('POST', url, true);
        http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        _lblMessage.className = 'message';
        _lblMessage.innerHTML = Resources.LabelWait;
        http.onreadystatechange = function () {
            if (http.readyState == 4 && http.status == 200) {
                _lblMessage.innerHTML = '';
                var result = Famark.parseJSON(http.responseText);
                var stepCount = parseInt(result.StepCount);
                if (stepCount >= 0) {
                    var inputDomain = _inputElement.value.trim().toUpperCase();
                    var registeredDomains = Famark.getCookie('RegisteredDomains');
                    if (registeredDomains != null && registeredDomains != '') {
                        if (('|' + registeredDomains + '|').indexOf('|' + inputDomain + '|') < 0) {
                            registeredDomains += '|' + inputDomain;
                        }
                    } else {
                        registeredDomains = inputDomain;
                    }
                    Famark.setCookie('RegisteredDomains', registeredDomains);
                    window.location = Famark._appRootUrl + _inputElement.value + '/';
                } else {
                    _lblMessage.className = 'error';
                    _lblMessage.innerHTML = result.ErrorMessage;
                }
            } else {
                _lblMessage.className = 'error';
                _lblMessage.innerHTML = Resources.LabelFailed;
            }
        }
        http.send('DomainName=' + _inputElement.value);
    }
}

function setEventHandler(el, eventName, handler) {
    if (el.addEventListener)
        el.addEventListener(eventName, handler, false);
    else if (el.attachEvent)
        el.attachEvent('on' + eventName, handler);
    else
        el[eventName] = handler;
}

window.addEventListener('pageshow', function () {
    if (_inputElement)
        resetWelcome();
});

var Famark = Famark || {};

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) {
        try {
            return window.JSON.parse(data);
        } catch (e) {
            alert('Invalid JSON: ' + data);
            return null;
        }
    }
    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;
};