window.addEvent('domready', loadpage);

var Image2Blocks = new Class({

	numrows: 0,
	numcols: 0,
	blocks: new Array(),
	container: null,

 	options: {
 		blocksize: {x: 50, y: 50},
 		styles: {'overflow': 'hidden'}
 	},

	initialize: function(img, options){
		img = $(img);
 		this.setOptions(options);
 		this.blocks = new Array();
 		this.container = null;

		// Alias for 100%
 		if (this.options.blocksize.x == '100%') this.options.blocksize.x = img.offsetWidth;
 		if (this.options.blocksize.y == '100%') this.options.blocksize.y = img.offsetHeight;

 		this.options.blocksize.x = this.options.blocksize.x.toInt();
 		this.options.blocksize.y = this.options.blocksize.y.toInt();

 		this.numcols = Math.ceil(img.offsetWidth  / this.options.blocksize.x);
 		this.numrows = Math.ceil(img.offsetHeight / this.options.blocksize.y);

 		// Create blocks of image
 		var blockidx = 0;
		for (var i=0; i<this.numrows; i++) {
			var bpy = i*this.options.blocksize.y;
			var bwy = (i==this.numrows-1?(img.offsetHeight-bpy):this.options.blocksize.y).toInt();
			for (var j=0; j<this.numcols; j++) {
				var bpx = j*this.options.blocksize.x;
				var bwx = (j==this.numcols-1?(img.offsetWidth-bpx):this.options.blocksize.x).toInt();
				this.blocks[blockidx] = new Element('div', {
						'styles': {
							'position': 'absolute',
							'top': (bpy)+'px',
							'left': (bpx)+'px',
							'width': bwx+'px',
							'height': bwy+'px',
							'background': 'url('+img.src+') no-repeat',
							'background-position': (-1*bpx)+'px '+(-1*bpy)+'px'
						}
					});
				this.blocks[blockidx].posx = (bpx)+'px';
 				this.blocks[blockidx].posy = (bpy)+'px';
 				blockidx++;
			}
		}

		// Replace img with new div
 		this.container = new Element('div');
 		this.container.setStyles({
				'position': 'relative',
				'width': img.offsetWidth,
				'height': img.offsetHeight
			});
 		this.container.setStyles(this.options.styles);
		this.container.adopt(this.blocks);
		img.replaceWith(this.container);
	},

	getBlocks: function(order, rowcol) {
		rowcol = rowcol?rowcol.toInt():0;
		if (order == 'random') {
			// Return blocks randomized
			var blockscp = this.blocks.copy();
			blockscp.shuffle();
			return blockscp;
		} else if (order == 'row') {
			// Return 1 row of blocks
			if (rowcol >= this.numrows) return null;
			var blockscp = new Array();
			for (var i=0; i<this.numcols; i++) {
				blockscp[i] = this.blocks[(rowcol*this.numcols)+i];
			}
			return blockscp;
		} else if (order == 'column') {
			// Return 1 column of blocks
			if (rowcol >= this.numcols) return null;
			var blockscp = new Array();
			for (var i=0; i<this.numrows; i++) {
				blockscp[i] = this.blocks[rowcol+(i*this.numcols)];
			}
			return blockscp;
		} else {
			// Return blocks as is
			return this.blocks;
		}
	}
});
Image2Blocks.implement(new Options);

