var custonSelect = {
    length: 0,
    active: null
};

(function($) {
    //SELECT PERSONALIZADO
    $.fn.custonSelect = function() {
        $(this).each(function() {

            //SELECT ORIGINAL
            var select = $(this);
            var options = $('option', select);
            var estilo = select.attr('class') ? select.attr('class') : 'select-padrao';

            //SELECT PERSONALIZADO
            var combo = select.after('<div class="select ' + estilo + '"></div>').next();
            var box = $('<ul>').appendTo(combo);
            var button = $('<button>&#9660;</button>').appendTo(combo);

            var validator;

            var jQueryValidateListener = function(select) {
                //SUPORTE JUERY.VALIDATOR
                var form = select.parents('form'), validator;
                if (form.length > 0)
                    var validator = $.data(form[0], 'validator');

                return validator;
            }

            //FUNCOES

            //ABRIR E FECHAR LISTA
            combo[0].openClose = function(e) {
                if (e) e.preventDefault();

                //disparado por document, e trajeto foi o propio button?
                if (this === document && e.target === $('button', combo)[0]) {
                    //ignora evento
                    return false;
                }

                validator = jQueryValidateListener(select);

                //contem lista?
                if ($('option', select).length > 1) {
                    //ativa ou inativa
                    combo.toggleClass('select-opened');
                    $('button', combo).toggleClass('active');

                    //esta ativo?
                    if (combo.hasClass('select-opened')) {

                        //caso existir outro select ativo, inativa
                        if (custonSelect.active && custonSelect.active !== combo)
                            custonSelect.active[0].openClose();

                        //atualiza as informacoes geral	
                        custonSelect.active = combo;

                        //seta tamanho da lista
                        var larguraLista = box.width(), larguraCombo = combo.width();
                        larguraLista = (larguraLista < larguraCombo ? larguraCombo : larguraLista);
                        larguraLista = 155;

                        box.css('width', larguraLista);

                        //box.css('min-width', larguraLista );

                        var quantidade = $('option', select).length;
                        if (quantidade > 10) {
                            box.css('height', 21 * 10); //$('li', box).height()
                            box.css('overflow-y', 'auto');
                            box.css('overflow-x', 'hidden');
                        }

                        //aumenta o nivel do z-index
                        combo.css('z-index', '10');

                        //adiciona evento de fechar select no document
                        $(document).bind('click.custonselect', combo[0].openClose);

                        //SUPORTE JQUERY.VALIDATE
                        if (validator) {
                            $(validator.currentForm).trigger("focusin", select);
                            $(select).trigger("focusin");
                        }
                    }
                    else {

                        //caso existir o select ativo for ele mesmo, remove
                        if (custonSelect.active && custonSelect.active === combo)
                            custonSelect.active = null;

                        //diminui o nivel do z-index
                        combo.css('z-index', '1');

                        //remove evento de fechar select do document
                        $(document).unbind('click.custonselect');

                        box[0].scrollTop = 0;

                        //exclui tamanho da lista
                        box.attr('style', '');
                        box.css('width', 'auto');

                        var quantidade = $('option', select).length;
                        if (quantidade > 10) {
                            box.css('height', 'auto');
                            box.css('overflow-y', 'visible');
                            box.css('overflow-x', 'visible');
                            box.css('overflow', 'visible');
                        }

                        if (validator) {
                            $(validator.currentForm).trigger("focusout", select);
                            $(select).trigger("focusout");
                        }
                    }

                }

                return this;
            };

            //ADCICIONA OPTION APENAS NO PERSONALIZADO
            combo[0].addOption = function(opt) {
                var option = $(opt);
                var select = option.parent();
                var combo = $(this);
                var box = $('ul', combo);
                var button = $('button', combo);

                //cria
                var newOption = $('<li><a href="#option">' + option.text() + '</a></li>').appendTo(box);

                //adiciona metodo de selecao no option personalizado
                newOption[0].select = function() {
                    $('li.selected', $(this).parent()).removeClass('selected');
                    $(this).addClass('selected');
                    return this;
                }

                //adiciona metodo no option original de selecao
                option[0].select = function() {
                    var op = $('option:selected', $(this).parent());
                    op.removeAttr('selected');
                    if (op) {
                        op.selected = false;
                    }

                    $(this).attr("selected", "selected");
                    this.selected = true;
                    newOption[0].select();
                    return this;
                }

                //seta como selecionado
                if (option[0].selected) {
                    option[0].select();
                }

                //adiciona evento click no option personalizado
                newOption
					.bind('click.custonselect', function() {
					    //ja esta selecionado?
					    if (option[0].selected) {
					        //ignora evento
					        combo[0].openClose();
					        return false;
					    }

					    //seleciona
					    option[0].select();

					    //fecha lista
					    combo[0].openClose();

					    //dispara evento no select original
					    select.trigger("select");
					    select.trigger("change");

					    //SUPORTE PARA JQUERY.VALIDATE
					    if (validator) {

					        var c = 0;
					        for (var n in validator.submitted)
					            c++;

					        if (c > 0) {

					            var errorElement = combo.prev(validator.settings.errorElement)[0] || combo.prev($.validator.defaults)[0] || $(this)[0];

					            if (validator.check(select[0])) {
					                $(errorElement).removeClass(validator.settings.errorClass).addClass(validator.settings.validClass);
					            }
					            else {
					                $(errorElement).removeClass(validator.settings.validClass).addClass(validator.settings.errorClass);
					            }
					        }
					    }


					    return false;
					})
					.hover(function() {
					    $(this).addClass('hover');
					}, function() {
					    $(this).removeClass('hover');
					});

                return this;
            };

            //ADCICIONA OPTION NO ORIGINAL E NO PERSONALIZADO
            select[0].addOption = function(text, value, selected) {
                //cria
                var option = $('<option value="' + value + '">' + text + '</option>').appendTo(this);

                //seleciona
                if (selected) {
                    option.attr("selected", "selected");
                }

                //adiciona no personalizado
                $(this).parent().get(0).addOption(option);
                return this;
            }

            //DELETA TODOS OPTIONS DO PERSONALIZADO
            combo[0].clearOptions = function() {
                $('ul', this).empty();
                return this;
            }

            //DELETA TODOS OPTIONS DO ORIGINAL E PERSONALIZADO
            select[0].clearOptions = function() {
                $(this).empty();
                $(this).parent().get(0).clearOptions();
                return this;
            }

            //EVENTOS DO COMBO
            combo
				.bind('click.custonselect', function(e) {
				    if (e.target !== this) return;
				    setTimeout(function() {
				        combo[0].openClose();
				    }, 0);
				})
				.hover(function() {
				    $(this).addClass('select-hover');
				}, function() {
				    $(this).removeClass('select-hover');
				});

            //EVENTOS DO BOTAO					
            button
				.bind('click.custonselect', combo[0].openClose)
				.hover(function() {
				    $(this).addClass('hover');
				}, function() {
				    $(this).removeClass('hover');
				});


            //GERAR

            //SETA DISPLAY
            //if (select.css('display') != 'block')
            // combo.addClass('select-inline');

            //SETA TAMANHO
            var width = select.css('width');

            if (width && width != '')
                combo.css('width', width);
            else
                combo.addClass('select-auto-size');

            //box.css('min-width', parseInt( combo.width() ) );

            //ADICIONA NO PALCO
            select.appendTo(combo);

            //SELECIONA O ATUAL
            if ($('option:selected', select).length < 1) {
                var selected = $('option', select);
                selected[0].select();
            }

            //ADICIONA OPTIONS PERSONALIZADOS
            options.each(function() {
                combo[0].addOption(this);
            });

            //ATUALIZA INFORMACOES GERAL
            custonSelect[custonSelect.length] = combo;
            custonSelect.length++;

        })
    }

    //substituir funcao delegate para suportar jquery.validator caso existir
    /* if (!$.fn.validate) return;

    $.extend($.fn, {
    delegate: function(type, delegate, handler) {
    return this.bind(type, function(event, target) {
    var target = $(target || event.target);
    if (target.is(delegate)) {
    return handler.apply(target, arguments);
    }
    });
    }
    })
    */
})(jQuery);
