// ############################## MAIN VARS ##############################
buttonColourOver	= '#edd2d2';
buttonColourOut		= '#f0f0f0';
tempElementID		= Math.random();
// ############################## NEW PROTOTYPES ##############################
String.prototype.repeat = function(l){
	return new Array(l+1).join(this);
};

function getExtension (inputString) {
	var dotIndex;
	try {dotIndex = inputString.lastIndexOf(".");} catch (e) {}

	if(dotIndex!=-1) {
		return inputString.substr(dotIndex,inputString.length);
	} else {
		return "";
	}
}

function stripExtension (inputString) {
	var charIndex;
	try {charIndex = inputString.lastIndexOf("/");} catch (e) {}

	if(charIndex!=-1) {
		return inputString.substr(charIndex+1, inputString.length);
	} else {
		return inputString;
	}
}

// ############################## SHOWRESULT FUNCTIONS ##############################
function print_showResults ( results ) {
	var resultsBox = document.getElementById('divShowResults');
	resultsBox.innerHTML = results;
}

function print_pagecontent ( content, targetObjectID ) {
	var targetObject = document.getElementById(targetObjectID);
	targetObject.innerHTML = content;
}

// ############################## STATISTICS FUNCTIONS ##############################
/* Get HTTP object */
function getHTTPObject() {
  var xmlhttp;
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
	  //If fetching xml, use overrideMimeType
	  //xmlhttp.overrideMimeType("text/xml"); 
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}
//http object called - default not active
var isWorking = false;
/* Create the HTTP object */
var http = getHTTPObject();

function writeFileStatistics ( fileName, fileType, pageLocation ) {
	var pageLocation = (pageLocation == null) ? "default" : "";
	if(!fileType) {return;}	
	if (trim(fileName) && !isWorking && http) {	
		// The server-side script
		var url = "static/scripts/script_writefilestats.php?fileName="+escape(fileName)+"&fileType="+escape(fileType)+"&pageLocation="+escape(pageLocation);
		//Send http request
		isWorking = true;
		http.open("GET", url, true);

		http.onreadystatechange = function () {
			//http.onreadystatechange = handleHttpResponse; [handleHttpResponse is a function]
			if (http.readyState == 4) {
				if (http.responseText.indexOf('invalid') == -1) {
					isWorking = false;
					//var xmlDocument = http.responseXML;
				}
			}
		};
		http.send(null);		
	}
	return;
}

// ############################## ADD/STRIP SLASHES ##############################
function addslashes(str) {
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}

// ############################## TRIM ##############################
function trim( inputString ) {
	//leading whitespace
	var regex1 = /\s*((\S+\s*)*)/;
	//trailing whitespace
	var regex2 = /((\s*\S+)*)\s*/;
	if(inputString) {
		inputString = inputString.replace(regex1, "$1");
		inputString = inputString.replace(regex2, "$1");
	}
	return inputString;
};

// ############################## DEBUG FUNCTIONS ##############################
/**
* Function : dump()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
*/
function print_r (arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects
	 for(var item in arr) {
	  var value = arr[item];
	 
	  if(typeof(value) == 'object') { //If it is an array,
	   dumped_text += level_padding + "'" + item + "' ...\n";
	   dumped_text += dump(value,level+1);
	  } else {
	   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
	  }
	 }
	} else { //Stings/Chars/Numbers etc.
	 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
} 

function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}

// ############################## SPRINTF LEADING ZEROES #############
function padDigits(n, totalDigits) {
	n = n.toString(); 
	var pd = ''; 
	if (totalDigits > n.length) { 
		for (i=0; i < (totalDigits-n.length); i++) {
			pd += '0';
		}
	}
	return pd + n.toString(); 
} 

// ############################## ISSET ##############################
function isset(varname)  {
  if(typeof( window[ varname ] ) != "undefined") return true;
  else return false;
}

// ############################## PRINT EMAIL ADDRESSES ##############################
function printEmailAddress ( emailUser, emailDomain, emailTopLevel, innerHTML ) {
 	if(!trim(innerHTML) || innerHTML.toLowerCase()=="email") {innerHTML = emailUser+'@'+emailDomain+'.'+emailTopLevel;	}
	var emailString = '<a href="mailto:'+emailUser+'@'+emailDomain+'.'+emailTopLevel+'">'+innerHTML+'</a>';
	document.write (emailString);
}

