Cms.ModalForm = Class.create({
	form: null,
	window: null,
	options: null,
	
	initialize: function(form, options) {
		this.form = $(form);
		this.options = options;
		this.window = this.window_factory(form);
		//this.window = new Control.Modal(
		//	form, {
		//		
		//	}
		//);
		
		this.form.observe('submit', this.submitHandler.bind(this));
	},
	
	window_factory: function(container){  
		var window_header = new Element('div',{  
			className: 'window_header'  
		});  
		var window_title = new Element('div',{  
			className: 'window_title'  
		});  
		var window_close = new Element('div',{  
			className: 'window_close'  
		});  
		var w = new Control.Modal(container,Object.extend({  
			className: 'window',  
			closeOnClick: window_close,  
			draggable: window_header,
			//fade: true,  
			//insertRemoteContentAt: window_contents,  
			afterOpen: function(){  
				window_title.update(this.options.title)  
			}  
		},this.options || {}));  
		w.container.insert({top:window_header});  
		window_header.insert(window_title);  
		window_header.insert(window_close);  
		return w;  
	}, 
	
	submitHandler: function (e) {
		if (this.form.enctype == 'multipart/form-data' ) {
			AIM.submit(this.form, {
				onStart: this.AIMonCreate.bind(this),
				onComplete: this.AIMonComplete.bind(this)
			});
		}
		else {
			Event.stop(e);
		}
		
	},
	
	AIMonCreate: function () {
		this.window.close();
		if ( typeof this.options.ajax.onCreate == 'function' ) {
			this.options.ajax.onCreate(content);
		} 
	},
	AIMonComplete: function (responseBody) {
		var content;
		var response;
		if ( responseBody.isJSON() ) {
			response = { responseJSON: responseBody.evalJSON(), responseText: responseBody };
			content = response.responseJSON.content.unescapeHTML();
			
			if ( response.responseJSON.errors ) {
				if ( typeof this.options.ajax.onFailure == 'function' ) {
					this.options.ajax.onFailure(response);
				}  
			}
		}
		else {
			response = { responseText: responseBody, responseJSON: null };
			content = responseBody;
		} 


		if ( this.options.success ) {
			this.options.success.update(content);
		}
		
		if ( typeof this.options.ajax.onComplete == 'function' ) {
			this.options.ajax.onComplete(response);
		} 
	},
	
	open: function () {
		this.window.open();
	}
	
});
