/* ParPilot
	(c) 2006-2010 Omines - www.omines.nl
	
	All rights explicitly reserved - unauthorized reproduction strictly prohibited
*/

// Compatibility stuff
Element.implement({
	effect: function(property, options){
		return new Fx.Tween(this, $extend({property: property}, options));
	},

	effects: function(property, options){
		return new Fx.Tween(this, $extend({property: property}, options));
	}
});

function base64_encode(input) {
	var output = "";
	var chr1, chr2, chr3 = "";
	var enc1, enc2, enc3, enc4 = "";
	var i = 0;

	var keyStr = "ABCDEFGHIJKLMNOP" +
				"QRSTUVWXYZabcdef" +
				"ghijklmnopqrstuv" +
				"wxyz0123456789+/" +
				"=";

	do {
		chr1 = input.charCodeAt(i++);
		chr2 = input.charCodeAt(i++);
		chr3 = input.charCodeAt(i++);

		enc1 = chr1 >> 2;
		enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		enc4 = chr3 & 63;

		if (isNaN(chr2)) {
			enc3 = enc4 = 64;
		} else if (isNaN(chr3)) {
			enc4 = 64;
		}

		output = output +
			keyStr.charAt(enc1) +
			keyStr.charAt(enc2) +
			keyStr.charAt(enc3) +
			keyStr.charAt(enc4);
		chr1 = chr2 = chr3 = "";
		enc1 = enc2 = enc3 = enc4 = "";
	} while (i < input.length);
	
	return output;
}

// Site class - main active content wrapper
var Site = {
	delay: 0,
	regionIndex: -1,
	sortable: null,
	start: function()
	{
		new SmoothScroll({duration:300, transition:Fx.Transitions.Expo.easeOut});
		this.initDropshadows();
		Ellipses.start();
		Menu.initialize();
		if (headerRotateImages.length >= 2)
			HeaderRotation.initialize();
		$$('input.DatePicker').each( function(el){
			new DatePicker(el);
		});
		if (!(typeof google == 'undefined') && !(typeof google.maps == 'undefined') && typeof google.maps.MapLoad == 'function')
			google.maps.MapLoad();
		if ($('sortable-source'))
			this.initSortables();
		if ($('supported'))
		{
			$('supported').getElements('li').each(function(e) {
				if (!e.hasClass('active'))
				{
					br		= new Element('br');
					span	= new Element('span', {'class':'comingsoon','html':'(Coming soon!)'});
					br.injectInside(e);
					span.injectInside(e);
				}
			});
		}
	},
	initSortables: function()
	{
		if ($('trackholes'))
		{
			$('trackholes').getElements('img').each(function(el){
				el.addEvent('click', function(e1){
					var ul = el.getParent().getParent();
					this.sortable.removeItems(el.getParent());
					el.getParent().dispose();
					this.setSortOrder(ul);
				}.bind(this));
			}, this);
		}
		$('sortable-source').getElements('img').each(function(el){
			el.addEvent('click', function(e){
				var li = el.getParent();
				var newEl = new Element('li', {'class':'sortme', 'alt':li.get('alt'), 'html':li.getFirst('span').get('html')})
				var deleteImg = new Element('img', {'src':'/static/images/icon-delete.png', 'alt':''});
				deleteImg.addEvent('click', function(e1){
					var ul = newEl.getParent();
					this.sortable.removeItems(newEl);
					newEl.dispose();
					this.setSortOrder(ul);
				}.bind(this));
				deleteImg.injectInside(newEl);
				newEl.injectInside($('trackholes'));
				this.sortable.addItems(newEl);
				this.setSortOrder(newEl.getParent());
			}.bind(this));
		}, this);
		this.sortable = new Sortables('trackholes', {
			clone:true,
			revert: true,
			initialize: function() { 
				
			},
			onStart: function(el) { 
				el.addClass('dragging');
			},
			onComplete: function(el) {
				el.removeClass('dragging');
				Site.setSortOrder(el.getParent());
			}
		});
	},
	setSortOrder: function(el)
	{
		var sort_order = '';
		el.getElements('li').each(function(li) {
			sort_order = sort_order +  li.get('alt')  + '|';
		});
		if (sort_order.length > 0)
			sort_order = sort_order.substring(0, sort_order.length - 1);
		$('SortOrder').value = sort_order;
	},
	submitTrackCheck: function()
	{
		var error = false;
		if ($('SortOrder').value.length == 0)
		{
			$('sortorderheader').addClass('error');
			error = true;
		}
		else
			$('sortorderheader').removeClass('error');
		if ($('TrackName').value.length == 0)
		{
			$('TrackName').addClass('error');
			error = true;
		}
		else
			$('TrackName').removeClass('error');
		if ($('Difficulty').value.length == 0)
		{
			$('Difficulty').addClass('error');
			error = true;
		}
		else
			$('Difficulty').removeClass('error');
		if (error)
			alert('There were errors in your input. Check the marked input fields and try again.');
		return !error;
	},
	preloadImages: function(images)
	{
		var loader = new Asset.images(images);
	},
	showImage: function(imgObj, url, hoverLi)
	{
		imgObj.set('src', url);
		if ($('courselist'))
		{
			$('courselist').getElements('li').each(function(el){
				el.removeClass('active');
			});
			hoverLi.addClass('active');
		}
	},
	initDropshadows: function()
	{
		$$('.shadow').each(function(el) {
			var txt = el.get('text');
			el.setStyle('z-index', 0);
			el.setStyle('position', 'relative');
			new Element('span', {'html': txt, 'class': 'dropshadow-tl'}).inject(el, 'top');
			new Element('span', {'html': txt, 'class': 'dropshadow-br'}).inject(el, 'top');
		}, this);
	}
};

