/**
 * @copyright		(C)2013 DM Digital S.r.l
 * @author 			DM Digital <support@dmjoomlaextensions.com>
 * @link				http://www.dmjoomlaextensions.com
 * @license 			GNU/LGPL http://www.gnu.org/copyleft/gpl.html
 **/

var jDM = jQuery.noConflict();
var DMFUM = {

    root: '',
    groups: [],
    newUserClicked: false,


    getUsers : function() {

        jDM.post(
            DMFUM.root+"index.php?option=com_dmfrontendusermanager&controller=usermanager&task=getusers",
            {
                'filterGroup': jDM('#filterGroup').val(),
                'filterSearch': jDM('#filterSearch').val(),
                'orderBy': jDM('#orderBy').val()
            },
            function(data){
                    var myReply = jDM.parseJSON(data);
                    if (myReply.result == 'OK')
                        jDM('#dmfum_cont').html(myReply.content);
                    else
                        DMFUM.showError(myReply.error);

            }
        );

    },

    toggleUserInfo : function(userId) {

        if (jDM('#userinfo_'+userId).is(':visible')) {
            if (userId == 'new') {
                    jDM('#userinfo_'+userId).slideToggle(250,function(){});
                    jDM('#userinfo_'+userId).next().removeClass("next");
            } else {
                jDM('#user_'+userId).slideToggle(400,function(){
                    jDM('#userinfo_'+userId).animate({
                        margin: '0'
                    }, 400, function() {
                        jDM('#userinfo_'+userId).slideToggle(250,function(){});
                        jDM(jDM('#user_'+userId).prev()).prev().removeClass("prev");
                        jDM('#userinfo_'+userId).next().removeClass("next");
                    });
                });
            }

        } else {
            jDM.post(
                DMFUM.root+"index.php?option=com_dmfrontendusermanager&controller=usermanager&task=getuserinfo",
                {
                    'userId': userId
                },
                function(data){
                    jDM('#userinfo_'+userId).html(jDM.parseJSON(data));
                    jDM('#userinfo_'+userId).slideToggle(250,function(){});
                    jDM('#userinfo_'+userId).animate({
                        margin: '10px 0 10px 0'
                    }, 400, function() {
                        // Animation complete.
                        jDM('#user_'+userId).slideToggle(400,function(){});
                        jDM(jDM('#user_'+userId).prev()).prev().addClass("prev");
                        jDM('#userinfo_'+userId).next().addClass("next");
                    });
                }
            );
        }

    },

    deleteUser : function(userId) {

        if (confirm('Are you sure?')) {
            jDM.post(
                DMFUM.root+"index.php?option=com_dmfrontendusermanager&controller=usermanager&task=deleteuser",
                {
                    'userId': userId
                },
                function(data){
                    var myReply = jDM.parseJSON(data);
                    if (myReply.result == 'OK') {
                        jDM(jDM('#user_'+userId).prev()).prev().removeClass("prev");
                        jDM('#userinfo_'+userId).next().removeClass("next");
                        jDM('#userinfo_'+userId).remove();
                        jDM('#user_'+userId).remove();
                    } else {
                        DMFUM.showError(myReply.error, userId);
                    }
                }
            );
        }

    },

    editUser : function(userId) {

        if (jDM('#userinfo_'+userId+' .delete').val() == 1) {
            DMFUM.deleteUser(userId);
        } else {
            /* Retrieve the groups ids */
            DMFUM.groups = [];
            jDM('#userinfo_'+userId+' .groupids:checked').each(function(){
                DMFUM.groups.push(jDM(this).val());
            });
            /* Check if all user's info are correct */
            if (DMFUM.checkUserInfos(userId)) {
                 jDM.post(
                     DMFUM.root+"index.php?option=com_dmfrontendusermanager&controller=usermanager&task=edituser",
                     {
                         'userId': userId,
                         'name': jDM('#userinfo_'+userId+' .name').val(),
                         'username': jDM('#userinfo_'+userId+' .username').val(),
                         'email': jDM('#userinfo_'+userId+' .email').val(),
                         'password': jDM('#userinfo_'+userId+' .password').val(),
                         'groups': DMFUM.groups,
                         'infoemail': jDM('#userinfo_'+userId+' .infoemail').val(),
                         'blockuser': jDM('#userinfo_'+userId+' .blockuser').val()
                     },
                     function(data){
                         console.log(data);
                         var myReply = jDM.parseJSON(data);
                         if (myReply.result == 'OK') {
                             if (userId == 'new' || myReply.error == 'canonlydel') {
                                 jDM('#userinfo_new').animate({
                                     margin: '0'
                                 }, 400, function() {
                                     jDM('#userinfo_new').slideToggle(250,function(){});
                                     DMFUM.getUsers();
                                 });
                             } else {
                                 /* Update info on user list */
                                 DMFUM.updateUserTitle(userId);
                                 /* hide current user infos */
                                 DMFUM.toggleUserInfo(userId);
                             }
                         } else {
                             DMFUM.showError(myReply.error, userId);
                         }
                     }
                 );
            }
        }

    },

    showError : function(error, userId) {
        if (userId == undefined)
            jDM('#dmfum_cont').html('<div class="box-warning"><ul><li>' + 'Nada Encontrado...' + '</li></ul></div>');
        else
            jDM('#userinfo_'+userId+' .box-warning').html('<ul><li>' + error + '</li></ul>');
            jDM('#userinfo_'+userId+' .box-warning').show();
    },

    updateUserTitle : function(userId) {

        jDM('#user_'+userId+' .title_user').html(jDM('#userinfo_'+userId+' .username').val());
        jDM('#user_'+userId+' .title_email').html(jDM('#userinfo_'+userId+' .email').val());

    },

    checkUserInfos : function(userId) {

        var name = jDM('#userinfo_'+userId+' .name').val();
        var username = jDM('#userinfo_'+userId+' .username').val();
        var email = jDM('#userinfo_'+userId+' .email').val();
        var password = jDM('#userinfo_'+userId+' .password').val();
        var retypepassword = jDM('#userinfo_'+userId+' .retypepassword').val();
        var infoemail = jDM('#userinfo_'+userId+' .infoemail').val();
        var blockuser = jDM('#userinfo_'+userId+' .blockuser').val();

        allOK = true;

        jDM('#userinfo_'+userId+' .box-warning').empty();
        jDM('#userinfo_'+userId+' .box-warning').append("<ul>");

        /* Check name not empty */
        if (name == '') {
            jDM('#userinfo_'+userId+' .box-warning').append('<li>Nome Vazio</li>');
            jDM('#userinfo_'+userId+' .name').addClass('dmnotfilled');
            allOK = false;
        } else {
            jDM('#userinfo_'+userId+' .name').removeClass('dmnotfilled');
        }
        /* Check username not empty */
        if (username == '') {
            jDM('#userinfo_'+userId+' .box-warning').append('<li>Usuário Vazio</li>');
            jDM('#userinfo_'+userId+' .username').addClass('dmnotfilled');
            allOK = false;
        } else {
            jDM('#userinfo_'+userId+' .username').removeClass('dmnotfilled');
        }

        /* Check email format */
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (!filter.test(email)) {
            jDM('#userinfo_'+userId+' .box-warning').append('<li>E-mail Inválido</li>');
            jDM('#userinfo_'+userId+' .email').addClass('dmnotfilled');
            allOK = false;
        } else {
            jDM('#userinfo_'+userId+' .email').removeClass('dmnotfilled');
        }

        /* Check password match */
        if (password != retypepassword) {
            jDM('#userinfo_'+userId+' .box-warning').append("<li>Senha Não Combina</li>");
            jDM('#userinfo_'+userId+' .password').addClass('dmnotfilled');
            jDM('#userinfo_'+userId+' .retypepassword').addClass('dmnotfilled');
            allOK = false;
        } else {
            jDM('#userinfo_'+userId+' .password').removeClass('dmnotfilled');
            jDM('#userinfo_'+userId+' .retypepassword').removeClass('dmnotfilled');
        }

        /* Check that user groups are not empty */
        if (DMFUM.groups.length == 0) {
            allOK = false;
            jDM('#userinfo_'+userId+' .box-warning').append("<li>Selecione Um Departamento</li>");
            jDM('#userinfo_'+userId+' .groupids').addClass('dmnotfilled');
        } else {
            jDM('#userinfo_'+userId+' .groupids').removeClass('dmnotfilled');
        }

        jDM('#userinfo_'+userId+' .box-warning').append("</ul>");

        if (allOK == false)
            jDM('#userinfo_'+userId+' .box-warning').show();
        else
            jDM('#userinfo_'+userId+' .box-warning').hide();

        return allOK;

    }

};