 /*
 * MooTools
 * version 1.11
 * documentation at http://docs111.mootools.net
 * dom ready functions
 */

window.onDomReady(function() {
	//drop-down menu in main-navigation
	new DropdownMenu($E('ul', 'main-navigation'));

	/**
	 *	Home Image Carousel
	 */
	if ($('home') != null) {
		new HomeRotator();
	};
	
	/**
	 * set correct defaults for navigation
	 */
	if ($('list-vacancies') != null) {
		$$('tr.vacancy').each(function(item){
			//add unobtrusive javascript for mouseover event to <tr> tag that highlights selected row
			$(item).addEvent("mouseover", function(event) {
				$(item).addClass('selected');
			});
			$(item).addEvent("mouseout", function(event) {
				$(item).removeClass('selected');
			});
			$(item).addEvent("click", function(event) {
				document.location.href = $(item).getProperty('name');
			});
		});
	};
	
	/**
	 *	Display Contact Form errors correctly
	 */
	 if ($('FormBuilderForm') != null) {
		$$('.form label.error').each(function(item){
			error = new Element('p').setText(item.getText());
			error.injectInside($('errors-form'));
		});	
	};
	
	/**
	 *	Contact Form
	 */
	 if ($('topic-field') != null) {
	 	contactform = new ContactForm($('topic-field'), $('food-service-field'), $('support-service-field'));
	 };
});

var ContactForm = new Class({
	mainElement: null,
	selectFood: null,
	selectSupport: null,

	initialize: function(mainElement, selectFood, selectSupport) {
		this.mainElement = mainElement;
		this.selectFood = selectFood;
		this.selectSupport = selectSupport;
	
		mainElement.addEvent('change', function(event) {
	 		this.updateFormSelects();
	 	}.bind(this));

		selectFood.addEvent('change', function(event) {
	 		this.updateFormSelects();
	 	}.bind(this));

		selectSupport.addEvent('change', function(event) {
	 		this.updateFormSelects();
	 	}.bind(this));

	 	
	 	this.updateFormSelects();
	 },

	updateFormSelects: function () {
		element = this.mainElement;

		var vacancy = foodservice = supportservice = false;
		var value = '';
	
		switch(element.value) {
			case 'Werken bij':
				vacancy = true;
				value = element.value;
				break;
			case 'Foodservice':
				foodservice = true;
				break;
			case 'Support Services':
				supportservice = true;
				break;
			default:
				value = element.value;
		}
		
		if (vacancy) {
			$('vacancy-promo').setStyle('display', 'block');
			//$('vacancies').addClass('selected');
		} else {
			$('vacancy-promo').setStyle('display', 'none');
			//$('vacancies').removeClass('selected');
		}
		if (foodservice) {
			$('food-service-field').removeProperty('disabled');
			$('food-service-select').setStyle('display', 'block');
	
		value = element.value + ';' + $('food-service-field').getValue();
		} else {
			$('food-service-field').setProperty('disabled', 'disabled');
			$('food-service-select').setStyle('display', 'none');
		}
		if (supportservice) {
			$('support-service-field').removeProperty('disabled');
			$('support-service-select').setStyle('display', 'block');
	
			value = element.value + ';' + $('support-service-field').getValue();
		} else {
			$('support-service-field').setProperty('disabled', 'disabled');
			$('support-service-select').setStyle('display', 'none');
		}
		
		$('service-type').setProperty('value', value);
	}
});

var HomeRotator = new Class({
	totalimages: null,
	currentimage: null,
	images: null,
	
	initialize: function() {
		this.images = $$('#home #header-image img');
		
		this.totalimages = this.images.length;
		this.currentimage = 0;

		//	Set initial state
		if ( this.totalimages > 1) {
			this.images.each(function(image, index) {
				if (index == this.currentimage) {
					image.setStyle('opacity', '1');
				} else {
					image.setStyle('opacity', '0');
				}
			}.bind(this));
	
			setInterval(this.rotateImage.bind(this), 5000);
		}
	},
	
	rotateImage: function () {
		nextimage = this.currentimage + 1;

		if (nextimage == this.totalimages) {
			nextimage = 0;
		}

		var myElementsEffects = new Fx.Elements([this.images[this.currentimage],this.images[nextimage]], {duration:1500});
		myElementsEffects.start({
		    '0': {
		    	'opacity': [1,0]
		    },
		    '1': {
		        'opacity': [0, 1]
		    }
		});

		this.currentimage = this.currentimage + 1;
		
		if (this.currentimage == this.totalimages) {
			this.currentimage = 0;
		}
	}
});

/* dropdown menu for main navigation */
var DropdownMenu = new Class({
	initialize: function(element) {
		$A($(element).childNodes).each(function(el) {
			if(el.nodeName.toLowerCase() == 'li') {
				$A($(el).childNodes).each(function(el2) {
					if(el2.nodeName.toLowerCase() == 'ul') {
						$(el2).hide();
						
						/*el.addEvent('click', function() {
							$A(this.getParent().childNodes).each(function(el3) {
							    if(el3.nodeName.toLowerCase() == 'li') {
							        if (el3.getFirst().hasClass('selected')) {
							            el3.getFirst().removeClass('selected');
							        };
							    };
						    });
						    this.getFirst().addClass('selected');
							return false;
						});*/

						el.addEvent('mouseover', function() {
							el2.show();
							this.getFirst().addClass('over');
							return false;
						});

						el.addEvent('mouseout', function() {
							el2.hide();
							this.getFirst().removeClass('over');
							return false;
						});

                        new DropdownMenu(el2);
					};
				});
			};
		});
		return this;
	}
});

