var DefaultText = Class.create({
	initialize: function(element, text) { 
		element = $(element);
		text = text || '';
		this.type = DefaultText.getType(element);
		
		// Only allow this object to be set on a textarea or a password/text input field
		if (this.type == DefaultText.NONE)
		{
			throw new Error('Only a Text/Password input field or a Textarea is allowed');
		}

		this.element = element;
		
		// Use the text in the text field if no text is given
		this.text = (text.blank()) ? this.element.value : text;
		this.text.strip();
		
		this.element.observe('focus', this.onfocus.bindAsEventListener(this));
		this.element.observe('blur', this.onblur.bindAsEventListener(this));
		
		if (this.element.value.blank() || this.element.value.strip().toLowerCase() == this.text.toLowerCase()) {
			this.element.addClassName('default');

			this.active = true;
			
			if (!Prototype.Browser.IE && this.type == DefaultText.PASSWORD) {
				try { this.element.type = 'text'; } catch (e) { }
			}

			setTimeout(this.setdefault.bind(this), 0); // "default" class needs some time to process                                
		}
	},
	onfocus: function(event){
		if (!this.active) {
			return;
		}
		
		this.element.value = '';

		if (!Prototype.Browser.IE && this.type == DefaultText.PASSWORD) {
			try { this.element.type = 'password'; } catch (e) { }
		}
		
		this.element.removeClassName('default');
	},
	onblur: function(event){
		if (this.element.value.blank()) {
			this.active = true;
			
			if (!Prototype.Browser.IE && this.type == DefaultText.PASSWORD) {
				try { this.element.type = 'text'; } catch (e) { }
			}

			this.element.addClassName('default'); 
			setTimeout(this.setdefault.bind(this), 0); // "default" class needs some time to process
		} else {
			this.active = false;    
		}
	},
	setdefault: function() {
		this.element.value = this.text;
	}
});
 
Object.extend(DefaultText, {
	TEXTFIELD: 1,
	TEXTAREA: 2,
	PASSWORD: 3,
	NONE: 0,
	getType: function (element) {
		element = $(element);

		switch (element.tagName.toLowerCase()) {
			case 'input':
				switch (element.type.toLowerCase())     {
						case 'text':
								return DefaultText.TEXTFIELD;
						case 'password':
								return DefaultText.PASSWORD;
				}
				
				break;
			
			case 'textarea':
				return DefaultText.TEXTAREA;
		}
		
		return DefaultText.NONE
	}
});


// ----------------------------------------------------------------------------- //

Object.extend(Form.Methods, {
	setAction: function (form, value) {
		form = $(form);
		value = value || '';
		
		form.appendChild(new Element('input', { type: 'hidden', name: 'action', value: value }));
		
		return form;
	}
});

// ----------------------------------------------------------------------------- //

Event.observe(document, 'dom:loaded', function () { 
	$$('input.button, input.bigbutton, button.button, button.bigbutton')
		.invoke('observe', 'mouseover', function(event) { Event.element(event).addClassName('over'); })
		.invoke('observe', 'mouseout', function(event) { Event.element(event).removeClassName('over'); });

	$$('.form form div.upload').each(function(div) {
		var id = div.down('input[type="hidden"]');
		var key = id.next('input[type="hidden"]').getValue();
		id = id.getValue();
		
		div.down('input[type="button"]').observe('click', function (event, id, key) {
			options = new Hash();
			
			options.set('parameters', {'action':'remove', 'id': id, 'key': key});
			options.set('method', 'get');
			
			new Ajax.Request('/scripts/file.storage.php', options.toObject());
			
			this.replace(this.next('div').innerHTML.unescapeHTML());
		}.bindAsEventListener(div, id, key));
	});

	new Lib.Scroll.Banner();
});

// ----------------------------------------------------------------------------- //

