var CONFIG = {};

window.addEvent('domready', function() {
	CONFIG.BASE_URL = $(document.head).getElement('base').get('href');
	
	if($('visual'))
	{
		var objVisual = new Visual('visual','#visual > div.slide');
		objVisual.start();
	}
	
	if($$('select')) {
		new CustomSelect();
	}

	if($('subject') && $('level')) {
		new SelectSubject($('level'), $('subject'));
	}
	
	if($('ad_subject') && $('ad_level')) {
		new SelectSubject($('ad_level'), $('ad_subject'));
	}

	var objFormCheck = new FormCheck('signup', { display: { showErrors: 1 } });
	var objFormCheck2 = new FormCheck('search_form', { display: { showErrors: 1 } });
	
	/*$('login').addEvent('click', function(e)
	{
		e.stop();
		this.toggleClass('open');
		$('login_box').toggleClass('open');
		if($('username'))
		{
			$('username').focus();
		}
	});
	
	$(document.body).addEvent('click',function(e) {
		if($$('div.login')[0] && !e.target || !$(e.target).getParents().contains($$('div.login')[0])) { 
			$('login').removeClass('open');
			$('login_box').removeClass('open');
		}
	});*/

	
	var objFocus = new FormFocus('step2');
	var objFocus = new FormFocus('step3');
									 
	var objTooltips = new Tips('.tooltip', 
	{ 
		'fixed':true,
		'offset':
		{
			'x':16,
			'y':16
		},
		title: function(elItem)
		{
			var strTitle = elItem.title;
			if($('tooltip_title_' + strTitle))
			{
				elItem.get('tip');
				elItem.set('tip', strTitle);
				return $('tooltip_title_' + strTitle).innerHTML;
			}
			else
			{
				return '';
			}
		},
		text: function(elItem)
		{
			var strTitle = elItem.get('tip');
			if(strTitle)
			{
				return $('tooltip_text_' + strTitle).innerHTML;
			}
			else
			{
				return '';	
			}
		},
		'hideDelay': 300
	});

	//var objUpload = new MultipleUpload('.upload');
	
	if($$('div.faq').length > 0)
	{
		var objAccordion = new Fx.Accordion($$('div.faq strong.the-question'), $$('div.faq p.answer'),
		{
			initialDisplayFx: false,
			alwaysHide: true,
			onActive: function(toggler, element)
			{
				toggler.addClass('open');
			},
			onBackground: function(toggler, element)
			{
				toggler.removeClass('open');
			}
		});
	}
	
	$$('a.toggler').addEvent('click', function(e) {
		e.stop();
	});
	
	if($('subjects')) {
		var objAccordion = new Fx.Accordion($$('.toggler'), $$('.element'), {
			initialDisplayFx: false,
			alwaysHide: true,
			onActive: function(toggler, element) {
				toggler.addClass('open');
			},
			onBackground: function(toggler, element) {
				toggler.removeClass('open');
			}
		});
	}
	
	$$('input.value').each(function(elInput)
	{
		elInput.addEvent('focus', function()
		{
			doClear(elInput);
		});
		elInput.addEvent('blur', function()
		{
			resetField(elInput);
		});
	});
	
	if($('zipcode'))
	{
		$('zipcode').addEvent('keyup', function()
		{
			this.value = this.value.toUpperCase();
		});
	}
	
	/*$('signup').addEvent('submit', function(e)
	{
		$$('input').each(function(elInput)
		{
			if(elInput.value == elInput.defaultValue && !elInput.hasClass('submit'))
			{
				elInput.value = '';
				elInput.addClass('error');
				e.stop();
				return;
			}
		});
	});*/
	
	if($('btn-email'))
	{	
		$('btn-email').addEvent('click', function(e)
		{
			e.stop();
			document.location = $(document).location.pathname + $(document).location.search + '#email';
			$('user-email').toggleClass('show');
		});
	}
	
	if($('btn-phone'))
	{	
		$('btn-phone').addEvent('click', function(e)
		{
			e.stop();
			this.set('html', this.getNext('div.hidden').get('html'));
		});
	}
	
	
});

