/**
 * Depends on YUI library, concretely on yahoo.js, event.js and
 * connection.js
 */

var regConsts = {
    receiver: '/reg/reg-receiver.php',
    countries: '/reg/reg-countries.php',
    input_border_good: '1px solid black',
    input_border_bad: '1px solid #C9292D'
}

var regErrors = {
    msgs: new Array(),
    clear: function () { this.msgs = new Array(); },
    add: function (str) { this.msgs[this.msgs.length] = str; },
    get: function () { return this.msgs; },

    toHtml: function () {
        var html = "";
        var err = this.get();

        for (var i=0; i < err.length; i++){
            html = html + err[i] + '<br />';
        }

        return html;
   }
}

var regBadInputs = {
    inputs: new Array(),
    clear: function () {
        for (var i=0; i < this.inputs.length; i++) {
            reg_input_good(document.getElementById(this.inputs[i]));
        }
        this.inputs = new Array();
    },

    add: function (id) {
        for (var i=0; i < this.inputs.length; i++){
            if (this.inputs[i] == id){
                return;
            }
        }

        this.inputs[this.inputs.length] = id;
    },

    apply: function () {
        for (var i=0; i < this.inputs.length; i++){
            reg_input_bad(document.getElementById(this.inputs[i]));
        }
    }

}


/* Checks of inputs */
var reg_mandatory = new Array(
        "reg_first_name",
        "reg_surename",
        "reg_street",
        "reg_city",
        "reg_postcode",
        "reg_country",
        "reg_phone",
        "reg_email_id",
        "reg_nationality",
        "reg_date_of_birth",
        "reg_sex",

        "reg_name_org",
        "reg_street_org",
        "reg_city_org",
        "reg_postcode_org",
        "reg_country_org",
        "reg_phone_org",
        "reg_email_org",
        "reg_web_org",
        "reg_position_org"
);

var reg_email_re1 = new RegExp("([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})", "i");
var reg_email_re2 = new RegExp("[a-zA-Z0-9 ]* <([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})>", "i");
function reg_is_email(str) {
    if (!str.match(reg_email_re1) && !str.match(reg_email_re2)){
        return false;
    }

    return true;
}

var reg_date_of_birth_re = new RegExp("[0-9]{4}.[0-9]{2}.[0-9]{2}", "i");
function reg_is_date_of_birth(str) {
    if (!str.match(reg_date_of_birth_re)){
        return false;
    }

    return true;
}

function reg_input_good(input)
{
    input.style.border = regConsts.input_border_good;
}

function reg_input_bad(input)
{
    input.style.border = regConsts.input_border_bad;
}

function reg_form_check_mandatory() {    
    var input;
    var ok = true;

    for (var i=0; i < reg_mandatory.length; i++){
        input = document.getElementById(reg_mandatory[i]);
        if (input.value.length < 1){
            ok = false;
            regBadInputs.add(reg_mandatory[i]);
        }
    }

    if (!ok){
        regErrors.add("Check that you have entered all mandatory values!");
    }

    return ok;
}

function reg_form_check() {
    var ok = true;
    var input;

    regErrors.clear();
    regBadInputs.clear();

    ok = reg_form_check_mandatory();

    input = document.getElementById('reg_email_id');
    if (input.value.length > 0 && !reg_is_email(input.value)){
        ok = false;
        regBadInputs.add('reg_email_id');
        regErrors.add("Invalid format of E-mail in personal identification!");
    }

    input = document.getElementById('reg_email_org');
    if (input.value.length > 0 && !reg_is_email(input.value)){
        ok = false;
        regBadInputs.add('reg_email_org');
        regErrors.add("Invalid format of E-mail in sending organisation!");
    }

    input = document.getElementById('reg_date_of_birth');
    if (input.value.length > 0 && !reg_is_date_of_birth(input.value)){
        ok = false;
        regBadInputs.add('reg_date_of_birth');
        regErrors.add("Invalid format of field date of birth!");
    }

    regBadInputs.apply();

    return ok;
}
/* Checks of inputs END */

/* Divs */
var regDivError = {
    text: "",
    
    _obj: function () {
        return document.getElementById('reg_form_error_id');
    },
    _applyText: function () {
        this._obj().innerHTML = this.text;
    },

    show: function () {
        if (arguments.length > 0){
            if (arguments[0].length > 0){
                this.setText(arguments[0]);
            }
        }
        this._applyText();
        this._obj().style.display = 'block';
        scroll(0, 0);
    },
    hide: function () {
        this._obj().style.display = 'none';
    },
    setText: function (new_text) {
        this.text = new_text;
    }
}

