// ============================================================================
// Developed by Kernel Team.
// http://kernel-team.com
// ============================================================================

String.prototype.trim = function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
}

// Common functions for reuse =================================================

function stub() {
}

function commonGet(id) {
    return document.getElementById(id);
}

function commonValidId(id) {
    return (id && commonGet(id));
}

function commonShow(id) {
    if (commonValidId(id)) {
        commonGet(id).style.display = 'block';
    }
}

function commonHide(id) {
    if (commonValidId(id)) {
        commonGet(id).style.display = 'none';
    }
}

function commonGetRadioGroupValue(form, fieldName) {
    var group = form[fieldName];
    if (group.tagName == 'INPUT') {
        group = [group];
    }
    for (var i = 0; i < group.length; i++) {
        if (group[i].checked) {
            return group[i].value;
        }
    }
    return 0;
}

function commonProcessFieldError(fieldName, errorId) {
    for (var i = 0; i < 10; i++) {
        commonHide(fieldName + '_error_' + i);
    }
    commonShow(fieldName + '_' + errorId);
    return (errorId == null);
}

function commonValidateRequired(form, fieldName, errorCode) {
    if (!form[fieldName]) {
        return true;
    }
    if (form[fieldName].tagName.toLowerCase() == 'select') {
        if (form[fieldName].selectedIndex == 0) {
            return commonProcessFieldError(fieldName, errorCode);
        } else {
            return commonProcessFieldError(fieldName, null);
        }
    }
    if (form[fieldName].value.trim().length == 0) {
        return commonProcessFieldError(fieldName, errorCode);
    } else {
        return commonProcessFieldError(fieldName, null);
    }
}

function commonValidateMinLength(form, fieldName, length, errorCode) {
    if (!form[fieldName]) {
        return true;
    }
    if (form[fieldName].value.trim().length < length) {
        return commonProcessFieldError(fieldName, errorCode);
    } else {
        return commonProcessFieldError(fieldName, null);
    }
}

function commonValidateSymbols(form, fieldName, errorCode) {
    if (!form[fieldName]) {
        return true;
    }
    if (form[fieldName].value.trim().length == 0) {
        return commonProcessFieldError(fieldName, null);
    }
    var symbols = /^[0-9A-Za-z._\-@]+$/;
    if (!symbols.test(form[fieldName].value)) {
        return commonProcessFieldError(fieldName, errorCode);
    } else {
        return commonProcessFieldError(fieldName, null);
    }
}

function commonValidatePasswords(form, fieldName1, fieldName2, errorCode) {
    if (!form[fieldName1] || !form[fieldName2]) {
        return true;
    }
    if (form[fieldName1].value != form[fieldName2].value) {
        return commonProcessFieldError(fieldName2, errorCode);
    } else {
        return commonProcessFieldError(fieldName2, null);
    }
}

function commonValidateEmail(form, fieldName, errorCode) {
    if (!form[fieldName]) {
        return true;
    }
    if (form[fieldName].value.trim().length == 0) {
        return commonProcessFieldError(fieldName, null);
    }
    var email = /^\w[\w\-]*(\.\w[\w\-]*)*@\w[\w\-]+(\.\w[\w\-]+)*\.(a[c-gil-oq-uwz]|b[a-bd-jm-or-tvwyz]|c[acdf-ik-orsuvx-z]|d[ejkmoz]|e[ceghr-u]|f[i-kmorx]|g[abd-ilmnp-uwy]|h[kmnrtu]|i[delm-oq-t]|j[emop]|k[eg-imnprwyz]|l[a-cikr-vy]|m[acdghk-z]|n[ace-giloprtuz]|om|p[ae-hk-nrtwy]|qa|r[eouw]|s[a-eg-ort-vyz]|t[cdf-hjkm-prtvwz]|u[agkmsyz]|v[aceginu]|w[fs]|y[etu]|z[admrw]|com|edu|net|org|mil|gov|biz|pro|aero|coop|info|name|int|museum)$/;
    if (!email.test(form[fieldName].value)) {
        return commonProcessFieldError(fieldName, errorCode);
    } else {
        return commonProcessFieldError(fieldName, null);
    }
}

function commonGetAjaxParams() {
    return 'mode=async&rand=' + new Date().getTime();
}