var HelpText = Class.create({
	initialize: function(mark) { 
		// Bind
		this.show = this.show.bind(this);
		this.hide = this.hide.bind(this);
		this.cancel = this.cancel.bind(this);
		
		// Items
		this.mark = $(mark);
		this.text = this.mark.next('.item');
		this.input = this.mark.previous('input, textarea, select, button');
		
		// Observe
		this.mark.observe('mouseout', this.hide.curry(2000)).observe('mouseover', this.show);
		this.text.observe('mouseout', this.hide.curry(2000)).observe('mouseover', this.cancel);
		
		if (this.input) {
			// if textarea check if its a tinymce field
			if ( tinyMCE && (editor = tinyMCE.getEditorId(this.input.name)) ) {
				doc = tinyMCE.getInstanceById(editor).getDoc()
				
				// IE doesnt trigger document.onfocus
				if (Prototype.Browser.IE) {
					setTimeout(function () {
						Event.observe(doc.body, 'focus', this.show);
						Event.observe(doc.body, 'blur', this.hide.curry(0));
					}.bind(this), 0); // wait for the document to load
				} else {
					Event.observe(doc, 'focus', this.show);
					Event.observe(doc, 'blur', this.hide.curry(0));
				}
			} else {
				this.input.observe('focus', this.show).observe('blur', this.hide.curry(0));
			}
		}

		this.text.hide();
	},
	show: function() {
		if (!this.mark.visible()) { return; }
		
		$$('.faq.item').invoke('setStyle', {display: 'none'});

		this.cancel();
		this.text.setStyle({display: 'block'});
	},
	hide: function(timeout) {
		if (!this.timeout) {
			this.timeout = window.setTimeout(function () {
				Effect.Fade(this.text);
				this.timeout = false;
			}.bind(this), timeout);
		}
	},
	cancel: function() {
		if (this.timeout) { 
			window.clearTimeout(this.timeout); 
			this.timeout = false;
		}
	}
});

Event.observe(document, 'dom:loaded', function () { 
	if (tinyMCE) { tinyMCE.onLoad(); }

	$$('.faq.mark').each(function(elm){	new HelpText(elm); })
});

/*
doShow = function() {
	$$('.faq.item').invoke('setStyle', {display: 'none'});
}

doHide = function(timeout) {
	if (!this._hideTimeout) {
		this._hideTimeout = window.setTimeout(function () {
			Effect.Fade(this);
			this._hideTimeout = false;
		}.bind(this), timeout);
					
		this.stopObserving('mouseout', doHide);
	}
}

cancelHide = function() {
	if (this._hideTimeout) { 
		window.clearTimeout(this._hideTimeout); 
		this._hideTimeout = false;
	}
}

Event.observe(document, 'dom:loaded', function () { 
	$$('.faq.mark').each(function(elm){
		elm.observe('mouseover', function() { 
			$$('.faq.item').invoke('setStyle', {display: 'none'});
	
			elm = $(this).next('.item');
			this.observe('mouseout', doHide.bind(elm, 2000))
								
			cancelHide.bind(elm)();
			
			elm.setStyle({display: 'block'}).observe('mouseover', cancelHide.bind(elm)).observe('mouseout', doHide.bind(elm, 2000));
		});
		
		elm = elm.previous('input, textarea');
		elm;
	})
});
*/

// ----------------------------------------------------------------------------- //

var Lib = {};

Lib.Form = {};
Lib.Form.Hash = Class.create({
	initialize: function(form, name) { 
		form = $(form);
		name = name.toString();

		if (!(form.tagName && form.tagName.toLowerCase() == 'form')) {
			throw new TypeError('first argument needs to be a FORM.');
		}
		
		if (name.blank()) {
			throw new Error('a valid field name is required.');
		}
		
		this.form = form;
		this.name = name;
		
		this.form.getElements().each(function(element) { 
			if (element.name.toLowerCase() == this.name.toLowerCase()) { element.name = ''; } 
		});
	},
	set: function(value) {
		if (this.get(value)) { return this; } // check for double values
		
		// add the value as a hidden field to the form
		this.form.appendChild(new Element('input', { type: 'hidden', name: this.name + '[]', value: value }));
	
		return this;
	},
	get: function(value) {
		value = value.toString();
		
		if (value.blank()) { return false; }
		
		regex = new RegExp("^" + this.name + "(\\[.*\\])*$", "i");
		found = false;

		this.form.getInputs('hidden').each(function(element) {
			if (element.name.match(regex)) { 
				if (element.getValue().toLowerCase() == value.toLowerCase()) { 
					found = element;
					throw $break;
				}
			} 
		});
		
		return found;
	},
	unset: function(value) {
		value = value.toString();
		
		if (element = this.get(value)) {
			this.form.removeChild(element);
		}
		
		return this;
	},
	values: function() {
		result = new Array();
		
		regex = new RegExp("^" + this.name + "(\\[.*\\])*$", "i");
		
		this.form.getInputs('hidden').each(function(element) {
			if (element.name.match(regex)) { 
				result.push(element.getValue());
			} 
		});
		
		return result.uniq();
	}
});