// ############################## FORM FUNCTIONS ##############################
function txtOnFocus (obj) {
        obj.style.backgroundImage = '';
}

function txtOnBlur (obj,image) {
        if (obj.value == '') {
        obj.style.backgroundImage = 'url(' + image + ')';
		obj.style.backgroundRepeat = 'no-repeat';
		obj.style.backgroundPositon = 'left center';
	}
}

function bgcolor (thisObjectID, color) {
if (!color) {color='';}
	var thisObject = document.getElementById(thisObjectID);
	if (objectClickedID==thisObjectID) {
		color=markedBGcolor;
	} else {
		thisObject.style.backgroundColor=color;
	}
}

function confirm_logout( targetURL ) {
	input_box = confirm("Weet u zeker dat u wilt uitloggen?");
	if (input_box==true) {
		//window.location = "index.php?show=login&do=logout";
		window.location = targetURL;
	}
}

// ############################## UPLOAD FUNCTIONS ##############################
function preloadimages ( ) {
	var myimages=new Array();
	for (i=0;i<preloadimages.arguments.length;i++) {
		alert("preloading "+preloadimages.arguments[i]);
		img_pre[i]=new Image();
		img_pre[i].src=preloadimages.arguments[i];
	}
}

function showTestAnswer (targetObject, newStatus) {
	if(is_ie) {newStatus="block";}
	if (document.getElementById) {
		// this is the way the standards work
		//alert("document.getElementById");
		var targetObject_style = document.getElementById(targetObject).style;
		if(targetObject_style.display=="none"){targetObject_style.display=newStatus;}
		else {targetObject_style.display="none";}
	}
	 else if (document.all) {
		// this is the way old msie versions work
		//alert("document.all");
		var targetObject_style = document.all[targetObject].style;
		if(targetObject_style.display=="none"){targetObject_style.display=newStatus;}
		else {targetObject_style.display="none";}
	} else if (document.layers) {
		// this is the way nn4 works
		//alert("document.layers");
		var targetObject_style = document.layers[targetObject].style;
		if(targetObject_style.display=="none"){targetObject_style.display=newStatus;}
		else {targetObject_style.display="none";}
	}
}

function setBackground(thisObjectID, imageName) {
	var imageObject = "url(./images/"+imageName+")";
	if (document.getElementById) {
		// this is the way the standards work
		var thisObject = document.getElementById(thisObjectID);
		thisObject.style.backgroundImage=imageObject;
	}
	 else if (document.all) {
		// this is the way old msie versions work
		var thisObject = document.all[thisObjectID];
		thisObject.style.backgroundImage=imageObject;
	} else if (document.layers) {
		// this is the way nn4 works
		var thisObject = document.layers[thisObjectID];
		thisObject.style.backgroundImage=imageObject;
	}
}

/* Toggle layer */
function toggleLayer(layer1, layer2) {
	if (document.getElementById) {
		// this is the way the standards work
		var layer1_style = document.getElementById(layer1).style;
		var layer2_style = document.getElementById(layer2).style;
		layer1_style.display = "block";
		layer2_style.display = "none";
	}
	 else if (document.all) {
		// this is the way old msie versions work
		var layer1_style = document.all[layer1].style;
		var layer2_style = document.all[layer2].style;
		layer1_style.display = "block";
		layer2_style.display = "none";
	} else if (document.layers) {
		// this is the way nn4 works
		var layer1_style = document.layers[layer1].style;
		var layer2_style = document.layers[layer2].style;
		layer1_style.display = "block";
		layer2_style.display = "none";
	}
}

function showhideLayer (targetObject, newStatus) {
	if(is_ie) {newStatus="block";}
	if (document.getElementById) {
		// this is the way the standards work
		//alert("document.getElementById");
		var targetObject_style = document.getElementById(targetObject).style;
		if(targetObject_style.display=="none" || targetObject_style.display==""){targetObject_style.display=newStatus;}
		else {targetObject_style.display="none";}
	}
	 else if (document.all) {
		// this is the way old msie versions work
		//alert("document.all");
		var targetObject_style = document.all[targetObject].style;
		if(targetObject_style.display=="none" || targetObject_style.display==""){targetObject_style.display=newStatus;}
		else {targetObject_style.display="none";}
	} else if (document.layers) {
		// this is the way nn4 works
		//alert("document.layers");
		var targetObject_style = document.layers[targetObject].style;
		if(targetObject_style.display=="none" || targetObject_style.display==""){targetObject_style.display=newStatus;}
		else {targetObject_style.display="none";}
	}
}