function commonSendRequest(url, data, isPost, callback) {
    var req = null;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        req = new ActiveXObject('Microsoft.XMLHTTP');
    }
    if (!req) {
        return null;
    }
    try {
        var postData = null;
        var method = null;
        if (isPost) {
            method = 'POST';
            postData = data;
        } else if (!data) {
            method = 'GET';
        } else if (data.length > 0) {
            method = 'GET';
            if (url.indexOf('?') >= 0) {
                url += '&' + data;
            } else {
                url += '?' + data;
            }
        }
        req.open(method, encodeURI(url), true);
        if (method == 'POST') {
            req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        }
        req.onreadystatechange = function() {
            if (req.readyState == 4) {
                var xml = req.responseXML;
                if (xml && xml.documentElement) {
                    if (xml.documentElement.nodeName == 'success') {
                        callback(xml.documentElement, null);
                    } else if (xml.documentElement.nodeName == 'failure') {
                        var childs = xml.documentElement.childNodes;
                        var errors = [];
                        for (var i = 0; i < childs.length; i++) {
                            if (childs[i].nodeName == 'error') {
                                var content = null;
                                if (childs[i].textContent) {
                                    content = childs[i].textContent;
                                } else if (childs[i].innerText) {
                                    content = childs[i].innerText;
                                } else if (childs[i].text) {
                                    content = childs[i].text;
                                }
                                errors.push(content);
                            }
                        }
                        callback(null, errors);
                    }
                }
            }
        };
        req.send(postData);
    } catch (e) {
        return e;
    }
    return null;
}

// Logon block functions ======================================================

function logonEnableForm(params) {
    var form = params['form_id'];
    var useCaptcha = params['use_captcha'];

    if (commonValidId(form)) {
        commonGet(form).onsubmit = function() {
            var errorField = null;
            if (!commonValidateRequired(this, 'username', 'error_1')) {
                errorField = (errorField ? errorField : 'username');
            }
            if (!commonValidateRequired(this, 'pass', 'error_1')) {
                errorField = (errorField ? errorField : 'pass');
            }
            if (useCaptcha) {
                if (!commonValidateRequired(this, 'code', 'error_1')) {
                    errorField = (errorField ? errorField : 'code');
                }
            }
            if (errorField) {
                this[errorField].focus();
            }
            return !errorField;
        }
    }
}

// Signup block functions =====================================================

var signupSmsSelectedCountryId = null;
var signupSmsSelectedCountryCode = null;
var signupSmsIdToCodeMapping = {};