var regDivSuccess = {
    _obj: function () {
        return document.getElementById('reg_form_success_id');
    },

    show: function () {
        this._obj().style.display = 'block';
        this.displayed = true;
        scroll(0, 0);
    },
    hide: function () {
        this._obj().style.display = 'none';
        this.displayed = false;
    }
}

var regDivMain = {
    _obj: function () {
        return document.getElementById('reg_form_id');
    },
    _objForm: function () {
        return document.getElementById('reg_form_form_id');
    },

    disableForm: function () {
        var len = this._objForm().elements.length;
        for (var i=0; i < len; i++){
            this._objForm().elements[i].disabled = true;
        }
    },
    enableForm: function () {
        var len = this._objForm().elements.length;
        for (var i=0; i < len; i++){
            this._objForm().elements[i].disabled = false;
        }
    },

    show: function () {
        this._obj().style.display = 'block';
        this.displayed = true;
    },
    hide: function () {
        this._obj().style.display = 'none';
        this.displayed = false;
    }
}

var regDivWait = {
    text: "Please wait...",
    default_text: "Please wait...",
    
    _obj: function () {
        return document.getElementById('reg_form_wait_id');
    },
    _textObj: function () {
        return document.getElementById('reg_form_wait_text');
    },
    _applyText: function () {
        this._textObj().innerHTML = this.text;
    },

    show: function () {
        if (arguments.length > 0){
            if (arguments[0].length > 0){
                this.setText(arguments[0]);
            }
        }
        this._applyText();
        this._obj().style.display = 'block';
        scroll(0,0);
    },
    hide: function () {
        this._obj().style.display = 'none';
        this.displayed = false;
    },
    setText: function (new_text) {
        this.text = new_text;
    },
    setDefaultText: function () {
        this.text = this.defaultText;
    }
}

/* Divs END */


function reg_form_success() {
    regDivError.hide();
    regDivMain.hide();
    regDivWait.hide();
    regDivSuccess.show();
}


/* AJAX Part: */
function reg_set_countries(countries, select) {
    for (var i=0; i < countries.length; i++){
        if (countries[i].length > 0)
            select[select.options.length] = new Option(countries[i], countries[i]);
    }
}


function reg_countries_success(response) {
    var text = response.responseText.split('\n');
    var countries;

    regDivWait.hide();
    regDivMain.enableForm();

    if (text.length <= 0){
        err = "Regitration server is not responding, try it later.<br />";
        regDivError.show(err);
        regDivMain.disableForm();
    }else if (text[0] == "FAIL"){
        err = "Error on regitration server.<br />";
        for (var i=1; i < text.length; i++){
            err = err + text[i] + "<br />";
        }
        regDivError.show(err);
        regDivMain.disableForm();
    }else if (text[0] == "OK"){
        countries = new Array();
        for (var i=1; i < text.length; i++){
            countries[countries.length] = text[i];
        }

        reg_set_countries(countries, document.getElementById('reg_country'));
        reg_set_countries(countries, document.getElementById('reg_country_org'));
    }
}

function reg_countries_failure(response) {
    regDivWait.hide();
    regDivMain.disableForm();

    err = "Registration server is not available! <br />";
    err = err + "Please, try it later<br />";
    regDivError.show(err);
}

function reg_countries() {
    var callback = {
        success: reg_countries_success,
        failure: reg_countries_failure
    }

    regDivWait.show('Obtaining list of countries from Registration Server.  Please wait...');
    regDivMain.disableForm();

    YAHOO.util.Connect.asyncRequest("GET", regConsts.countries, callback);
}

function reg_success(response) {
    var text = response.responseText.split('\n');
    var err;

    regDivWait.hide();
    regDivMain.enableForm();

    if (text.length <= 0){
        err = "Registration server is not responding, try it later.<br />";
        regDivError.show(err);
    }else if (text[0] == "FAIL"){
        err = "";
        for (var i=1; i < text.length; i++){
            err = err + text[i] + "<br />";
        }
        regDivError.show(err);
    }else if (text[0] == "OK"){
        reg_form_success();
    }
}

function reg_failure(response) {
    var err;

    regDivWait.hide();
    regDivMain.enableForm();

    err = "Registration server is not available! <br />";
    err = err + "Please, try it later<br />";
    regDivError.show(err);
}

function reg_sent(uri) {
    var form_data = YAHOO.util.Connect.setForm('reg_form_form');
    var callback = {
        success: reg_success,
        failure: reg_failure
    }

    regDivWait.show('Connecting to Registration Server. Please wait...');
    regDivMain.disableForm();

    YAHOO.util.Connect.asyncRequest("POST", uri, callback, form_data);
}



/* Main function */
function reg_form() {
    regDivError.hide();
    if (!reg_form_check()){
        regDivError.show(regErrors.toHtml());
    }else{
        reg_sent(regConsts.receiver);
    }
}

