<!-- hide from old browsers

/******************************************************************************
* $Id: knowledgeDB.js 11 2010-03-12 15:12:18Z husi $
* Project	  : Palextra Common
* Name		 : knowledgeDB.js
* Description  : Default knowledgeDB java script functions
* Author	   : Patrick Husi <patrick.husi@arpage.ch>
* Copyright	: (c) 2007 by Arpage AG
*				CH-8700 Kuesnacht
*				All rights reserved
******************************************************************************/

/******************************************************************************
*** MCE editor funcions ***
*******************************************************************************/

function initializeMceEditor(contentCss, lang, resourcesPath) {
	loadjscssfile("tiny_mce/tiny_mce.js", "js");
	if (resourcesPath == null)
		resourcesPath = "";
	dojo.addOnLoad(function() {
		initializeMceEditorImpl(contentCss, lang, resourcesPath, 0);
	});
}

function initializeMceEditorDynContent(contentCss, lang, resourcesPath) {
	loadjscssfile("tiny_mce/tiny_mce.js", "js");
	if (resourcesPath == null)
		resourcesPath = "";
	dojo.addOnLoad(function() {
		initializeMceEditorDynContentImpl(contentCss, lang, resourcesPath, 0);
	});
}

function initializeMceEditorResourcepool(contentCss, lang, resourcesPath) {
	loadjscssfile("tiny_mce/tiny_mce.js", "js");
	if (resourcesPath == null)
		resourcesPath = "";
	dojo.addOnLoad(function() {
		initializeMceEditorResourcepoolImpl(contentCss, lang, resourcesPath, 0);
	});
}

// Implementations of mce initialization functions
function initializeMceEditorImpl(contentCss, lang, resourcesPath, index) {
	// Checking if tiny mce already loaded
	if (typeof(tinyMCE) == "undefined") {
		if (index < 10)
			window.setTimeout("initializeMceEditorImpl('" + contentCss + "', '" + lang + "', '" + resourcesPath + "', " + index++ + ")", 250);
		return;
	}
	// Initializing it
	tinyMCE.init({
		mode			 : "textareas",
		textarea_trigger : "mceEditor",
		language		 : lang,
		plugins		  : "safari,contextmenu,paste,table,advimage,advlink,fullscreen",
		content_css	  : contentCss,
		strict_loading_mode : true,
		entity_encoding  : "numeric",
		doctype		  : '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
		theme			: "advanced",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align	: "left",
		theme_advanced_styles		   : "Comment=comment;Chapter Text=bodytext",		
		theme_advanced_buttons1_add	 : "fontselect,fontsizeselect",
		theme_advanced_buttons2_add	 : "pastetext,pasteword,selectall,forecolor,fullscreen",
		theme_advanced_buttons3_add	 : "tablecontrols",
		theme_advanced_disable		  : "strikethrough,help,hr,visualaid",
		external_image_list_url		 : resourcesPath + "/js/image_list.js",
		table_styles	 : "List=table1",
		table_row_styles : "Odd=table1-bg1;Even=table1-bg2",
		height		   : "300",
		width			: "550",
		debug			: false
	});
}

function initializeMceEditorDynContentImpl(contentCss, lang, resourcesPath, index) {
	// Checking if tiny mce already loaded
	if (typeof(tinyMCE) == "undefined") {
		if (index < 10)
			window.setTimeout("initializeMceEditorDynContentImpl('" + contentCss + "', '" + lang + "', '" + resourcesPath + "', " + index++ + ")", 250);
		return;
	}
	// Initializing it
	tinyMCE.init({
		mode			 : "textareas",
		textarea_trigger : "mceEditor",
		language		 : lang,
		plugins		  : "safari,contextmenu,paste,table,advimage,advlink,fullscreen",
		content_css	  : contentCss,
		strict_loading_mode : true,
		entity_encoding  : "numeric",
		doctype		  : '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
		theme			: "advanced",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align	: "left",
		theme_advanced_styles		   : "Comment=comment;Chapter Text=bodytext",
		theme_advanced_buttons2_add	 : "pastetext,pasteword,selectall,fullscreen",
		theme_advanced_buttons3_add	 : "tablecontrols",
		theme_advanced_disable		  : "strikethrough,help,hr,visualaid",
		external_image_list_url		 : resourcesPath + "/js/image_list.js",
		table_styles	 : "List=table1",
		table_row_styles : "Odd=table1-bg1;Even=table1-bg2",
		debug			: false
	});
}

