/**
* Griffioen
* Dependencies: Prototype, Scriptaculous, Google Maps
*/

/** Get IE version: */
var IEversion = 0;
var isIE = false;
var isSafari = false;
try {
	if(navigator.userAgent && document.all) {
		var regex = new RegExp(/MSIE ([0-9\.]{3,})\;/);
		var IEversion = regex.exec(navigator.userAgent)[1];
		IEversion = parseInt(IEversion);
		isIE = (IEversion > 0);
	}
	
	if(navigator.userAgent.indexOf('Safari') != -1) {
		isSafari = true;
	}
	
} catch(e) { /* not supported, but not IE. */ }

var busy = false;


function setCookie(name,value,expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + exdate.toGMTString());
}


var SlideShow = Class.create({
	// Settings:
	interval: 5,
	fadeInSpeed: 1,
	fadeOutSpeed: 1,
	
	// Working vars:
	paused: false,
	element: null,
	images: $A(),
	current: 0,
	pe: 'bad',
	useDots: false,
	dotElement: null,
	dotLinks: $A(),
	initialize: function() {
		try { this.pe.stop(); } catch(e) { }
		var elements = $$('.slideshow');
		if(elements.length > 0) {
			this.element = $(elements[0]);
			this.images = this.element.select('img');//$A(this.element.getElementsByTagName('img'));
			var newHeight = this.element.getHeight();//-(this.element.id == 'full' ? 0 : 0)+'px';
			this.element.style.height = newHeight;
			if($('slideshowwrapper')) {
				$('slideshowwrapper').style.height = newHeight;
			}
		}
		
		for(var i=0; i<this.images.length; i++) {
			Event.observe(this.images[i],'click',function(event) { this.pause(); }.bind(this));
			if(this.images[i].style.display != 'none') {
				this.current = i;
			}
		}
		if(this.images.length > 1) {
			this.start();
			this.active = true;
		}
	},
	start: function() {
		this.pe = new PeriodicalExecuter(this.next.bind(this), this.interval);
	},
	pause: function(event) {
		try {
			if(this.paused) {
		        this.start();
		        this.paused = false;
				$('pause').removeClassName('current');
			} else {
				this.stop();
				this.paused = true;
				$('pause').addClassName('current');
			}
		} catch(e) {
			//alert("can't pause/resume because: "+e);
		}
	},
	stop: function() {
	    try {
	        this.pe.stop();    
	    } catch(e) {
	        //alert('cant stop because: '+e);// can't stop because it's not started :)
	    }
	},
	next: function(pe) {
		new Effect.Fade($(this.images[this.current]),{
			duration: this.fadeOutSpeed,
			queue: 'end',
			afterFinish: function() {
				// double check, everything is hidden:
				$(this.images[this.current]).siblings().invoke('hide');
			}.bind(this)
		});
		this.current = (this.images[this.current+1]) ? this.current+1 : 0;
		// double check, everything is hidden:
		//$(this.images[this.current]).siblings().invoke('hide');
		
		new Effect.Appear($(this.images[this.current]),{
			duration: 0.5, 
			queue: 'end'
		});
	},
	show: function(e) {
		this.newIndex = e.href.substr(e.href.indexOf('#')+1,e.href.length)-1;
		//$A(e.parentNode.getElementsByTagName('a')).each(function(e) { $(e).removeClassName('current'); });
		this.stop();
		new Effect.Fade($(this.images[this.current]),{ duration: this.fadeInSpeed, afterFinish: function() {
			// double check, everything is hidden:
			//alert('show');
			$(this.images[this.newIndex]).siblings().invoke('hide');
			
			this.current = this.newIndex;
			new Effect.Appear($(this.images[this.newIndex]),{
				afterFinish: function() {
					this.siblings().invoke('hide');
				}.bind($(this.images[this.current]))
			});
			
			if(this.useDots) {
				this.dotLinks.each(function(e) { $(e).removeClassName('current'); });
			}
			if(this.dotLinks[this.current]) {
				this.dotLinks[this.current].addClassName('current');
			}
			if(!this.paused) {
				this.start();
			}
		}.bind(this)});
	}
});

var SpinnerControl = Class.create({
    element: null,
    isOn: false,
    initialize: function(el) {
        this.element = $(el);
    },
    
    toggle: function() {
        this.element.style.backgroundImage = (!this.isOn) ? "url('"+baseurl+"/img/spinner.gif')" : "url('')";
        this.isOn = (!this.isOn);
    }
});

