/*
* Cache van javascripts.script.js
* Created: 2011-11-22 14:08:35
*/

/*
$Author: sjors $
$LastChangedDate: 2006-10-19 14:05:31 +0200 (do, 19 okt 2006) $
$Id: javascripts.js 28 2006-10-19 12:05:31Z sjors $
$Rev: 28 $
*/

var google = '';
if (document.location.href.indexOf('gids.nl') > 0) {
	google = 'UA-4544761-1';
} else if (document.location.href.indexOf('gids.be') > 0) {
	google = 'UA-4544761-2';
}
if (google) {
	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
}

var numtweets = 4;
window.addEvent('domready', function(e) {

	if (google) {
		var pageTracker = _gat._getTracker(google);
		pageTracker._initData();
		pageTracker._trackPageview();
	}
	
	new mouseOvers();

	$$('li.newwindow a').each(function(node) {
		node.addEvent('click', opennewwin);
	});
	$$('a.newwindow').each(function(node) {
		node.addEvent('click', opennewwin);
	});
	$$('a.externlink').each(function(node) {
		node.addEvent('click', opennewwin);
	});

	$$('div.thumbnails').each(function(div) {
		var imglarge = new Element('div').setStyle('width', '3000px').inject($(div.get('id')+'_large'));
		var thumbs = div.getElements('a');
		var imgsfx;
		var imgs;
		function showimage(idx) {
 			imgsfx.start(
 				'margin-left',
 				imglarge.getStyle('margin-left'),
 				-1 * idx * imglarge.getParent('div').getStyle('width').toInt()
 			);
			thumbs.removeClass('current');
			thumbs[idx].addClass('current');
		}
		thumbs.each(function(img, i) {
			new Asset.image(img.get('href')).inject(imglarge);
			img.addEvent('click', function(e) {
				new Event(e).stop();
				showimage(i);
			});
		});
		imgsfx = new Fx.Tween(imglarge, {
			duration: 300,
			transition: Fx.Transitions.Sine.easeInOut
		});
		if (thumbs[0]) {
			showimage(0);
		}
	});

	$$('ul.imagefader').each(function(el) {
		var fader = new imageFader(
			$(el.get('id')+'_images').getElements('img'), {
				duration: 500,
				auto: false,
				link: 'cancel'
			}
		);
		el.getElements('a').addEvent('mouseenter', function(e) {
			fader.display($(this.get('id')+'_img'));
		});
		el.addEvent('mouseleave', function(e) {
			fader.display($(el.get('id')+'_images').getElement('img'));
		});
		el.fireEvent('mouseleave');
	});

	$$('ul#footermenu li').each(function(el, i) {
		if (i > 0) {
			new Element('li').set('html', '|').inject(el, 'before');
		}
	});

	if (Browser.Engine.trident) {
		if (Browser.Engine.version <= 4) {
			$$('ul#menu li.current').each(function(el) {
				el.addClass(el.get('class').replace(' ', '_'));
				el.removeClass('current');
			});
		}
	}

	$$('ul#menu ul li:last-child').addClass('last');
	$$('ul#menu > li').each(function(el) {
		el.addEvent('mouseenter', function(e) {
			$$('ul#menu > li > a').removeClass('hover');
			$$('ul#menu ul').setStyle('display', 'none');
			el.getElement('a').addClass('hover');
			if (el.getElement('ul')) {
				el.getElement('ul').setStyle('display', 'block');
			}
		});
	});
	$('menu').addEvent('mouseleave', function(e) {
		$$('ul#menu > li > a').removeClass('hover');
		$$('ul#menu ul').setStyle('display', 'none');
	});

	$$('.homeslider').each(function(slider, i) {
		var id = 'hs'+i+'_';
		var elms = slider.getElements('.element');
		var numelms = elms.length;
		if (numelms == 0) return;
		var container = slider.getElement('.sliding');
		var controls = slider.getElement('.controls');
		var curel = 0;
		var prevel = -1;
		var timer = null;
		elms[0].clone().inject(elms[0].getParent());
		var width = slider.getStyle('width').toInt();
		var fx = new Fx.Scroll(container, {
			duration: 1000,
			transition: Fx.Transitions.Sine.easeInOut,
			onComplete: function() {
				if (prevel < curel && curel == numelms) {
					curel = 0;
					this.set(0, 0);					
				}
			},
			onStart: function() {
				controls.getElements('a').removeClass('current');
				if (curel == numelms) {
					$(id + '0').addClass('current');
				} else {
					$(id + curel).addClass('current');
				}
				if (prevel > curel && curel == 0) {
					curel = numelms - 1;
					this.set(curel * width, 0, 0);
				}
			}
		});
		var nextSlide = function() {
			prevel = curel;
			curel++;
			fx.start(curel * width, 0);
		};
		for (var i=0; i<numelms; i++) {
			new Element('a', {
				'href': '#',
				'id': id + i
			}).set('html', i+1).inject(controls);
		};
		$(id + '0').addClass('current');
		controls.addEvent('click', function(e) {
			var target = $(e.target);
			if (target.get('tag') == 'a') {
				var i = target.get('id').substr(id.length);
				e.stop();
				$clear(timer);
				prevel = curel;
				curel = i;
				fx.start(curel * width, 0);
			}
		});
		slider.addEvent('mouseenter', function(e) {
			$clear(timer);
		});
		slider.addEvent('mouseleave', function(e) {
			$clear(timer);
			timer = nextSlide.periodical(6000);
		});
		slider.fireEvent('mouseleave');
	});

	if ($('searchstudio')) {
		var fields = ['country', 'province', 'city', 'name'];
		fields.each(function(fld, i) {
			if ($(fld)) {
				$(fld).addEvent('change', function(e) {
					for (var k=1; fields[i+k]; k++) {
						var values = '';
						fields.each(function(fld) {
							if ($(fld)) {
								values += '&' + fld + '=' + encodeURIComponent($(fld).get('value'));
							}
						});
						
						new Request({
							'url': $('searchstudio').get('action'),
							'method': 'post',
							'autoCancel': true,
							'onSuccess': function(respText, respXML) {
								var optionflds = respXML.getElementsByTagName('option');
								var numresponses = optionflds.length;
								var updatefield = $(respXML.getElementsByTagName('field')[0].getAttribute('value'));
								updatefield.set('html', '');
								for (var j=0; j<numresponses; j++) {
									new Element('option', {
										'value': optionflds[j].getAttribute('value')
									})
										.set('html', optionflds[j].getAttribute('name'))
										.inject(updatefield);
								}
							}
						}).send('field=' + fields[i+k] + values);
					}
				});
			}
		});

		$('searchstudio').addEvent('submit', function(e) {
			if (!$('searchextra') || $('searchextra').getStyle('height').toInt() == 0) {
				new Event(e).stop();
				var url = $('searchstudio').get('action');
				fields.each(function(fld, i) {
					if ($(fld)) {
						url += '/' + encodeURIComponent($(fld).get('value'));
					}
				});
				window.location.href = url;
			}
		});
	}
	if ($('searchextra')) {
		var sefx = new Fx.Tween($('searchextra'));
		sefx.set('height', 0);
		$('searchextra_button').addEvent('click', function(e) {
			if ($('searchextra').getStyle('height').toInt() == 0) {
				sefx.start('height', $('searchextra').getScrollSize().y);
				this.set('value', 'Eenvoudig zoeken');
			} else {
				sefx.start('height', 0);
				this.set('value', 'Uitgebreid zoeken');
			} 
		});
		if ($('searchextra').getParent('form').hasClass('searchextra')) {
			$('searchextra_button').fireEvent('click');
		}
	}

	$$('div.program').each(function(el) {
		new Element('a', {
			'href': '#'
		})
			.set('html', '&gt; Bekijk het programma van deze kookstudio &lt;')
			.injectBefore(el)
			.addEvent('click', function(e) {
				var clone = el.clone().setStyle('display', 'block');
				new Event(e).stop();

				if (!$('bodyoverlay')) {
					new Element('div', {
						'id': 'bodyoverlay',
						'styles': {
							'opacity': 0.8,
							'width': window.getScrollWidth()+'px',
							'height': window.getScrollHeight()+'px'
						}
					}).injectInside(document.body);
				} else {
					$('bodyoverlay').setStyles({
						'width': window.getScrollWidth()+'px',
						'height': window.getScrollHeight()+'px',
						'display': 'block'
					});
				}
				clone.addClass('popup');
				clone.injectInside(document.body);
				clone.setStyle('top', window.getScroll().y + 160);

				clone.getElements('a').each(function(node) {
					node.addEvent('click', opennewwin);
				});

				var aclose = new Element('a', {
					'class': 'close',
					'href': '#'
				}).injectInside(clone);
				aclose.addEvent('click', function(e) {
					new Event(e).stop();
					clone.setStyle('display', 'none');
					$('bodyoverlay').setStyle('display', 'none');
				});
				aclose.innerHTML = 'sluiten';
			});
		el.setStyle('display', 'none');
	});

	if ($('kbwdeelnemers')) {
		//var details = $('details');
		new Accordion('ul#kbwdeelnemers li', 'div.deelnemers_prov');
		$$('ul#kbwdeelnemers li').each(function(prov) {
			prov.addEvent('click', function(e) {new Event(e).stop();});
		});
		$$('div.deelnemers_prov li').each(function(dln) {
			dln.addEvent('mouseenter', function() {
				dln.addClass('hover');
			});
			dln.addEvent('mouseleave', function() {
				dln.removeClass('hover');
			});
		});
	}

	$$('.expandinglist').each(function(list) {
		var defopen = -1;

		var togglers = list.getElements('a.toggler');
		togglers.each(function(a, i) {
			a.addEvent('click', function(e) {
				if (e) new Event(e).stop();
				if (a.getParent('div.faqblock').hasClass('faqblock-open')) {
					list.getElements('div.faqblock-open').removeClass('faqblock-open');
				} else {
					list.getElements('div.faqblock-open').removeClass('faqblock-open');
					a.getParent('div.faqblock').addClass('faqblock-open');
				}
			});
			if (defopen == -1 && document.location.href.substr(document.location.href.indexOf('#')) == a.get('href')) {
				defopen = i;
			}
		});
		list.getElements('a.toggler2').each(function(a, i) {
			a.addEvent('click', function(e) {
				new Event(e).stop();
				togglers[i].fireEvent('click');
			});
		});

		var listacc = new Accordion(togglers, list.getElements('div.details'), {
			'display': defopen,
			'show': defopen,
			'alwaysHide': true,
			duration: 300
		});

		list.getElements('a.close').each(function(a, i) {
			a.addEvent('click', function(e) {
				new Event(e).stop();
				togglers[i].fireEvent('click');
			});
		});
	});

	if ($('studiovdweek')) {
		$('studiovdweek').removeClass('studiovdweek').addClass('studiovdweek-close');
		$('studiovdweek').getElement('a.close').addEvent('click', function(e) {
			new Event(e).stop();
			$('studiovdweek').removeClass('studiovdweek-open').addClass('studiovdweek-close');
		});
		$('studiovdweek').getElement('a.open').addEvent('click', function(e) {
			new Event(e).stop();
			$('studiovdweek').removeClass('studiovdweek-close').addClass('studiovdweek-open');
		});
	}

	$$('a.mov360').each(function(movlink) {
		movlink.addEvent('click', function(e) {
			new Event(e).stop();
			if (!$('bodyoverlay')) {
				new Element('div', {
					'id': 'bodyoverlay',
					'styles': {
						'opacity': 0.9,
						'width': window.getScrollWidth()+'px',
						'height': window.getScrollHeight()+'px'
					}
				})
				.injectInside(document.body)
			}

			var appletTag = '<applet\n' +
 'codebase = "/mov360/39" \n ' +
 'code     = "com.easypano.tourweaver.TWViewerApplet.class"\n ' + 
 'archive  = "tw2.jar"\n ' + 
 'name     = "TWViewer" \n ' + 
 'width    = "540"\n ' + 
 'height   = "350"\n ' + 
 'hspace   = "0"\n ' + 
 'vspace   = "0"\n ' + 
 'align    = "middle"\n ' + 
 'mayscript = "true"\n ' + 
 '> \n' + 
'<PARAM name = lwImg value = "wait.jpg">\n ' + 
 '<PARAM name = lwBgColor value = "255,255,255,255">\n ' + 
 '<PARAM name = lwBarBgColor value = "255,255,255,255">\n ' + 
 '<PARAM name = lwBarColor value = "255,122,192,67">\n  ' + 
 '<PARAM name = lwBarBounds value = "51,292,460,7">\n ' + 
 '<PARAM name = iniFile value = "config.bin">\n ' + 
 '<PARAM name = skin.archive value = "images.zip">\n ' + 
 '<PARAM name = defaultMovie value = "SlideShow">\n ' + 
 '<PARAM name = isInitFullScreen value = "false">\n ' + 
 '<PARAM name = isShowToolbar value = "true">\n ' + 
 '<PARAM name = isAutoRunMovie value = "true">\n ' + 
 '<PARAM name = hasBgSound value = "false">\n ' + 
 '<PARAM name = hasSceneSound value = "false">\n ' + 
 '<PARAM name = hasMovieSound value = "false">\n ' + 
 '<PARAM name = hasActionSound value = "false">\n ' + 
 '</applet>\n<p>Wacht tot het plaatje in beeld komt. Houd de muisknop ingedrukt en beweeg over het plaatje.</p>';
			new Element('div', {
				'id': 'appletcontainer',
				'styles': {
					'position': 'absolute',
					'top': '50%',
					'left': '50%',
					'margin-top': '-175px',
					'margin-left': '-270px',
					'border': '1px solid #0050f0',
					'background-color': '#ffffff'
				}
			}).injectInside(document.body);
			$('appletcontainer').innerHTML = appletTag;
			new Element('a', {
				'id': 'closeappcont',
				'class': 'fakebutton readmore',
				'href': '#',
				'events': {
					'click': function(e) {
						new Event(e).stop();
						$('bodyoverlay').dispose();
						$('appletcontainer').dispose();
					}
				}
			}).injectInside($('appletcontainer'));
			$('closeappcont').innerHTML = 'Sluiten';
		});
	});

	if ($('persons') && $('giftPackage') && $('total') && $('price') && $('priceGift')) {
		var updatePrice = function() {
			var price = $('price').get('value') * $('persons').get('value').toInt();
			price = price + $('priceGift').get('value') * ($('giftPackage').get('checked')?1:0);
			price = price.toFixed(2).replace('.', ',');
			$('total').set('html', price);
		};
		$('persons').addEvent('keyup', updatePrice.bindWithEvent());
		$('giftPackage').addEvent('change', updatePrice.bindWithEvent());
		updatePrice();
	}

	if ($('twitter')) {
		$('twitter').set('html', '<ul id="twitter_update_list"></ul>');

		new Asset.javascript('http://twitter.com/statuses/user_timeline/kookstudiopers.json?callback=twitterCallback2&count=' + (numtweets*2));
	}

	if ($('flickr')) {
		new MooFlick('flickr', '62450144@N08', {
			num: 4
		});
	}

});

