/*description: Overlay*/
var Overlay=new Class({Implements:[Options,Events],options:{id:"overlay",color:"#000",duration:500,opacity:0.5,zIndex:5000},initialize:function(a,b){this.setOptions(b);this.container=document.id(a);this.overlay=new Element("div",{id:this.options.id,opacity:0,styles:{position:"absolute",background:this.options.color,left:0,top:0,"z-index":this.options.zIndex},events:{click:function(){this.fireEvent("click");}.bind(this)}}).inject(this.container);this.tween=new Fx.Tween(this.overlay,{duration:this.options.duration,link:"cancel",property:"opacity",onStart:function(){this.overlay.setStyles({width:"100%",height:this.container.getScrollSize().y});}.bind(this),onComplete:function(){this.fireEvent(this.overlay.get("opacity")==this.options.opacity?"show":"hide");}.bind(this)});},open:function(){this.fireEvent("open");this.tween.start(this.options.opacity);return this;},close:function(){this.fireEvent("close");this.tween.start(0);return this;}});
var MooDialog = new Class({
	Implements: [Options,Events],
	options: {
		size: {
			width: 300,
			height: 100
		},
		offset: {
			x: 0,
			y: -100
		},
		title: null,
		scroll: true,
		jsscroll: false,
		useEscKey: true,
		disposeOnClose: true,
		closeButton: true,
		fx: {
			type: 'tween',
			open: 1,
			close: 0,
			options: {
				property: 'opacity',
				duration: 400
			}
		}/*,
		onOpen: $empty,
		onClose: $empty,
		onShow: $empty,
		onHide: $empty*/
	},

	initialize: function(options){
		this.setOptions(options);

		var x = this.options.size.width,
			y = this.options.size.height;
		if (this.options.scroll == true && this.options.jsscroll == false){
			var position = 'fixed';
		}else{
			var position = 'absolute';
		}
		
		this.wrapper = new Element('div', {
			'class': 'MooDialog',
			styles: {
				width: x,
				height: y,
				position: position,
				'z-index': 6000,	
				opacity: 0
			}
		}).inject(document.body);
		
		if (this.options.scroll == true && this.options.jsscroll == true){
			window.addEvent('scroll', function(){
				var docSize = document.id(document.body).getSize();
				this.setPosition((docSize.x - x)/2,(docSize.y - y)/2);
			}.bind(this))
		}

		this.content = new Element('div', {
			styles: {
				width: x,
				height: y,
				overflow: 'auto'
			}
		}).inject(this.wrapper);

		if(this.options.title){
			this.title = new Element('div',{
				'class': 'title',
				'text': this.options.title
			}).inject(this.wrapper);
			this.wrapper.addClass('MooDialogTitle');
		}
		
		if(this.options.closeButton){
			this.closeButton = new Element('a',{
				'class': 'close',
				events: {
					click: function(){
						this.close();
					}.bind(this)
				}
			}).inject(this.wrapper);
		}

		
		// Set the position of the dialog
		var docSize = document.id(document.body).getSize();
		this.setPosition((docSize.x - x)/2,(docSize.y - y)/2);
		
/*		// IE 6 scroll
		if(this.options.scroll && Browser.Engine.trident && Browser.Engine.version <= 4){
			window.addEvent('scroll',function(e){
				this.setPosition((docSize.x - x)/2,(docSize.y - y)/2,true);
			}.bind(this));
		}
*/
		// Add the fade in/out effects if no other effect is defined
		if(!this.fx){
			this.fx = this.options.fx.type == 'morph' ? 
				new Fx.Morph(this.wrapper,this.options.fx.options) : 
				new Fx.Tween(this.wrapper,this.options.fx.options);
		}
		this.fx.addEvent('complete',function(){
			this.fireEvent(this.open ? 'show' : 'hide');
			if (this.options.disposeOnClose && !this.open) {
				this.dispose();
			}			
		}.bind(this));
		
		this.overlay = new Overlay(document.body, {
			onClick: function(){
				//this.close();
			}.bind(this),
			duration: this.options.fx.options.duration
		});
	},

	setContent: function(content){
		this.content.empty();
		switch($type(content)){
			case 'element':
				this.content.adopt(content);
			break;
			case 'string':
			case 'number':
				this.content.set('text',content);
			break;
		}
		return this;
	},
	
	setPosition: function(x,y,relative){
		x = x + this.options.offset.x;
		y = y + this.options.offset.y;
		x = x < 10 ? 10 : x;
		y = y < 10 ? 10 : y;
		if(this.wrapper.getStyle(relative || 'position') != 'fixed'){
			var scroll = document.id(document.body).getScroll();
			x = x + scroll.x;
			y = y + scroll.y
		}
		this.wrapper.setStyles({
			left: x,
			top: y
		});
		return this;
	},

	open: function(){
		this.open = true;
		this.fireEvent('open');
		this.fx.start(this.options.fx.open);
		this.overlay.open();
		
		if(this.options.useEscKey){
			// Add event for the esc key
			document.id(document.body).addEvent('keydown', function(e){
				if (e.key == 'esc') this.close();
			}.bind(this));
		}
		return this;
	},
	
	close: function(){
		this.open = false;
		this.fireEvent('close');
		this.fx.start(this.options.fx.close);
		this.overlay.close();
		return this;
	},
	
	dispose: function(){
		this.wrapper.destroy();
		this.overlay.overlay.destroy();
	},
	
	toElement: function(){
		return this.wrapper;
	}
	
});



