﻿/* 
## Plugin - ListMake
By : Adelson 01/04/2011
	
###########################################################################
    ## Chamada do script
        $(document).ready(function () {
            $('.AddItem').listMake();
        });
			
    ## html
        <div id="listaEmail" class="AddItem"></div>
            id:	id que sera usado no nome 'input' que contera os itens inclusos ex: txtlistaEmail, sera adicionado um txt a frente do id
            class:	Classe que o sistema esta referenciando para chamada do jquery
        **	o id é obrigatorio para itendificação do input
	
    ## Dependencias
        jquery-1.4.4.min.js	-> Jquery 1.4.4 - Engine do listMake
        jquery.color.js		-> Plugin jquery que captura cor dos objetos
        jquery.listMake.css	-> Folha de estilo do listMake
###########################################################################
*/

(function ($) {
    $.fn.listMake = function (options) {

        // Define os parametros defaults do plugin
        var settings = {
            // Nome da classe principal
            cssMain: "_MainlistMake",
            // Define um id personalizado para o input
            idInput: null,
            // Tempo de animação para itens removidos
            removeTime: 100,
            // Tempo para mostrar o iten errado na listagem
            erroTime: 1000,
            // Limita a quantidade de itens a sere incluidos, sendo 0 sem limite
            limit: 0,
            // Expressão regular que valida o item a ser incluido, nesse caso email
            validar: /^([A-Za-z0-9_-][A-Za-z0-9_.-]+@([A-Za-z0-9_-]+\.)+[A-Za-z]{2,4})$/,
            // Separadores
            separador: /(,|;| )/gi
        };

        if (options) {
            $.extend(settings, options);
        };

        return $(this).each(function () {

            var ths = $(this);
            $(this).addClass(settings.cssMain);
            var outId = (settings.idInput == null ? "txt" + $(ths).attr('id') : settings.idInput);

            $(this).prepend('<ul class="_ul"></ul>');
            $(this).append('<input type="text" class="_add"/>');
            $(this).append('<input type="hidden" class="_txtitens" name="' + outId + '" id="' + outId + '" >');

            $(this).click(function () {
                $(this).find('._add').focus();
            });

            $(this).find('._add').bind({
                keypress: function (e) {
                    if (e.keyCode == 13) {

                        var Emails = $(this).val().split(settings.separador);
                        if (settings.limit > 0 && Emails.length > settings.limit) {
                            alert("ATENÇÃO\nO NUMERO MAXIMO DE EMAILS FOI EXEDIDO!");
                            return false;
                        }

                        for (var iE in Emails) {
                            if (settings.validar.test(Emails[iE])) {
                                var IdRepet = 0;
                                var valor = Emails[iE];
                                var Put = true;

                                var valores = "";
                                $(ths).find('ul li div._email').each(function (i) {
                                    if ($(this).html() == valor) {
                                        Put = false;
                                        IdRepet = i;
                                        return false;
                                    }
                                    valores += (i > 0 ? "," : "") + $(this).html();
                                });

                                valores += (valores.length > 0 ? "," : "") + valor;

                                if (Put) {
                                    $(ths).find('ul').append('<li class="_li"><div class="_email">' + valor + '</div><div class="_del">X</div></li>');

                                    if (settings.limit > 0 && settings.limit <= $(ths).find('ul li div._email').length)
                                        $(ths).find('._add').fadeOut();


                                    $(ths).find('ul li:last').each(function () {
                                        $(this).find('div._del').click(function () {
                                            if (confirm("Deseja remover o email: '" + $(this).parent().find('div._email').html() + "' ?")) {
                                                $(this).parent().animate({ height: "0px" }, settings.removeTime, function () {
                                                    $(this).remove();

                                                    if (settings.limit > 0 && settings.limit > $(ths).find('ul li div._email').length)
                                                        $(ths).find('._add').fadeIn();

                                                    var newValores = "";
                                                    $(ths).find('ul li div._email').each(function (i) {
                                                        newValores += (i > 0 ? "," : "") + $(this).html();
                                                    });
                                                    $(ths).find('input._txtitens').val(newValores);
                                                });
                                                return false;
                                            }
                                        });
                                    });

                                    $(ths).find('input._txtitens').val(valores);
                                    $(this).val('');

                                    var target_offset = $(this).offset();
                                    var target_top = (target_offset.top);
                                    $(this).parent().animate({ scrollTop: target_top }, 500);
                                }
                                else {
                                    var oldCor = $(ths).find('ul li div._email:eq(' + IdRepet + ')').css("backgroundColor");
                                    $(ths).find('ul li div._email:eq(' + IdRepet + ')').css("background", "#ff0000").animate({ 'backgroundColor': oldCor }, settings.erroTime);
                                }
                            }
                        }
                        return false;
                    }
                }
            });
        });
    };
})(jQuery);
