var Dwindow = Class.create();

Dwindow.zorder = new Array();
Dwindow.windows = new Hash();

Dwindow.prototype = {
    initialize: function( elementId, options ) {
 		this.elm = $(elementId);
 		this.close = this.elm.down( '.close' );
 		this.fold  = this.elm.down( '.fold' );
 		
 		this.fullHeight = this.elm.getHeight();
 		
 		this.draggable = new Draggable( this.elm, options ); 
 		Dwindow.zorder.push( this.elm );
 		Dwindow.windows[this.elm.id] = this;
 		
 		this.elm.observe( 'click', this.doClick );
 		if ( this.close ) this.close.observe( 'click', this.doClose );
 		if ( this.fold ) this.fold.observe( 'click', this.doMinimize );
    },
    
    doClick: function ( event ) {
        var src = Event.element( event );
		if ( !src.hasClassName( 'window' ) ) {
			src = src.up( '.window' );
		}
		
		var index = Dwindow.zorder.indexOf( src );
		if ( index == -1 ) return;
		
		Dwindow.zorder.splice( index, 1 );
		Dwindow.zorder.push( src );
		var i = 0;
		Dwindow.zorder.each( function ( drag )  {
			drag.style.zIndex = i++; 
		});
	},
	
	doClose: function( event ) {
		var win = Event.element( event ).up( '.window' );
		var drag = Dwindow.windows.remove( win.id );
		Dwindow.zorder.splice( Dwindow.zorder.indexOf( drag.elm ), 1 );
		
		drag.elm.stopObserving( 'click', drag.doClick );
		drag.close.stopObserving( 'click', drag.doClose );
		
		Effect.SwitchOff( win, {afterFinish: function() {win.remove(); } } );
	},
	
	doMinimize: function( event ) {
		var src = Event.element( event );
		var win = src.up( '.window' );
		var content = win.down( '.content' );
		
		var drag = Dwindow.windows[win.id];
		
		scale = (src.getHeight() / win.getHeight())*100;
		
		Effect.BlindUp( win, {duration: 0.15, 
			scaleTo: scale, 
			restoreAfterFinish: false, 
			queue:'end',
			afterFinishInternal: function(effect) {
	        	effect.element.undoClipping();
	        	if ( content ) content.hide();
      		}
		});
		
		
		Effect.BlindDown( win, {duration: 0.15, scaleMode: 'contents', scaleFrom: 100, scaleTo: 200, restoreAfterFinish: false, queue:'end' } );
		
		Effect.BlindUp( win, {duration: 0.10, 
				restoreAfterFinish: false, 
				queue:'end', 
				scaleTo: 40,
				afterFinishInternal: function(effect) {
	        		effect.element.undoClipping();
      			} 
      	});
		
		src.stopObserving( 'click', drag.doMinimize );
		src.observe( 'click', drag.doMaximize );
	},
	
	doMaximize: function( event )  {
		var src = Event.element( event );
		var win = src.up( '.window' );
		var content = win.down( '.content' );
		var drag = Dwindow.windows[win.id];
		
		var scale = Math.floor( ( drag.fullHeight / win.getHeight() ) )*100;
		Effect.BlindDown( win, {duration: 0.15, scaleMode: 'contents', scaleFrom: 100, scaleTo: scale, restoreAfterFinish: false, afterFinish: function() {if ( content ) content.show();} } );
		
		src.stopObserving( 'click', drag.doMaximize );
		src.observe( 'click', drag.doMinimize );
	}
}