Element.implement({
	MooDialog: function(options){
		var box = new MooDialog(options)
			.setContent(this)
			.open();
		this.store('MooDialog',box);
		return this;
	}
});

/*
description:     MooDialog.Alert
*/

MooDialog.Alert = new Class({	
	
	Extends: MooDialog,	

	options: {
		okText: 'Ok',
		focus: true
	},

	initialize: function(msg,options){
		this.parent(options);
		
		var okButton = new Element('input',{
			type: 'button',
			events: {
				click: function(){
					this.close();
				}.bind(this)
			},
			value: this.options.okText
		});
		
		this.setContent(
			new Element('div').adopt(
					new Element('p',{
						'class': 'MooDialogAlert',
						text: msg
					})
				).adopt(
					new Element('div',{
						'class': 'buttons'
					}).adopt(okButton)
				)
		).open();	

		if(this.options.focus){
			this.addEvent('show',function(){
				okButton.focus();
			});
		}

	}
});

/*
description:     MooDialog.Confirm
*/

MooDialog.Confirm = new Class({	
	
	Extends: MooDialog,	

	options: {
		okText: 'Ok',
		cancelText: 'Cancel',
		focus: true
	},

	initialize: function(msg,fn,fn1,options){
		this.parent(options);
		
		fn = fn ? fn : $empty;
		fn1 = fn1 ? fn1 : $empty;
		
		var cancelButton = new Element('input',{
			type: 'button',
			events: {
				click: function(){
					fn1();
					this.close();
				}.bind(this)
			},
			value: this.options.cancelText
		});
		
		this.setContent(
			new Element('div')
				.adopt(
					new Element('p',{
						'class': 'MooDialogConfirm',
						text: msg
					})
				).adopt(
					new Element('div',{
						'class': 'buttons'
					}).adopt(cancelButton).adopt(
						new Element('input',{
							type: 'button',
							events: {
								click: function(){
									fn();
									this.close();
								}.bind(this)
							},
							value: this.options.okText
						})
					)
				)
		).open();
		
		if(this.options.focus){
			this.addEvent('show',function(){
				cancelButton.focus();
			});
		}
	}
});