var imgFxs = new Array();
function loadpage()
{
	if ($("navigatie")) {
		initmenu();
	}

	new imageFader($$('#imgfader-home img'), {duration: 1000, interval: 3500});
	new imageFader($$('#imgfader img'), {duration: 1000, interval: 3500});
	new imageFader($$('#imgfader-collection img'), {duration: 1000, interval: 3500});
	//var imgfades = $$('#imgfader img');
	/*[$$('#imgfader img'), $$('#imgfader-home img')].each(function(imgfades) {
		imgfades.each(function(img, q) {
				imgFxs[q] = new Image2Blocks(img, {blocksize:{x: '100%', y: 10}, 'styles': {'position': 'absolute', 'top': '0px', 'left': '0px'}});
				var blocks = imgFxs[q].getBlocks();
				blocks.each(function(block, j) {
						block.fx = new Fx.Style(block, 'left', {duration:1000, transition:Fx.Transitions.Elastic.easeOut});
						block.fx.set(-500);
					});
			});

		if (imgfades[0]) showimg(0);
	});*/

	$$('div.thumbs').each(function(div) {
		var imglarge = new Element('div').setStyle('width', '3000px').inject($(div.getProperty('id')+'_large'));
		var thumbs = div.getElements('a');
		var imgsfx;
		var imgs = [];
		function showimage(idx) {
 			var obj = {};
			imgs.each(function(img, i) {
				if (i == idx) {
					obj[i] = {'opacity': [imgs[i].getStyle('opacity'), 1]};
					imgs[i].setStyle('z-index', 2);
				} else {
					obj[i] = {'opacity': [imgs[i].getStyle('opacity'), 0]};
					imgs[i].setStyle('z-index', 1);
				}
			});
			imgsfx.start(obj);
			thumbs.removeClass('current');
			thumbs[idx].addClass('current');
		}
		thumbs.each(function(img, i) {
			imgs[imgs.length] = new Asset.image(img.getProperty('href')).inject(imglarge);
			img.addEvent('click', function(e) {
				new Event(e).stop();
				showimage(i);
			});
		});
		imgsfx = new Fx.Elements(imgs, 'opacity', {
			duration: 300,
			transition: Fx.Transitions.Sine.easeInOut
		});
		if (thumbs[0]) {
			showimage(0);
		}
	});

	if ($('ticker')) {
		var speed = 10000;
		var width = $('ticker').getSize().size.x;
		$('ticker').setHTML($('ticker').innerHTML + $('ticker').innerHTML + $('ticker').innerHTML);
		$('ticker').setStyles({
			'overflow': 'hidden',
			'width': width*3
		});	
		
		var tickerfx = new Fx.Style($('ticker'), 'margin-left', {
			duration: speed,
			transition: Fx.Transitions.linear,
			onComplete: function tick() {
				tickerfx.start(0, -1*width);
			}
		});
		tickerfx.start.delay(1000, tickerfx, [0, -1*width]);
	}

	// Get all elements with className newwindow and attach handler
	var newwinlinks = document.getElements('.newwindow');
  newwinlinks.each(function(node) {
      node.addEvent('click', opennewwin);
    });
}

function showimg(curimgFxs)
{
	var blocks, i, k;

	// Swap z-index
	var previmgFxs = curimgFxs==0?imgFxs.length-1:curimgFxs-1;
	imgFxs[previmgFxs].container.setStyle('z-index', 1);
	imgFxs[curimgFxs].container.setStyle('z-index', 2);

	// Start animation
	for (i=0, k=0; blocks = imgFxs[curimgFxs].getBlocks('row', i); i++)
	{
 		blocks.each(function(block) {
  			(function(){block.fx.start(block.posx)}).delay(50*k);
  			k++;
  		});
	}

	if (curimgFxs != previmgFxs)
	{
		// Reset position
		blocks = imgFxs[previmgFxs].getBlocks();
		blocks.each(function(block) {(function(){block.fx.set(-500)}).delay(50*k);});
		
		curimgFxs = imgFxs[curimgFxs+1]?curimgFxs+1:0;
		setTimeout('showimg('+curimgFxs+')', 10000);
	}
}

function opennewwin(event)
{
	// Open link in new window
	window.open(searchtagup(this, 'A').href, '_blank');
	eventObj = new Event(event);
	eventObj.stop();
}

function searchtagup(el, tag)
{
	tag = tag.toUpperCase();
	if (!el.parentNode) return false;
	return el.tagName==tag?el:searchtagup(el.parentNode, tag);
}

