// This code block extends the uiDialog widget by adding a new boolean option 'sticky' which,
// by default, is set to false. When set to true on a dialog instance, it will keep the dialog's
// position 'anchored' regardless of window scrolling.

// Start of uiDialog widget extension...
var _init = $.ui.dialog.prototype._init;
$.ui.dialog.prototype._init = function() {
    var self = this;
    _init.apply(this, arguments);
    this.uiDialog.bind('dragstop', function(event, ui) {
        if (self.options.sticky) {
            var left = Math.floor(ui.position.left) - $(window).scrollLeft();
            var top = Math.floor(ui.position.top) - $(window).scrollTop();
            self.options.position = [left, top];
        };
    });
    if (window.__dialogWindowScrollHandled === undefined) {
        window.__dialogWindowScrollHandled = true;
        if(__browserSupportsFixed()) {
	        $(window).scroll(function(e) {
	        	if(window.__dialogFixedHandled === undefined) {
	        		window.__dialogFixedHandled = true;
		            $('.ui-dialog-content').each(function() {
		                var isSticky = $(this).dialog('option', 'sticky');
		                if (isSticky) {
		                    $(this).parent().css('position', 'fixed');
		                }
		            });
	        	}
        	});
        } else {
	        $(window).scroll(function(e) {
	            $('.ui-dialog-content').each(function() {
	                var isSticky = $(this).dialog('option', 'sticky') && $(this).dialog('isOpen');
	                if (isSticky) {
	                    var position = $(this).dialog('option','position');
	                    $(this).dialog('option', 'position', position);
	                }
	            });
	        });
        }
    };
};

$.ui.dialog.defaults.sticky = false;

function __browserSupportsFixed() {
	if(navigator.userAgent.indexOf("Chrome") > 0 || navigator.userAgent.indexOf("Safari") > 0) {
		// dB - 12/30/2009 - For some reason, Chrome is having fits when
		//      dragging a sticky dialog.  For now, don't use fixed positioning
		// dB - 05/15/2010 - Added Safari to this workaround
		return false;
	} else {
	    var testDiv = document.createElement("div");
	    testDiv.id = "testingPositionFixed";
	    testDiv.style.position = "fixed";
	    testDiv.style.top = "0px";
	    testDiv.style.right = "0px";
	    document.getElementsByTagName('body').item(0).appendChild(testDiv);
	    var offset = 1;
	    if (typeof testDiv.offsetTop == "number" && testDiv.offsetTop != null
	        && testDiv.offsetTop != "undefined") {
	      offset = parseInt(testDiv.offsetTop);
	    }
	    return (offset == 0);
	}
}
// End of uiDialog widget extension... 
