/**
 *	Scripts for BuitenKans.
 *	mixed jQuery and 'old school', sorry ;)
 *
 *	@author frank at frankbosma dot nl
 */
var MENU; /** menu attributes */

$(document).ready(function(){
	if($("body").attr("id") == "body"){

		/**
		 * Add deprecated _blank targets
		 */
		$("a[@rel='external']").each(function(){

			$(this).attr("target", "_blank");

			var addToTitle = "(opent in een nieuw scherm)";
			if(typeof $(this).attr("title") != "undefined"){
				$(this).attr("title", $(this).attr("title") +" "+ addToTitle);
			}else{
				$(this).attr("title", addToTitle);
			}
		});

		/** Clock */
		var clock	= new Clock("clock");

		/** Scale site to available height */
		resizeSite();

		/** Add mouse over submenu's */
		MENU = {
			pos		: $.iUtil.getPosition($("#menu")[0]),
			size	: $.iUtil.getSize($("#menu")[0])
		}
		createSubMenuus($("#menu"));

		/** activate 'other site' tool */
		$("#moreSites select").bind("change", function(){
			if($(this).val() != "-1"){
				document.location.href = $(this).val();
			}else{
				$(this).blur();
				window.focus();
			}
		});

		/** activate 'choose activity' */
		initActivityPull();

		/** search */
		$('a.search').attr("href", "#").bind("click", function(){
			$(this).parent().submit();
			return false;
		});
	}
});

function initActivityPull(){
	if($('#activities').length > 0){
		$('#activities select').bind('change', pulled)[0].selectedIndex=0;
	}
}

function pulled(){

	$(this).blur();
	window.focus();

	/** remove all pulls after this one */
	$(this).nextAll('select').remove();

	/** based on choice, get new pulls */
	var id = parseFloat($(this).val());
	if( id != -1){

		var pull = $(this);
		var list = $.ajax({
			url: "scripts/activities.php",
			async: false,
			data: "folder="+ id,
			dataType: "xml",
			success: function(data){

				/** if elements are found, create an element pull */
				if( $(data).find("list > elements > element").length > 0 ){

					var newPull = $('<select><option value="-1" selected="selected">kies een activiteit</option></select>');

					$(data).find("list > elements > element").each(function(){
						newPull.append('<option value="'+ $(this).attr("id") +'">'+ $(this).attr("name") +'</option>');
					});
					newPull[0].selectedIndex = 0;
					newPull.bind("change", function(){

						/** open URL */
						document.location.href = "index.php?item="+ $(this).val();
					});
					pull.after(newPull);
					window.onresize();

				/** otherwise folders */
				}else if( $(data).find("list > folders > folder").length > 0 ){

					var newPull = $('<select><option value="-1" selected="selected">kies een categorie</option></select>');

					$(data).find("list > folders > folder").each(function(){
						newPull.append('<option value="'+ $(this).attr("id") +'">'+ $(this).attr("name") +'</option>');
					});
					newPull[0].selectedIndex = 0;
					newPull.bind("change", pulled);
					pull.after(newPull);
					window.onresize();
				}
			}
		});
	}
}
/**
 * activity functions
 */

/**************************************************************************
 * Screener functions
 */

var Screener = {
	ieLow: (($.browser.msie && !isNaN($.browser.version) && parseInt($.browser.version) < 7)? true : false)
};


/**************************************************************************
 * Conventional functions
 */


function isBrowserSupported(){
	return(typeof(document.getElementById) != "undefined");
}