//Ellipses class - controls ellipsis elements on the site
var Ellipses = {
	start: function()
	{
		this.boundmove = this.mousemove.bindWithEvent(this);
		this.boundout = this.mouseout.bindWithEvent(this);
		this.count = 1;
		this.lookup = new Array();
		this.hovertip = new Element('span', {'class':'ellipsisHover'}).injectInside(document.body);
		this.hovertip.addEvent('mouseleave', this.boundout).addEvent('mousemove', this.boundmove);
		$$('.ellipsis').each(this.prepare, this);
	},
	prepare: function(el)
	{	
		var parent = el.getParent();
		var clipWidth = parent.offsetWidth - (el.offsetLeft - parent.offsetLeft);
		if(el.offsetWidth > clipWidth)
		{
			el.addEvent('mouseenter', this.hover.bindWithEvent(this));
			if(el.id == '')
				el.id = 'ellipsis'+this.count++;
			var content = el.get('text');
			this.lookup[el.id] = content;
			el.title = '';
			if(!window.ie)
			{
				content = content.substring(0, (clipWidth / (el.offsetWidth)) * content.length);
				do {
					el.set('html', content+'&hellip;');
					content = content.substring(0, content.length - 1);
				} while(el.offsetWidth > clipWidth);
			}
		}
	},
	hover: function(e)
	{
		var el = e.target;
		var cnt = this.lookup[el.id];
		this.hovertip.setStyles(el.getStyles('font-size','font-style','color'));
		this.hovertip.setStyles({position:'absolute',left:el.getLeft()-2,top:el.getTop()-2,visibility:'hidden'});
		if(el.get('tag') == 'a')
			cnt = '<a href="'+el.href+'">'+cnt+'</a>';
		this.hovertip.set('html', cnt);
		el.addEvent('mouseleave', this.boundout).addEvent('mousemove', this.boundmove);
		if(this.fx) this.fx.cancel();
		this.show.delay(150, this);
		this.target = el;
	},
	mousemove: function(e)
	{
		$clear(this.timer);
	},
	mouseout: function(e)
	{
		var c = e.target.getCoordinates();
		if(c.left > e.client.x || c.right < e.client.x || c.top > e.client.y || c.bottom < e.client.y)
			this.timer = this.hide.delay(250, this);
	},
	show: function(e)
	{
		this.fx	= new Fx.Tween(this.hovertip, {duration:'short'});
		this.fx.start('opacity', 0.5, 1);
		//this.fx = new Fx.Style(this.hovertip, 'opacity').start(0.5, 1);
	},
	hide: function(e)
	{
		this.fx.cancel();
		this.hovertip.setStyle('visibility','hidden');
		if(this.target)
			this.target.removeEvent('mouseleave', this.boundout).removeEvent('mousemove', this.boundmove);
		this.target = null;
	}
};

var HeaderRotation = {
	initialize: function()
	{
		this.rotateDelay	= 12000;
		this.rotateDuration	= this.rotateDelay / 10;
		this.rotateActive	= 0;
		new Element('div', {'id':'header-rotation'}).inject('imagefader', 'bottom');
		headerRotateImages.each(function(imgName, idx){
			rimg = new Element('div', {'styles':{'background':'url('+imgName+')'}});
			rimg.setStyles({'opacity':0}).set('tween', {duration: this.rotateDuration}).inject($('header-rotation'));
		}.bind(this));
		this.headers	= $('header-rotation').getChildren('div');
		this.rotateHeader.periodical(this.rotateDelay, this);
	},
	rotateHeader: function()
	{
		nImg = (this.rotateActive + 1 >= this.headers.length) ? 0 : this.rotateActive + 1;
		this.headers[this.rotateActive].tween('opacity', 0);
		this.headers[nImg].tween('opacity',1);
		this.rotateActive = nImg;
	}
};