function signupEnableSignupForm(params) {
    var form = params['form_id'];
    var v2validation = params['v2_validation'];
    var captchaBlock = params['captcha_block_id'];
    var cardBlock = params['card_block_id'];
    var smsBlock = params['sms_block_id'];
    var smsCountriesBlock = params['sms_countries_block_id'];
    var smsOperatorsBlock = params['sms_operators_block_id'];
    var smsOperatorBlockPrefix = params['sms_operator_block_prefix'];
    var smsPasscodeBlock = params['sms_passcode_block_id'];
    var smsCountries = params['sms_countries'];
    var smsDefaultCountryCode = params['sms_default_country_code'];
    var smsSelectedCountryId = params['sms_selected_country_id'];

    if (!commonValidId(form)) {
        return;
    }

    if (v2validation) {
        var formElement = commonGet(form);
        formElement['username'].onblur = function() {
            if (commonValidateRequired(formElement, 'username', 'error_1')) {
                if (commonValidateMinLength(formElement, 'username', 3, 'error_2')) {
                    if (commonValidateSymbols(formElement, 'username', 'error_3')) {
                        commonSendRequest('?' + commonGetAjaxParams(), 'action=check_user&username=' + encodeURIComponent(formElement['username'].value), true, function(successNode, errorsList) {
                            if (errorsList) {
                                commonProcessFieldError('username', 'error_4');
                            } else {
                                commonProcessFieldError('username', null);
                            }
                        });
                    }
                }
            }
        }
        formElement['pass'].onblur = function() {
            if (commonValidateRequired(formElement, 'pass', 'error_1')) {
                commonValidateMinLength(formElement, 'pass', 5, 'error_2');
            }
        }
        formElement['pass2'].onblur = function() {
            if (commonValidateRequired(formElement, 'pass2', 'error_1')) {
                commonValidatePasswords(formElement, 'pass', 'pass2', 'error_2');
            }
        }
        formElement['email'].onblur = function() {
            if (commonValidateRequired(formElement, 'email', 'error_1')) {
                if (commonValidateEmail(formElement, 'email', 'error_2')) {
                    commonSendRequest('?' + commonGetAjaxParams(), 'action=check_email&email=' + encodeURIComponent(formElement['email'].value), true, function(successNode, errorsList) {
                        if (errorsList) {
                            commonProcessFieldError('email', 'error_3');
                        } else {
                            commonProcessFieldError('email', null);
                        }
                    });
                }
            }
        }
    }

    commonGet(form).onsubmit = function() {
        var errorField = null;
        if (!commonValidateRequired(this, 'username', 'error_1')) {
            errorField = (errorField ? errorField : 'username');
        } else if (!commonValidateMinLength(this, 'username', 3, 'error_2')) {
            errorField = (errorField ? errorField : 'username');
        } else if (!commonValidateSymbols(this, 'username', 'error_3')) {
            errorField = (errorField ? errorField : 'username');
        }
        if (!commonValidateRequired(this, 'pass', 'error_1')) {
            errorField = (errorField ? errorField : 'pass');
        } else if (!commonValidateMinLength(this, 'pass', 5, 'error_2')) {
            errorField = (errorField ? errorField : 'pass');
        }
        if (!commonValidateRequired(this, 'pass2', 'error_1')) {
            errorField = (errorField ? errorField : 'pass2');
        } else if (!commonValidatePasswords(this, 'pass', 'pass2', 'error_2')) {
            errorField = (errorField ? errorField : 'pass2');
        }
        if (!commonValidateRequired(this, 'email', 'error_1')) {
            errorField = (errorField ? errorField : 'email');
        } else if (!commonValidateEmail(this, 'email', 'error_2')) {
            errorField = (errorField ? errorField : 'email');
        }

        var paymentOption = 1;
        if (this['payment_option']) {
            paymentOption = commonGetRadioGroupValue(this, 'payment_option');
        }
        if (paymentOption == 0) {
            commonProcessFieldError('payment_option', 'error_1');
            errorField = (errorField ? errorField : 'payment_option');
        } else {
            commonProcessFieldError('payment_option', null);
        }
        if (paymentOption == 1) {
            if (!commonValidateRequired(this, 'code', 'error_1')) {
                errorField = (errorField ? errorField : 'code');
            }
        } else {
            commonProcessFieldError('code', null);
        }
        if (paymentOption == 2) {
            if (commonGetRadioGroupValue(this, 'card_package_id') == 0) {
                commonProcessFieldError('card_package_id', 'error_1');
                errorField = (errorField ? errorField : 'card_package_id');
            } else {
                commonProcessFieldError('card_package_id', null);
            }
        }
        if (paymentOption == 3) {
            commonProcessFieldError('sms_package_id', null);
            commonProcessFieldError('sms_country_id', null);
            commonProcessFieldError('sms_passcode', null);
            if (commonGetRadioGroupValue(this, 'sms_package_id') == 0) {
                commonProcessFieldError('sms_package_id', 'error_1');
                errorField = (errorField ? errorField : 'sms_package_id');
            } else if (!commonValidateRequired(this, 'sms_country_id', 'error_1')) {
                errorField = (errorField ? errorField : 'sms_country_id');
            } else if (!commonValidateRequired(this, 'sms_passcode', 'error_1')) {
                errorField = (errorField ? errorField : 'sms_passcode');
            }
        } else {
            commonProcessFieldError('sms_country_id', null);
            commonProcessFieldError('sms_passcode', null);
        }

        if (errorField && this[errorField].focus) {
            this[errorField].focus();
        }
        return !errorField;
    }

    var i = 0;
    for (var packageId in smsCountries) {
        var countries = smsCountries[packageId];
        for (i = 0; i < countries.length; i++) {
            signupSmsIdToCodeMapping[countries[i]['id']] = countries[i]['code'];
            if (smsSelectedCountryId == countries[i]['id']) {
                signupSmsSelectedCountryCode = countries[i]['code'];
            }
        }
    }

    if (commonGet(form)['sms_country_id']) {
        commonGet(form)['sms_country_id'].onchange = function() {
            commonHide(smsOperatorBlockPrefix + signupSmsSelectedCountryId);
            var countryId = this.options[this.selectedIndex].value;
            if (countryId > 0) {
                commonShow(smsOperatorsBlock);
                commonShow(smsPasscodeBlock);
            } else {
                commonHide(smsOperatorsBlock);
                commonHide(smsPasscodeBlock);
            }
            signupSmsSelectedCountryId = countryId;
            signupSmsSelectedCountryCode = signupSmsIdToCodeMapping[countryId];
            commonShow(smsOperatorBlockPrefix + signupSmsSelectedCountryId);
        }
    }

    var options = commonGet(form)['payment_option'];
    if (options) {
        if (options.tagName == 'INPUT') {
            options = [options];
        }
        for (i = 0; i < options.length; i++) {
            options[i].onclick = function() {
                if (this.value == '1') {
                    commonShow(captchaBlock);
                    commonHide(cardBlock);
                    commonHide(smsBlock);
                } else if (this.value == '2') {
                    commonShow(cardBlock);
                    commonHide(smsBlock);
                    commonHide(captchaBlock);
                } else if (this.value == '3') {
                    commonShow(smsBlock);
                    commonHide(cardBlock);
                    commonHide(captchaBlock);
                }
            };
            if (options[i].checked) {
                options[i].onclick();
            }
        }
    }

    var packages = commonGet(form)['sms_package_id'];
    if (packages) {
        if (packages.tagName == 'INPUT') {
            packages = [packages];
        }
        for (i = 0; i < packages.length; i++) {
            packages[i].onclick = function() {
                var sb = commonGet(form)['sms_country_id'];
                var i = 0;
                for (i = sb.options.length - 1; i >= 0; i--) {
                    if (sb.options[i].value > 0) {
                        sb.remove(i);
                    }
                }
                if (smsCountries[this.value]) {
                    for (i = 0; i < smsCountries[this.value].length; i++) {
                        var country = smsCountries[this.value][i];
                        var selected = false;
                        if (signupSmsSelectedCountryCode) {
                            selected = (signupSmsSelectedCountryCode == country['code']);
                        } else {
                            selected = (smsDefaultCountryCode == country['code']);
                        }
                        sb.options.add(new Option(country['title'], country['id'], selected, selected));
                    }
                }
                commonGet(form)['sms_country_id'].onchange();
                commonShow(smsCountriesBlock);
            };
            if (packages[i].checked) {
                packages[i].onclick();
            }
        }
    }
}