function resizeSite(){
	if(isBrowserSupported()){

		if(Screener.ieLow){
			window.onresize = function(){}
		}else{
			window.onresize = function(){

				var objWrapper 	= $("#siteWrapper");
				var objContent 	= $("#content");
				var objNav		= $("#navigation");
				var objSide		= $("#sidebar");
				var objBleft	= $("#navigation div.bottom");
				var objBright	= $("#sidebar div.bottom");

				var heights		= {
					"wrapper" : objWrapper[0].offsetHeight,
					"content" : objContent[0].offsetHeight,
					"nav" : objNav[0].offsetHeight - objBleft[0].offsetHeight,
					"side" : objSide[0].offsetHeight - objBright[0].offsetHeight,
					"bleft" : objBleft[0].offsetHeight,
					"bright" : objBright[0].offsetHeight
				}

				var hStart 		= $("#header")[0].offsetHeight;

				intBh = getInnerHeight();
				intCh = hStart + ((heights['content'] > heights['side'])? ((heights['content'] > heights['nav'])? heights['content'] : heights['nav']) : ((heights['side'] > heights['nav'])? heights['side'] : heights['nav'])) + 30;

				if(intBh > intCh){
					objWrapper[0].style.height = intBh +"px";

					/** also size .bottoms to what's left - 10 */
					objBleft[0].style.height = (intBh - hStart - heights['nav'] - 10) +"px";
					objBright[0].style.height = (intBh - hStart - heights['side'] - 10) +"px";

				}else{
					objWrapper[0].style.height = intCh +"px";

					/** also size .bottoms */
					objBleft[0].style.height = (intCh - hStart - heights['nav'] - 10) +"px";
					objBright[0].style.height = (intCh - hStart - heights['side'] - 10) +"px";
				}
			};
			window.onresize();

			window.onload = onresize;

		}
	}
}

function getInnerHeight(){
	if(self.innerWidth){
		return self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientWidth)
	{
		return document.documentElement.clientHeight;
	}
	else if (document.body)
	{
		return document.body.clientHeight;
	}
	else return 0;
}

/**************************************************************************
 **************************************************************************
 * JS SubMenus
 */

 function createSubMenuus(root){

 	root.find("a").each(function(){

 		$(this).bind("mouseover", function(){

 			var id = $(this).attr("id").match(/\d+$/)[0];
 			if(typeof SUBMENU[id] != "undefined"){

				if( SUBMENU[id].subs > 0 && !SUBMENU[id].open){

					/** hover if LI */
					if($(this).parent().is("li")){
						$(this).parent().removeClass("nav").addClass("navActive");
					}

					activateSubMenu(id);

					if($("#submenu"+ id).length == 0){
						var pos		= $.iUtil.getPositionLite($(this).parents()[0]);

						/** create a new div */
						var sdiv 	= $('<div id="submenu'+ id +'" class="submenu"><img src="images/loader.gif" width="16" height="16" /></div>');

						$("#menu").append(sdiv);

						var left = ($.browser.msie)? pos.x - MENU.pos.x + MENU.size.wb : (Math.ceil((pos.x - MENU.pos.x) / MENU.size.wb) * MENU.size.wb + MENU.size.wb); /** :( */

						sdiv.css({
							left: 	left +"px",
							top: 	(pos.y - MENU.pos.y) +"px"
						});


						/** (de)activate submenu */
						sdiv.bind("mouseover", function(){

							var id = parseFloat($(this).attr("id").match(/\d+$/)[0]);
							activateSubMenu(id);

						}).bind("mouseout", function(){

							var id = parseFloat($(this).attr("id").match(/\d+$/)[0]);
							deActivateSubMenu(id);
						});

						/** and load subitems by ajax */
						$.ajax({
							url: 	"scripts/subs.php",
							type: 	"POST",
							async: 	true,
							data: 	"folder="+ id,
							dataType:"xml",
							success: function(data){

									/** parent */
								var pId = parseFloat($(data).find("list > folders").attr("root"));

								/** create entries in SUBMENU and links in the div */
								var smenu = $("#submenu"+ pId);
									smenu.empty();


								$(data).find("list > folders > folder").each(function(){

									var sId		= parseFloat($(this).attr("id"));
									var subs	= parseFloat($(this).attr("subs"));
									var name	= unescape($(this).attr("name"));

									SUBMENU[sId] = {
										open:		false,
										active:		false,
										parent:		pId,
										name:		name,
										subs:		subs
									};

									var alink = $("<a id=\"submenulink"+ sId +"\" href=\""+ SUBMENU_BASE + sId +"\">"+ name +"</a>");
									smenu.append(alink);
								});

									/** add footer */
								//smenu.append("<div class=\"submenuFooter\"></div>");

								/** enable subs */
								createSubMenuus(smenu);


                                // AANPASSING MARKVDS:
                                if ($('#submenulink' + pId).offset()) {
                                    var selector = '#submenu' + id + '.submenu';
                                    var newTop = ($('#submenulink' + pId).offset().top - MENU.pos.y);
                                    //$('#clock').html(newTop + 'px');
                                    $(selector).css({ top:  + newTop + 'px' });
                                }

							}
						});

					}else{
						/** content is still loading, just show the div */
						$("#submenu"+ id).show();
					}
				}
 			}

 		}).bind("mouseout", function(){

 			var id = $(this).attr("id").match(/\d+$/)[0];
			if(SUBMENU[id].subs > 0){
				deActivateSubMenu(id);
			}
 		});

 	});
 }

 function activateSubMenu(id){
 	/** activate sub and each parent */
 	if(typeof SUBMENU[id] != "undefined"){
 		SUBMENU[id].active = true;
 		var parent = SUBMENU[id].parent;
 		while(parent != 0){
 			if(typeof 	SUBMENU[parent] != "undefined"){
 						SUBMENU[parent].active = true;
 				parent = SUBMENU[parent].parent;

 			}else{
 				break;
 			}
 		}
 	}
 }

 function deActivateSubMenu(id){
  	/** deactivate sub and each parent */
  	if(typeof SUBMENU[id] != "undefined"){

  		hideSubMenu(id);
  		var parent = SUBMENU[id].parent;
  		while(parent != 0){
  			if(typeof SUBMENU[parent] != "undefined"){
  				hideSubMenu(parent);
  				parent = SUBMENU[parent].parent;
  			}else{
  				break;
  			}
  		}
  	}
 }

 function hideSubMenu(id){
	if(typeof SUBMENU[id] != "undefined"){

		/** set timeout for hiding, if after timeout menu != active, hide */
		SUBMENU[id].active = false;
		setTimeout(function(){
			if(!SUBMENU[id].active){
				if( $("#submenu"+ id).length > 0){
					$("#submenu"+ id).hide();

					if( $("#navlink"+ id).length > 0){
						/** also deHOVER link */
						$("#navlink"+ id).parent().removeClass("navActive").addClass("nav");
					}
				}
			}
		}, 250);
	}
 }


