﻿(function ($) {

    //Devuelve el estilado completo del objeto
    $.fn.getStyleObject = function () {
        var dom = this.get(0);
        var style;
        var returns = {};
        if (window.getComputedStyle) {
            var camelize = function (a, b) {
                return b.toUpperCase();
            }
            style = window.getComputedStyle(dom, null);
            for (var i = 0; i < style.length; i++) {
                var prop = style[i];
                var camel = prop.replace(/\-([a-z])/g, camelize);
                var val = style.getPropertyValue(prop);
                returns[camel] = val;
            }
            return returns;
        }
        if (dom.currentStyle) {
            style = dom.currentStyle;
            for (var prop in style) {
                returns[prop] = style[prop];
            }
            return returns;
        }
        return this.css();
    };

    //Devuelve el nombre del tag de un elemento
    $.fn.tagName = function () {
        return this.get(0).tagName.toLowerCase();
    };

    //Pone a todos los pop ups como hijos DIRECTOS del form
    $.fn.moverPopUpAlForm = function () {
        var _this = $(this),
            popupContainer = _this.parent();

        if (!popupContainer.parent().is("form"))
            popupContainer.appendTo($("form:eq(0)"));
    };

    var buscarModal = function (identifier) {
        return $("body>div.dialogModal" + generateIndentifierClass(identifier, "."));
    },
        generateIndentifierClass = function (identifier, prefijo) {
            return ((identifier) ? prefijo + "id-" + identifier : prefijo + "id-none");
        },
        allModals = function () {
            return $("body>div.dialogModal");
        };

    //Agrega el modal
    $.addModalDiv = function (identifier) {
        var modal = buscarModal(identifier);
        if (modal.length == 0) {
            modal = $("<div class=\"dialogModal" + generateIndentifierClass(identifier, " ") + "\"></div>").appendTo("body");
            if ($.browser.msie) {
                //Si es IE tengo que hacer algunas correcciones en el tamaño del modal
                var ajustarWidthParaIE = function () {
                    var windowWidth = (($.browser.version >= 6 && $.browser.version < 9) ? document.documentElement.offsetWidth : window.innerWidth),
                        windowHeight = (($.browser.version >= 6 && $.browser.version < 9) ? document.documentElement.offsetHeight : window.innerHeight);

                    if ($.browser.version >= 6 && $.browser.version < 7) {
                        //IE6:
                        if ($(document.body).width() <= windowWidth) //Cuando no hay scroll horizontal le sobra un poquito de ancho.
                            windowWidth -= 17;
                        this.css("position", "absolute");

                        $(window).scroll(function () {
                            allModals().css("top", $(document).scrollTop()).css("left", $(document).scrollLeft());
                        }).trigger("scroll");

                        modal.bgiframe();
                    }

                    this.css({
                        width: windowWidth + "px",
                        height: windowHeight + "px"
                    });
                };

                $(window).resize(function () {
                    ajustarWidthParaIE.call(modal);
                }).trigger("resize");
            }
            else {
                modal.css({
                    width: "100%",
                    height: "100%",
                    zoom: "50%"
                });
            }
        }

        modal.show();
    };

    //Quita el modal
    $.removeModalDiv = function (identifier) {
        var modal = buscarModal(identifier);
        if (modal.length == 0)
            return;

        modal.hide();
    };

    $.fn.dialogPlugin = function (options, name, val) {

        //Referencias
        var _this = $(this);

        if (options == "option") {
            if (val == undefined)
                return _this.dialog("option", name);
            else
                return _this.dialog("option", name, val);
        }
        else if (options == "fn") {
            return _this.dialog(name);
        }

        //Opciones por defecto.
        options = $.extend({
            content: "", //Contenido del pop up, HTML o elementos.
            intBgColorIframe: "#FFFFFF", //Background color si es un iframe.
            intIframeScrolling: "auto", //Que scrolls permitir si es un iframe.
            intSrcIframe: "", //Src del iframe en caso de serlo.
            intTieneIframe: false, //Si es un iframe o no.
            modal: true, //Si tiene modal.
            title: "",
            width: 600,
            autoOpen: false
        }, options);

        //Fuerzo algunas opciones a los valores que quiero por jQuery UI.
        options.buttons = {};
        options.stack = true;
        options.zIndex = 1000;

        if (options.intTieneIframe) {
            //Es un iframe que tengo que cargar.
            options.content = $("<iframe></iframe>")
                .attr("src", options.intSrcIframe)
                .attr("frameborder", 0)
                .attr("scrolling", options.intIframeScrolling)
                .css("background-color", options.intBgColorIframe)
                .attr("height", "100%")
                .attr("width", "100%");

            //Fix para cuando tengo un iframe.
            _this.css("paddingLeft", 0).css("paddingRight", 0);
        }
        else if (options.content == "") {
            //No es un iframe, tengo que cargar poner el contenido HTML.
            options.content = _this.innerHtml;
        }

        //Cargo el título.
        if (options.title == "") {
            options.title = _this.attr("title");
        }
        _this.attr("title", ($(options.title).length > 0) ? $(options.title).text() : options.title);

        //Hago que el dialogo se mantenga siempre en su posicion a pesar de los posibles scrolls de la ventana.
        var fnOpenOriginal = $.ui.dialog.prototype.open;
        $.ui.dialog.prototype.open = (function () {
            if ((!$.browser.msie || $.browser.version >= 7) && this.element.dialog("widget").css("position") != "fixed")
                this.element.dialog("widget").css("position", "fixed");
            fnOpenOriginal.apply(this, arguments);
        });

        //Si tiene modal
        if (options.modal) {
            //Cambio la opcion "modal" para que no se use el modal de jQuery UI
            options.modal = false;

            //Cambio las funciones open y close para que hagan lo mismo que hacen MAS el comportamiento del modal.
            var openOriginal = $.ui.dialog.prototype.open,
                closeOriginal = $.ui.dialog.prototype.close;

            $.ui.dialog.prototype.open = (function () {
                var elemento = $(this.element);
                $.addModalDiv();
                // Le agrego un id al contenedor de todo el dialogo creado por la UI de jQuery para poder estilar a ese dialogo en particular.
                elemento.parent().attr("id", "uiContenedor-" + elemento.attr("id"));
                // Fix'es de estilo para IE6
                if ($.browser.msie && $.browser.version < 7) {
                    var fn = function (e) {
                        e.children().each(function () {
                            $(this).css($(this).getStyleObject());
                            fn($(this));
                        });
                    };
                    fn(elemento.parent());
                }
                openOriginal.apply(this, arguments);
            });
            $.ui.dialog.prototype.close = (function () {
                $.removeModalDiv();
                closeOriginal.apply(this, arguments);
            });
        }

        var startResizeDragFn = function (event, ui) {
            $("body").append($("<div></div>").attr("id", "mask").css({
                backgroundImage: "url(/SitioNosisWeb/Images/spacer.gif)",
                display: "block",
                height: "100%",
                left: "0px",
                position: "absolute",
                top: "0px",
                width: "100%",
                zIndex: parseInt(ui.helper.css("zIndex")) + 100
            }));
        },
            stopResizeDragFn = function (event, ui) {
                $("body #mask").remove();
            };

        //Cargo el plugin de dialogo de jQuery UI.
        _this.dialog(options).dialog("widget")
            .draggable("option", "iframeFix", true)
            .draggable("option", "start", startResizeDragFn)
            .draggable("option", "stop", stopResizeDragFn)
            .resizable("option", "start", startResizeDragFn)
            .resizable("option", "stop", stopResizeDragFn);

        //Meto el pop up en el form.
        _this.moverPopUpAlForm();

        //Cargo el contenido. Tiene que ser despues de mover el pop up al form para que si tiene un iframe IE9 no cargue la pagina contenida en el iframe mas de una vez ni con errores.
        _this.html(options.content);

        //Fix para cuando tengo un iframe.
        if (options.intTieneIframe)
            _this.css("overflow", "hidden");

        //Devuelvo la instancia del contexto.
        return _this;
    };

})(jQuery);