function signupEnableReminderForm(params) {
    var form = params['form_id'];

    if (commonValidId(form)) {
        commonGet(form).onsubmit = function() {
            var errorField = null;
            if (!commonValidateRequired(this, 'email', 'error_1')) {
                errorField = (errorField ? errorField : 'email');
            } else if (!commonValidateEmail(this, 'email', 'error_2')) {
                errorField = (errorField ? errorField : 'email');
            }
            if (!commonValidateRequired(this, 'code', 'error_1')) {
                errorField = (errorField ? errorField : 'code');
            }
            if (errorField) {
                this[errorField].focus();
            }
            return !errorField;
        }
    }
}

// Invite friend block functions ==============================================

function inviteFriendEnableForm(params) {
    var form = params['form_id'];

    if (commonValidId(form)) {
        commonGet(form).onsubmit = function() {
            var errorField = null;
            if (!commonValidateRequired(this, 'email', 'error_1')) {
                errorField = (errorField ? errorField : 'email');
            } else if (!commonValidateEmail(this, 'email', 'error_2')) {
                errorField = (errorField ? errorField : 'email');
            }
            if (!commonValidateRequired(this, 'message', 'error_1')) {
                errorField = (errorField ? errorField : 'message');
            }
            if (!commonValidateRequired(this, 'code', 'error_1')) {
                errorField = (errorField ? errorField : 'code');
            }
            if (errorField) {
                this[errorField].focus();
            }
            return !errorField;
        }
    }
}

// Feedback block functions ==============================================

function feedbackEnableForm(params) {
    var form = params['form_id'];
    var useCaptcha = params['use_captcha'];
    var useCustom1 = params['use_custom1'];
    var useCustom2 = params['use_custom2'];
    var useCustom3 = params['use_custom3'];

    if (commonValidId(form)) {
        commonGet(form).onsubmit = function() {
            var errorField = null;
            if (!commonValidateRequired(this, 'message', 'error_1')) {
                errorField = (errorField ? errorField : 'message');
            }
            if (useCustom1) {
                if (!commonValidateRequired(this, 'custom1', 'error_1')) {
                    errorField = (errorField ? errorField : 'custom1');
                }
            }
            if (useCustom2) {
                if (!commonValidateRequired(this, 'custom2', 'error_1')) {
                    errorField = (errorField ? errorField : 'custom2');
                }
            }
            if (useCustom3) {
                if (!commonValidateRequired(this, 'custom3', 'error_1')) {
                    errorField = (errorField ? errorField : 'custom3');
                }
            }
            if (useCaptcha) {
                if (!commonValidateRequired(this, 'code', 'error_1')) {
                    errorField = (errorField ? errorField : 'code');
                }
            }
            if (errorField) {
                this[errorField].focus();
            }
            return !errorField;
        }
    }
}
