var Form = new Class({
	Implements : [Options],
	options : {
		'collapse' : true,
		'hideall' : false,
		'trigger' : 'click',
		'tinymce' : {
			'basic' : {
				'mode' : 'none',
				'theme' : 'advanced',
				'language' : 'nl',
				'verify_css_classes' : true,
				'convert_urls' : false,
				'entity_encoding' : 'raw',
				'invalid_elements' : 'font,span,xml',
				'theme_advanced_toolbar_location' : 'top',
				'theme_advanced_toolbar_align' : 'left'
			},
			'options' : {
				'theme_advanced_blockformats' : 'p,h1,h2,h3,h4',
				'plugins' : 'table,uploader',
				'theme_advanced_buttons1' : 'undo,redo,separator,formatselect,separator,bold,italic,separator,justifyleft,justifycenter,justifyright,separator,bullist,numlist,separator,code',
				'theme_advanced_buttons2' : 'tablecontrols,separator,image,link,unlink',
				'theme_advanced_buttons3' : ''
			},
			'enduseroptions' : {
				'theme_advanced_blockformats' : 'p,h1,h2,h3,h4',
				'extended_valid_elements' : 'a[name|href|target=_blank|title]',
				'plugins' : 'table,uploader',
				'theme_advanced_buttons1' : 'undo,redo,separator,link,unlink,separator,bold,italic,underline,separator,bullist,numlist',
				'theme_advanced_buttons2' : '',
				'theme_advanced_buttons3' : ''
			},
			'config' : {
				'mode' : 'none',
				'theme' : 'advanced',
				'language' : 'nl',
				'theme_advanced_buttons1' : 'undo,redo',
				'theme_advanced_buttons2' : '',
				'theme_advanced_buttons3' : '',
				'theme_advanced_toolbar_location' : 'top',
				'theme_advanced_toolbar_align' : 'left',
				'valid_elements' : ''
			}
		},
		'date' : {
			'days' : ['Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag'],
			'months' : ['Januari', 'Februari', 'Maart', 'April', 'Mei', 'Juni', 'Juli', 'Augustus', 'September', 'Oktober', 'November', 'December'],
			'dateformat' : 'Y-m-d',
			'datetimeformat' : 'Y-m-d H:i:00'
		},
		'autolocation' : true,
		'map' : {
			'zoom' : 15
		}
	},
	itsForm : null,
	itsTogglers : new Array(),
	itsElements : new Array(),
	itsAccordion : null,
	itsDefault : 0,
	initialize : function(form, options) {
		this.setOptions(options);
		this.itsForm = form;
		this.parseForm();
		this.parseInput();
	},
	parseForm : function() {
		if (!this.options.collapse)
			return true;
		this.itsForm.getElements('fieldset').each((function(element, i) {
			if (element.hasClass('form-fieldsetdefault'))
				this.itsDefault = i;
			var legend = element.getElement('legend');
			legend.setStyle('display', 'none');
			if (Browser.Engine.gecko) element = (new Element('div', {'class' : 'form-fieldset form-fieldset-wrapper'})).wraps(element); // Firefox fieldset workaround.
			var toggler = new Element('h2', {
				'class' : 'form-toggler',
				'html' : legend.innerHTML
			});
			toggler.inject(element, 'before');
			this.itsTogglers.push(toggler);
			this.itsElements.push(element);
		}).bind(this));
		this.setAccordion();
		return true;
	},
	setAccordion : function() {
		this.itsAccordion = new Fx.Accordion(this.itsTogglers, this.itsElements, {
			'opacity' : false,
			'show' : this.itsDefault,
			'onActive' : function(toggler, element) {
				toggler.addClass('form-toggler-active');
			},
			'onBackground' : function(toggler, element) {
				toggler.removeClass('form-toggler-active');
			},
			'alwaysHide' : this.options.hideall,
			'trigger' : this.options.trigger
		});
	},
	parseInput : function() {
		this.itsForm.getElements('.text').each((function(element, i) {
			// Location
			$try((function() {
				if (element.hasClass('text-location')) {
					var lat = 0,
						lng = 0;
					if (element.hasClass('text-locationmap')) {
						var mapElement = (new Element('div', {'class' : 'google-map form-input-map'})).inject(element, 'after'),
							location = new google.maps.LatLng(lat, lng),
							map = new google.maps.Map(mapElement, {
								'zoom' : this.options.map.zoom,
								'center' : location,
								'mapTypeId' : google.maps.MapTypeId.ROADMAP
							}),
							marker = new google.maps.Marker({
								'position' : location,
								'draggable' : true,
								'map' : map
							});
						/*google.maps.event.addListener(map, 'click', function(event) {
							updateLocation(event.latLng.lat(), event.latLng.lng());
						});*/
						google.maps.event.addListener(marker, 'dragend', function(event) {
							updateLocation(event.latLng.lat(), event.latLng.lng());
						});
					}
					var updateLocation = function(lat, lng) {
						element.set('value', lat + ', ' + lng);
						if (!(map instanceof google.maps.Map)) 
							return true;
						var location = new google.maps.LatLng(lat, lng);
						marker.setPosition(location);
						map.panTo(location);
						return true;	
					};
					if (element.get('value')) {
						if (match = (/(-?\d{1,4}(\.\d+)?)\s*,\s*(-?\d{1,4}(\.\d+)?)/).exec(element.get('value'))) 
							updateLocation(match[1], match[3]);
					} else if (navigator.geolocation && this.options.autolocation) {
						navigator.geolocation.getCurrentPosition(function (position) {
							lat = position.coords.latitude;
							lng = position.coords.longitude;
							updateLocation(lat, lng);
						});
					}
				}
			}).bind(this));
			// Date and time
			$try((function() {
				if (element.hasClass('text-datetime')) {
					new DatePicker(element, {
						'allowEmpty' : true,
						'timePicker' : true, 
						'format' : this.options.date.datetimeformat,
						'inputOutputFormat' : 'Y-m-d H:i:s',
						'days' : this.options.date.days,
						'months' : this.options.date.months
					});
				}
				if (element.hasClass('text-date')) {
					new DatePicker(element, {
						'allowEmpty' : true,
						'timePicker' : false, 
						'format' : this.options.date.dateformat,
						'inputOutputFormat' : 'Y-m-d',
						'days' : this.options.date.days,
						'months' : this.options.date.months
					});
				}
			}).bind(this));
			// TinyMCE
			$try((function() {
				if (element.hasClass('text-rte')) {
					var options = this.options.tinymce.basic;
					if (element.hasClass('text-rteenduser')) 
						$extend(options, this.options.tinymce.enduseroptions);
					else 
						$extend(options, this.options.tinymce.options);
					tinyMCE.init(options);
					tinyMCE.execCommand('mceAddControl', true, element);
				}
				
				if (element.hasClass('text-config')) {
					/*var options = $extend(this.options.tinymce.basic, this.options.tinymce.config)
					tinyMCE.init(options);
					tinyMCE.execCommand('mceAddControl', true, element);*/
				}
			}).bind(this));
		}).bind(this));
		return true;
	}
});
window.addEvent('load', function() {
	var options = {};
	$try(function() {
		$extend(options, cfg.form);
	});
	$$("form").each(function(form) {
		new Form(form, options);
	});
});

