var mfnDialog = Class.create({
	
	dialogId : "mfnDialog",
	
	iframeId : "mfnFrame",
	
	dialogHeaderId : "mfnDialogHeader",
	
	dialogContentId : "mfnDialogContent",
	
	dialogTitleId : "mfnDialogTitle",
	
	initialize : function() {
		// nothing yet
	},
	
	create : function(url, title) {
		if (!this.exists()) {
			this.build();
		} else {
			this.clearTitle();
			this.clearContent();
		}
		
		ie6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
		
		if (ie6) {
			this.framePos = 'absolute';	
		} else {
			this.framePos = 'fixed';
		}

		this.show();
		this.setTitle(title);
		this.doGet(url, true);
        this.centralize();
	},
	
	doGet : function( url, doCentralize ) {
		if ( this.exists() ) {
                        var noncacheurl = url + ( url.indexOf( '?' ) > -1 ? '&' : '?' ) + 'dialogdatetime=' + new Date().getTime();
                        new Ajax.Request( noncacheurl, {
				method : 'get',
				onCreate : function() {
					Dialog.clearContent();
					Dialog.resize();
					$(Dialog.dialogContentId).addClassName("loading");
				},
				onSuccess : function(response) {
					Dialog.loadAjaxContent( response, doCentralize );
				},
				onFailure : function() {
					Dialog.loadFailureContent("Request failed");
				}
			});
		}
	},
	
	doPost : function( form, doCentralize ) {
		form.request( {
			method : form.readAttribute("method"),
			onCreate : function() {
				$(Dialog.dialogContentId).update('');
				Dialog.resize();
				$(Dialog.dialogContentId).addClassName("loading");
			},
			onSuccess : function(response) {	
				Dialog.loadAjaxContent( response, doCentralize );
			},
			onFailure : function() {
				Dialog.loadFailureContent("Request failed");
			}
		});
	},
	
	loadAjaxContent : function( response, doCentralize ) {
		if ( response.getHeader('redirect') != null ) {
			Dialog.hide(); 
			window.location.href = response.getHeader('redirect');
		} else {
			// remove loading class
			$(this.dialogContentId).removeClassName("loading");
			// set content
			$(this.dialogContentId).update( response.responseText );
			// set header if available
			if (response.getHeader( 'dialogTitle' ) != null) {
				this.setTitle( response.getHeader('dialogTitle') );
			}
			// resize according to content
			this.resize();
			if( doCentralize )
				this.centralize();
			this.addFormHandlers();
			this.addlinkHandlers();
		}
	},
	
	loadFailureContent : function( message ) {
		$(this.dialogContentId).removeClassName("loading");
		// set content
		$(this.dialogContentId).update( message );
		// resize according to content
		this.resize();
		this.centralize();
		this.addFormHandlers();
		this.addlinkHandlers();
	},
	addFormHandlers : function() {
		$(this.dialogContentId).select("form").each( function ( form ) {
			Event.observe( form, "submit", function ( e ) {
				Dialog.doPost( form );
				e.stop();
			});
		});
	},
	
	addLinkHandlers : function() {
		$(this.dialogContentId).select("a").each( function( link ) {
			if (link.readAttribute("rel") == "closedialog") {
				Event.observe( link, "click", function ( e ) {
					Dialog.hide(); 					
					e.stop();
				});
			} else if (link.readAttribute("rel") == "dialog") {
				Event.observe( link, "click", function ( e ) {
					Dialog.doGet( link.readAttribute("href") );
					e.stop();
				});
			}
		});
	},
	
	setTitle : function( title ) {
		if ( this.exists() ) {
			$(this.dialogTitleId).update( '<h2>' + title + '</h2>' );
		}
	},
	
	clearContent : function() {
		if ( this.exists() ) {
			$(this.dialogContentId).update('');
			$(this.dialogContentId).setStyle( {
				height : 'auto'
			});
		}
	},
	
	clearTitle : function() {
		if ( this.exists() ) {
			$(this.dialogTitleId).update();
		}	
	},
	
	build : function() {
		if ( this.exists() ) {
			this.clearContent();
		} else {
			
			dialogFrame = new Element( "iframe" , {
				id : this.iframeId,									  
				'frameborder' : 0,
				'scrolling' : 'no',
				'style' : 'display:block; padding:1px; border:1px solid #fff; background-color:#fff; color:#fff; left:0; top:0; z-index:999 !important; width:100px; height:100px; position:' + this.framePos + ';',				
				'src' : ''				
			});					
			
			dialogBox = new Element( "div" , {
				id : this.dialogId,
				'style' : 'display:block; left:0; top:0; z-index:1000 !important; width:100px; height:100px; position:absolute;'								
			});				
			
			dialogHeader = new Element ( "div" , {
				id : this.dialogHeaderId
			});
			dialogTitle = new Element ( "div" , {
				id : this.dialogTitleId
			});
			dialogClose = new Element ( "a" , {
				href : 'javascript:Dialog.hide()',
				'class' : 'icon closedialog'
			});
			dialogContent = new Element ( "div" , {
				id : this.dialogContentId,
				'class' : 'clearfix'
			});	
			$$('body')[0].insert( dialogFrame );
			$$('body')[0].insert( dialogBox );
						
			this.hide();
			$(this.dialogId).insert( dialogHeader ).insert( dialogContent );
			$(this.dialogHeaderId).insert( dialogTitle ).insert( dialogClose );
			this.addDragHandlers();
			this.setDropHandler();
		}
	},
	
	addDragHandlers : function() {
		ie6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
			
		if (! ie6) {			
			new Draggable ( this.dialogId , {
				scroll : window,
				handle : this.dialogHeaderId,
				onDrag : Dialog.showIframe,
				onEnd : Dialog.setDropHandler			
			});
		}
	},

	hideIframe : function() {	
		if ($('mfnFrame')) {
			$('mfnFrame').setStyle( {
				visibility : 'hidden',
				display : 'none'
			});
		}
	},
	
	showIframe : function() {	
		if ($('mfnFrame')) {
			
			dialogDim = $('mfnDialog').cumulativeOffset();
			dialogLeft = dialogDim.left + 'px';
			dialogTop = dialogDim.top + 'px';
			
			ie6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
			
			if (ie6) {				
				$('mfnFrame').setStyle( {
					position : 'absolute',
					left : dialogLeft,
					top : dialogTop,
					visibility : 'visible',
					display : 'block'
				});						
			} else {
				$('mfnFrame').setStyle( {
					position : 'fixed',
					left : dialogLeft,
					top : dialogTop,
					visibility : 'visible',
					display : 'block'
				});								
			}
		}

	},	

	setDropHandler : function() {	
		var ie6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;

		if (!ie6) {		
			$('mfnFrame').setStyle( {
				position : 'fixed'
			});				
			$(Dialog.dialogId).setStyle( {
				position : 'fixed'
			});				
		}
		try {
			if ($(Dialog.dialogId).getStyle("top").replace('px','') < 0) {
				$('mfnFrame').setStyle( {
					top : '10px'
				});				
				$(Dialog.dialogId).setStyle( {
					top : '10px'
				});
			}
		} catch (e) {
			// IE ACTING WEIRD
		}			
	},
	
	destroy : function() {
		if ( $(this.dialogId) != null ) {
			$(this.dialogId).remove();
			$(this.iframeId).remove();			
		}
	},
	
	show : function() {
		if ( this.exists() ) {	
			$(this.iframeId).setStyle( {
				visibility : 'visible',
				display : 'block'
			});			
			$(this.dialogId).setStyle( {
				visibility : 'visible',
				display : 'block'
			});
		}
		this.resize();
		this.centralize();
	},
	
	hide : function() {		
		if ( this.exists() ) {
			$(this.iframeId).setStyle( {
				visibility : 'hidden',
				display : 'none'
			});		
			$(this.dialogId).setStyle( {
				visibility : 'hidden',
				display : 'none'
			});		
		}
	},
	
	resize : function() {
		if ( Dialog.exists() ) {
			// resize dialog according to its content
			// this might be a step in the good direction :)
			contentDim = $(this.dialogContentId).getDimensions();
			minWidth = 300;
			maxHeight = document.viewport.getHeight() - 50;
			minHeight = 40;
			var biggestChildWidth = 0;
			var biggestChildHeight = 0;
			children = $(this.dialogContentId).immediateDescendants(); 
			for ( i = 0; i < children.size(); i++ ) {
				if (children.size() != 0 && children[i].getWidth() > minWidth && children[i].getWidth() > biggestChildWidth) {
					biggestChildWidth = children[i].getWidth();
				}
				if (children.size() != 0 && children[i].getHeight() > minHeight && children[i].getHeight() > biggestChildHeight) {
					biggestChildHeight = children[i].getHeight();
				}
			}
			if (biggestChildWidth > minWidth) {
				contentDim.width = biggestChildWidth;
			} else {
				contentDim.width = minWidth;
			}
			if (biggestChildHeight > minHeight) {
				contentDim.height = biggestChildHeight;
			} else if (biggestChildHeight > maxHeight) {
				contentDim.height = maxHeight;
				$(this.dialogContentId).setStyle( {
					overflow : auto
				});
			} else {
				contentDim.height = minHeight;
			}
			$(this.dialogContentId).setStyle( {
				height : contentDim.height + 'px',
				width : contentDim.width + 'px'
			});
			$(this.dialogId).setStyle( {
				width : $(this.dialogContentId).getWidth() + 'px',
				height : $(this.dialogContentId).getHeight() + 30 + 'px'
			});	
			$(this.iframeId).setStyle( {
				width : $(this.dialogContentId).getWidth() + 'px',
				height : $(this.dialogContentId).getHeight() + 30 + 'px'
			});	
		}
	},
	
	centralize : function() {
		dialogDim = $(this.dialogId).getDimensions();
		windowDim = document.viewport.getDimensions();
		dialogLeft = ( windowDim.width / 2 ) - ( dialogDim.width / 2) + 'px';
		dialogTop = ( windowDim.height / 2 ) - ( dialogDim.height / 2) + 'px';	
			
		$(this.iframeId).setStyle( {
			position : "absolute",
			left : dialogLeft,
			top : dialogTop
		});	
		$(this.dialogId).setStyle( {
			position : "absolute",
			left : dialogLeft,
			top : dialogTop
		});	
		
		var ie6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
		
		if (ie6) {
			$('header').scrollTo();						
		}
		
		this.setDropHandler();
	},
	
	exists : function() {
		if ( $(this.dialogId) != null && $(this.dialogContentId) != null && $(this.dialogTitleId) != null ) {
			return true;
		}
		return false;
	}
});

var Dialog = new mfnDialog();