// initialize page
var data = { xml : "" };

function init() {
	// create page elements
	page.build();
	
	// load product in page
	startProduct();
}

function startProduct() {
	// do this when xml is loaded
	var XMLdoOnLoad = function(dataXML) {
		data.xml = dataXML;
		page.empty();
		if (data.xml && data.xml.getElementsByTagName("method").length > 0) {
			oMethod.init();
		} else if (data.xml && (data.xml.getElementsByTagName("learning-unit").length > 0 || data.xml.getElementsByTagName("webquest").length > 0)) {
			learningUnit.init();
		} else {
			alert("Geen geldige data gevonden... (TODO with flash!)");
			return false;
		}
	}
	loadXML("data.xml",XMLdoOnLoad);
}

function ignoreEvents(returnValue){
  var ev = window.event; // for backward compatibility
  if (!ev)
    return false;
  ev.returnValue  = returnValue ? true:false;
	ev.cancelBubble = true;
}
/* general helper functions
cssAddRule                          : adds css rule
cssRemoveRule                       : removes css rule
stripTags(str)                      : strip tags from string
colorPercentage(color,percentage)	: calculate percentage of a certain hex color value
alternate(el,parentTag,childTag)	: alternate class=odd/even on childTags in parentTag in element el
getInnerHeight()					: returns height of viewport
thisMovie(movieName)				: returns flash-object with id=movieName
URLencode(sStr)						: url-encode a string
pause(ms)							: pause ms milliseconds
empty(el)							: remove all childs and content from el
focusById(id)						: focus element by id
getElementsByClassName(classname)	: return array of all elements that have classname
rnd(max)							: return random number between 1 and max
addEvent(obj, evType, fn)			: add eventhandler: do fn, when evType, on obj
getSelectedOptionValue(id)			: get value of selected option in id
getSelectedOptionText(id)			: get text of selected option in id
selectOptionByValue(id,val)			: select option in id where value = val
addClass(el,clName)					: add clName to className of el
removeClass(el,clName)				: remove clName from className of el
showLayer(IDs)						: set visibility="visible" on IDs
hideLayer(IDs)						: set visibility="hidden" on IDs
displayBlock()						: set display="block" on IDs
displayInline()						: set display="inline" on IDs
displayNone()						: set display="none" on IDs
*/

// adds css rule
function cssAddRule(selector, declaration) {
	if (document.all)
		document.styleSheets[0].addRule(selector, declaration);
	else
		document.styleSheets[0].insertRule(selector + "{" +declaration + "}", 0)
}
// removes css rule
function cssRemoveRule(selector) {
	var mysheet = document.styleSheets[0];
	for (var i=0; i<mysheet.rules.length; i++) {
		if (mysheet.rules[i].selectorText == selector) {
			if (document.all)
				mysheet.removeRule(i);
			else
				mysheet.deleteRule(i);
		}
	}
}

// strip tags from string
function stripTags(str) {
	return str.replace(/<\/?[^>]+>/gi, '');
}

// calculate percentage of a certain hex color value
function colorPercentage(color,percentage) {
	//
	// helper functions for converting hex
	var hexCharacters = "0123456789ABCDEF";
	function hexValue(decimal) {
		return hexCharacters.charAt((decimal>>4)&0xf)+hexCharacters.charAt(decimal&0xf);
	}
	function decValue(hexadecimal) {
		return parseInt(hexadecimal.toUpperCase(),16);
	}
	//
	// calculate color
	var f      = percentage / 100;
	var color  = color.replace("#","");
	var colorR = decValue(color.substr(0,2));
	var colorG = decValue(color.substr(2,2));
	var colorB = decValue(color.substr(4,2));
	var newR   = hexValue(Math.round(255-(255-colorR)*f));
	var newG   = hexValue(Math.round(255-(255-colorG)*f));
	var newB   = hexValue(Math.round(255-(255-colorB)*f));
	var newHexColor = newR+newG+newB;
	return newHexColor;
}


/* alternate sub in el with class=alternate (class=odd, class=even) */
alternate = function(el,parentTag,childTag) {
	if (document.getElementById) {
		els = el.getElementsByTagName(parentTag);
		for (var i=0; i<els.length; i++) {
			if (els[i].className.indexOf("alternate") > -1) {
				even = false;
				subs = els[i].getElementsByTagName(childTag);
				for (var j=0; j<subs.length; j++) {
					if (even) {
						subs[j].className = subs[j].className.replace(" odd","");
						subs[j].className += " even";
					} else {
						subs[j].className = subs[j].className.replace(" even","");
						subs[j].className += " odd";
					}
					even = !even;
				}
			}
		}
	}
}

function getInnerHeight() {
	var y;
	if (self.innerHeight) // all except Explorer
		y = self.innerHeight;
	else if (document.documentElement && document.documentElement.clientHeight) // Explorer 6 Strict Mode
		y = document.documentElement.clientHeight;
	else if (document.body) // other Explorers
		y = document.body.clientHeight;
	return y;
}