activeVideoID = "";
function toggleVideo (newStatus, videoFile, targetObjectID, width, height) {
	var targetObject			 = document.getElementById(targetObjectID);	
	var videoExtension			 = getExtension(videoFile);
	var videoRandomExtension	 = Math.round(10000000*Math.random());
	var containerID				 = "";
	//videoFile					+= '?'+videoRandomExtension;
	var avType					 = 4;
	var avImage					 = "";
	var avBackgroundColor		 = "#ffffff";
		
	//Close active video before opening new video
	if(activeVideoID!=="" && activeVideoID!==targetObjectID) {
		var activeVideoObject = document.getElementById(activeVideoID);
		activeVideoObject.innerHTML='';
	}
	
	switch (videoExtension) {
		case ".wmv":
			if(!width) { width = 270;}
			if(!height) { height = 270;}
			if(newStatus) {
				activeVideoID = targetObjectID;	
				targetObject.innerHTML='<table border=0 cellpadding=0 cellspacing=0><tr><td style=\"text-align:right;background-color:#b3aed1;\"><a href=\"javascript:toggleVideo(0,\'dummyName\',\''+targetObjectID+'\');\"><img src=\"./static/images/icons/icon_closewindow.jpg\" border=\"0\"></a></td></tr><tr><td><div style=\"width:'+width+'px;height:'+height+'px;text-align:center;vertical-align:middle;background-image:url(\'./static/images/background/bg_videoplayer.jpg\');background-repeat:no-repeat;\"><object id=\"WMV\" classid=\"CLSID:2179C5D3-EBFF-11CF-B6FD-00AA00B4E220\" codebase=\"http://www.microsoft.com/netshow/download/en/nsmp2inf.cab#Version= 5,1,51,415\" standby=\"Loading Microsoft Media Player components...\" type=\"application/x-oleobject\" width=\"'+width+'\" height=\"'+height+'\"><param name=\"FileName\" value=\"'+videoFile+'\"><param name=\"autostart\" value=\"true\"><param name=\"ShowControls\" value=\"true\"><param name=\"ShowDisplay\" value=\"false\"><param name=\"ShowStatusBar\" value=\"true\"><embed type=\"application/x-mplayer2\" name=\"MediaPlayer\" background=\"images/testclip.jpg\" transparentAtStart=\"true\" autostart=\"true\" width=\"'+width+'\" height=\"'+height+'\" src=\"'+videoFile+'\" showstatusbar=\"true\" showcontrols=\"true\" showdisplay=\"false\" pluginspage=\"http://www.microsoft.com/netshow/download/player.htm\"></embed></object></div></td></tr></table>';
				//Write file statistics
				writeFileStatistics(videoFile.substring(videoFile.lastIndexOf("/")+1) , "MOVIE" ,"");
			} else {
				targetObject.innerHTML='';
			}
		break;
		case ".flv":
			if(newStatus) {
				if(!width) { width = 270;}
				if(!height) { height = 203;}
				activeVideoID	= targetObjectID;	
				containerID		= "flashcontent_"+targetObjectID;
				//videoFile		= stripExtension(videoFile);
				videoFile		= "../"+videoFile;
				avType			= 3;
				
				targetObject.innerHTML='<table border=0 cellpadding=0 cellspacing=0><tr><td style=\"text-align:right;background-color:#b3aed1;\"><a href=\"javascript:toggleVideo(0,\'dummyName\',\''+targetObjectID+'\');\"><img src=\"./static/images/icons/icon_closewindow.jpg\" border=\"0\"></a></td></tr><tr><td><div id=\"'+containerID+'\" style=\"width:'+width+'px;height:'+height+'px;text-align:center;vertical-align:middle;background-image:url(\'./static/images/background/bg_videoplayer.jpg\');background-repeat:no-repeat;\">asdasd</div></td></tr></table>';

				try {
					var flashvars = {
						bgColor: '0xFFFFFF', 
						avFile: videoFile,
						avTitle: "",
						showIntroFrame: 0,
						avType: avType,
						instantStartPlayback: 1, 
						autoReplay: 0
					};
					var params = {
						wmode: 'transparent',
						allowFullScreen: 'true',
						allowScriptAccess: 'sameDomain'
					};
					var attributes = {
						//$printJS		.= "id: 'myId',
						//$printJS		.= "name: 'myId'
					};
					//2.1
					//$printJS		.= "swfobject.embedSWF('$swfFile', '$swfID', '300', '18', '9.0.0', '$swfExpressInstallFile', flashvars, params, attributes);
					//1.5
					//swfobjectEmbed('./flash/videoplayer.swf', containerID, '270', '203', '9.0.0', '', flashvars, params, attributes, '#FFFFFF');
					swfobjectEmbed('./flash/avplayer.swf', containerID, '270', '203', '9.0.0', '', flashvars, params, attributes, '#FFFFFF');
				} catch (e) {
					targetObject.innerHTML='';
				}

				//Write file statistics
				writeFileStatistics(videoFile.substring(videoFile.lastIndexOf("/")+1) , "MOVIE" ,"");
			} else {
				targetObject.innerHTML='';
			}
		break;
		case ".mp3":
			if(newStatus) {
				if(!width) { width = 270;}
				if(!height) { height = 203;}
				activeVideoID		= targetObjectID;	
				containerID			= "flashcontent_"+targetObjectID;
				//videoFile			= stripExtension(videoFile);
				videoFile			= videoFile;
				avType				= 2;
				
				targetObject.innerHTML='<table border=0 cellpadding=0 cellspacing=0><tr><td style=\"text-align:right;background-color:#b3aed1;\"><a href=\"javascript:toggleVideo(0,\'dummyName\',\''+targetObjectID+'\');\"><img src=\"./static/images/icons/icon_closewindow.jpg\" border=\"0\"></a></td></tr><tr><td><div id=\"'+containerID+'\" style=\"width:'+width+'px;height:'+height+'px;text-align:center;vertical-align:middle;background-image:url(\'./static/images/background/bg_videoplayer.jpg\');background-repeat:no-repeat;\">asdasd</div></td></tr></table>';

				try {
					var flashvars = {
						bgColor: '0xFFFFFF', 
						avFile: videoFile,
						avTitle: "",
						showIntroFrame: 0,
						avType: avType,
						instantStartPlayback: 1, 
						autoReplay: 0, 
						avImage: avImage, 
						avBackgroundColor: avBackgroundColor
					};
					var params = {
						wmode: 'transparent',
						allowFullScreen: 'true',
						allowScriptAccess: 'sameDomain'
					};
					var attributes = {
						//$printJS		.= "id: 'myId',
						//$printJS		.= "name: 'myId'
					};
					//2.1
					//$printJS		.= "swfobject.embedSWF('$swfFile', '$swfID', '300', '18', '9.0.0', '$swfExpressInstallFile', flashvars, params, attributes);
					//1.5
					//swfobjectEmbed('./flash/videoplayer.swf', containerID, '270', '203', '9.0.0', '', flashvars, params, attributes, '#FFFFFF');
					swfobjectEmbed('./flash/avplayer.swf', containerID, '270', '203', '9.0.0', '', flashvars, params, attributes, '#FFFFFF');
				} catch (e) {
					targetObject.innerHTML='';
				}

				//Write file statistics
				writeFileStatistics(videoFile.substring(videoFile.lastIndexOf("/")+1) , "MOVIE" ,"");
			} else {
				targetObject.innerHTML='';
			}
		break;
		default:
			targetObject.innerHTML='';
		break;
	}
}