Element.implement({
	confirmLinkClick: function(msg,options){
		this.addEvent('click',function(e){
			e.stop();
			new MooDialog.Confirm(msg,function(){
				location.href = this.get('href');
			}.bind(this),null,options)
		});
		return this;
	},
	confirmFormSubmit: function(msg,options){
		this.addEvent('submit',function(e){
			e.stop();
			new MooDialog.Confirm(msg,function(){
				this.getElements('input').each(function(el){
					if(el.get('type') == 'submit') el.set('type','hidden');
				});
				this.submit();
			}.bind(this),null,options)
		}.bind(this));
		return this;
	}	
});

/*
description:     MooDialog.Form
Requared MooForm
Dialog to send email to user
*/

MooDialog.Form = new Class({
	Extends: MooDialog,

	options: {
		okText: 'Ok',
		cancelText: 'Cancel',
		runerror: 'Runtime error, contact support.',
		focus: true,
		scroll: true,
		jsscroll: true,
		baseParams: {},
		size: {
			width: 425,
			height: 60
			
			//width: 425,
			//height: 290
		},
		form:{
			url: '',
			onComplete: null
		},
		useDefaultButtons: true,
		defaultButtons: {
			ok: {
				onClick: function(){
					this.submit();
				}, lable: 'okText'
			},
			cancel: {
				onClick: function(){
					this.close();
				}, lable: 'cancelText'
			}
		},
		formConfig: null,
		onComplete: $empty,
		beforeSubmit: null
	},
	
	defaultButton: {
		lable: '',
		onClick: function(){}
	},
	innerForm: null,
	buttons: {},

	initialize: function(options){
		this.parent(options);
		if (this.options.useDefaultButtons == true){
			this.setButtons(this.options.defaultButtons);
		}
		var c = this.options.form;
		if (this.options.scroll == false || this.options.jsscroll == true){
			this.options.masked = true;
		}else{
			this.options.masked = false;
		}
		c['masked'] = false;
		c['baseParams'] = this.options.baseParams;
		this.innerForm = new MooAjaxForm(null, c);
		this.innerForm.addEvent('resize', function(size, form){
			var y = size.y + this.options.size.height;
			this.wrapper.setStyle('height', y);
			this.content.setStyle('height', y);
		}.bind(this));
		this.innerForm.addEvent('mask', function(){
			if (this.options.masked) {
				this.content.mask();
			}
		}.bind(this));
		this.innerForm.addEvent('unmask', function(){
			if (this.options.masked) {
				this.content.unmask();
			}
		}.bind(this));
		this.setFormEvents();
		if (this.options.formConfig){
			this.initForm(this.options.formConfig);
		}
	},
	
	setFormEvents: function(){
		this.innerForm.addEvent('success', function(form, data){
			this.fireEvent('complete', [this, data]);
			this.close();
		}.bind(this));
		this.innerForm.addEvent('fail', function(form, data){
			this.content.unmask();
			if (data.errors){
				var err = '';
				$each(data.errors, function(text){
					err += text + '\n';
				}.bind(this));
				if (err != ''){
					new MooDialog.Alert(err);
				}
			}else{
				new MooDialog.Alert(this.options.runerror);
			}
		}.bind(this));
	},
	
	initForm: function(formConfig){
		if (formConfig instanceof Object ){
			this.innerForm.setElements(formConfig);
		}else{
			this.innerForm.setContent(formConfig);
		}
		var buttons = new Element('div', {
			'class': 'buttons'
		});
		$each(this.buttons, function(b){
			buttons.adopt(b);
		}.bind(this));
		this.setContent(
			new Element('div').adopt(
				new Element('div').adopt(
					this.innerForm.getForm(),
					new Element('div', {'class': 'clear'})
				), buttons
			)
		).open();
		
		this.innerForm.onResize();

		if(this.options.focus){
			this.addEvent('show',function(){
				if (this.buttons['ok']) this.buttons['ok'].focus();
			}.bind(this));
		}
	},
	
	setButtons: function(config){
		$each(config, function(c, index){
			this.addButton(index, c);
		}.bind(this));
	},
	
	addButton: function(name, config){
		config = $extend(this.defaultButton, config);
		if(config.lable == 'false') return false;
		var l = $chk(this.options[config.lable])?this.options[config.lable]:config.lable;
		var b = new Element('input',{
			type: 'button',
			events: {click: config.onClick.bind(this)},
			value: l
		});
		this.buttons[name] = b;
	},
	
	submit: function(){
		if(typeof this.options.beforeSubmit == "function"){
			this.options.beforeSubmit();
		}
		this.innerForm.submit();
	}
});