function initializeMceEditorResourcepoolImpl(contentCss, lang, resourcesPath, index) {
	// Checking if tiny mce already loaded
	if (typeof(tinyMCE) == "undefined") {
		if (index < 10)
			window.setTimeout("initializeMceEditorResourcepoolImpl('" + contentCss + "', '" + lang + "', '" + resourcesPath + "', " + index++ + ")", 250);
		return;
	}
	// Initializing it	
	tinyMCE.init({
		mode			 : "textareas",
		editor_selector  : "mceEditor",
		language		 : lang,
		plugins		  : "safari,contextmenu,paste",
		content_css	  : contentCss,
		strict_loading_mode : true,
		entity_encoding  : "numeric",
		doctype		  : '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
		theme			: "advanced",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align	: "left",
		theme_advanced_buttons3_add	 : "pastetext,pasteword,selectall",
		theme_advanced_disable		  : "strikethrough,styleselect,link,unlink,image,help,anchor,hr,visualaid",
		height		   : "200",
		width			: "400",
		debug			: false
	});
}

function parse4MceEditors(rootElementId) {
	// Cheking tiny mce
	if (typeof tinymce == 'undefined') {
		if (dojo.config.isDebug || !dojo.isIE)
			console.warn("Tiny Mce is not active");
		return;
	}
	
	// Parsing code
	var s = tinyMCE.settings;
	dojo.forEach(dojo.byId(rootElementId).getElementsByTagName("textarea"), function(v) { 
		if (s.editor_deselector && tinymce.DOM.hasClass(v, s.editor_deselector))
			return;

		if (!s.editor_selector || tinymce.DOM.hasClass(v, s.editor_selector)) {
			// Can we use the name
			var e = tinymce.DOM.get(v.name);
			if (!v.id && !e)
				v.id = v.name;

			// Generate unique name if missing or already exists
			if (!v.id || tinyMCE.get(v.id))
				v.id = tinymce.DOM.uniqueId();

			new tinymce.Editor(v.id, s).render();
		}
	});
}

/******************************************************************************
*** Common funcions ***
*******************************************************************************/

function saveEditClassification(oldClassificationId, newClassificationSelect, selfPage, object, setEditParam) {
	var currentSelcetedIndex = newClassificationSelect.selectedIndex;
	var newClassificationId = newClassificationSelect.options[currentSelcetedIndex].value;
	var myForm = newClassificationSelect.form;
	if (setEditParam == null)
		setEditParam = false;

	myForm.elements['old_classification_id'].value = oldClassificationId;
	myForm.elements['new_classification_id'].value = newClassificationId;
	
	// Nothing changed
	if (oldClassificationId == newClassificationId)
		return;
		
	// The action
	if (oldClassificationId == ""  && newClassificationId != "") {
		myForm.action = selfPage + ".add-" + object + ".exec?" + myForm.elements['form-vars'].value;
	} else if (oldClassificationId != ""  && newClassificationId == "") {
		myForm.action = selfPage + ".del-" + object + ".exec?" + myForm.elements['form-vars'].value;
	} else if (oldClassificationId != ""  && newClassificationId != "") {
		myForm.action = selfPage + ".upd-" + object + ".exec?" + myForm.elements['form-vars'].value;
	}
	
	// Redirection
	if (setEditParam)
		myForm.elements['redirect-to-self'].value += '&amp;edit=classification';
	
	// Commit change
	myForm.submit();
}