// ----------------------------------------------------------------------------- //

Lib.Form.Selector = Class.create({
	initialize: function(form, name) { 
		this.form = $(form);
		this.name = name.toString();
		
		this.hash = new Lib.Form.Hash(this.form, this.name);
		
		Event.observe('input_' + this.name, 'keydown', this.onKeydown.bindAsEventListener(this));
		this.refresh();
	},
	add: function(value) {
		value = value.toString();
		
		if (value.blank()) { return; }
		
		this.hash.set(value);
		this.refresh();
	},
	refresh: function() {
		selector = $('selector_' + this.name).update();
	
		this.hash.values().sort().each(function(value) {
			option = new Element('option').update(value);
			option.observe('dblclick', this.onClick.bindAsEventListener(this));

			selector.insert(option, 'after');
		}.bind(this));
		
		$('input_' + this.name).setValue('');
	},
	remove: function(value) {
		value = value.toString();
		
		if (value.blank()) { return; }

		this.hash.unset(value);
		this.refresh();				
	},
	onKeydown: function(event) {
		if (event.keyCode == Event.KEY_RETURN) { 
			this.add(Event.element(event).getValue());
			Event.stop(event);
		}
	},
	onClick: function(event) {
		this.remove(Event.element(event).value);
	}
});

// ----------------------------------------------------------------------------- //

Lib.Scroll = {};
Lib.Scroll.Interval = Class.create({
	initialize: function(element, interval) { 
		this.element = $(element);
		this.interval = parseInt(interval);
		
		this.active = false;
		
		// draging of the scollbar
		this.element.observe("mousedown", this.onMouseDown.bindAsEventListener(this));
		document.observe("mouseup", this.onMouseUp.bindAsEventListener(this));

		// IE workaround as IE doesnt return a mouseup event on the scrollbar
		if (Prototype.Browser.IE) { document.observe("mousemove", this.onMouseMove.bindAsEventListener(this)); }

		// Scroll IE and Gecko
		this.element.observe('DOMMouseScroll', this.onScroll.bindAsEventListener(this));
		this.element.observe('mousewheel', this.onScroll.bindAsEventListener(this));
	},
	onMouseDown: function(event) {
		if (Event.isLeftClick(event)) {
			offset = this.element.viewportOffset();
			offset.left = event.clientX - offset.left + this.element.scrollLeft;
			offset.top = event.clientY - (offset.top + this.element.scrollTop);
			
			if (offset.left - this.element.clientWidth >= 0) {
				this.active = true;
				
				if (offset.top > this.element.clientHeight / 2) {
					this.direction = Lib.Scroll.DOWN;
				} else {
					this.direction = Lib.Scroll.UP;
				}
			}
		}
	},
	onMouseUp: function(event) {
		if (this.active) {
			this.active = false;
			
			switch (this.direction) {
				case Lib.Scroll.UP:
					this.element.scrollTop = Math.floor(this.element.scrollTop / this.interval) * this.interval;
					break;
					
				case Lib.Scroll.DOWN:
					this.element.scrollTop = Math.ceil(this.element.scrollTop / this.interval) * this.interval;
					break;
					
				default:
					this.element.scrollTop = Math.round(this.element.scrollTop / this.interval) * this.interval;
					break;
			}
		}
	},
	onMouseMove: function(event) {
		if (this.active) {
			// IE workaround as IE doesnt return a mouseup event on the scrollbar
			if (!Event.isLeftClick(event)) {
				this.onMouseUp(event);
			} else {
				this.direction = Lib.Scroll.SCROLL;
			}
		}
	},
	onScroll: function(event) {
		var wheelData = Math.round((event.detail ? event.detail * -1 : event.wheelDelta / 40) / 3);
		this.element.scrollTop = (Math.round(this.element.scrollTop / this.interval) - wheelData) * this.interval;

		Event.stop(event);
	}
});