/*
description:     MooDialog.Mail
Dialog to send email to user
*/
MooDialog.Mail = new Class({
	Extends: MooDialog.Form,
	options: {
		subjectText: 'Subject',
		bodyText: 'Text'
	},
	
	initialize: function(id, subject,options){
		this.parent(options);
		var formConfig = [
			{
				xtype: 'hidden',
				name: 'viewer_id',
				value: id
			},{
				xtype: 'input',
				lable: this.options.subjectText,
				'class': 'inp-text big',
				name: 'subject',
				value: subject
			},{
				xtype: 'textarea',
				lable: this.options.bodyText,
				'class': 'textarea-input',
				name: 'body'
			}
		];
		this.initForm(formConfig);
	}
});


MooDialog.Mail2 = new Class({
	Extends: MooDialog.Form,
	options: {
		subjectText: 'Subject',
		bodyText: 'Text'
	},
	
	initialize: function(id, subject,options){
		this.parent(options);
		var formConfig = [
			{
				xtype: 'hidden',
				name: 'viewer_id',
				value: id
			},{
				xtype: 'hidden',
				'class': 'inp-text big',
				name: 'subject',
				value: subject
			},{
				xtype: 'textarea',
				lable: this.options.bodyText,
				'class': 'textarea-input',
				name: 'body'
			}
		];
		this.initForm(formConfig);
	}
});


/*
description:     MooDialog.Event
Dialog to edit calendar events
*/
MooDialog.Event = new Class({
	Extends: MooDialog.Form,
	options: {
		eventName: 'Name',
		eventDescription: 'Details',
		deleteText: 'Delete Event',
		title: '',
		dateFormat: '%d/%m/%Y'
	},
	
	initialize: function(options, values){
		this.parent(options);
		if (!$chk(values)) values = {};
		var formConfig = [];
		var formConfig = [
			{
				xtype: 'hidden',
				name: 'old',
				value: $chk(values.old)?values.old:''
			},{
				xtype: 'date',
				lable: 'Date',
				'class': 'inp-text big',
				name: 'date',
				value: $chk(values.date)?values.date.clone():''
			},{
				xtype: 'text',
				name: 'title',
				'class': 'inp-text big',
				lable: this.options.eventName,
				value: $chk(values.title)?values.title:''
			},{
				xtype: 'textarea',
				lable: this.options.eventDescription,
				name: 'description',
				'class': 'textarea-input',
				value: $chk(values.description)?values.description:''
			}
		];
		
		if (values.title && values.past == false){
			var d = values.date.format(this.options.dateFormat);
			//var d = values.date;
			//Add delete button
			this.addButton('delete', {
				onClick: function(){
					this.innerForm.mask();
					var request = new Request.JSON({
						url: this.innerForm.options.url,
						onSuccess: function(json, response){
							this.innerForm.unmask();
							if (json.success){
								this.fireEvent('complete', [this, json]);
								this.close();
							}else{
								new MooDialog.Alert(json.errors);
							}
						}.bind(this)
					});
					var v = {format: 'json',cmd: 'delete',date: d};
					request.send({data: $merge(v, this.options.baseParams)});
				},
				lable: this.options.deleteText
			});
		}
		
		this.initForm(formConfig);
	}
});