function initmenu()
{
	var szNormal = 29;
	var szFull   = 40;
	var szSmall  = Math.round($("navigatie").hasClass('home')?(szNormal*6-szFull)/5:(szNormal*5-szFull)/4);

	$('tohome').addEvent('click', tohome);

	var kwicks = $$("#navigatie li a");
	var fx = new Fx.Elements(kwicks, {wait: false, duration: 300, transition: Fx.Transitions.Sine.easeOut});
	kwicks.each(function(kwick, i) {
		kwick.addEvent('click', menuclicked);
		kwick.addEvent("mouseenter", function(event) {
			if (kwick.hasClass('selected')) {
				$("navigatie").fireEvent('mouseleave');
				return;
			}
			var o = {};
			o[i] = {height: [kwick.getStyle("height").toInt(), szFull]}
			kwicks.each(function(other, j) {
				if(i != j) {
					var w = other.getStyle("height").toInt();
					if(w != szSmall && !other.hasClass('selected')) o[j] = {height: [w, szSmall]};
				}
			});
			fx.start(o);
		});
	});

	$("navigatie").addEvent("mouseleave", function(event) {
		var o = {};
		kwicks.each(function(kwick, i) {
			o[i] = {height: [kwick.getStyle("height").toInt(), szNormal]}
		});
		fx.start(o);
	})
}

function tohome(event)
{
	var navel = $("navigatie");
	if (!navel.hasClass('home'))
	{
		eventObj = new Event(event);
		eventObj.stop();
		$E("#navigatie li a.selected").removeClass('selected');
		var navChange = new Fx.Style(navel, 'width', {duration:1000, onComplete: function(){window.open('home', '_self');}});
		navChange.start(820);
	}
}

function menuclicked(event)
{
	var navel  = $("navigatie");
	var kwicks = $$("#navigatie li a");
	var oldsel = '';

	eventObj = new Event(event);
	eventObj.stop();

	kwicks.each(function(kwick) {
		kwick.removeEvents('mouseenter');
		kwick.removeEvents('click');
		if (kwick.hasClass('selected'))
		{
			oldsel = kwick.id;
			kwick.removeClass('selected');
		}
	});

	this.addClass('selected');

	navel.fireEvent('mouseleave');
	navel.removeEvents('mouseleave');

	setTimeout("swapmenu('"+this.id+"', '"+oldsel+"')", 300);
}

function swapmenu(menuid, oldsel)
{
	var navel = $("navigatie");
	var curel = $(menuid);
	if (navel.hasClass('home'))
	{
		if (oldsel)
		{
			$('submenu').removeClass(oldsel);
		}
		$('submenu').addClass(curel.id);
		var navChange = new Fx.Style(navel, 'width', {duration:1000, onComplete: function(){window.open(curel.href, '_self');}});
		navChange.start(382);
	}
	else
	{
		var _curel = curel;
		var navChange = new Fx.Style(navel, 'width', {duration:1000, onComplete: function(){
				$('submenu').empty();
				if (oldsel)
				{
					$('submenu').removeClass(oldsel);
				}
				$('submenu').addClass(_curel.id);
				var navChange2 = new Fx.Style(navel, 'width', {duration:1000, onComplete: function(){window.open(_curel.href, '_self');}});
				navChange2.start(382);
			}});
		navChange.start(820);
	}
}

Array.prototype.shuffle = function() {
	var l = this.length;
	for (var i = 0; i < l; i++) {
		// Random item in this array.
		var r = parseInt(Math.random() * l);
		var obj = this[r];

		// Swap.
		this[r] = this[i];
		this[i] = obj;
}
}

var imageFader = Fx.Elements.extend({

	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();
			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(idx) {
		var obj = {};
		this.elements.each(function(el, i) {
			if (el.getStyle('opacity') != 0 && i != idx) {
				obj[i] = {'opacity': 0};
				el.setStyle('z-index', 1);
			} else if (i == idx) {
				obj[i] = {'opacity': 1};
				el.setStyle('z-index', 2);
			}
		});
		return this.start(obj);
	}
});