function saveEditClassificationAx(myForm, selectObj, selfPage, object, successCb, cbParams) {
	var oldClassificationId = selectObj.attr('_resetValue');
	var newClassificationId = selectObj.attr('value');
	myForm.elements['old_classification_id'].value = oldClassificationId;
	myForm.elements['new_classification_id'].value = newClassificationId;
	
	// Nothing changed
	if (oldClassificationId == newClassificationId)
		return;
		
	// The action
	var theAction = "";
	if (oldClassificationId == ""  && newClassificationId != "") {
		theAction = "add";
	} else if (oldClassificationId != ""  && newClassificationId == "") {
		theAction = "del";
	} else if (oldClassificationId != ""  && newClassificationId != "") {
		theAction = "upd";
	} else
		return;
		
	// Submit data
	dojo.xhrPost({
		url: selfPage + "." + theAction + "-" + object + ".exec?cocoon-ajax=true",
		form: myForm.id,
		load: function(response, ioArgs) {
			if (dojo.config.isDebug)
				console.debug(response);
			
			// The result
			if (response.status != null) {
				if (response.status != 'failed') {
					// Seting new text
					selectObj.attr('_resetValue', newClassificationId);
					// Calling callback
					if (typeof(successCb) != "undefined")
						successCb(cbParams);
				} else {
					// An error occured
					if (dojo.config.isDebug || !dojo.isIE)
						console.error("An error occurred: " + response.details);
				}
			}
			return response;
		},
		error: function(response, ioArgs) {
			var errorMsg = (response instanceof Error) ? response.message : response;
			if (dojo.config.isDebug || !dojo.isIE)
				console.error("An error occurred, with response: " + errorMsg);
			return response;
		},
		handleAs: "json"
	});
}

var saveEditClassificationDjLastValues = null;
function saveEditClassificationDj(selectId, selfPage, object, requestParams, successCb, cbParams) {
	// Initialization
	var selectObj = dijit.byId(selectId);
	if (saveEditClassificationDjLastValues == null)
		saveEditClassificationDjLastValues = new Array();
	var oldClassificationId = saveEditClassificationDjLastValues[selectId];
	if (oldClassificationId == null)
		oldClassificationId = selectObj.attr('_resetValue');
	var newClassificationId = selectObj.attr('value');
	
	// Nothing changed
	if (oldClassificationId == newClassificationId)
		return;
		
	// The action
	var theAction = "";
	if (oldClassificationId == ""  && newClassificationId != "") {
		theAction = "add";
	} else if (oldClassificationId != ""  && newClassificationId == "") {
		theAction = "del";
	} else if (oldClassificationId != ""  && newClassificationId != "") {
		theAction = "upd";
	} else
		return;
		
	// Submit data
	dojo.xhrPost({
		url: selfPage + "." + theAction + "-" + object + "-classification.exec?" + requestParams + "&cocoon-ajax=true",
		content: {
			old_classification_id: oldClassificationId,
			new_classification_id: newClassificationId
		},
		load: function(response, ioArgs) {
			if (dojo.config.isDebug)
				console.debug(response);
			
			// The result
			if (response.status != null) {
				if (response.status != 'failed') {
					// Setting new text
					saveEditClassificationDjLastValues[selectId] = newClassificationId;
					// Calling callback
					if (typeof(successCb) != "undefined")
						successCb(cbParams);
				} else {
					// An error occured
					if (dojo.config.isDebug || !dojo.isIE)
						console.error("An error occurred: " + response.details);
				}
			}
			return response;
		},
		error: function(response, ioArgs) {
			var errorMsg = (response instanceof Error) ? response.message : response;
			if (dojo.config.isDebug || !dojo.isIE)
				console.error("An error occurred, with response: " + errorMsg);
			return response;
		},
		handleAs: "json"
	});
}

function resetFilterChoice() {
	var filterForm = document.forms['filter'];
	var classificationList = "";
	
	// Going trough all select fields and checking selected classification
	for (var i = 0; i < filterForm.elements.length; i++) {
		var currentField = filterForm.elements[i];
		if (currentField.type != 'select-one')
			continue;
		var currentSelcetedIndex = currentField.selectedIndex;
		var slectedItemValue = currentField.options[currentSelcetedIndex].value;
		if (slectedItemValue != '') {
			if (classificationList != '')
				classificationList += ',';
			classificationList += slectedItemValue;
		}
	}
	
	// The result
	filterForm.elements['classification_list'].value = classificationList;
}

function loadPageSubHref(parentElement) {
	if (parentElement == null)
		return;
	var hrefs = parentElement.getElementsByTagName("a");
	if (hrefs == null || hrefs.length != 1)
		return;
	var onclick = hrefs[0].onclick;
	if (onclick == null)
		window.location.href = hrefs[0].href;
	else
		onclick();
	return false;
}