function youtubeVideo (videoID, height) {
	if (height)	{
		height	= Math.round(height);
		width	= Math.round(height*(425/356));
	} else {
		height	= 200;
		width	= 240;
	}
	var tempID	= tempElementID++;
	document.write("<div id='"+tempID+"' class='span_youtubeclip'>You need Flash player 8+ and JavaScript enabled to view this video.</div>");
	var params = { allowScriptAccess: "always" };
	var atts = { id: "myytplayer" };
	swfobject.embedSWF("http://www.youtube.com/v/"+videoID+"&enablejsapi=1&playerapiid=ytplayer", tempID, width, height, "8", null, null, params, atts);
}

function flvVideo (videoFile, videoTitle) {
	document.getElementById('flashcontent').style.display = "block";
	document.getElementById('main_image').innerHTML = '<img src="./static/images/1pix.gif" width="160" height="122" border="0" align="top">';
	var so = new SWFObject("./flash/tw_videoplayer.swf", "mymovie", "200", "150", "8", "#ffffff");
	so.addVariable("videoFile", videoFile);
	//so.addVariable("videoFile", "luisteren_high.flv");
	so.addVariable("videoTitle", videoTitle);
	so.write("flashcontent");
}

function swfobjectEmbed (swfFile, swfID, width, height, fVersion, expressInstallFile, flashvars, params, attributes, bgColor) {
	//alert(swfFile+",\n "+swfID+",\n "+width+",\n "+height+",\n "+fVersion+",\n "+expressInstallFile+",\n "+flashvars+",\n "+params+",\n "+attributes+",\n "+bgColor);
	var so = new SWFObject(swfFile, swfID, width, height, fVersion, bgColor, true);
	for ( keyVar in flashvars ) 		{  so.addVariable(keyVar, flashvars[keyVar]);	}
	for ( keyVar in params ) 			{  so.addParam(keyVar, params[keyVar]);			}
	for ( keyVar in attributes ) 		{  so.addAttribute(keyVar, attributes[keyVar]);	}
	
	so.write(swfID);
}

