YAHOO.util.Event.addListener(window, "load", initEvents); 
YAHOO.util.Event.addListener(window, "resize", setMenuPosition); 

var cachedboxes = new Array();

function initEvents(){
	// Init map
	initialize();
	setMenuPosition();	
	initContentNavigation();
	setMenuMouseOvers();
	setIntro();
	YAHOO.util.Event.addListener(window, "keydown", DisableTab); 
}

function initContentNavigation(){
	// Get all elements in menu that should open a content box
	var contentLinks =	getElementsByClassName(document, 'a', 'contentlink');
	for (var i in contentLinks){
 		YAHOO.util.Event.addListener(contentLinks[i], "click", toggleContent); 
  		YAHOO.util.Event.addListener(contentLinks[i], "focus", function(){ this.blur();}); 
	}
}

function setMenuMouseOvers(){
	
	var imgLinks = new Array('dolls', 'game', 'commercial');
	for( var i=0; i<imgLinks.length; i++){
		YAHOO.util.Event.addListener(document.getElementById(imgLinks[i]), "mouseover", function(){
			imgs = this.getElementsByTagName('img');
			imgs[0].src = '/img/banners/' + this.id + '_hover.gif';
		}); 
		YAHOO.util.Event.addListener(document.getElementById(imgLinks[i]), "mouseout", function(){
			imgs = this.getElementsByTagName('img');
			imgs[0].src = '/img/banners/' + this.id + '.gif';
		}); 
	}
}

function toggleContent(e){
	
	// Prevent the default browser behaviour 
	if (e.preventDefault) e.preventDefault();
	else e.returnValue = false;

	// We replace the /html/ part in de url with /ajax/
	var ajaxHref = this.href.replace('\/html\/', '\/ajax\/');

	// Hide all open boxes and check if it has been openened before
	var isCached = false;
	for(var i=0; i < cachedboxes.length; i++){
		
		if(cachedboxes[i].visible && cachedboxes[i].showAnimFinished ){
			cachedboxes[i].hide();
		}
		if(cachedboxes[i].url == ajaxHref){
			var boxToShow = cachedboxes[i];
			isCached = true;
		}
	}
	
	if(!isCached){
		urchinTracker(ajaxHref); // Google Analytics 
		var box = new ContentBox(ajaxHref);
		box.getContent();
		box.animatedShow();
		cachedboxes.push(box);
	}else if(isCached && !boxToShow.visible ){
		urchinTracker(ajaxHref); // Google Analytics 
		boxToShow.animatedShow();
	}
}

function triggerContentBox(url){
	var ajaxUrl = '/ajax/' + url;
	var box = new ContentBox(ajaxUrl);
	urchinTracker(ajaxUrl);
	box.getContent();
	box.animatedShow();
	cachedboxes.push(box);		
}

