jQuery.fn.modal = function(options) {

    // VERIFICANDO O HREF
    if (!options) {
        if (this.attr('href'))
            var options = {
                url: this.attr('href'),
                closeClickOut: this.attr('closeClickOut') || true,
                modal: this.attr('modal') || null
            };
    } else {
        if (!options.url) if (this.attr('href')) options.url = this.attr('href');
    }

    var settings = {
        url: '#',
        modal: null,
        backgroundColor: '#000',
        backgroundOpacity: 0.5,
        position: 'center',
        referencePosition: this,
        top: 0,
        left: 0,
        closeEsc: true,
        closeClickOut: false,
        autoOpen: false,
        preservDoPostBack: true,
        onSuccessAnimateAttr: { marginTop: -60 },
        onSuccessCall: null,
        onClose: null,
        onLoad: null
    };
    options = jQuery.extend(settings, options);


    function openModal() {

        if (options.onLoad != null)
            options.onLoad();


        var larguraHtml = $('html')[0].scrollWidth;
        /*CREATE ELEMENTS*/
        $('body').append($('<img />').attr({ src: "/nescau2.0/images/jquery.modal/carregando.gif", width: 100, height: 100, alt: "", className: 'load' })).append($('<div></div>').addClass('bg_modal')).append($('<div></div>').addClass('view_modal'));

        // verificando se o body é menor do que o screen
        var altura = $('html')[0].scrollHeight < $(window).height() ? $(window).height() : $('html')[0].scrollHeight;
        $('.bg_modal').width(larguraHtml).height(altura);

        /*OPACITY*/
        if (options.backgroundOpacity != 0) {

            $('.bg_modal').css('background-color', options.backgroundColor);
            $('.view_modal').css('opacity', null);
            $('.bg_modal').css('opacity', null);
        }

        // escondendo selects
        $('select').css('visibility', 'hidden');

        // posicionamento
        if (options.position == 'relative') {
            var offset = options.referencePosition.offset();
            leftModal = offset.left;
            topModal = offset.top;
        }

        /*SHOW BACKGROUND*/
        //Buscar conteudo via Ajax


        $('.bg_modal').fadeTo(1, options.backgroundOpacity, function() {
            if (options.url != '#') {
                $.ajax({
                    async: true,
                    type: "GET",
                    url: options.url,
                    data: '',
                    contentType: "application/json; charset=utf-8",
                    dataType: "text",
                    cache: false,
                    success: function(texto) {
                        setTimeout(function() {
                            $('.view_modal').html(texto);
                            $('.view_modal').css('opacity', null);

                            /*CLOSE MODAL*/
                            $("a[rel='modalclose']").click(function() {
                                closeModal();
                                return false;
                            });

                            if (options.onSuccessAnimateAttr)
                                $('div.view_modal').animate(options.onSuccessAnimateAttr, 1000);

                            if (options.onSuccessCall != null)
                                options.onSuccessCall($('.view_modal'));
                        }, 400);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert('XMLHttpRequest:' + JSON.stringify(XMLHttpRequest) + '\n\n\ntextStatus:' + JSON.stringify(textStatus) + '\n\n\nerrorThrown:' + JSON.stringify(errorThrown));
                    }
                });

            } else {
                $(options.modal).clone().appendTo('div.view_modal');
                $('.view_modal').css('opacity', null);
                /*CLOSE MODAL*/
                $("a[rel='modalclose']").click(function() {
                    closeModal();
                    return false;
                });

                if (options.onSuccessAnimateAttr) {
                    if ($.browser.msie)
                        $('div.view_modal').animate(options.onSuccessAnimateAttr, 1500);
                    else
                        $('div.view_modal').css(options.onSuccessAnimateAttr);

                }
                if (options.onSuccessCall != null)
                    options.onSuccessCall($('.view_modal'));
            }
        });

        {//<config>
            $('.load').remove();
            GB_getPageScrollTop = function() {
                var yScrolltop;
                if (self.pageYOffset) {
                    yScrolltop = self.pageYOffset;
                } else if (document.documentElement && document.documentElement.scrollTop || document.documentElement.scrollLeft) {
                    yScrolltop = document.documentElement.scrollTop;
                } else if (document.body) {
                    yScrolltop = document.body.scrollTop;
                }
                return yScrolltop;
            }

            /*CENTRALIZE MODAL*/
            if (options.position != 'center') {
                var alturaModal = parseInt(options.top) + parseInt(topModal) + parseInt($('.view_modal').height());
                if (altura < alturaModal) {
                    options.top = 0;
                    topModal = altura - parseInt($('.view_modal').height());
                }
                $('.view_modal').css({
                    marginTop: topModal,
                    marginLeft: leftModal,
                    left: options.left,
                    top: options.top
                }
					);

            } else {
                $('.view_modal').css({ marginTop: parseInt(GB_getPageScrollTop() - ($('.view_modal').height() / 2)), marginLeft: -parseInt($('.view_modal').width() / 2) });
            }

            /*MODAL HIDE*/
            //if (options.backgroundOpacity != 0) $('.view_modal').fadeTo('fast', 1);
            if (options.backgroundOpacity != 0) $('.view_modal').show();


        }; //</config>


        if (options.closeClickOut == true) {
            $('.bg_modal').click(function() {
                closeModal();
            });
        }


        if (options.closeEsc == true) {
            $(window).keydown(function(event) {
                if (event.keyCode == 27) closeModal();
            });
        }
        return false;
    }



    if (options.autoOpen == false) {
        this.click(openModal);
    } else {
        openModal();
    }




    /*CLOSE MODAL*/
    function closeModal() {
        if ($.browser.msie) {
            $('.view_modal').css({ background: 'none' })
        }
        /*HIDE MODAL*/
        $('.view_modal').remove();

        /*HIDE BACKGROUND*/
        $('.bg_modal').remove();
        $('select').css('visibility', 'visible');

        $(window).unbind();
        $('.bg_modal').unbind();

        if (options.preservDoPostBack)
            __doPostBack = newDoPostBack;

        if (options.onClose != null)
            options.onClose();
    }

    function newDoPostBack(eventTarget, eventArgument) {
        var theForm = document.forms[0];
        if (!theForm) {
            theForm = document.aspnetForm;
        }
        if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
            document.getElementById("__EVENTTARGET").value = eventTarget;
            document.getElementById("__EVENTARGUMENT").value = eventArgument;
            theForm.submit();
        }
    }
    this.css('visibility', 'visible');
};

$(document).ready(function() {
    $('a[rel="modal"]').each(function() {
        $(this).modal();
    });
});