/**************************************************************************
 **************************************************************************
 * A simple clock with Dutch date abbreviations.
 */
function Clock(divClock){

	this.divClock		= divClock;//***	String, Div id
	this.intervalClock;
	this.arrDutchMonths = new Array("Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec");
	this.arrDutchDays = new Array("Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za");

	this._init();
}

Clock.prototype._init = function(){
	this.draw_clock();
	this.setInterval(this, "draw_clock", 1000*10, new Array());//*** each 10 seconds
};

Clock.prototype.get_dutch_date = function(dateNow){
	return( this.get_dutch_day(dateNow) +" "+ dateNow.getDate() +" "+ this.arrDutchMonths[dateNow.getMonth()]);
};

Clock.prototype.get_dutch_day = function(dateNow){
	return(this.arrDutchDays[dateNow.getDay()]);
};

Clock.prototype.draw_clock = function(){

	var dateNow	= new Date();

	var strDate	= this.get_dutch_date(dateNow);

	var strMin	= ""+ dateNow.getMinutes();
	if(strMin.length == 1){strMin	= "0"+ strMin;}

	var strHours	= ""+ dateNow.getHours();
	if(strHours.length == 1){strHours	= "0"+ strHours;};

	if(typeof(document.getElementById) != "undefined"){
		strDate += " "+ strHours +":"+ strMin;
		if(strDate != document.getElementById(this.divClock).innerHTML){
			document.getElementById(this.divClock).innerHTML	= "<span>"+ strDate.toLowerCase() +"</span>";
		}
	}
};

Clock.prototype.setInterval = function(a, b, c, arrArgs){
	var ID, func = function(){
		a[b].apply(a, arrArgs);
	}
	ID = setInterval(func, c, arrArgs);
	return ID;
}