Lib.Scroll.Banner = Class.create({
	initialize: function() { 
		this.elm = $A($$('.panel_dart_scrollable')).first();

		if (!this.elm) { return; }

		viewport = document.viewport.getScrollOffsets();

		this.offset = {
			'abs':0,
			'top':viewport.top
		};

		// this one always work
		Element.observe(window, 'scroll', this.onScroll.bindAsEventListener(this));

//		// Scroll IE and Gecko (smootscrolling)
//		Element.observe(window, 'DOMMouseScroll', this.onMousewheel.bindAsEventListener(this));
//		Element.observe(window, 'mousewheel', this.onMousewheel.bindAsEventListener(this));

		this.setPadding(document.viewport.getScrollOffsets());
	},
//	onMousewheel: function (event) {
//		viewport = document.viewport.getScrollOffsets();
//
//		this.offset = {
//			'abs':Math.abs(this.offset.top - viewport.top),
//			'top':viewport.top
//		};
//
//		wheelData = Math.round((event.detail ? event.detail * -1 : event.wheelDelta / 40) / 3);
//		viewport.top = viewport.top - (-1 * this.offset.abs);
//
//		this.setPadding(viewport);
//	},
	onScroll: function(event) {
		this.setPadding(document.viewport.getScrollOffsets());
	},
	getMaxPadding: function() {
		container = this.elm.up(1);
		container = container.cumulativeOffset().top - 15 + container.clientHeight;

		last = this.elm.up(0).immediateDescendants().last();
		last = last.cumulativeOffset().top + last.clientHeight;

		ret = (container - last) + this.getPadding();
		return ret < 0 ? 0 : ret;
	},
	getPadding: function() {
		ret = parseInt(this.elm.style.paddingTop);
		return (isNaN(ret)) ? 0 : ret;
	},
	setPadding: function(viewport) {
		element = this.elm.cumulativeOffset();

		padding = viewport.top - element.top;
		padding = (padding < 0) ? 0 : padding;

		this.elm.style.paddingTop = Math.min(padding, this.getMaxPadding()) + 'px';
	}
});

Object.extend(Lib.Scroll, {
	DOWN: 1,
	UP: 2,
	SCROLL: 3
});

// ----------------------------------------------------------------------------- //

