$().ready(function() {

    // captcha validation
    $("#captcha").bind("blur", function() {
        var $this = $(this);
        var validator = $("#formRegistra").validate().element("#captcha");
        if (!validator || config.captcha) return;

        $.get(config.url.checkCaptcha, { captcha: $this.val()}, function(data) {
            var result = data === true;
            if (result) {
                config.captcha = true;
                $("div[id^=captcha-error]").each(function(index, value) {
                    $(this).hide();
                });
                $this.attr("readonly", true);

            } else {
                config.captcha = false;
                var $msg = $("<div/>").html(config.messages.captcha.required);
                $("div[id^=captcha-error]").each(function(index, value) {
                    if (index == 1) {
                        $(this).empty().append($msg);
                    }
                    $(this).show();
                });
                utils.changeCaptcha();
            }
        }, "json");


    });

    $("#formRegistra").validate({
        //debug:true,
        errorElement:"div",
        focusInvalid: false,
        onkeyup: false,

        onfocusout: function(element) {
            $(element).valid();
        },

        submitHandler: function(form) {
            var $nick = $("#nick");
            if (!(config.nickOK || $nick.attr("readonly"))) {
                $nick.blur();
                //$("div[id^=nick-error]").show();
            } else if (!config.captcha) {
                $("#captcha").blur();
                //$("div[id^=captcha-error]").show();
            } else {
                form.submit();
            }
        },

        showErrors: function(errorMap, errorList) {

            for (var i = 0; i < this.currentElements.length; i++) {

                var input = this.currentElements[i];
                $("div[id^=" + input.name + "-struts]").remove(); //elimino i div validazione server

                var found = false;
                for (var err in errorList) {
                    if (errorList[err].element === input) {
                        // l'elemento e' stato validato ed ho trovato un errore
                        // devo inserire il testo di errore e mostrare i div
                        found = true;
                        $("div[id^=" + input.name + "-error]").each(function(index, value) {
                            if (index == 1) {
                                $(this).empty().append("<div>" + errorMap[input.name] + "</div>");
                            }
                            $(this).show();
                        });
                    }
                }
                if (!found) {
                    try { // non ho trovato errori devo nascondere i div di validazione
                        $("div[id^=" + input.name + "-error]").each(function(index, value) {
                            $(this).hide();
                        });
                    } catch(e) {
                        // do nothing...
                    }
                }
            }


        },

        rules: {
            cellulare: {
                rangelength: [8, 15],
                msisdn: true
            },
            flagDeveloper: "required",
            /*captcha: {
             required: true,
             remote: config.url.checkCaptcha
             },*/
            captcha:"required",
            consensoCondizioniContrattuali: "required",
            consensoClausoleVessatorie: "required"
        },
        messages: config.messages
    });

    // aggiungo le regole per mail e password solo se presenti e compilabili
    var $email = $("#email");
    if ($email.size() && $email.attr("type") != "hidden") {
        $email.rules("add", {
            required: true,
            email: true,
            emailGroup: true
        })
    }

    var $password = $("#password");
    if ($password.size() && $password.attr("type") != "hidden") {
        $password.rules("add", {
            required: true,
            rangelength: [6, 24],
            rexpPassword: true
        });
        $("#passwordConfirm").rules("add", {
            required: true,
            equalTo: "#password"
        });
    }

    var $nick = $("#nick");
    if ($nick.attr("readonly")) {
        config.nickOK = true;
    } else {

        $nick.rules("add", {
            required: true,
            rangelength: [2, 15],
            rexpNick: true
        });

        // propose nick
        $nick.bind("blur", function() {
            var $this = $(this);
            // rieseguo la validazione sintattica del nick. Se non ci sono errori
            // allora posso effettuare la check
            var validator = $("#formRegistra").validate().element("#nick");
            if (!validator) return;

            $.ajax({
                url: config.url.checkNick,
                data: { nickname: $this.val(), comunita: "MU"},
                success: function(data, textStatus, XMLHttpRequest) {
                    if (data != null && data.propose.result == "200") {
                        config.nickOK = true;
                        $("div[id^=nick-error]").each(function(index, value) {
                            $(this).hide();
                        });
                    } else {
                        config.nickOK = false;

                        var $msg = $("<div/>").html("Nick non disponibile. Ecco qualche suggerimento per la scelta del tuo nickname:<br />");
                        //{"propose":{"result":300,"nicklist":{"string":["pippo1","pippo2","pippo3","pippo4","pippo5"]}}}
                        try {
                            var nickList = data.propose.nicklist ? data.propose.nicklist.string : [];
                            if (nickList.length > 0) {
                                for (var i = 0; i < nickList.length; i++) {
                                    $msg.append(utils.creaLink(nickList[i])).append("&nbsp;&nbsp;")
                                }
                            }
                        } catch(e) {
                            // we should do something
                        }
                        $("div[id^=nick-error]").each(function(index, value) {
                            if (index == 1) {
                                $(this).empty().append($msg);
                            }
                            $(this).show();
                        });

                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $("div[id^=nick-error]").each(function(index, value) {
                        if (index == 1) {
                            var $msg = $("<div/>").html("Impossibile verificare il nick scelto");
                            $(this).empty().append($msg);
                        }
                        $(this).show();
                    });
                },
                dataType: "json"
            });

        });
    }

});