function doClear(field) 
{
	if (field.value == field.defaultValue) 
	{
	 	field.value = "";
		field.removeClass('inactive');
	}
}
function resetField(field) 
{
	if (field.value == '') 
	{
		field.value = field.defaultValue;
		field.addClass('inactive');
	}
}
function valueCheck(el){
    if (el.value == el.defaultValue) {
        el.errors.push('<strong>' + el.defaultValue + "</strong><br />Dit veld is verplicht.");
        return false;
    } else {
        return true;
    }
}
function postcodeCheck(el){
	if(!el.value.match(/^[1-9]\d{3}[A-Z]{2}$/i))
	{
		el.errors.push("Dit is geen geldige postcode. Een geldige postcode bestaat uit 4 cijfers, gevolgd door 2 letters.");
		return false;
	} else {
		return true;
	}
}


var FormFocus = new Class({
	initialize: function(argStrFormClass) 
	{
		var self = this;
		
		if($$('form.' + argStrFormClass))
		{	
			$$('form.' + argStrFormClass).getElements('.f').each(function(elInput,i)
			{
				elInput.addEvents({
					'focus': function()
					{
						self.doFocus(this);
					},
					'blur': function()
					{
						self.doFocus(this);
					}
				});
			});
		}
	},
	doFocus: function(elInput)
	{
		if(elInput.get('type') == 'radio' && elInput.getParent().get('class') == 'options')
		{
			if($defined(elInput.getParent().getPrevious('label.legend')))
			{
				elInput.getParent().getPrevious('label.legend').toggleClass('focus');
			}
			else
			{
				elInput.getParent().getPrevious('label').toggleClass('focus');
			}
		}
		else
		{
			if($defined(elInput.getPrevious('label.legend')))
			{
				elInput.getPrevious('label.legend').toggleClass('focus');
			}
			else
			{
				elInput.getPrevious('label').toggleClass('focus');
			}
		}
		elInput.toggleClass('focus');	
	}
});


var Visual = new Class({
	
	//implements
	Implements: [Options, Events],

	options: {
		showDuration: 7000,
		currentIndex: 0,
		tocLeft: 8,
		tocRight: 40,
		tocMargin: 3,
		tocWidth: 10,
		tocActive: 'toc-active'
	},
	
	initialize: function(container, elements, options) {
		this.setOptions(options);
		
		this.container = $(container);
		this.elements = $$(elements);
		this.currentIndex = 0;
		this.interval = '';
		this.toc = [];
		
		this.elements.each(function(el,i){
			this.toc.push(new Element('a',{
				//text: i+1,
				href: '#',
				rel: i,
				'class': 'toc' + (i == 0 ? ' ' + this.options.tocActive : ''),
				events: {
					click: function(e) {
						if(e) e.stop();
						this.stop();
						this.show(i);
					}.bind(this)
				}
			}).inject(this.container));

			this.toc.each(function(el,i){
				//el.setStyle('left', (this.options.tocLeft + (this.options.tocWidth + this.options.tocMargin) * (this.elements.length - i - 1))+'px');
				el.setStyle('left', (this.options.tocLeft + (this.options.tocWidth + this.options.tocMargin) * i)+'px');
			},this);
		},this);
		
		this.container.addEvents({
			mouseenter: function() { this.stop();  }.bind(this),
			mouseleave: function() { this.resume(); }.bind(this)
		});
	},
	
	show: function(to) {
		this.elements[this.currentIndex].fade('out');
		this.toc[this.currentIndex].removeClass(this.options.tocActive);
		this.elements[this.currentIndex = ($defined(to) ? to : (this.currentIndex < this.elements.length - 1 ? this.currentIndex + 1 : 0))].fade('in');
		this.toc[this.currentIndex].addClass(this.options.tocActive);
	},
	
	start: function() {
		this.show(0);
		this.elements.fade('hide');
		this.elements[0].fade('show');
		this.interval = this.show.bind(this).periodical(this.options.showDuration);
	},

	stop: function() {
		$clear(this.interval);
	},
	
	resume: function() {
		this.interval = this.show.bind(this).periodical(this.options.showDuration);
	}

});