/******************************************************************************
*** Klassifikation neu laden ***
******************************************************************************/

function writeClassificationHtmlTree(href, destinationId) {
	// Checking href
	if (href == null) {
		if (dojo.config.isDebug || !dojo.isIE)
			console.error("No href specified");
		return;
	}
	
	// Loading page
	dojo.xhrGet({
		url: href + "&view=content",
		load: function(response, ioArgs) {
			if (dojo.config.isDebug)
				console.debug(response);
			// Taking only subset of result document
			var innerHtml = "";
			var srcNode = getElementByTagTree(response, "root/area[@name = 'module-navigation-airport']/content/div[@id = 'box-body-module_nav_airport']");
			if (srcNode != null) {
				srcNodes = srcNode.childNodes;
				for (var i = 0; i < srcNodes.length; i++) {
					innerHtml += serializeNode(srcNodes[i]);
				}
			}
			dojo.byId(destinationId).innerHTML = innerHtml;
			return response;
		},
		error: function(response, ioArgs) {
			var errorMsg = (response instanceof Error) ? response.message : response;
			dojo.byId(destinationId).innerHTML =  "An error occurred, with response: " + errorMsg;
			if (dojo.config.isDebug || !dojo.isIE)
				console.error("An error occurred, with response: " + errorMsg);
			return response;
		},
		handleAs: "xml"
	});
}

/******************************************************************************
*** Notepad / Bewertung darstellen ***
******************************************************************************/

function displayNotepad(home, baseId, moduleId) {
	// Dojo
	dojo.require("dijit.form.Form");
	dojo.require("dijit.form.SimpleTextarea");
	
	// Loading page
	dojo.xhrGet({
		preventCache: true,
		url: home + "common/tools/notepad.html?base_id=" + baseId + "&module_id=" + moduleId + "&home=" + home + "&view=content",
		load: function(response, ioArgs) {
			if (dojo.config.isDebug)
				console.debug(response);
			// Taking only subset of result document
			var innerHtml = "";
			var srcNode = getElementByTagTree(response, "root/area[@name = 'note']/content");
			if (srcNode != null) {
				srcNodes = srcNode.childNodes;
				for (var i = 0; i < srcNodes.length; i++) {
					innerHtml += serializeNode(srcNodes[i]);
				}
			}
			Tip(innerHtml, FADEIN, 500, FADEOUT, 500, SHADOW, true, TITLE, "Notizen", CLOSEBTN, true, STICKY, true, WIDTH, -400);
			return response;
		},
		error: function(response, ioArgs) {
			var errorMsg = (response instanceof Error) ? response.message : response;
			Tip("An error occurred, with response: " + errorMsg, FADEIN, 500, FADEOUT, 500, SHADOW, true, TITLE, "Notizen", CLOSEBTN, true, STICKY, true, BGCOLOR, '#FFFFCC', WIDTH, -400);
			if (dojo.config.isDebug || !dojo.isIE)
				console.error("An error occurred, with response: " + errorMsg);
			return response;
		},
		handleAs: "xml"
	});
}

function closeNotepad() {
	UnTip();
	tt_HideInit();
}