Lib.Dialog = Class.create({
	initialize: function(url) { 
		// do somebinding
		this.close = this.close.bind(this);
		
		this._onResize = this._onResize.bindAsEventListener(this);
		this._onSubmit = this._onSubmit.bindAsEventListener(this);
		
		this._onCreate = this._onCreate.bind(this);
		this._onFailure = this._onFailure.bind(this);
		this._onSuccess = this._onSuccess.bind(this);
		this._onException = this._onException.bind(this);
	
		// Overlay
		var height = Math.max($$('html').first().getHeight(), document.viewport.getHeight(), document.body.offsetHeight) + 'px';
		this.overlay = new Element('div', {'class': 'overlay', style: 'height:' + height +'; width:100%; top:0px; position:absolute'});
		
		// Popup
		this.container = new Element('div', {style: 'top:' + (document.viewport.getScrollOffsets().top + 100) + 'px; position:absolute; width:100%;'});
		this.popup = new Element('div', {'class': 'popup'});
		this.button = new Element('input', {'class': 'button close', type: 'button'});
		this.content = new Element('div', {'class': 'content'});
		this.indicator = new Element('img', {src: '/images/indicator.gif', 'class': 'indicator'});

		// Add everything to gether
		//this.content.update(this.indicator);

		this.popup.insert(this.button, 'top');
		this.popup.insert(this.content, 'bottom');
		
		this.container.update(this.popup);
		
		// event listners
		this.overlay.observe('click', this.close.curry(false) );
		Element.observe(window, 'resize', this._onResize );
		//Element.observe(window, 'submit', this._onSubmit );
		
		this.container.observe('click', function(event) { if (Event.element(event) == this.container) { this.close(false); } }.bindAsEventListener(this) );
		//this.container.observe('resize', this.event.onResize );
		this.button.observe('click', this.close.curry(false) );
		
		$(document.body).insert(this.overlay, 'bottom');
		$(document.body).insert(this.container, 'bottom');
		
		// setup the ajax call
		options = new Hash();
		
		options.set('method', 'get');
		options.set('onCreate', this._onCreate );
		options.set('onFailure', this._onFailure );
		options.set('onSuccess', this._onSuccess );
		options.set('onException', this._onException );

		this.ajax = new Ajax.Request(url, options.toObject());
	},
	close: function(reload) {
		try { this.ajax.transport.abort(); } catch (ex) {}
		
		if (reload) {
			window.location.reload();
		} else {
			// remove the event listners
			Element.stopObserving(window, 'resize', this._onResize );
			//Element.stopObserving(window, 'submit', this._onSubmit );
			
			this.overlay.remove();
			this.container.remove();			
		}
	},
	_onResize: function(event) {
		// redo the overlay height
		var height = Math.max($$('html').first().getHeight(), document.viewport.getHeight(), document.body.offsetHeight, (this.container.offsetTop + this.container.getHeight() + 100)) + 'px';
		this.overlay.setStyle({'height': height});				
	},
	_onSubmit: function(event) {
		Event.stop(event);

		elm = Event.element(event);

		// setup the ajax call
		options = new Hash();
		
		options.set('onFailure', this._onFailure );
		options.set('onSuccess', this._onSuccess );
		options.set('onException', this._onException );

		this.ajax = elm.request(options.toObject());
		
		this.content.update(this.indicator);
	},
	//_onload: function() { this.content.update(this.iframe); },
	_onCreate: function() { this.content.update(this.indicator); },
	_onException: function(req, ex) { throw ex; this._onFailure(); },
	_onFailure: function() { this.content.update(Lib.Dialog.Error); },
	_onSuccess: function(transport) { 
		/*
		var iframe = new Element('iframe', {style: "width:100%; height:0px; border:none; overflow:hidden"});
		this.content.insert(iframe);
		//console.debug(iframe.contentDocument.body);
		
		//iframe.setStyle({width:'100%', height:'0px', border:'none', overflow: 'hidden'});
		var doc = (iframe.contentDocument || iframe.contentWindow.document);
		
		//alert(iframe.contentWindow.document);
		//alert(iframe.contentDocument);
		//alert(doc);
		
		doc.open();
		doc.write(transport.responseText);
		doc.close();
		//iframe.show();
		
		Element.addMethods();

		setTimeout(function() {
			this.indicator.remove();
			this.content.setStyle({height: doc.documentElement.scrollHeight + 10 + 'px'});
			iframe.setStyle({height:'100%'});
		}.bind(this), 0);
		*/
		//console.debug($A(iframe.contentDocument.body.down('.button.close, a.close')));
		//$A(iframe.down('.button.close, a.close')).invoke('observe', 'click', this.close);
		
		if (transport.responseText.blank()) {
			this.close(true);
		} else {
			try {
				this.content.update(transport.responseText.match(/<body.*>([\s\S]*)<\/body>/i)[0]);
				this.content.insert('<div class="clear"></div>');		
				$A(this.content.select('.bigbutton[rel~=popup.close], .button[rel~=popup.close], a[rel~=popup.close]')).invoke('observe', 'click', function (event) { this.close(false); Event.stop(event); }.bindAsEventListener(this) );
				$A(this.content.select('.bigbutton[rel~=popup.close.reload],.button[rel~=popup.close.reload], a[rel~=popup.close.reload]')).invoke('observe', 'click', function (event) { this.close(true); Event.stop(event); }.bindAsEventListener(this) );
				$A(this.content.select('form')).invoke('observe', 'submit', this._onSubmit );
			} catch (e){
				this.content.update(Lib.Dialog.Error);
			}

			// redo the overlay height
			var height = Math.max($$('html').first().getHeight(), document.viewport.getHeight(), document.body.offsetHeight, (this.container.offsetTop + this.container.getHeight() + 100)) + 'px';
			this.overlay.setStyle({'height': height});
		}		
	}
});

Lib.Dialog.Error = '<div class="error"><h1>Er is een fout opgestreden</h1></div>';
	
// ----------------------------------------------------------------------------- //

Element.addMethods();

// ----------------------------------------------------------------------------- //

try { 
	if (tinyMCE) {}
 } catch(e) { var tinyMCE = null; }