function twitterCallback2(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length && i<numtweets; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
    statusHTML.push('<li><span>'+status+'</span> <a class="time" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li>');
  }
  document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'minder dan een minuut geleden';
  } else if(delta < 120) {
    return 'ongeveer een minuut geleden';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minuten geleden';
  } else if(delta < (120*60)) {
    return 'ongeveer een uur geleden';
  } else if(delta < (24*60*60)) {
    return '' + (parseInt(delta / 3600)).toString() + ' uur geleden';
  } else if(delta < (48*60*60)) {
    return 'gisteren';
  } else {
    return (parseInt(delta / 86400)).toString() + ' dagen geleden';
  }
}

function opennewwin(e) {
	var el = this.tagName.toLowerCase() == 'a' ? this : this.getParent('a');
	if (el) {
		new Event(e).stop();
		window.open(el.href, '_blank');
	}
}

var mouseOvers = new Class({
	initialize: function(elements) {
		elements = elements || $$('img.mouseover');
		elements.each(function(image) {
			if (image.hasClass('specialmo')) {
				image.set('src_mouseover', image.get('class').replace(/.*mouseover=/, ''));
				image.set('src_mouseout',  image.get('src'));
				image.addEvent('mouseenter', this.mouseover);
				image.addEvent('mouseleave', this.mouseout);
				new Asset.image(image.get('src_mouseover'));
			} else {
				var xsrc = image.src;
				if (xsrc.substring(xsrc.length-7, xsrc.length-3) == '_up.')	{
					image.set('src_mouseover', image.get('src').replace(/_up\.([a-z]{3})/, '_ov.$1'));
					image.set('src_mouseout',  image.get('src'));
				
					image.addEvent('mouseenter', this.mouseover);
					image.addEvent('mouseleave', this.mouseout);

					// Preload
					new Asset.image(image.get('src_mouseover'));
				}
			}
		}, this);
	},
	mouseover: function() {
		this.set('src', this.get('src_mouseover'));
	},
	mouseout: function()	{
		this.set('src', this.get('src_mouseout'));
	}
});

