(function ($) {
    var old = $.fn.dialog;
    $.fn.extend({
        dialog: function (opts) {
            if (!opts) {
                opts = {};
            }
            if (!opts.minHeight) {
                opts.minHeight = 10;
            }
            var args = arguments;
            args[0] = opts;
            var ret = old.apply(this, args);
            if (String(typeof (arguments[0])).toLowerCase() == "string") {
                if (arguments[0] == "open") {
                    setTimeout(function() {
						ret.find("input:first").trigger("blur");
					}, 1);
                }
                return ret;
            }
            var _this = this,
			closeDialog = function (e) {
			    if ($(e.target).parents().filter(function () {
			        return (this === _this[0])
			    }).length > 0) {
			        _this.dialog('close');
			        return false;
			    }
			};
            $('.close').live('click', closeDialog);
            if (opts && opts.focusInput === true) {
                _this.find('input').focus();
            }
            //reapply the png fix in dialogs for IE6
            if (document.all && $.initFixPNGElements) {
                this.one("dialogopen", function (event, ui) {
                    setTimeout($.initFixPNGElements, 50);
                });
                setTimeout($.initFixPNGElements, 10);
            }

            // fix for .NET compatibility
            if (opts.FormDialog !== true && $('form#form1').length) {
                this.parent().appendTo($('form:first'));
                this.bind("dialogopen", function (event, ui) {
                    $(this).parent().appendTo($('form:first'));
                });
            }
            
            return ret;
        },
        FormDialog: function () {
            var formDialogInit = function (e) {
                var $this = $(this),
				refreshOnClose = false,
				cancelClose = false,
				exts = (e.type == "ajaxInit") ? e.exts : $this.ParseClass(),
				loadingMessage = ($("form.es").length > 0) ? "Cargando" : "Loading";
                dialog = $('<div title="' + loadingMessage + '..."></div>').dialog({
                    modal: true,
                    FormDialog: true,
                    close: function (event, ui) {
                        if (cancelClose == true) return;
                        dialog.dialog('destroy').remove();
                        if (refreshOnClose === true) {
                            window.location.reload();
                        }
                    },
					beforeClose: function() {
						$(this).find(":input").trigger('blur');
					},
                    width: exts.width || 300,
                    dialogClass: exts.dialogClass || null,
                    closeOnEscape: exts.closeOnEscape || null
                }),
				sendRequest = function (url, additional, sendFormValues) {
				    if (url.indexOf("FormDialog=true") === -1) {
				        url += ((url.indexOf("?") === -1) ? "?" : "&") + "FormDialog=true";
				    }
				    if (sendFormValues !== false) {
				        var data = dialog.find("input, textarea, select").serializeArray();
				    } else {
				        data = {};
				    }
				    if (additional) {
				        for (var key in additional) {
				            data.push({
				                name: key,
				                value: additional[key]
				            });
				        }
				    }
				    $.post(url, data, function (data) {
				        /*if (data && data.action) {
				        switch (data.action) {
				        case "close":
				        dialog.dialog("close");
				        return;
				        case "redirect":
				        window.location = data.location;
				        return;
				        }
				        }*/

				        if (data && (data.action || $.isArray(data))) {
				            if (!$.isArray(data)) {
				                data = [data];
				            }
							for (var i=0, length=data.length; i<length; i++) {
				                switch (data[i].action) {
				                    case "close":
				                        dialog.dialog("close");
				                        break;
				                    case "redirect":
				                        window.location = data[i].location;
				                        break;
									case "PostRefresh":
										window.__doPostBack(data[i].eventTarget, data[i].eventArgument);
										break;
				                }
				            }
				            return;
				        }

				        dialog.html(data);
				        cancelClose = true;
				        dialog.dialog("close", { "test": true }).dialog("open");
				        cancelClose = false;
				        var form = dialog.find("form:first"),
						formObj = form.ParseClass();
				        var title = form.attr("title");
				        if (!title && exts.title) title = unescape(exts.title);
				        if (!title) title = "";
				        dialog.dialog("option", "title", form.attr("title") || "");
				        if (formObj.refreshOnClose === true || formObj.refreshOnClose === false) {
				            refreshOnClose = formObj.refreshOnClose;
				        }
				        if (formObj.triggerButtonEvent) {
				            $this.trigger(formObj.triggerButtonEvent);
				        }

				        form.trigger("TrackWT");

				        dialog.find("input[type='submit']").click(function (e) {
				            var ele = $(e.target),
							params = {};
				            params[ele.attr("name")] = ele.val();
				            sendRequest(form.attr("action"), params);
				            if (ele.hasClass('throb') || ele.parents("span.button").hasClass('throb')) {
				                form.trigger("throb");
				            }
				            return false;
				        });
				        dialog.find("a.loadInFormDialog").click(function (e) {
				            sendRequest($(this).attr("href"), {}, false);
				            return false;
				        });

				        form.find('select.showMore,input.showMore,span.showMore input').trigger("change");

				        form.trigger("DOMupdated");

				        if ($.RoundBox && $.RoundBox.init) {
				            $.RoundBox.init();
				        }

				        if ($.datepicker && $.datepicker.init) {
				            $.datepicker.init();
				        }

				        if ($.VideoPlayer && $.VideoPlayer.init) {
				            $.VideoPlayer.init();
				        }
				        if ($.initShowDialog) {
				            $.initShowDialog();
				        }
				        if ($.ShoppingAutoComplete && $.ShoppingAutoComplete.init) {
				            $.ShoppingAutoComplete.init();
				        }

				        if ($.mySpecificMethod) {
				            $.mySpecificMethod();
				        }

				        //reapply the png fix in dialogs for IE6
				        if (document.all && $.initFixPNGElements) {
				            setTimeout($.initFixPNGElements, 10);
				        }
				    });
				};
                sendRequest($this.ParseClass().FormDialogURL || $this.attr("href"));

                return false;
            };
            this.live("click", formDialogInit);
            this.bind("ajaxInit", formDialogInit);

            this.each(function () {
                var $this = $(this);
                if ($this.ParseClass().autoLaunch === true) {
                    $this.trigger("click");
                }
            });
        }
    });
    $('a.showDetails').live("click", function () {
        $('div.planDetailsDialog').dialog('close');
        var $this = $(this),
		exts = $this.ParseClass(),
		pos = $this.offset(),
		scrollTop = $(document).scrollTop(),
		dialogTop = Math.round(pos.top - scrollTop),
		dialogLeft = Math.round(pos.left + $this.width() + 9),
		dialogSelector = exts.dialog || "#" + exts.id,
		dialog = $this.data("dialog");
        if (!dialog) {
			
            dialog = $(dialogSelector).dialog(
				{
				    width: exts.width || 440,
				    minHeight: 0,
				    position: [dialogLeft, dialogTop],
				    dialogClass: 'planDetailsDialog arrowLeft',
				    draggable: false,
				    close: function (event, ui) {
				        //dialog.dialog('destroy');
				    },
				    autoOpen: true,
				    focusInput: exts.focusInput || false
				}
			);
            dialog.dialog('widget').append('<div class="arrow"></div>');

            // fix for .NET compatibility
            if ($('form:first').length > 0) {
                dialog.parent().appendTo($('form:first'));
            }
            $this.data("dialog", dialog);
        }
        dialog.dialog("option", "position", [dialogLeft, dialogTop]);
        dialog.dialog("open");

        var arrow = dialog.dialog('widget').find('div.arrow'),
		offset = dialog.parent().offset();
        if (arrow.length > 0 && offset && offset.top) {
            arrow.css('top', $this.offset().top - offset.top + 'px');
        }
        return false;
    });
    $(function () {
        $("div.autoDialog").each(function () {
            var $this = $(this),
			obj = $this.ParseClass();
			if(obj.hideTitlebarClose === 'true') {
				$this.bind("dialogopen", function(e, ui) {
                    $('.ui-dialog-titlebar-close', e.target.parentElement).hide();
				})
            }
            $this.dialog({
                width: obj.width || 440,
                minHeight: 0,
                autoOpen: true,
                modal: true,
                dialogClass: obj.dialogClass || '', 
                title: (obj.title ? decodeURIComponent(obj.title) : "")
            });
        });
        $.initShowDialog = function () {
            $("a.showDialog").each(function () {
                var $this = $(this);
                if ($this.data("ShowDialogInit") === true) return;
                $this.data("ShowDialogInit", true);
                var obj = $this.ParseClass(),
				dialog = $(obj.dialog),
				dialogObj = dialog.ParseClass();
                dialog.dialog({
                    width: dialogObj.width || 440,
                    minHeight: 0,
                    autoOpen: false,
                    modal: true,
                    title: (dialogObj.title ? decodeURIComponent(dialogObj.title) : ""),
                    dialogClass: dialogObj.dialogClass || ''
                });
                $this.click(function (e) {
                    if (dialogObj.position != "center") {
                        var pos = $this.offset();
                        dialog.dialog("option", "position", [pos.left - dialog.dialog("option", "width") + (dialogObj.relativeX || 0), pos.top + dialogObj.relativeY || 0]);
                    }
                    dialog.dialog("open");
                    e.preventDefault();
                });
            });
        };
        $.initShowDialog();
        $(document).bind("DOMupdated", $.initShowDialog);
        $("a.FormDialog").FormDialog();
		$.LaunchFormDialog = function(url, options) {
			var fd = document.createElement("a");
            fd.href = url;
            $fd = $(fd);
            $fd.FormDialog();
            var event = jQuery.Event("ajaxInit");
            event.exts = options;
            $fd.trigger(event);
		};
    });
})(jQuery);

