/**
 * File: apme.profile.js
 * Author: João Fonseca (j.fonseca@netcabo.pt)
 */
var apme = apme || {};

apme.profile = {
    showProfile: function () {
        var that = this;
        apme.visuals.createOverlay();
        apme.visuals.createBox('profile_container');
        $('#profile_container')
        .load("profile.php", {
            section: 0,
            action: 'form'
        },
        function () {
            that.fillPersonalData();
        });
    },
    closeProfile: function () {
        $('#profile_container').remove();
        apme.visuals.deleteOverlay();
    },
    fillPersonalData: function () {
        $.ajax({
            url: "profile.php",
            data: {
                section: '0',
                action: 'get'
            },
            dataType: 'json',
            success: function (data) {
                $("#ind_nome").val(data.name);
                $("#ind_nome_cartao").val(data.cardname);
                $("#ind_cargo").val(data.position);
                $("#ind_morada").val(data.address);
                $("#ind_localidade").val(data.city);
                $("#ind_cod_postal").val(data.postalcode[0]);
                $("#ind_cod_postal2").val(data.postalcode[1]);
                $("#ind_cod_postal3").val(data.postalcode[2]);
                $("#ind_telefone").val(data.phone);
                $("#ind_telemovel").val(data.mobile);
                $("#ind_fax").val(data.fax);
                $("#ind_email").val(data.email);
                $("#ind_url").val(data.website);
                $("#ind_estadocivil").val(data.civilstate);
                $("#ind_nascimento").val(data.birthdate);
                $("#ind_bi").val(data.idcard);
                $("#ind_nif").val(data.taxid);
                var literacy = parseInt(data.literacy);
                if (literacy & 1<<0) {
                    $("#ind_hab_basico").attr('checked','checked');
                }
                if (literacy & 1<<1) {
                    $("#ind_hab_sec").attr('checked','checked');
                }
                if (literacy & 1<<2) {
                    $("#ind_hab_bach").attr('checked','checked');
                }
                if (literacy & 1<<3) {
                    $("#ind_hab_lic").attr('checked','checked');
                }
                if (literacy & 1<<4) {
                    $("#ind_hab_pos").attr('checked','checked');
                }
                if (literacy & 1<<5) {
                    $("#ind_hab_dout").attr('checked','checked');
                }
                $(data.public==1?'#ind_divulg_sim':'#ind_divulg_nao').click();
            }
        });
    },
    changepassword: function() {
        if ($("input[name='password']").val() == '')
        {
            alert("Tem que preencher a senha actual");
            return false;
        }
        if ($("input[name='newpassword']").val() == '')
        {
            alert("Tem que preencher a nova senha");
            return false;
        }
        if ($("input[name='newpassword']").val() != $("input[name='newpassword2']").val())
        {
            alert("Os valores da nova senha não coincidem");
            return false;
        }

        $.post('profile.php', {
            'action': 'changepwd',
            'old': $("input[name='password']").val(),
            'new': $("input[name='newpassword']").val()
        },
        function (msg) {
            alert(msg);
            $("input[name='password']").val('');
            $("input[name='newpassword']").val('');
            $("input[name='newpassword2']").val('');
        });
    },
    init: function () {
        var that = this;
        $('#profileButton').live('click', function(){
            that.showProfile();
        });
        $('#profile_container .closeButton').live('click', function(){
            that.closeProfile();
        });
        $('a[data-profile-section]').live('click', function() {
            var $this = $(this);
            var section = $this.attr('data-profile-section');
            $('a[data-profile-section]').removeClass('buttonSelected');
            $this.addClass('buttonSelected');
            $('#profileSection').load('/profile.php',
            {
                'noheader': 1,
                'section': section
            },
            function(){
                if (section == '0') {
                    apme.profile.fillPersonalData();
                }
            });
        });
        $('a.profileCompanyButton').live('click', function() {
            var $this = $(this);
            var id = $this.attr('data-company-id');
            $('a.profileCompanyButton').removeClass('buttonSelected');
            $this.addClass('buttonSelected');
            $('#profileSection > fieldset[data-company-id!="'+id+'"]').hide();
            $('#profileSection > fieldset[data-company-id="'+id+'"]').show();
        });

        $('.marketOnCheck').live('change', function() {
            var $this = $(this);
            var maxHeight = $this.is(':checked')?'none':'40px';
            $this.parents('fieldset.marketFieldSet').css('max-height', maxHeight);
        });


        $('#profileSection input, #profileSection textarea, #profileSection select').live('change', function() {
            var values = $(this).parents('form').serialize();
            var section = $('a.buttonSelected[data-profile-section]').attr('data-profile-section');
            if (section == '4')	{
                return;
            }
            $.ajax({
                url: 'profile.php?action=update&section='+section+'&'+values,
                success: function(msg) {
                    if (msg != '')
                    {
                        alert("Erro: "+msg);
                    }
                    else
                    {
                        if (section=='1' && $('#profileSection form:visible').attr('data-company-id') == '0')
                        {
                            var index = $("#profileSection form").index($('#profileSection form:visible'));
                            $('.sectionButton[data-profile-section=1]').click();
                            setTimeout(function () {
                                $('.profileCompanyButton').eq(index).click();
                                setTimeout(function () {
                                    $('#profileSection form:visible input[type=text]').eq(1).focus();
                                },100);
                            },100);

                        }
                    }
                }
            });
        });

        $('#galleryEditFieldset li button').live('click', function () {
            $('#profileSection').load('/gallery.php?edit=1&id='+$(this).data('galId')+'&delete='+$(this).data('imgId'));
        });

    }
};