function saveNotepad(home, elementPrefix) {
	// Nothing to do
	var editform = dojo.byId(elementPrefix + '-form');
	if (editform.upd_action.value == "")
		return;
	// Trim note
	editform.note.value = editform.note.value.replace(/^\s+|\s+$/g, '');
		
	// Save notepad
	var kw = {
		form: editform,
		url: home + "common/tools/" + editform.upd_action.value + ".exec?cocoon-ajax=true",
		handleAs:"json",
		load: function(response){
			if (dojo.config.isDebug)
				console.debug(response);
			if (response.status != null && response.status != 'failed') {
				// Notepad saved --> apply data in page
				var hrefElement = dojo.byId(elementPrefix + '-href');
				var iconElement = dojo.byId(elementPrefix + '-icon');
				if (editform.note.value != '' && editform.upd_action.value != 'notepad.del-note') {
					iconElement.className = "notepad-image notepad-image-active";
					var text = 
					hrefElement.onmouseover = new Function("Tip('" + editform.note.value.replace(/\'/g, '\\\'').replace(/(?:\r\n|\r|\n)/g, '<br/>') + "', SHADOW, true, PADDING, 5, TITLE, 'Notepad', BGCOLOR, '#FFFFCC', WIDTH, -300)");
				} else {
					iconElement.className = "notepad-image";
					hrefElement.onmouseover = "";
				}
			}
			// Close tooltip
			closeNotepad();
			// Returning response
			return response;
		},
		error: function(response) {
			var errorMsg = (response instanceof Error) ? response.message : response;
			if (dojo.config.isDebug || !dojo.isIE)
				console.error("An error occurred, with response: " + errorMsg);
			return response;
		},
		timeout: 2000
	};
	dojo.xhrPost(kw); // Servlet get argement with doPost
}

var knowledgeDBRating = new Array();
function saveRating(home, action, module_id, base_id, rating) {
	// The action
	var currentAction = knowledgeDBRating["bs_" + base_id];
	if (currentAction == null)
		currentAction = action;
	if (currentAction == "running")
		return;
	knowledgeDBRating["bs_" + base_id] = "running";
	// Save data
	dojo.xhrGet({
		url: home + "common/tools/notepad." + currentAction + "-rating.exec?module_id=" + module_id + "&base_id=" + base_id + "&rating=" + rating + "&cocoon-ajax=true",
		load: function(response){
			if (dojo.config.isDebug)
				console.debug(response);
			knowledgeDBRating["bs_" + base_id] = "upd";
			return response;
		},
		error: function(response) {
			var errorMsg = (response instanceof Error) ? response.message : response;
			if (dojo.config.isDebug || !dojo.isIE)
				console.error("An error occurred, with response: " + errorMsg);
			return response;
		},
		handleAs:"json"
	});
}

/******************************************************************************
*** Dynamische Tooltips ***
******************************************************************************/

var tooltipAddonActive = false;
function displayTooltipAddon(home, moduleId) {
	tooltipAddonActive = true;
	// Loading page
	dojo.xhrGet({
		preventCache: false,
		url: home + "common/tools/addon.html?module_id=" + moduleId + "&home=" + home + "&view=content",
		load: function(response, ioArgs) {
			if (dojo.config.isDebug)
				console.debug(response);
			// Taking only subset of result document
			var innerHtml = "";
			var srcNode = getElementByTagTree(response, "root/area[@name = 'learning-object']/content");
			if (srcNode != null) {
				srcNodes = srcNode.childNodes;
				for (var i = 0; i < srcNodes.length; i++) {
					innerHtml += serializeNode(srcNodes[i]);
				}
			}
			if (tooltipAddonActive)
				Tip(innerHtml, FADEIN, 500, FADEOUT, 500, SHADOW, true, BGCOLOR, '#FFFFCC', WIDTH, -400, DURATION, 20000, CLICKCLOSE, true);
			return response;
		},
		error: function(response, ioArgs) {
			var errorMsg = (response instanceof Error) ? response.message : response;
			if (tooltipAddonActive)
				Tip("An error occurred, with response: " + errorMsg, FADEIN, 500, FADEOUT, 500, SHADOW, true, BGCOLOR, '#FFFFCC', WIDTH, -400, DURATION, 10000, CLICKCLOSE, true);
			if (dojo.config.isDebug || !dojo.isIE)
				console.error("An error occurred, with response: " + errorMsg);
			return response;
		},
		handleAs: "xml"
	});
}

function hideTooltipAddon() {
	tooltipAddonActive = false;
	UnTip();
}

function displayDialogAddon(url, windowName, windowFeatures) {
	// Dialog size
	var style = "";
	if (windowFeatures != null) {
		var result = windowFeatures.match(/width=(\d+)/);
		if (result != null && result)
			style += "width:" + result[1] + "px;";
		else
			style += "width:500px;";
	}
	// Displaying dialog
	dojo.require("dijit.Dialog");
	var dialog = new dijit.Dialog({ title: "Add-on", style: style, href: url });
	dialog.show();
}

// end hiding from old browsers -->