Element.extend( {
	hide: function() {
		this.setOpacity(0);
	},

	show: function() {
		this.setOpacity(0.90);
	}
});

var VacancyForm = new Class({
	validationFields: null,

	initialize: function(fields){
		$('FormBuilderForm').addEvent('submit', this.check_submit.bindWithEvent(this));

		validationFields = new Array();

		fields.each(function(item) {
			fieldName =  item.field.replace('field_', '');
			elements = $$('#FormBuilderForm input[name=' + fieldName + ']', '#FormBuilderForm input[name=' + fieldName + '_file]','#FormBuilderForm textarea[name=' + fieldName + ']');

			if (item.value == 'Nee') {
				//	Remove Formfield
				elements.each(function(item) {
					container = item.getParent();
					container.remove();
				});
			} else {
				//	Set Required
				elements.each(function(item) {
					container = item.getParent();
					items = container.getChildren().filterByTag('label');
					if (items.length > 0) {
						item = items[0];
						//.each(function(item) {
						item.appendText(' *');
						//});
					}
				});
			
				// Add to validation
				validationFields[validationFields.length] = fieldName;
			}
		});
		this.validationFields = validationFields;
	},
	get_label: function(element) {
		text = element.getParent().getChildren().filterByTag('label');
		text = text[0].getText().clean();
		text = text.replace(':', '');
		text = text.replace('*', '');
		return text;
	},
	
	check_submit: function(event) {
		errors = false;
		event.preventDefault();
		
		//	Remove old errors.
		if ($('errors-form') !== null) {
			$('errors-form').empty();
		}

		// Check Fields
		this.validationFields.each(function(fieldName){
			elements = $$('#FormBuilderForm input[name=' + fieldName + ']', '#FormBuilderForm input[name=' + fieldName + '_file]', '#FormBuilderForm textarea[name=' + fieldName + ']');

			switch (elements.length) {
				case 1:
					var element = elements[0];

					value = element.value.trim();

					if (value == '') {
						// Display Error ...
						error = new Element('p').setText('Vul uw ' + this.get_label(element) + ' in a.u.b.');
						if ($('errors-form') !== null) {
							error.injectInside($('errors-form'));
						}

						if ($('error-block').getStyle('display') == 'none') {
							$('error-block').setStyle('display', 'block');
						}

						errors = true;
					}

					/*if (element.getValue() === false) {
						// file?

						alert(element);
						alert(element.value);
						alert((element.value == ''));
						
						
						if (element.files !== null) {
							if (element.files.length == 0) {
								// Display Error ...
								error = new Element('p').setText('Vul uw ' + this.get_label(element) + ' in a.u.b.');
	
								if ($('errors-form') !== null) {
									error.injectInside($('errors-form'));
								}
								
								if ($('error-block').getStyle('display') == 'none') {
									$('error-block').setStyle('display', 'block');
								}
								
								errors = true;
							}
						}
					} else {
						//text/textarea
						if (element.getValue() == '') {
							// Display Error ...
							error = new Element('p').setText('Vul uw ' + this.get_label(element) + ' in a.u.b.');
							if ($('errors-form') !== null) {
								error.injectInside($('errors-form'));
							}

							if ($('error-block').getStyle('display') == 'none') {
								$('error-block').setStyle('display', 'block');
							}

							errors = true;
						}
					}*/
					break;
				case 2:
					//	Both hidden input & hile. Always filled.
					break;
				default:
					break;
			}
		}.bind(this));
		
		if (errors) {
			return false;
		} else {
			if ($('error-block').getStyle('display') !== 'none') {
				$('error-block').setStyle('display', 'none');
			}
		}

		$('FormBuilderForm').submit();
	}
});


var textCharCounter = new Class({

	counterObject: null,

	areaObject: null,

	areaLimit: 300,

	areaCounter: 0,

	initialize: function(areaId, targetId, options) {

		this.areaLimit = options.limit;
		this.areaObject = $(areaId);
		this.counterObject = $(targetId);
		this.counterObject.innerHTML = this.areaLimit;
		this.setCountEvents();
	},

	setCountEvents: function(){
		this.areaObject.addEvent('keyup',this.checkAreaSize.bind(this));
	},

	checkAreaSize: function(){
		this.areaCounter = this.areaObject.getValue().length;
		if(this.areaCounter > this.areaLimit){
			this.counterObject.innerHTML = 0;
			this.areaObject.value = this.areaObject.getValue().substring(0,this.areaLimit);
		}else{
			this.counterObject.innerHTML = this.areaLimit - this.areaCounter;
		}
	}

});

textCharCounter.implement(new Events);
textCharCounter.implement(new Options);