/*
	shared.js
	v1.0 - 22/jul/2008 - Bob Kersten - Initial version.
	(C) Copyright 2008 Fellownet.
	All rights reserved.
*/

Element.addMethods(['input', 'select', 'textarea', 'button', 'a'], {
	my_disable: function(el_) {
		var el = $(el_);
		try {
			el.addClassName('disabled');
			el.setAttribute('disabled', 'disabled');
			el.old_onclick = el.onclick;
			el.onclick = function() { return false; }
		} catch(e_) {}
		return el;
	},
	my_enable: function(el_) {
		var el = $(el_);
		try {
			el.removeClassName('disabled');
			el.removeAttribute('disabled');
			el.onclick= el.old_onclick;
		} catch(e_) {}
		return el;
	}
} );

Element.addMethods(['input', 'textarea'], {
	my_focus: function(el_) {
		var el = $(el_);
		setTimeout( function() {
			try {
				el.focus();
			} catch(e_) {}
		}, 100);
	}
} );

Element.addMethods('form', {
	my_serialize: function(el_) {
		var el = $(el_);
		el.select('input').concat(el.select('textarea')).each( function(input_) {
			input_.setAttribute('oldvalue', input_.value);
			if (
				typeof(input_.getAttribute('title')) == 'string' &&
				input_.getAttribute('title') == $F(input_)
			) input_.setValue('');
		} );
		var result = el.serialize();
		el.select('input').concat(el.select('textarea')).each( function(input_) {
			if (typeof(input_.getAttribute('oldvalue')) == 'string') {
				input_.value = input_.getAttribute('oldvalue');
			}
		} );
		return result;
	},
	my_extend: function(el_) {
		var el = $(el_);

		if (typeof(el.events) != 'undefined') return;
		if (typeof(Form.dirtyflags) == 'undefined') Form.dirtyflags = new Hash();

		el.events = new Hash();
		el.events.set('onfocus', function() {
			try {
				this.removeClassName('default');
				if (this.getAttribute('title') == $F(this)) this.setValue('');
			} catch(e_) {}
		} );
		el.events.set('onblur', function() {
			try {
				if ($F(this) == '') {
					this.addClassName('default');
					this.setValue(this.getAttribute('title'));
				}
			} catch(e_) {}
		} );
		el.events.set('onchange', function() {
			var self = this;
			Form.dirtyflags.set(this.parentform.getAttribute('id'), true);
			this.linked.each( function(field_) {
				try {
					if (
						$F(self.parentform[field_]) == '' ||
						$F(self.parentform[field_]) == $(self.parentform[field_]).getAttribute('title') ||
						$F(self.parentform[field_]) == $(self.parentform[field_]).getAttribute('force_title')
					) {
						$(self.parentform[field_]).setValue($F(self));
						$(self.parentform[field_]).removeClassName('default');
					}
					$(self.parentform[field_]).setAttribute('force_title', $F(self));
				} catch(e_) {}
			} );
		} );


		el.getElements().each( function(input_) {
			var def = input_.getAttribute('title');
			if (typeof(def) == 'string') {
				if ($F(input_) == '') input_.setValue(def);
				if ($F(input_) == def) input_.addClassName('default');
				Event.observe(input_, 'focus', el.events.get('onfocus').bindAsEventListener(input_));
				Event.observe(input_, 'blur', el.events.get('onblur').bindAsEventListener(input_));
			}
			var linked = input_.getAttribute('linked');
			if (typeof(linked) == 'string') {
				input_.linked = $A(linked.split(','));
			} else input_.linked = new Array();
			input_.parentform = el;
			Event.observe(input_, 'change', el.events.get('onchange').bindAsEventListener(input_));
		} );

		return el;
	},
	set_dirty:function(el_) { Form.dirtyflags.set(el_.getAttribute('id'), true); },
	is_dirty:function(el_) { return typeof(Form.dirtyflags.get($(el_).getAttribute('id'))) == 'boolean' && Form.dirtyflags.get($(el_).getAttribute('id')); },
	is_clean:function(el_) { return ! $(el_).is_dirty(); },
	ignore:function(el_) { Form.dirtyflags.set($(el_).getAttribute('id'), false); },
	my_submit:function(el_, options_) {
		var el = $(el_);
		if (typeof(Form.dirtyflags) == 'undefined') Form.dirtyflags = new Hash();

		var options = $H( {
			modal:true,
			button:false,
			buttons:'Sluiten',
			button_default:false,
			button_cancel:false,
			action:'untitled.html'
		} );
		options.update($H(options_));

		var dlg;
		if (
			options.get('modal') &&
			typeof(dialog) != 'undefined' &&
			typeof(dlg = dialog.onTop()) != 'boolean'
		) return false;

		if (typeof(options.get('button')) !== 'boolean') {
			if (typeof(options.get('button')) == 'string') {
				options.set('button', $A(options.get('button').split(',')));
			} else {
				var buttons = new Array(options.get('button'));
				options.set('button', $A(buttons));
			}



			options.get('button').each( function(button_) {
				$(button_).my_disable();
			} );
		}

		el.select('.field_error').each( function(field_) {
			field_.removeClassName('field_error');
		} );

		var marker = el.appendChild(new Element('input', {
			'type':'hidden',
			'name':'__ajaxcall',
			'value':'1'
		} ));

		new Ajax.Request(
			options.get('action'), {
				method:'post',
				parameters:el.my_serialize(),
				onComplete:function(req_) {
					el.removeChild(marker);

					var results = req_.responseText.toQueryParams();
					if (typeof(results['result']) != 'string') {
						alert(req_.responseText);
						if (typeof(options.get('button')) !== 'boolean') {
							$(options.get('button')).each( function(button_) {
								$(button_).my_enable();
							} );
						}
						if (typeof(options.get('onError')) == 'function') options.get('onError')(results);
					} else {
						switch(results['result']) {
							case 'OK':
								Form.dirtyflags.set(el.getAttribute('id'), false);
								if (typeof(options.get('onSuccess')) == 'function') options.get('onSuccess')(results);
								break;
							case 'NOTICE':
								Form.dirtyflags.set(el.getAttribute('id'), false);
								dialog.open( {
									content:'<p>' + results['content'] + '</p>',
									title:results['title'],
									buttons:options.get('buttons'),
									button_default:options.get('button_default'),
									button_cancel:options.get('button_cancel'),
									width:380,
									duration:0,
									callback:function(action_, dialog_) {
										try {
											dialog_.close( function() {
												if (typeof(options.get('button')) !== 'boolean') {
													$(options.get('button')).each( function(button_) {
														$(button_).my_enable();
													} );
												}
												if (typeof(el[errors[0]]) != 'undefined') el[errors[0]].my_focus();
											} );
										} catch(e_) {}
										if (typeof(options.get('onSuccess')) == 'function') options.get('onSuccess')(results);
									}
								} );
								break;
							default:
								var errors;
								try {
									(errors = $A(results['fields'].split(';'))).each( function(field_) {
										if (typeof(el[field_]) != 'undefined') {
											Element.addClassName(el[field_], 'field_error');
										}
									} );
								} catch(e_) {}
								dialog.open( {
									content:'<p>' + results['content'] + '</p>',
									title:results['title'],
									buttons:options.get('buttons'),
									button_default:options.get('button_default'),
									button_cancel:options.get('button_cancel'),
									width:380,
									duration:0,
									callback:function(action_, dialog_) {
										try {
											dialog_.close( function() {
												if (typeof(options.get('button')) !== 'boolean') {
													$(options.get('button')).each( function(button_) {
														$(button_).my_enable();
													} );
												}

												if (typeof(el[errors[0]]) != 'undefined') el[errors[0]].my_focus();
											} );
										} catch(e_) {}
										if (typeof(options.get('onError')) == 'function') options.get('onError')(action_, results);
									}
								} );
								break;
						}
					}
				}
			}
		);
		return el;
	}
} );