function getInnerWidth() {
	var w;
	if (self.innerWidth) // all except Explorer
		w = self.innerWidth;
	else if (document.documentElement && document.documentElement.clientWidth) // Explorer 6 Strict Mode
		w = document.documentElement.clientWidth;
	else if (document.body) // other Explorers
		w = document.body.clientWidth;
	return w;
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    }
    else {
        return document[movieName];
    }
}

function openLink(href) {
	if(href ) {
		var newWindow = window.open(null,'id','toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=600');
		with(newWindow.document){
			writeln('<html><head><title>-</title></head><body ><iframe id="linkedObjects" src="'+href+'" width="100%" height="100%"></iframe></body></html>');
		}
	}
}

function animateBy(obj,dX,dY,steps,speed,doWhenReady) {
	steps = steps || 5;
	speed = speed || 40;
	curX  = findPosX(obj);
	curY  = findPosY(obj);
	newX  = curX + dX;
	newY  = curY + dY;
	stepX = dX / steps;
	stepY = dY / steps;
	moveObj = function() {
		steps--;
		curX += stepX;
		curY += stepY;
		obj.style.left = curX + "px";
		obj.style.top  = curY + "px";
		if (steps > 0)
			timerID = window.setTimeout("moveObj();",speed);
		else if (doWhenReady)
			doWhenReady();
	}
	moveObj();
}

function fadeOut(obj,doWhenReady) {
	var obj = obj;
	var doWhenReady = doWhenReady;
	var curO  = 100;
	fadeObj = function() {
		curO -= 24;
		setOpacity(obj,curO);
		if (curO > 0)
			timerID = window.setTimeout("fadeObj();",40);
		else {
			setOpacity(obj,100);
			if (doWhenReady)
				doWhenReady();
		}
	}
	fadeObj();
}

function setOpacity(node,percent) {
	var is_ie   = typeof(document.all) != 'undefined';
	var opacity = (is_ie) ? "filter" : "opacity";
	changeOpacity = function(node,percent) {
		percent = (is_ie) ? "alpha(opacity=" + percent + ")" : percent/100;
		node.style[opacity] = percent;
	}
	changeOpacity(node,percent);
}

function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent)
		curleft = obj.offsetLeft;
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent)
		curtop = obj.offsetTop;
	else if (obj.y)
		curtop = obj.y;
	return curtop;
}