var Menu = {
	initialize: function()
	{
		if (!$('menu'))
			return;
		this.ie7		= false;
		if (Browser.Engine.trident && Browser.Engine.version == 5)
			this.ie7	= true;
		this.mainOffset	= 0;
		this.initMenu	= this.activeMenu	= false;
		this.timers		= { menuHover: false, menuOut: false };
		this.maxLeft	= $('menu').getFirst('li').getPosition($('menu'))['x'];
		this.maxRight	= $('submenu').getWidth() - parseInt($('submenu').getStyle('padding-left')) - parseInt($('submenu').getStyle('padding-right'));
		if (this.maxLeft == 0)
			this.maxRight	= this.maxRight - 11;
		
		$$('#menu > li').each(function (r) {
			if ($('sub'+r.get('id')))
			{
				if (r.hasClass('active')) this.activeMenu	= r.get('id');
				if (!$('sub'+r.get('id')).hasClass('active')) $('sub'+r.get('id')).addClass('active');
				var listItem		= r.getWidth();
				var submenu			= $('sub'+r.get('id')).getWidth();
				// ie 7 fix
				if (this.ie7)
				{
					var submenu 	= 1;
					var submenuKids	= $('sub'+r.get('id')).getChildren('li');
					for (var si = 0; si < submenuKids.length; si++)
						submenu	= submenu + parseInt(submenuKids[si].offsetWidth);
				}
				var itemCenter		= r.getPosition($('menu'))['x'] + Math.floor(listItem / 2);
				var childLeft		= itemCenter - Math.floor(submenu / 2);
				if (childLeft < this.maxLeft)
					$('sub'+r.get('id')).setStyle('left', 0);
				else if (itemCenter + Math.floor(submenu / 2) > this.maxRight)
					$('sub'+r.get('id')).setStyle('left', this.maxRight - submenu);
				else
					$('sub'+r.get('id')).setStyle('left', childLeft);
				//r.addEvent('click', function() { this.onClick(r.get('id')); }.bind(this));
				$('sub'+r.get('id')).removeClass('active');
			}
			r.addEvents({
				mouseout:	function() { this.onMouseOut(r.get('id')); }.bind(this),
				mouseover:	function() { this.cancelMouseOut(); this.onMouseOver(r.get('id')); }.bind(this)
			});
		}.bind(this));
		
		if (!this.activeMenu)
			this.activeMenu	= $('menu').getFirst('li');
		this.initMenu	= this.activeMenu;
		this.activateMenu(this.activeMenu, null);
	},
	onClick: function(id)
	{
		$clear(this.timers.menuHover);
		this.doMouseOver(id);
	},
	onMouseOver: function(id)
	{
		this.setHoverTimer(id);
	},
	doMouseOver: function(id)
	{
		$$('#menu li').each(function (r) {
			r.removeClass('active');
			if ($('sub'+r.get('id'))) $('sub'+r.get('id')).removeClass('active');
		});
		$('sub'+this.activeMenu).removeEvents('mouseout').removeEvents('mouseover');
		
		$(id).toggleClass('active');
		if ($('sub'+id)) $('sub'+id).toggleClass('active');
		$('sub'+id).addEvents({
			mouseout:	function() { this.onMouseOut(id); }.bind(this),
			mouseover:	function() { this.cancelMouseOut(id); this.cancelMouseOut(); }.bind(this)
		});
		this.activeMenu	= id;
	},
	onMouseOut: function()
	{
		$clear(this.timers.menuHover);
		if (this.activeMenu != this.initMenu)
			this.setOutTimer();
	},
	cancelMouseOut: function()
	{
		$clear(this.timers.menuOut);
	},
	setHoverTimer: function(id)
	{
		$clear(this.timers.menuOut);
		$clear(this.timers.menuHover);
		this.timers.menuHover	= this.onClick.delay(300, this, id);
	},
	setOutTimer: function()
	{
		$clear(this.timers.menuOut);
		$clear(this.timers.menuHover);
		this.timers.menuOut	= this.restoreMenu.delay(3000, this);
	},
	restoreMenu: function()
	{
		$clear(this.timers.menuOut);
		$clear(this.timers.menuHover);
		this.doMouseOver(this.initMenu);
	},
	activateMenu: function(menuId, subMenuId)
	{
		if ($(menuId))
		{
			$(menuId).addClass('active');
			if ($('sub'+menuId))
			{
				$('sub'+menuId).addClass('active');
				if ($('sub'+menuId+'-'+subMenuId))
					$('sub'+menuId+'-'+subMenuId).addClass('active');
			}
		}
		else
			$('menu-home').addClass('active');
	}
};

// Set event to start running active content when DOM is loaded
window.addEvent('domready', function() { Site.start(); });