function ContentBox(url){
	this.url = url;
	this.showAnimFinished = false;
	this.hideAnimFinished = false;
	this.visible = false;;
	this.height = 500;
		
	var uniqueUrl = this.url.replace(/:/g,'');
	this.uniqueId = uniqueUrl.replace(/\//g, '');
	this.init();
}

ContentBox.prototype.init = function(){
	this.response = '';
	this.boxesContainer = document.getElementById('boxesContainer');
	var boxC = document.createElement('div');
	boxC.className = 'contentBox';
	boxC.id = this.uniqueId;
	this.boxesContainer.appendChild(boxC);
	this.dynamicContent = document.getElementById(this.uniqueId);
}

ContentBox.prototype.getContent = function(){
	this.clearResponse();
	currObj = this;
	var callback = {
		success:function(o){
			currObj.storeResponse(o);	
			currObj.fill();		
		}
	}
	url = this.url;
	var request = YAHOO.util.Connect.asyncRequest('GET',url, callback); 
}

ContentBox.prototype.animatedShow = function(){

	this.dynamicContent.style.background = 'url("/img/layout/box_top_bg.gif")';
	this.dynamicContent.style.zIndex = 20;
	this.dynamicContent.innerHTML = '<img class="loader" src="/img/layout/ajax_loader.gif" alt="loading" title="loading" />';
	
	var anim = new YAHOO.util.Anim(this.dynamicContent);
    anim.attributes.height = { from: 0, to: this.height }; 
    anim.method = YAHOO.util.Easing.easeOut;
    anim.duration = 0.7;
  
    var animCallback = delegate(this, function(){
		this.showAnimFinished = true;
		this.fill();
	})
    
	anim.onComplete.subscribe(animCallback); 
	this.visible = true;
	anim.animate();
}

ContentBox.prototype.simpleShow = function(){
	this.dynamicContent.style.zIndex = 20;
	//this.dynamicContent.innerHTML = '<img class="loader" src="/img/layout/ajax_loader.gif" alt="loading" title="loading" />';
	this.visible = true;
}

ContentBox.prototype.fill = function(){
	
	// Only fill the box when animation is finished
	if(!this.showAnimFinished || this.response == ''){
		return;
	}

	this.dynamicContent.innerHTML =	this.response;
	
	// Insert close image before h2
	h2 = this.dynamicContent.getElementsByTagName('h2')[0];
	var closeImg = document.createElement('img');
	closeImg.className = "contentClose";
	closeImg.src = "/img/layout/button_close.gif";
	closeImg.alt = "Venster sluiten";
	closeImg.title = "Venster sluiten";
	
	var closeFunc = delegate(this, function(){
		this.hide();
	})
	closeImg.onclick = closeFunc;
	
	this.dynamicContent.insertBefore(closeImg, h2);
	
	// Handle links in ajax generated content
	var links = this.dynamicContent.getElementsByTagName('a');
	for (var i = 0; i<links.length; i++){
		
		if(!links[i].href.contains('geenwapen') || links[i].href.indexOf('#') > -1 || links[i].className == 'externalLink' ){	// External links -> don't load internally 
			continue;
		}
		var a = links[i]
		if(a.attachEvent)
			a.attachEvent('onclick', delegateWithEvent(this, this.handleInternalLink, a));
		else if(a.addEventListener)
			a.addEventListener('click', delegateWithEvent(this, this.handleInternalLink, a), true);
		else
			a.onclick = delegate(this, this.handleInternalLink, a);
	}	
	
	// Now check if this page contains the addFriends form
	var aForm = document.getElementById('addReaction');
	var noScriptButton = document.getElementById('submitHTML');
	if(aForm && noScriptButton ){
		// remove html button and insert ajax button
		
		
		noScriptButton.style.display = 'none';
		noScriptButton.parentNode.removeChild(noScriptButton);

		var img = document.createElement('img');
		img.id="submitaddReaction";
		img.src="/img/verstuur.gif";
		img.alt="verstuur";
		img.title="verstuur";
		img.style.cursor = "pointer";
		
		insertAfter(aForm.parentNode, img, aForm)
		var callback = {
			success:function(o){
				
				var resp = o.responseText.split('|');
				if(resp !='')
					alert(resp[1]);
			},
			failure:function(o){
				alert('fail');
			}
		};
		img.onclick = function(){
			var postData = '&email=' + document.getElementById('email').value;
			postData += '&friend1=' + document.getElementById('friend1').value;
			postData += '&friend2=' + document.getElementById('friend2').value;
			postData += '&friend3=' + document.getElementById('friend3').value;			
			postData += '&friend4=' + document.getElementById('friend4').value;	
			postData += '&friend5=' + document.getElementById('friend5').value;		
							
			var request = YAHOO.util.Connect.asyncRequest('POST','/page.php?go=invite&tpl=ajax', callback, postData );	
			return false;
		}; 
		
	}
	
	// Check for MSN Form
	var msnForm = document.getElementById("inviteMsnContacts");
	var msnSubmit = document.getElementById("htmlGetFriends");

	if(msnForm && msnSubmit){

		// Remove html submit button and add an image
		msnSubmit.style.display = 'none';
		msnSubmit.parentNode.removeChild(msnSubmit);

		var img = document.createElement('img');
		img.id="getFriends";
		img.src="/img/verder.gif";
		img.alt="verstuur";
		img.title="verstuur";
		img.style.cursor = "pointer";
		insertAfter(msnForm.parentNode, img, msnForm);
		img.onclick = function(){
			
			var msnEmail = document.getElementById("MSNemail").value;
			var msnPwd	 = document.getElementById("MSNpassword").value;
			if (!msnEmail || !msnPwd){
				alert ('De gegevens zijn onjuist');
				return;
			}
			
			document.getElementById("getFriends").style.display = "none";
			document.getElementById("inviteMsnContacts").style.display = "none";
			document.getElementById("MSNloadingIcon").style.display = "inline";
			
			document.getElementById("addReaction").style.display = "none";
			document.getElementById("submitaddReaction").style.display = "none";
			document.getElementById("msnInfo").style.display = "none";
			document.getElementById("otherInfo").style.display = "none";	
		
			// getXML in messenger.js
			getXML(msnEmail, msnPwd);
		}

		
	}
	
}

ContentBox.prototype.handleInternalLink =function(e,a){
	
	// Prevent the default browser behaviour 
	if (e.preventDefault) e.preventDefault();
	else e.returnValue = false;
	var ajaxUrl = a.href.replace('\/html\/', '\/ajax\/');
	this.url = ajaxUrl;
	
	// Notify Analytics that a certain page has been openened
	urchinTracker(ajaxUrl); 
	this.getContent();
	
}


ContentBox.prototype.storeResponse = function(o) { this.response = o.responseText; }
ContentBox.prototype.clearResponse = function(o) { this.response = ''; }

ContentBox.prototype.hide = function(){

	this.dynamicContent.style.zIndex = 10;
	this.dynamicContent.innerHTML = '';
    var anim = new YAHOO.util.Anim(this.dynamicContent);
    anim.attributes.height = { from: this.height, to: 0}
    anim.method = YAHOO.util.Easing.easeIn;
    anim.duration = 0.4;
        var animCallback = delegate(this, function(){
		this.visible = false;
	})
    
	anim.onComplete.subscribe(animCallback); 

	anim.animate();
}

/*
 * 	Menu Repositioning Functions
 */

var minHeight = 688; // When the viewport gets below this height, menu should be repositioned
var menuContainerHeight = 33;
var bottomMargin = 10; // The margin between menu and the viewport (when repositioned)
var defaultVertPos = 645; // The default distance from menu till top of the viewport
var menuContainerWidth = 822; 
var defaultHorzPos = 100; // Distance from left map border to menu

function setMenuPosition() {
	moveIntro(); // position the intro movie as well
	if (document.getElementById) {	
		var menuContainer 	= document.getElementById('menuContainer');
		// Set vertical position
		var windowHeight=getWindowHeight();	
		if (windowHeight < minHeight) {
			// Viewport has too little height to display menu in regular position , so manually position			
			menuContainer.style.top= (windowHeight-(menuContainerHeight) - bottomMargin) + 'px';
		}else{
			// Use default position
			menuContainer.style.top = defaultVertPos + 'px';
		}
		
		// Set horizontal position
		var windowWidth = getWindowWidth();
		// Reposition the menu when screen gets wider
		var menuLeftPos = ( windowWidth / 2 ) - ( menuContainerWidth / 2 );
		if (menuLeftPos > defaultHorzPos){
			menuContainer.style.left = menuLeftPos + 'px';
		}else{
			// Use default position
			menuContainer.style.left = defaultHorzPos + 'px';
		}	

	}
}

function setIntro() {
	var c = readCookie('showintro');
	if(c == null) {
		createCookie('showintro', '1', 1);
		var o = document.getElementById("intro");
		if(o) {
			moveIntro();
			o.style.display = "block";
		}
	}
}

function moveIntro() {
	var o = document.getElementById("intro");
	if(o) {
		var dim = getClientDimensions();	
		var tx = Math.round((dim.width / 2) - 360);
		var ty = Math.round((dim.height / 2) - 288);
		o.style.left = tx + "px";
		o.style.top = ty + "px";
	}
}

function hideIntro() {
	var osx = document.getElementById("intro");
	if(osx) {
		osx.style.left = "0px";
		osx.style.top = "1000px";
		osx.style.display = 'none';
	}
}