var imageFader = new Class({

	Extends: Fx.Elements,

	options: {
		auto: true,
		interval: 10000
	},

	initialize: function(elements, options) {
		this.elements = elements;
		this.setOptions(options);

		this.elements.setStyle('opacity', 0);

		if (this.elements[0]) {
			this.elements[0].setStyle('opacity', 1);
			if (this.elements[0].getParent().getStyle('position') != 'absolute' && this.elements[0].getParent().getStyle('position') != 'relative') {
				this.elements[0].getParent().setStyle('position', 'relative');
			}
		}

		this.curel = 0;
		if (this.options.auto) {
			this.auto.periodical(this.options.interval, this);
		}
	},

	auto: function() {
		if (!this.elements[this.curel]) {
			this.curel = 0;
		}
		this.display(this.curel);
		
		this.curel += 1;
	},

	display: function(elm) {
		var obj = {};
		this.elements.each(function(el, i) {
			if (el.getStyle('opacity') != 0 && el != elm) {
				obj[i] = {'opacity': 0};
				el.setStyle('z-index', 1);
			} else if (el == elm) {
				obj[i] = {'opacity': 1};
				el.setStyle('z-index', 2);
			}
		});
		return this.start(obj);
	}
});

/*
---
description: MooFlick Class. Takes a container div id, Flickr userid and optional options parameter and displays latest images from the users feed

license: MIT-style

authors:
- Matthew Wells

requires:
- core/1.2.1:*
- more:1.2.4.4:Request.JSONP
- more:1.2.4.4:Assets

provides: [MooFlick]

...
*/
var MooFlick = new Class({

	options: {
		'num':6,
		'url' : 'http://api.flickr.com/services/feeds/photos_public.gne?id={id}&lang=en-us&format=json',
		'delay':350,
		'max_rotation':8,
		'size_reduction':0.4
	},

	Implements: [Events, Options],

	initialize: function(div, user_id, options)
	{
		this.user_id = user_id;
		this.update_area = $(div);
		this.counter = 0;
		this.setOptions(options);
		this.options.url = this.options.url.substitute({id:user_id});
		this.make_request();
	},

	make_request: function()
	{
		new Request.JSONP({
			callbackKey: 'jsoncallback',
			url: this.options.url,
			onComplete: function(data) {
				this.queue_images(data)
			}.bind(this)
		}).send();
	},

	queue_images: function(data)
	{
		var images = $A([]);
		var images_data = $A([]);
		$A(data.items.splice(0,this.options.num)).each(function(item, index){
			images[index] = item.media.m;
			images_data[index] = item;
		},this)
		var loaded_images = new Asset.images(images,
			{
				onComplete:function(item){
					this.start_chain(loaded_images, images_data)
				}.bind(this)
			}
		)
	},

	start_chain: function(images, images_data)
	{
		images.each(function(item, index){
			(function() {
				this.add_image(item, images_data[index])
			}).delay(this.options.delay*index, this)
		},this)
	},

	add_image: function(item, data)
	{
		var cl = (this.counter % 2 == 0) ? 'even' : 'odd';
		var t_img = item;

		var d = new Element("div", {
			'class':'single-item '+cl,
			'styles': {
				'opacity':'0',
				'text-align':'center'
			}
		}).adopt( new Element("a", {
			'href':data.link,
			'title':data.title
		}).adopt( t_img ))

		this.update_area.adopt(d);

		this.fireEvent('onAdd', t_img);

		this.show_image(d, t_img)
	},

	show_image: function(container, img)
	{
		var t_size = img.getSize();
		var dest_height = t_size.y * this.options.size_reduction;
		var dest_width = t_size.x * this.options.size_reduction;
		var max = (dest_height > dest_width) ? dest_height : dest_width ;
		var rot = $random(-this.options.max_rotation,this.options.max_rotation)

		img.set('styles',{
			'height':0,
			'width':0,
			'-webkit-box-shadow': '3px 3px 10px rgba(0, 0, 0, 0.3)',
			'-moz-box-shadow': '3px 3px 10px rgba(0, 0, 0, 0.3)',
			'box-shadow': '3px 3px 10px rgba(0, 0, 0, 0.3)'
			});
		container.set('styles',{'height':max+8,'width':max+8, 'text-align':'center'})

		container.fade('in');
		img.get('morph').start({
			'height':dest_height,
			'width':dest_width,
			'vertical-align':'middle',
			'-moz-transform':'rotate('+rot+'deg)',
			'-webkit-transform':'rotate('+rot+'deg)',
			'padding':'4px',
			'border':'1px solid #DDDDDD'
		}).chain(function(){
			this.fireEvent('onShow', img)
		}.bind(this));
		this.counter++;
	}
})