function highlightText ( strSearchTerm ) {
	var searchTerm	= strSearchTerm.split(" ");
	var txt_search	= "";
	var txt_replace	= "";
	var txt_content	= "";
	//alert(txt_content);
	//alert(document.getElementById('main_content').innerText);
	for (i=0;i<searchTerm.length;i++) {
		txt_content	= document.getElementById('main_content').innerHTML;
		//myregexp = new RegExp(regexstring);
		//txt_search	= "/"+searchTerm[i]+"/g";
		// /<\S[^><]*>/g
		txt_search	= "/(?![^<]+>)"+searchTerm[i]+"(?![^<]+>)/g";
		txt_replace	= "<span class='tekst_highlight'>"+searchTerm[i]+"</span>";
		document.getElementById('main_content').innerHTML = txt_content.replace(eval(txt_search),txt_replace);
	}
}

function externalLinks() { 
	//HTML 4.0 standard, target="_blank" obsolete, use instead: rel="external" in combination with this function
	if (!document.getElementsByTagName)	{return;}
	try {
		var anchors = document.getElementsByTagName("a"); 
		for (var i=0; i<anchors.length; i++) { 
			var anchor = anchors[i]; 
			if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "external" || anchor.getAttribute("name") == "file")) {
				anchor.target = "_blank";
			}
		}
	} catch (e) {}
}
try {
	Event.observe(window, "load", externalLinks);
} catch (e) {}

function selectQuizWord (varID, varValue, spanElementBase) {
	//alert ("ID="+varID+", Value="+varValue);
	var spanWordElement = "";

	try {document.getElementById(varID).value = varValue;} catch (e) {}

	for (i=0;i<=6;i++) {
		spanWordElement = spanElementBase+"_"+i;
		if (i==varValue) {
			try {document.getElementById(spanWordElement).style.backgroundColor = "#ddddad";} catch (e) {}
			try {document.getElementById(spanWordElement).style.border = "1px solid #f0f000";} catch (e) {}
		} else {
			try {document.getElementById(spanWordElement).style.backgroundColor = "";} catch (e) {}
			try {document.getElementById(spanWordElement).style.border = "0";} catch (e) {}
		}
	}
}

// ############################## UTILITY FUNCTIONS ##############################
function addToFavorites (siteURL, siteName) {
	siteURL		= siteURL	?	siteURL		:	location.href;
	siteName	= siteName	?	siteName	:	document.title;
/*	
	if (window.external) {
		window.external.AddFavorite(siteURL, siteName);
	} else {
		alert("Sorry! Your browser doesn't support this function.");
	}
*/
	if (window.sidebar) // firefox
	window.sidebar.addPanel(siteName, siteURL, "");
	else if(window.opera && window.print){ // opera
	var elem = document.createElement('a');
	elem.setAttribute('href',siteURL);
	elem.setAttribute('title',siteName);
	elem.setAttribute('rel','sidebar');
	elem.click();
	}
	else if(document.all)// ie
	window.external.AddFavorite(siteURL, siteName);

}

function printContentHTML (targetID) {
	var targetHTML	= document.getElementById(targetID).innerHTML;
	alert(targetHTML);
	document.getElementById(targetID).print();
	return;
}

function sendPageToPrinter () {
	setTimeout("window.print();", 1000);
	return;
}
