/*
 * File: apme.register.js
 * Author: Joao Fonseca (j.fonseca@netcabo.pt)
 */
$.maxZIndex = $.fn.maxZIndex = function(opt) {
    var def = { inc: 10, group: "*" };
    $.extend(def, opt);
    var zmax = 0;
    $(def.group).each(function() {
        var cur = parseInt($(this).css('z-index'));
        zmax = cur > zmax ? cur : zmax;
    });
    if (!this.jquery)
        return zmax;

    return this.each(function() {
        zmax += def.inc;
        $(this).css("z-index", zmax);
    });
}

var apme = apme || {};

apme.register = {
    registerBox: function(){
        apme.visuals.createBox('registerbox_container').height(950);
        apme.visuals.createOverlay();
        $('#registerbox_container').load("register.php", function(){
            apme.register.registerInit();
        });
    },
    closeRegisterBox: function(){
        $('#registerbox_container').remove();
        apme.visuals.deleteOverlay();
    },
    registerInit: function(){
        apme.register.registerStep(0);
    },
    copyValue: function(from, to){
        $("input[name=" + to + "]").val($("input[name=" + from + "]").val());
    },
    companyCount: 0,
    usernameMails: [],
    usernameAdd: function(email){
        if (!this.usernameMails.exists(email)) {
            this.usernameMails.push(email);
        }
    },
    validateStep: function(step){
        var error = false;
        $("#registerbox fieldset").eq(step).find("[data-mandatory]:visible").each(function(idx, input){
            if ($(input).attr("data-mandatory") == 'true') {
                if ($(input).val().length < 1) {
                    var fieldName = $("label[for^=" +
                    $(input).attr("name").replace(']','').replace('[','') +
                    "], label[for=" +
                    $(input).attr("id") +
                    "]:visible").eq(0).text();
                    if (fieldName.length < 1) {
                        fieldName = $(input).attr("name");
                    }
                    $(".errorMsg").html("O campo '" +
                    fieldName +
                    "' &eacute; obrigat&oacute;rio");
                    error = true;
                    return false;
                }
            }
            else {
                if ($(input).attr("data-mandatory") != 'false') {
                    error = true;
                    var fieldNames = [];
                    $("[data-mandatory=" +
                    $(input).attr("data-mandatory") +
                    "]:visible").each(function(idx, otherinput){
                        error &= ($(otherinput).val().length <
                        1);
                        fieldNames[idx] = $("label[for^=" +
                    $(input).attr("name").replace(']','').replace('[','') +
                    "], label[for=" +
                        $(otherinput).attr("id") +
                        "]").eq(0).text();
                        if (fieldNames[idx].length < 1) {
                            fieldNames[idx] = $(otherinput).attr("name");
                        }
                    });
                    if (error) {
                        $(".errorMsg").html("Um dos campos ");
                        var isFirst = true;
                        for (var i in fieldNames) {
                            if (typeof(fieldNames[i]) == 'function') {
                                continue;
                            }
                            $(".errorMsg").append((isFirst ? "'" : ", '") +
                            fieldNames[i] +
                            "'");
                            isFirst = false;
                        }
                        $(".errorMsg").append(" &eacute; obrigat&oacute;rio");
                        return false;
                    }
                }
            }
        });
        if (error) {
            return step;
        }
        $("#registerbox fieldset").eq(step).find("[data-email=true]:visible").each(function(idx, input){
            var fieldName = $("label[for^=" +
                    $(input).attr("name").replace(']','').replace('[','') +
                    "], label[for=" +
            $(input).attr("id") +
            "]").eq(0).text();
            if (fieldName.length < 1) {
                fieldName = $(input).attr("name");
            }
            if (!$(input).val().match(apme.main.emailRegEx)) {
                $(".errorMsg").html("O campo '" +
                fieldName +
                "' n&atilde;o &eacute; v&aacute;lido");
                error = true;
                return false;
            }
        });
        if (error) {
            return step;
        }
        $("#registerbox fieldset").eq(step).find("[data-minlength]:visible").each(function(idx, input){
            var fieldName = $("label[for^=" +
                    $(input).attr("name").replace(']','').replace('[','') +
                    "]:visible, label[for=" +
            $(input).attr("id") +
            "]:visible").eq(0).text();
            if (fieldName.length < 1) {
                fieldName = $(input).attr("name");
            }
            var minLength = $(input).attr("data-minlength");
            if ($(input).val().length < minLength) {
                $(".errorMsg").html("O campo '" + fieldName +
                "' tem um m&iacute;nimo de " +
                minLength +
                " caracteres");
                error = true;
                return false;
            }
        });
        if (error) {
            return step;
        }
        $("#registerbox fieldset").eq(step).find("[data-numeric=true]").each(function(idx, input){
            var fieldName = $("label[for^=" +
                    $(input).attr("name").replace(']','').replace('[','') +
                    "], label[for=" +
            $(input).attr("id") +
            "]").eq(0).text();
            if (fieldName.length < 1) {
                fieldName = $(input).attr("name");
            }
            if (!$(input).val().match(/^[0-9]*$/)) {
                $(".errorMsg").html("O campo '" + fieldName +
                "' tem de ser num&eacute;rico");
                error = true;
                return false;
            }
        });
        if (error) {
            return step;
        }

        /*
         * specific step validations
         */
        if (step == 0) {
            this.usernameMails = [];
            if ($("input[name=jaAssociada]:checked").val() == 1) {
                var ok = false;
                $.ajax({
                    async: false,
                    cache: false,
                    data: {
                        action: 'checktaxid',
                        id: $('#jaAssociadaNumero').val(),
                        taxid: $('#jaAssociadaNif').val()
                    },
                    success: function(data){
                        if (data != '0') {
                            ok = true;
                        }
                    },
                    url: 'register.php'
                });
                if (!ok) {
                    $(".errorMsg").html("Os dados introduzidos n&atilde;o s&atilde;o v&aacute;lidos");
                    return 0;
                }
                $("#usernamemail").replaceWith('<input type="text" data-email="true" name="usernamemail" id="usernamemail" style="width:210px;">');
                return 6; //prompt username
            }
            return 1;
        }
        if (step == 1) {
            this.companyCount = parseInt($("select[name=empresas] option:selected").val());
            this.usernameAdd($("#email").val());
            if ($("input[name=individual]:checked").val() == 1) {
                this.copyValue("nome", "ind_nome");
                this.copyValue("nome", "ind_nome_cartao");
                this.copyValue("cargo", "ind_cargo");
                this.copyValue("telefone", "ind_telefone");
                this.copyValue("fax", "ind_fax");
                this.copyValue("email", "ind_email");
                return 2;
            }
            else {
                $("#recibos_emp").attr('checked', 'checked');

                if ($("input[name=individual]:checked").val() == 0) {
                    if ($("select[name=empresas] option:selected").val() == 0) {
                        $(".errorMsg").html("O valor do campo 'N.&ordm; de Empresas' n&atilde;o pode ser 0");
                        return step;
                    }
                    return 3;
                }
                else {
                    $(".errorMsg").html("Por favor, escolha o tipo: Individual / Empresarial");
                    return step;
                }
            }
        }
        if (step == 2) {
            this.usernameAdd($("#ind_email").val());
            if (this.companyCount == 0) {
                $("#recibos_ind").attr('checked', 'checked');
                return 5;
            }
            else {
                var companyFieldset = $("#registerbox fieldset").eq(3);
                for (i = 0; i < this.companyCount; i++) {
                    var newFieldsetHtml = ("<fieldset>" + companyFieldset.html() + "</fieldset>").replace(/\"emp_([^\"]*)_n\"/, "\"emp_$1_" + i + "\"");
                    if (this.companyCount > 1) {
                        newFieldsetHtml = newFieldsetHtml.replace("</legend", " " + (i + 1) + "</legend");
                    }
                    companyFieldset.before(newFieldsetHtml);
                }
                companyFieldset.remove();
                return 3;
            }
        }
        if (step >= 3 && step < 3 + this.companyCount) {
            this.usernameAdd($("#emp_mail_" + (step - 3)).val());
            return step + 1;
        }

        // fall back to one step
        return step + 1;
    },
    registerStep: function(step){
        //alert(step);
        $("#registerbox fieldset").hide();
        $("#registerbox fieldset").eq(step).show().append(
			$("#registerbox fieldset").eq(step).attr('data-submit') == 'true' ? 
			'<dl><span class="errorMsg"></span><input type="button" class="registerSubmitbutton" value="Concluir"/></dt></dl>' :
			'<dl><span class="errorMsg"></span><input type="button" class="registerNextbutton" value="Continuar"/></dt></dl>');
		if ($("#usernamemail").is(":visible"))
		{
			$('form[action="register.php"]').find('[data-email]').each(function () { 
				var mVal = $(this).val(); 
				if (mVal != '' && !$("#usernamemail option[value='"+mVal+"']").length) { 
					$('#usernamemail').append($("<option>"+mVal+"</option>").attr("value",mVal)) 
				}
			});
		}
        $(".registerNextbutton").bind('click', function(){
            var nextStep = apme.register.validateStep(step);
            if (nextStep != step) {
                apme.register.registerStep(nextStep);
            }
        });
        $(".registerSubmitbutton").bind('click', function(){
			if (apme.register.validateStep(step) == step) {
				return;
            }
			if ($('#password').val() != $('#passwordconfirm').val()) {
				$(".errorMsg").html("O valor das palavras-passe n&atilde;o coincide");
				return;
			}
			var formdata = $(this).parents('form').serialize();
            $(this).parents('fieldset').hide();
			$.ajax({
                data: {
                    action: 'insert',
                    form: formdata
                },
				success: function () {
					$("#registerbox fieldset").eq(step).html('O seu pedido foi submetido com sucesso e aguarda aprovação por parte da APME.<br/>Obrigado!').show();
				},
                url: 'register.php'
            })
        });
    },
    initActions: function(){
        var that = this;
        $('#registerButton').live('click', that.registerBox);
        $('#registerbox #closebox a').live('click', that.closeRegisterBox);
        $('[name=jaAssociada]').live('click', function(){
            $(this).val() == '1' ? $('.dlJaAssociadaInfo').show() : $('.dlJaAssociadaInfo').hide();
        });
        $.datepicker.setDefaults($.datepicker.regional["pt"]);
        $("[data-date=true]").live('focusin', function() {
  			var $this = $(this);
  			if (!$this.is(':data(datepicker)')) {
  				//this will attach a datepicker control &amp; datepicker will immediately fire
				$this.datepicker({
					changeMonth: true,
					changeYear: true,
					dateFormat: "yy-mm-dd",
					yearRange: '-99:-00',
					beforeShow: function() {$('#ui-datepicker-div').removeClass('ui-helper-hidden-accessible'); }
				});
			}
			return true;
		});
    },
    init: function(){
        this.initActions();
    }
};