var ScrollingThumbs = Class.create({
	element: null,
	step: 151,
	lastStep: 0,
	duration: 0.4,
	visibleWidth: 530,
	
	offset: 0,
	busy: false,
	initialize: function(element) {
		this.element = $(element);
		// bit of a hack:
		if (this.element.select('td').length > 3) {
			$('scroll-next').setOpacity(0.75).observe('click', this.next.bind(this));
			$('scroll-prev').setOpacity(0.25).addClassName('disabled').observe('click', this.prev.bind(this));
		} else {
			$$('span#scroll-next, span#scroll-prev').each(function(e) {
				e.setOpacity(0.25);
				e.addClassName('disabled');
			});
		}
		this.element.select('img').each(function(img) {
			img.observe('click',this.show.bind(this,img.alt));
		}.bind(this));
	},
	show: function(src) {
		$('project-image').src = src;
	},
	next: function(event) { if(!event.target.hasClassName('disabled')) this.move(-this.step) },
	prev: function(event) { if(!event.target.hasClassName('disabled')) this.move(this.step) },
	move: function(x) {
		//alert(this.offset+x);
		//alert(x);
		if (!this.busy && this.offset+x <= 75) { // dunno why 75, used to be 0. Probably 1/2 image width
			this.busy = true;
			// after last step:
			if(this.lastStep != 0 && x >= 0) {
				x = -this.lastStep;
				this.lastStep = 0;
				$('scroll-next').setOpacity(0.75).removeClassName('disabled');
			}
			// last step:
			if (this.lastStep != 0 && x < 0) { x = 0; }
			// calculate x:
			if (( -((this.offset+x) + this.element.getWidth())) > -this.visibleWidth) {
				// only show half of the next image:
				x = -((0 - ((this.offset+x) + this.element.getWidth())) - (0-this.visibleWidth));
				x = x+(this.element.select('img').length*3)
				this.offset += x;
				this.lastStep = x;
				$('scroll-next').setOpacity(0.25).addClassName('disabled');
			} else {
				this.offset += x;
			}
			// move
			new Effect.Move(this.element, {
				x: x,
				y: 0,
				duration: this.duration,
				mode: 'relative',
				afterFinish: function(){
					this.busy = false;
					if(this.offset == 0) {
						$('scroll-prev').setOpacity(0.25).addClassName('disabled');
					} else {
						$('scroll-prev').setOpacity(0.75).removeClassName('disabled');
					}
				}.bind(this)
			});
		} else {
			//alert(this.offset+x);
		}
	}
});

// Onload event
var SL;
var Spinner;
var Projects;
document.observe('dom:loaded', function(event) {
	// Set the cookie telling the server that this user supports JavaScript:
	setCookie('UserHasJS','yes',365);

	var menuItems = $$('div#header>ul>li');
	menuItems.invoke('observe','mouseover',function(event) { this.addClassName('hover'); });
	menuItems.invoke('observe','mouseout', function(event) { this.removeClassName('hover'); });

	// projects:
	Projects = $$('ul#projects li');

	Projects.invoke('observe','mouseover',function(event) { this.addClassName('hover'); this.prevOpacity = this.down('img').getOpacity(); this.down('img').setOpacity(0.25); });
	Projects.invoke('observe','mouseout', function(event) { this.removeClassName('hover'); this.down('img').setOpacity(this.prevOpacity); });
	Projects.invoke('observe','click',	  function(event) { window.location.href = this.down('a').href; });
	//$$('ul#checkboxes li').invoke('addClassName','selected');

	if($('project-thumbs')) {
		new ScrollingThumbs($('project-thumbs').down('table'));
	}

	$$('ul#checkboxes li').invoke('observe','click',function(event) {
		this.toggleClassName('checked');
		this.blur();
		$('projects').removeClassName('clear');
		if (this.hasClassName('checked')) {
			$('projects').select('li.' + this.id).invoke('addClassName', 'selected');
		} else {
			$('projects').select('li.' + this.id).invoke('removeClassName', 'selected');
		}
		if ($('projects').select('li.selected').length == 0) {
			$('projects').addClassName('clear');
			Projects.each(function(li) { li.down('img').setOpacity(1); });
		} else {
			$('projects').removeClassName('clear');
			Projects.each(function(li) { li.down('img').setOpacity(li.hasClassName('selected') ? 1 : 0.25); });
		}
	});
	
	if($('contact-form')) {
		$('contact-form').select('input.text, textarea.text').each(function(input) {
			var value = input.previous('label').innerHTML;
			if(input.tagName == 'TEXTAREA') {
				input.update(value);
			} else {
				input.value = value;
			}
			input.defaultValue = value;

			input.observe('blur',function() {
				if($F(this) == '') {
					var value = input.previous('label').innerHTML;
					if(this.tagName == 'TEXTAREA') {
						this.update(value);
					} else {
						this.value = value;
					}
				}
			});

			input.observe('focus',function() {
				if($F(this) == this.previous('label').innerHTML)
					this.clear();
			});
		});
	}
	
	$$('form.validate').each(function(form) {
		new Validate(form);
	});
	
	SL = new SlideShow();
});


Validate = Class.create({
	form: null,
	valid: true,
	initialize: function(form) {
		this.form = form;
		this.form.observe('submit',this.validate.bind(this));
	},
	
	validate: function(event) {
		this.valid = true;
		this.form.select('input.required, textarea.required').each(this.checkInput.bind(this));
		if(!this.valid) {
			event.stop();
			alert('Niet alle velden zijn correct ingevuld.');
		}
	},

	checkInput: function(input) {
		if($F(input).blank()) {
			this.valid = false;
		}
		if(input.defaultValue && $F(input) == input.defaultValue) {
			this.valid = false;
		}
	}
});