function URLencode(sStr)
{
	sStr = sStr.replace(/\t/g,"");
	sStr = sStr.replace(/\v/g,"");
	sStr = sStr.replace(/\n/g,"");
	sStr = sStr.replace(/\r/g,"");
	sStr = sStr.replace(/\f/g,"");

	// HTML breaks and newlines be converted to \n aan double \n 
	sStr = sStr.replace(/<BR\/>/g,'\n')
	sStr = sStr.replace(/<P>/g,'')
	sStr = sStr.replace(/<\/P>/g,'\n\n')

	// escape percent sign
	sStr = sStr.replace(/\%/g,"%25");
	// escape lesser than
	sStr = sStr.replace(/&lt;/g, "%26lt%3b");
	// escape ' and "
	sStr = sStr.replace(/\'/g, '%27');
	sStr = sStr.replace(/\"/g,'%22')
	// escape +
	sStr = sStr.replace(/\+/g, '%2B');
	// escape &amp;
	sStr = sStr.replace(/&amp;/g, '%26');
	// sometimes the & will come alone in the 'xml'
	sStr = sStr.replace(/&/g, '%26');
	// if there is a / left, replace it
	sStr = sStr.replace(/\//g,'%2F')

	return sStr;
}

function pause(ms) {
	var now = new Date();
	var exitTime = now.getTime() + ms;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

function empty(el) {
	if (el) {
		childs = el.childNodes;
		for (var i=0; i<childs.length; i++) {
			purge(childs[i]);
			cleanupIELeaks();
			el.removeChild(childs[i]);
		}
		el.innerHTML = "";
	}
}

//prevent a memory leak in IE (see UFO.js)
function cleanupIELeaks()  {
	var _o = page.content.getElementsByTagName("object");
	var _l = _o.length
	for (var i = 0; i < _l; i++) {
		_o[i].style.display = "none";
		for (var x in _o[i]) {
			if (typeof _o[i][x] == "function") {
				_o[i][x] = null;
			}
		}
	}
}

//Borrowed from internet to prevent a memory leak
function purge(d) {
	var a = d.attributes, i, l, n;
	if (a) {
		l = a.length;
		for (i = 0; i < l; i += 1) {
			n = a[i].name;
			if (typeof d[n] === 'function') {
				d[n] = null;
			}
		}
	}
	a = d.childNodes;
	if (a) {
		l = a.length;
		for (i = 0; i < l; i += 1) {
			purge(d.childNodes[i]);
		}
	}
}

function focusById(id) {
	setTimeout("try { document.getElementById('"+id+"').focus(); } catch(err) { return true; }",0);
}

function getElementsByClassName(classname) {
	var a = [];
	var re = new RegExp('\\b' + classname + '\\b');
	var els = document.all?document.all:document.getElementsByTagName("*");
	for(var i=0,j=els.length; i<j; i++)
		if(re.test(els[i].className))a.push(els[i]);
	return a;
}

function rnd(max) {
	var rndnum = max * Math.random();
	rndnum = Math.ceil(rndnum);
	return rndnum;
}

function addEvent(obj, evType, fn){
    if (obj.addEventListener){
		obj.addEventListener(evType, fn, true);
	return true;
    } else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
    } else {
	    return false;
    }
}

function getSelectedOptionValue(id) {
	sel = document.getElementById(id);
	if (sel.selectedIndex > -1) {
		optionValue = sel.options[sel.selectedIndex].value;
		return optionValue;
	} else {
		return false;
	}
}
function getSelectedOptionText(id) {
	sel = document.getElementById(id);
	if (sel.selectedIndex > -1) {
		optionText = sel.options[sel.selectedIndex].innerHTML;
		return optionText;
	} else {
		return false;
	}
}
function selectOptionByValue(id,val) {
	sel  = document.getElementById(id);
	opts = sel.options;
	for (var i=opts.length-1; i>=0; i--) {
		if (opts[i].value == val) {
			opts[i].selected = true;
		}
	}
}

function addClass(el,clName) {
	if (el) {
		if (el.className.indexOf(clName) < 0)
			el.className += " "+clName;
	}
}
function removeClass(el,clName) {
	if (el)
		el.className = el.className.replace(clName,"");
}

function showLayer() {
    res = showLayer.arguments;
    if (document.getElementById) { // IE5 & NN6
      for(i=0; i<res.length; i++) { if (document.getElementById(res[i])) document.getElementById(res[i]).style.visibility = "visible"; }
    }
}
function hideLayer() {
    res = hideLayer.arguments;
    if (document.getElementById) { // IE5 & NN6
      for(i=0; i<res.length; i++) { if (document.getElementById(res[i])) document.getElementById(res[i]).style.visibility = "hidden"; }
    }
}

function displayBlock() {
    if (document.getElementById) { // IE5 & NN6
      res = displayBlock.arguments;
      for(i=0; i<res.length; i++) { document.getElementById(res[i]).style.display = "block"; }
    }
}
function displayInline() {
    if (document.getElementById) { // IE5 & NN6
      res = displayInline.arguments;
      for(i=0; i<res.length; i++) { document.getElementById(res[i]).style.display = "inline"; }
    }
}
function displayNone() {
    if (document.getElementById) { // IE5 & NN6
      res = displayNone.arguments;
      for(i=0; i<res.length; i++) { document.getElementById(res[i]).style.display = "none"; }
    }
}

/**
 * document.createElement convenience wrapper
 *
 * The data parameter is an object that must have the "tag" key, containing
 * a string with the tagname of the element to create.  It can optionally have
 * a "children" key which can be: a string, "data" object, or an array of "data"
 * objects to append to this element as children.  Any other key is taken as an
 * attribute to be applied to this tag.
 *
 * Available under an MIT license:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @param {Object} data The data representing the element to create
 * @return {Element} The element created.
 */
function $E(data) {
	var el;
	if ('string'==typeof data) {
		el=document.createTextNode(data);
	} else {
		//create the element
		el=document.createElement(data.tag);
		delete(data.tag);
		//append the children
		if ('undefined'!=typeof data.children) {
			if ('string'==typeof data.children ||
				'undefined'==typeof data.children.length
			) {
				//strings and single elements
				el.appendChild($E(data.children));
			} else {
				//arrays of elements
				for (var i=0, child=null; 'undefined'!=typeof (child=data.children[i]); i++) {
					el.appendChild($E(child));
				}
			}
			delete(data.children);
		}
		//any other data is attributes
		for (attr in data) {
			el[attr]=data[attr];
		}
	}
	return el;
}


//
function updateStep(id)
{
	var retval = true;
	if (id > -1)
	{
		var lu = learningUnit.steps[id].getElementsByTagName("interaction-element");
		
		for(var i = 0; i < lu.length; i++)
		{  
			var  guid = lu[i].getAttribute("guid");              
			guid = guid.replace(/-/g, "_");  
			guid = "i_"+guid;
			if (thisMovie(guid) != null && thisMovie(guid).finalize != undefined)
			{
				retval = retval & thisMovie(guid).finalize();
			}
		}
	}
	return retval;
}






/**
* Loads the sound spoken sound applet for the C2.B6 when needed
* @param	appletName
*/
function loadSpokenTextApplet() {
	var applet = document.createElement('applet');
	var attr = {	code : "com.wolters.dldb.client.spokentext.SpokenTextApplet", 
					archive : config.logic_folder + "/html/SpokenTextApplet.jar", 
					id : "playbackApplet", 
					name : "capturePlayback", 
					height : 0, 
					width: 0, 
					mayscript : true};
	for (var i in attr) {
		applet.setAttribute(i, attr[i]);
	}
	document.body.appendChild(applet);
}