var SelectSubject = new Class(
{
	initialize: function(argElLevel, argElSubject)
	{
		// set selected subject
		var subjectSelected = argElSubject.get('rel');
		
		argElLevel.addEvent('change', function() {		
			var intLevelId = this.get('value');
			
			argElSubject.getChildren().dispose();
				
			var objRequest = new Request({
				url: 'index/getsubjects?level_id=' + intLevelId,
				method: 'get',
				onSuccess: function(response)
				{
					var arrData = JSON.decode(response);
					
					if(arrData.length > 0)
					{	
						var selectedSet = false;			
						arrData.each(function(objData, index)
						{
							var elOption = new Element('option',
							{
								'value': objData.id,
								'html': objData.title,
								'selected': subjectSelected==objData.id ? 'selected' : ''
							});
							
							elOption.inject(argElSubject);
							
							if(subjectSelected==objData.id) {
								selectedSet = true;
							}
						});
						
						var elDefaultOption = new Element('option',
						{
							'value': 0,
							'html': 'Kies je vak...',
							'selected': selectedSet ? '' : 'selected'
						});
						
						elDefaultOption.inject(argElSubject, 'top');
						
						new Element('option', {
							'value': 0,
							'html': 'Voeg een vak toe',
							'events': {
								'click': function(e) {
									e.stop();
									
									window.location = CONFIG.BASE_URL + 'vak/toevoegen';
								}
							}
						}).inject(argElSubject);
					}
				}
			}).send();
		});
				
		argElLevel.fireEvent('change');
	}
});

/*
Function: $get
	This function provides access to the "get" variable scope + the element anchor

Version: 1.3

Arguments:
	key - string; optional; the parameter key to search for in the url's query string (can also be "#" for the element anchor)
	url - url; optional; the url to check for "key" in, location.href is default

Example:
	>$get("foo","http://example.com/?foo=bar"); //returns "bar"
	>$get("foo"); //returns the value of the "foo" variable if it's present in the current url(location.href)
	>$get("#","http://example.com/#moo"); //returns "moo"
	>$get("#"); //returns the element anchor if any, but from the current url (location.href)
	>$get(,"http://example.com/?foo=bar&bar=foo"); //returns {foo:'bar',bar:'foo'}
	>$get(,"http://example.com/?foo=bar&bar=foo#moo"); //returns {foo:'bar',bar:'foo',hash:'moo'}
	>$get(); //returns same as above, but from the current url (location.href)
	>$get("?"); //returns the query string (without ? and element anchor) from the current url (location.href)

Returns:
	Returns the value of the variable form the provided key, or an object with the current GET variables plus the element anchor (if any)
	Returns "" if the variable is not present in the given query string

Credits:
		Regex from [url=http://www.netlobo.com/url_query_string_javascript.html]http://www.netlobo.com/url_query_string_javascript.html[/url]
		Function by Jens Anders Bakke, webfreak.no
*/
function $get(key,url){
	if(arguments.length < 2) url =location.href;
	if(arguments.length > 0 && key != ""){
		if(key == "#"){
			var regex = new RegExp("[#]([^$]*)");
		} else if(key == "?"){
			var regex = new RegExp("[?]([^#$]*)");
		} else {
			var regex = new RegExp("[?&]"+key+"=([^&#]*)");
		}
		var results = regex.exec(url);
		return (results == null )? "" : results[1];
	} else {
		url = url.split("?");
		var results = {};
			if(url.length > 1){
				url = url[1].split("#");
				if(url.length > 1) results["hash"] = url[1];
				url[0].split("&").each(function(item,index){
					item = item.split("=");
					results[item[0]] = item[1];
				});
			}
		return results;
	}
}

