
google.load("mootools", "1.2.4");
google.load('search', '1', { language : 'nl' });

google.setOnLoadCallback( function()
{		

	/* IE hack needed for gradient backgrounds and Ajax thumbs */
	var isIE = (Browser.Engine.trident);
	
	if (isIE) {
		$$('.widget').each(function(widget) {
			var widgetSize = widget.getSize();
			widget.setStyle('height', widgetSize.y);
			widget.setStyle('width', widgetSize.x);
		});
	}
	
	/* Table Rows */
	$$('table.alternating tr:nth-child(2n)').addClass('even');
	$$('table.alternating tr:nth-child(2n+1)').addClass('odd');
	
	/* Analytics */
	try {
		var pageTracker = _gat._getTracker("UA-1774056-1");
		pageTracker._trackPageview();
	} catch(err) {}

	/* KNSB.tv widget */
	if (typeof vids != "undefined") {
		var ajaxUrl = '/wp-content/plugins/capstone/page-knsbtv-feed.php';

		var jsonRequest = new Request.JSON({
			url: ajaxUrl, 
			onSuccess: function(result) {
				
				$('knsbtv').removeClass('spinner');
				
				result.each(function(item, index) {
					
					var vidContainer = new Element('div', {
					}).inject('knsbtv');
					
					var vidLink = new Element('a', {
						'href': vids.site + '/knsb-tv/item/' + item.id,
						'html': '<span>' + item.date + '</span>' + item.title
					}).inject(vidContainer, 'top');
					
					var vidThumb = new Element('div', {
						'class': 'vidThumb'
					}).inject(vidLink, 'top');
					
					var vidRuler = new Element('div', {'class': 'hr'}).inject(vidContainer, 'top');
					if (index == 0) vidRuler.addClass('hidden');
					
					var vidButton = new Element('span', {
						'class': 'icon'
					}).inject(vidThumb, 'top');
					
					var vidImg = new Element('img', {
						'src': item.picture,
						'alt': item.description
					}).inject(vidThumb);
						
				});
				
				
				if (!vids.widget) { // Standard widget
					
					var linkUrl = vids.site + '/knsb-tv/';
					if ($chk(vids.keywords)) linkUrl += 'tag/' + vids.keywords + '/';
					
					var moreLink = new Element('a', {
						'class': 'more',
						'href': linkUrl,
						'html': 'Meer KNSB.tv'
					}).inject('knsbtv', 'bottom');
					
					var bg = new Element('img', {
						'class': 'back',
						'src': '/wp-content/themes/knsb/images/widgetBack.png'
					}).inject('knsbtv', 'bottom');
					
				} else { // KNSB.tv page
				
					if (vids.offset > 0) {
						
						var prevButton = new Element('button', {
							'id': 'prevButton',
							'html': 'Vorige'
						}).inject('knsbtv', 'bottom');
						
						prevButton.addEvent('click', function() {
							vids.offset = vids.offset - vids.num;
							$('knsbtv').empty();
							$('knsbtv').addClass('spinner');
							jsonRequest.get(vids);
						});
					}
					
					if (result.length == vids.num) {
						
						var nextButton = new Element('button', {
							'id': 'nextButton',
							'html': 'Volgende'
						}).inject('knsbtv', 'bottom');
						
						nextButton.addEvent('click', function() {
							vids.offset = vids.offset + vids.num;
							$('knsbtv').empty();
							$('knsbtv').addClass('spinner');
							jsonRequest.get(vids);
						});
						
					}					
						
				}
				
				/* IE hacks */
				if (isIE) {
					$('knsbtv').setStyle('height', 'auto');
					$('knsbtv').setStyle('height', $('knsbtv').getSize().y);
				}
				
				
			},
			onFailure: function(e) {
				
			}
		});
		jsonRequest.get(vids);

	}
	
	/* KNSB.tv embed */
	if ($('embedLink')) {
		$('embedLink').addEvent('click', function(e) {
			e.stop();

			if ($('code').hasClass('hidden')) {
				$('code').removeClass('hidden');
			} else {
				$('code').addClass('hidden');
			}
		});
	}
	
	/* External Links */
	$$('a.external').addEvent('click', function(e) {
		e.stop();
		window.open(this.href);
	});
	
	/* Send to friend */
	if ($('send')) {
		
		$('friendForm').fade('hide');
		
		$('sendfriend').addEvent('click', function(e) {
			e.stop();
			
			if ($('success'))
				$('success').destroy();
				
			$('friendForm').removeClass('hidden');
			$('friendForm').fade('toggle');
		});
		
		$('friendSubmit').addEvent('click', function(e) {
			e.stop();
			
			var validMail = $('recipientMail').get('value');
			
			mailRegex = new RegExp('^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$');
			
			if (validMail.test(mailRegex)) {
				$('recipientMail').removeClass('error');
				
				$('friendForm').set('send', {
					onComplete: function(e) {
						if ($chk(e)) {
							
							var success = new Element('p', {
								'class': 'success',
								'html': 'Bericht verstuurd',
								'id': 'success'
							}).inject('friendForm', 'top');
							
							setTimeout("$('friendForm').fade('toggle')", 1000);
							pageTracker._trackEvent('Sendtofriend');
						}
					}
				});
				
				$('friendForm').send();
				
			} else {
				$('recipientMail').addClass('error');
			}
		
		});
		
		$('cancel').addEvent('click', function(e) {
			e.stop();
			$('friendForm').addClass('hidden');
			$('friendForm').fade('toggle');
		});
		
		
	}
	
	/* Nieuws / Kalender form */
	if ($('eventForm')) {
		$$('#eventForm select').addEvent('change', function(e) {
			e.stop();
			
			//var catSlug = $('catSelect').get('value');
			
			//$('eventForm').set('action', $('eventForm').get('action') + catSlug);
			$('eventForm').submit();
		});
		
		$$('a.page-numbers').addEvent('click', function(e) {
			e.stop();
			
			$('eventForm').set('action', this.get('href'));
			$('eventForm').submit();
		});
	}
	
	/* Zoekvereniging */
	if ($('map')) {
		if (GBrowserIsCompatible()) {
			var map = new GMap2(document.getElementById("map"));
			map.setCenter(new GLatLng(52.1, 5), 6, G_NORMAL_MAP);
			map.addControl(new GSmallMapControl());
			
			kunstijsbanen['banen'].each(function(loc) {
					var marker = new GMarker(new GLatLng(loc['lat'], loc['long']));
					GEvent.addListener(marker,'click', function() {
						
						marker.openInfoWindowTabsHtml(
							[
								new GInfoWindowTab(
									loc['plaats'], 
									'<b>' + loc['naam'] + '</b><br />' + 
									loc['adres'] + '<br />' + 
									loc['postcode'] + ' ' + 
									loc['plaats'] + '<br />' + 
									loc['telefoon'] + '<br />' + 
									'<form class="map" action="/actief/verenigingen/" method="post">' +
									'<input type="hidden" value="' + loc['afkorting'] + '" name="kunstijsbaan" />' +
									'<input type="submit" value="Toon verenigingen" />' +
									'</form>'
								)
								//, new GInfoWindowTab("Meer..","test")
							]); 

					});

					map.addOverlay(marker);
				});
			
		}
		
	}
	
	/* Sara */
	if ($('sara_persons')) {
		
		$$('.saraPerson').addEvent('click', function(e) {
			e.stop();
			$('form_sara_id').set('value', this.rel);
			$('sara_persons').submit();
		});
		
		$$('.seasonCode').addEvent('click', function(e) {
			e.stop();
			$('form_season_code').set('value', this.rel);
			$('sara_persons').submit();
		});

		$$('.saraCompetition').addEvent('click', function(e) {
			e.stop();
			$('form_comp_id').set('value', this.rel);
			$('sara_persons').submit();
		});

		$$('.saraShowCompetitions').addEvent('click', function(e) {
			e.stop();
			$('form_week_id').set('value', this.rel);
			$('sara_persons').submit();
		});

	}
	
	if ($('saraAll')) {
		
		var browser = (Browser.Engine.trident) ? 'block' : 'table-row';
		
		$('saraAll').addEvent('click', function(e) {
			e.stop();
			$('resultHeading').set('html', this.get('html'));
			$$('tr.hidden').setStyle('display', browser);
		});
		
		$('saraTop3').addEvent('click', function(e) {
			e.stop();
			$('resultHeading').set('html', this.get('html'));
			$$('tr.hidden').setStyle('display', 'none');
		});
	}
	
	
	/* MEDIA GALLERY */
	var gallery = $$('.gallery a');
	
	gallery.addEvent('click', function(e) {
		e.stop();
		
		var picViewer = new Element('div').inject('page', 'top');

		var overlay = new Element('div', {
			'id': 'overlay',
			'class': 'spinner'
		}).inject(picViewer);
		
		/* Check if video playing*/
		setVideo('hidden');

		var winSize = window.getSize();
		var offset = window.getScroll();
		
		/* Collect */
		var imageList = [ this.get('href') ];
		var captionText = this.get('rel');
		
		if (!$chk(captionText))
			captionText = this.getFirst('img').get('alt');
		
		/* Dynamic load */
		new Asset.images(imageList, {
			
			onComplete: function() {
				
				overlay.removeClass('spinner');

				var zoom = new Element('img', {
					'src': imageList[0],
					'id': 'zoom'
				}).inject(overlay, 'after');
	
				var zoomSize = $('zoom').getSize();
				var zoomPosTop = (winSize.y / 2) - (zoomSize.y / 2) + offset.y;
				var zoomPosLeft = (winSize.x / 2) - (zoomSize.x / 2);

				zoom.setStyle('top', zoomPosTop);
				zoom.setStyle('left', zoomPosLeft);
				
				/* Caption */
				var caption = new Element('span', {
					'id': 'caption',
					'html': captionText
				}).inject(zoom, 'after');

				caption.setStyle('top', zoomPosTop);
				caption.setStyle('left', zoomPosLeft);

				/* Close */
				var closeButton = new Element('a', {
					'id': 'closeButton',
					'html': 'Sluiten [x]',
					'href': 'close'
				}).inject(zoom, 'after');

				closeButton.setStyle('top', zoomPosTop);
				closeButton.setStyle('left', zoomPosLeft + zoomSize.x - 65);
				
				/* Close actions */
				zoom.addEvent('click', function(e) {
					e.stop();
					picViewer.destroy();
					
					setVideo('visible');
				});
					
				closeButton.addEvent('click', function(e) {
					e.stop();
					picViewer.destroy();
					
					setVideo('visible');
				});
			}
		});

	});
	
	/* Custom Search */
	if ($('cse')) 
	{
		var siteSearch = new google.search.WebSearch();
		siteSearch.setUserDefinedLabel('Zoekresultaten');
		siteSearch.setSiteRestriction('016438942514939008166:lawsza7kavq');
		
		var options = new google.search.SearcherOptions();
		options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
		options.setRoot($('cse'));
		
		var drawOptions = new google.search.DrawOptions();
		drawOptions.setInput($('zoek'));

		var searchControl = new google.search.SearchControl();
		searchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
		searchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET); 
		searchControl.addSearcher(siteSearch, options); 
		searchControl.draw(null, drawOptions);
		
		if ( $chk($('zoek').get('value')) ) 
		{
			siteSearch.execute($('zoek').get('value'));
			$('cse').removeClass('gsc-resultsbox-invisible');
		}
	}

	var rotateImg;

	/* Show/hide video for image zoom */
	function setVideo(style) {
		if ($('newsVideo'))
			$('newsVideo').setStyle('visibility', style);
	}

	/* ASSETS */
	MooTools.More={version:"1.2.4.2",build:"bd5a93c0913cce25917c48cbdacde568e15e02ef"};var Asset={javascript:function(f,d){d=$extend({onload:$empty,document:document,check:$lambda(true)},d);
	var b=new Element("script",{src:f,type:"text/javascript"});var e=d.onload.bind(b),a=d.check,g=d.document;delete d.onload;delete d.check;delete d.document;
	b.addEvents({load:e,readystatechange:function(){if(["loaded","complete"].contains(this.readyState)){e();}}}).set(d);if(Browser.Engine.webkit419){var c=(function(){if(!$try(a)){return;
	}$clear(c);e();}).periodical(50);}return b.inject(g.head);},css:function(b,a){return new Element("link",$merge({rel:"stylesheet",media:"screen",type:"text/css",href:b},a)).inject(document.head);
	},image:function(c,b){b=$merge({onload:$empty,onabort:$empty,onerror:$empty},b);var d=new Image();var a=document.id(d)||new Element("img");["load","abort","error"].each(function(e){var f="on"+e;
	var g=b[f];delete b[f];d[f]=function(){if(!d){return;}if(!a.parentNode){a.width=d.width;a.height=d.height;}d=d.onload=d.onabort=d.onerror=null;g.delay(1,a,a);
	a.fireEvent(e,a,1);};});d.src=a.src=c;if(d&&d.complete){d.onload.delay(1);}return a.set(b);},images:function(d,c){c=$merge({onComplete:$empty,onProgress:$empty,onError:$empty,properties:{}},c);
	d=$splat(d);var a=[];var b=0;return new Elements(d.map(function(e){return Asset.image(e,$extend(c.properties,{onload:function(){c.onProgress.call(this,b,d.indexOf(e));
	b++;if(b==d.length){c.onComplete();}},onerror:function(){c.onError.call(this,b,d.indexOf(e));b++;if(b==d.length){c.onComplete();}}}));}));}};

	/* Image Rotator class */
	var rotator = new Class({
				
		Implements: [Options, Events],
		
		options: {
			currentImg: 0,
			swapCycle: 10,
			imageContainers: [],
			text: [],
			numbers: []
		},
		
		initialize: function(options) {
			
			this.setOptions(options);
			this.protoTimer = new Hash({counter: 0});
			
			$$(this.options.text).fade('hide');
			$$(this.options.imageContainers).fade('hide');

			this.imageList = this.options.imageContainers.map(function(item, index) {
				return $(item).getFirst().get('rel');
			});
			
			this.preloadImages(this.imageList);
							
			$$(this.options.numbers).addEvent('mouseover', function(e) {
				
				index = this.options.numbers.indexOf(e.target);
				this.swapImage(index);
				
			}.bind(this), this);		
			
		},
		
		preloadImages: function(imageList) {
			
			this.loadedImages = new Asset.images(imageList, {
				
				onProgress: function(counter, index) {
					
					this.loadedImages[index].inject(this.options.imageContainers[index].getFirst());
					
					if (counter == 0)
						this.swapImage(index);
					
				}.bind(this),
				
				onComplete: function() { 
					
					$('photos').removeClass('spinner'); 
					this.timer('start');
				
				}.bind(this)
			
			});

		},
		
		fadeImage: function(fadeType) {
			
			number = this.options.currentImg;
			
			this.options.text[number].fade(fadeType);
			this.options.imageContainers[number].fade(fadeType);
			
			if (fadeType == 'in') {
				this.options.numbers[number].addClass('active');
			} else {
				this.options.numbers[number].removeClass('active');
			}
			
		},
					
		swapImage: function(newImage) {
			
			this.fadeImage('out');
			
			if ($chk(newImage)) {
				this.options.currentImg = newImage;
			} else {
				this.options.currentImg = (this.options.currentImg == (this.options.text.length - 1)) ? 0 : this.options.currentImg + 1;
			}
			
			this.fadeImage('in');
			this.timer('reset');
			
		},
		
		timer: function(action) {
			
			simpleTimer = function() {
			
				currentTime = this.protoTimer.counter++;

				if (currentTime >= this.options.swapCycle) { 
					this.swapImage();
				}
				
		
			}.bind(this);
			
			if (action == 'start')
				this.buttonTimer = simpleTimer.periodical(1000, this.protoTimer);
			
			else if (action == 'reset')
				this.protoTimer.set('counter', 0);
		}		
		
	});
	
	/* Headlines rotator */
	if ($('headlines')) {
		
		var myHeadlines = new rotator({
			imageContainers: $$('#photos li'), 
			text: $$('#text li'),
			numbers: $$('#numbers li a')			
		});
		
	}

// END
}, true);
