function toggleCheck(field, doCheck) {
	for (i = 0; i < field.length; i++) {
		field[i].checked = doCheck;
	}
}

function checkDom() {
	var cdom = false;
	if (document.hasChildNodes()) {
		cdom = document.hasChildNodes();
		// disable ie 5.2x for mac since buggy
		if (navigator.userAgent.indexOf("MSIE 5.2") != -1 ||
			navigator.userAgent.indexOf("MSIE 5.16") != -1 ){
			cdom = false;
		}
	}
	return cdom;
}

var dom = checkDom();
var kupuEnabled = (dom && (browser.isIE55up || browser.isGecko) && !browser.isSafari && !browser.isKonqueror);


function o_init() {
	// nothing to initialize yet
}

function launchLinkById(linkid) {
	// opens the link in the current window that has the given dom id (fg)
	if (dom) {
		var link = document.getElementById(linkid);
		window.location.href=link;
	}
}

function setFormDirty(formId) {
	// sets dirty form content flag to true and renders the submit button
	// of the form with given dom id as dirty.
	// (fg) 
	o2c=1;
	if (dom) {
		// fetch the form and the forms submit button is identified via the olat 
		// form submit name
		var myForm = document.getElementById(formId);
		var mySubmit = myForm.olat_fosm;
		// set dirty css class
		mySubmit.className ="o_form_button_changes";
	}
}

function addPermanentOlatRaw() {
	// parses whole html document and adds to all links the olatraw parameter
	// (fg)
	if (dom) {
	 	var links = document.getElementsByTagName("a");
	 	for(var i = 0; i < links.length; i++) {
	 		var link = links[i].href;
	 		if (link.indexOf("?") == -1) {
				links[i].href = link + "?olatraw=true";
			} else {
				links[i].href = link + "&olatraw=true";
			}
		}
	}
}

function moveMessagesToContent() {
	// Hack to move error messages from the o_main div to the 
	// o_content div. Works only with dom browsers
	// (fg)
	if (dom) {
		var messages = document.getElementById("o_messages");
		var content = document.getElementById("o_content");
		if (content != null) {
			content.insertBefore(messages, content.firstChild);
		}
	}
}

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}


function activateFirstTextInputField(){
	// Activates the first Element in a form that is of type 'text'. Does not however activate a text
	// area, radio buttons or alike, only the first text input field. Works only with modern browsers.
	// (fg) 
	if (dom) {
		var inputs = document.getElementsByTagName("input");
		if (inputs) {
			var i = 0;
			while(i<inputs.length){
				// if the current input item is of type text set the focus to this item (activate it)
				if (inputs[i] && inputs[i].getAttribute("type") == "text"){
					inputs[i].focus();
					return;
				}
				i++;
			}
		}
	}
}


var informMessages = new Array(); // Assoziative Array to store all places that do alread have an inform message displayed
var unsavedData = false;

function informChange(messageLocation){
	// Highlights the form input button to signal a form change and the need to submit the form.
	// The css class o_form_button_changes is used to format the text. This is a legacy method 
	// used eg. in the qti editor
	// PARAM: messageLocation: The DOM element ID of the button
	// (fg)
	o2c=1;
	if (dom){
		var button = document.getElementById(messageLocation + "_button");
		button.className = "o_form_button_changes";
	}
}

function shadeFormElement(elementId){
	// Makes a form input element uneditable. Uses CSS to shade content
	// PARAM: The ID of the element to be shaded
	// PARAM: The default value used when unshading element
	// (fg)
	if (!dom) { return; }
	var elem = document.getElementById(elementId);
	elem.className = "o_form_smallinput_gray";
	elem.readOnly = true;
	// set input focus (cursor) to current element
	elem.focus();
}

function o_updateFormElementVisibility(formName, selectionElementName, dependentElementName, ruleValue, ruleResult, resetValue, hideDisabledElements) {
	// updates a form elements visibility and editability according to
	// the configuration
	// formName: name of the form
	// selectionElementName: name of form selection element hat defines dependency
	// dependentElementName: name of form element that is dependent on the selection
	// ruleValue: the selection value that must match
	// trueResult: the visibility rule in case of a match
	// resetValue: the value to be set if visibiliy is set to false
	// hideDisabledElements: true: disabled elements will disapear from screen, false: disabled
	// elements will be disabled and greyed, but still visible
	// (fg)
	var selectionElement = document.forms[formName].elements[selectionElementName];
	var selectionValue = selectionElement.value;
	if (selectionValue == null) {
		for (i=0; i<selectionElement.length;i++) {
			var val = selectionElement[i];
			if (val.checked) selectionValue = val.value;
		}
	}
	var dependentElement = document.forms[formName].elements[dependentElementName];

	// dependentElement can be null if dependentElement is of type spacer or static text
	// in this case the element is not a form element and thus won't be found
	if (selectionValue == ruleValue) {
		if (ruleResult) {
			o_enableFormElement(formName, dependentElement, dependentElementName, hideDisabledElements);
		} else {
			o_disableFormElement(formName, dependentElement, resetValue, dependentElementName, hideDisabledElements);
			
		}	
	} else {
		if (ruleResult) {
			o_disableFormElement(formName, dependentElement, resetValue, dependentElementName, hideDisabledElements);
		} else {
			o_enableFormElement(formName, dependentElement,dependentElementName, hideDisabledElements);
		}		
	}	
}

function o_enableFormElement(formName, formElement, dependentElementName, hideDisabledElements) {
	// helper: enables a form element for editing (fg)
	if (formElement != null && formElement.style != null) {
		formElement.style.background = "white";
		formElement.readOnly = false;
	}
	if (dom && hideDisabledElements) {
		document.getElementById("oer_" + dependentElementName + formName).style.display="";	
	}
}

function o_disableFormElement(formName, formElement, resetValue, dependentElementName, hideDisabledElements) {
	// helper: disables a form element for editing (fg)
	if (formElement != null) {
		if (formElement.style != null)
			formElement.style.background = "#EEEEEE";
		formElement.readOnly = true;
		if (formElement.length) {
			if (formElement.type == "select-one") {
				formElement.value = resetValue;
			} else {
				for (var i=0; i < formElement.length; ++i){
					var elem = formElement[i];
					if (elem.type == "checkbox") {
						elem.checked = (resetValue == "true" ? true : false);
					} else if (elem.type == "radio") {
						elem.checked = (elem.value == resetValue ? true : false);
					} else {
						alert("OLAT unsupported element error: elemName::" + dependentElementName + " type::" + elem.type + " resetVal::" + resetValue);
					}
				}
			}
		} else {
			if (formElement.type == "checkbox") {
				formElement.checked = (resetValue == "true" ? true : false);
			} else if (formElement.type == "radio") {
				formElement.checked = (formElement.value == resetValue ? true : false);
			} else {
				formElement.value = resetValue;
			}
		}
	}
	if (dom && hideDisabledElements) {
		document.getElementById("oer_" + dependentElementName + formName).style.display="none";
	}
}


function unShadeFormElement(elementId){
	// Makes a form input element editable
	// PARAM: The ID of the element to be unshaded
	// (fg)
	if (!dom) { return; }
	var elem = document.getElementById(elementId);
	elem.className = "o_form_smallinput";
	elem.readOnly = false;
	// set input focus (cursor) to current element
	elem.focus();
}

function shadeFormTextareas(){
	// Makes all form input element uneditable. Uses CSS to shade content
	// (fg)
	var areas = document.getElementsByTagName("textarea");
	if (areas == null) return;
	for (var i=0; i < areas.length; ++i){
		areas[i].className = "o_form_smallinput_gray";
		areas[i].readOnly = true;
	}
}

function unShadeFormTextareas(){
	// Makes all form input text areas elements editable
	// (fg)
	var areas = document.getElementsByTagName("textarea");
	if (areas == null) return;
	for (var i=0; i < areas.length; ++i){
		areas[i].className = "o_form_smallinput";
		areas[i].readOnly = false;
	}
}

function changeQtiPreviewImage(mediaBaseURL){
	// Changes the image preview for the currently selected image
	// PARAM: mediaBaseURL will be prependend to the image 
	// (fg)
	if (!dom) { return; }
	var select = document.getElementById('mediaselect');

	if (select == null) { return; }
	var selected = select.value;

	var previewImage = document.getElementById('previewImage');
	if (selected == ""){
		previewImage.src = conpath + "/images/default/empty.gif";	
	} else {
		previewImage.src = mediaBaseURL + selected;
		previewImage.alt = selected;
	}
	// check file type radio
	document.getElementById("type_file").checked = "checked";
}

function changeQtiPreviewImageFromUri(){
	// Changes the preview image when entering an new media uri
	if (!dom) { return; }
	var uri = document.getElementById('imguri');
	var previewImage = document.getElementById('previewImage');
	previewImage.src = uri.value;
	previewImage.alt = uri.value;
	// check uri type radio
	document.getElementById("type_uri").checked = "checked";
}


// functions for tooltip layer
var _ie=(document.all)?1:0,_nn=(document.layers)?2:0,_w3=(document.getElementById)?3:0;

function showtip(e,n) { var x,y,ex,ey,dw,lw,z; 
if(_nn){
	z=document.layers[n];
	ex=e.pageX;
	ey=e.pageY;
if(document.width){
	dw=document.width;
}else if(window.innerWidth){
	dw=window.innerWidth;
}
else {
	dw=800;
}
if(z.clip.width) {
	lw=z.clip.width;
}else{
	lw=400;
} 
if(ex+lw>dw){
	x=ex-lw-12;if(x<0){x=0;}
}
else {
	x=ex+8;
} 
y=ey+12;

z.clip.width=lw;

z.left=parseInt(x);
z.top=parseInt(y);
z.visibility="show";
}
else if(_w3) {z=document.getElementById(n);if(e.pageX){ex=e.pageX;ey=e.pageY;} else {ex=e.clientX;ey=e.clientY;}

if(document.width){dw=document.width;}
else if(document.body.offsetWidth){dw=document.body.offsetWidth;}
else if(window.innerWidth){dw=window.innerWidth;}else {dw=800;}
if(z.style.width){lw=z.style.width;}else if(document.all){var _w=document.all[n];lw=_w.offsetWidth;}
if(!lw){lw=100;}if(ex+lw>dw){x=ex-lw-12;if(x<0){x=0;}} else {x=ex+8;}y=ey+12;
if(document.body.scrollTop){y+=document.body.scrollTop;}

//z.getAttributeNode("style").setAttribute("left", parseInt(x));

z.style.left=parseInt(x);
z.style.top=parseInt(y);
z.style.visibility="visible";
//alert("x"+x+","+z.style.left);
}

else if(_ie){z=document.all[n]; ex=e.clientX;ey=e.clientY;dw=document.body.offsetWidth;
lw=z.offsetWidth; if(!lw) {lw=100;}if(ex+lw>dw){x=ex-lw-12;if(x<0){x=0;}} else {x=ex+8;}
y=ey+12; if(document.body.scrollTop){y+=document.body.scrollTop;}

z.style.pixelLeft=parseInt(x);
z.style.pixelTop=parseInt(y);
z.style.visibility="visible";}}

function hidetip(n){if(_nn){document.layers[n].visibility="hide";}
else if(_w3){document.getElementById(n).style.visibility="hidden";}
else if(_ie){document.all[n].style.visibility="hidden";}
}


//Pop-up window for context-sensitive help
function contextHelpWindow(URI) {
helpWindow = window.open(URI, "HelpWindow", "height=400, width=600, left=0, top=0, location=no, menubar=no, resizable=yes, scrollbars=yes, toolbar=no");
helpWindow.focus();
}

var activeNode;
function o_debugHighlight(enabled, currentNode) {
	// highlight div in debuging mode
	// enabled: true: do highlight: false: do not
	// currentNode: the node to be highlighted
	// (fg)
	if (currentNode != activeNode) {
		o_debugHighlight(false, activeNode);
		activeNode = currentNode;
	}
	if (currentNode == null) return;
	if (currentNode.style == null) return;
	if (enabled) {
		currentNode.style.border='1px solid gold';
		currentNode.style.background='#FCFCB8';
	} else {
		currentNode.style.border='1px dotted black';
		currentNode.style.background='';
	}
}


function openMovieViewer(vieweraddress, maddress, mname, width, height) {
	// function to start movie viewer (see radeox macro s)
	// (fg)
	var args = 'width=' + (parseInt(width)+15) + ',height=' + (parseInt(height)+15) + ',resizable=yes,scrollbars=yes';
	var viewer =  window.open('', mname,args);
	var doc = viewer.document;
	doc.close();
	doc.open("text/html");
	doc.write("<html><body>");
	
	doc.write("<head><style type=\"text/css\">");
	doc.write("<!--");
	doc.write("body { margin:0; border:0; vertical-align: middle; text-align: center; height: 100%}");
	doc.write("object { margin:0; padding: 0; border:0;  vertical-align: middle; text-align: center;}");
	doc.write("embed { margin:0; padding: 0; border:0;  vertical-align: middle; text-align: center;}");
	doc.write("-->");
	doc.write("</style></head>");
	
	writeMovieViewerCode(doc, vieweraddress, maddress, mname, width, height);
	doc.write("</body></html>");
	doc.close();
}

function writeMovieViewerCode(doc, vieweraddress, maddress, mname, width, height) {
	// function to write movie viewer to given html document. 
	// Used by radeox macro and openMovieViewer function
	// (fg)
	doc.write("<object classid=\"clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B\"  width=\"" + width + "\" height=\"" + height + "\" codebase=\"http://www.apple.com/qtactivex/qtplugin.cab\">");
	doc.write("<param name=\"SRC\" value=\"" + vieweraddress + "\">");
	doc.write("<param name=\"CONTROLLER\" value=\"TRUE\">");
	doc.write("<param name=\"AUTOPLAY\" value=\"FALSE\">");
	doc.write("<param name=\"MOVIENAME\" value=\"" + mname + "\">");
	doc.write("<param name=\"CACHE\" value=\"FALSE\">");
	doc.write("<param name=\"MovieQTList\" value=\"<movieinfo><address>" + maddress + "</address></movieinfo>\">");
	doc.write("<embed");
	doc.write(" src=\"" + vieweraddress + "\"");
	doc.write(" width=\"" + width + "\" height=\"" + height + "\"");
	doc.write(" controller=\"TRUE\"");
	doc.write(" autoplay=\"FALSE\"");
	doc.write(" moviename=\"" + mname + "\"");
	doc.write(" cache=\"FALSE\"");
	doc.write(" MovieQTList=\"<movieinfo><address>" + maddress + "</address></movieinfo>\"");
	doc.write(" type=\"video/quicktime\"");
	doc.write(" pluginspage=\"http://www.apple.com/quicktime/download/\">");
	doc.write("</embed>");
	doc.write("</object>");
}


function o_hideDiv(divId) {
	// helper function: remove element from screen using css
	// (fg)
	var divElem = document.getElementById(divId);
	if (divElem != null) {
		divElem.style.display = "none";
	}
}

function o_showDiv(divId) {
	// helper function: show element on screen using css
	// (fg)
	var divElem = document.getElementById(divId);
	if (divElem != null) {
		divElem.style.display = "block";
	}
}
xMenuEnabled = false;
function o_xMenu(showMenu){
	// showMenu: true: show the menu layer
	//           false: hide the menu layer and show the opener instead
	// (fg)
	if (!xMenuEnabled && showMenu) {
		o_hideDiv("o_xmenuopener");
		o_showDiv("o_xmenucontent");
		xMenuEnabled = true;
	} else if (xMenuEnabled && !showMenu) {
		o_hideDiv("o_xmenucontent");
		o_showDiv("o_xmenuopener");
		xMenuEnabled = false;
	}
}

xToolsEnabled = false;
function o_xTools(showTools){
	// showTools: true: show the tools layer
	//           false: hide the tools layer and show the opener instead
	// (fg)
	if (!xToolsEnabled && showTools) {
		o_hideDiv("o_xtoolsopener");
		o_showDiv("o_xtoolscontent");
		xToolsEnabled = true;
	} else if (xToolsEnabled && !showTools) {
		o_hideDiv("o_xtoolscontent");
		o_showDiv("o_xtoolsopener");
		xToolsEnabled = false;
	}
}

function o_imOpenClient(url){
	// opens the instant messaging client window, only if client window is not already opened
	if (typeof(window["clientWindow"]) == "undefined") {
		clientWindow = window.open(url, "clientWindow", "height=452, width=430, left=100, top=100, location=no, menubar=no, resizable=yes, status=no, scrollbars=no, toolbar=no");
		clientWindow.focus();
	} else {
		// parse url and launch in main window
		// 1) get start and end position of the url and the chat partner
		var startUrl = url.indexOf("/");
		var endUrl = url.indexOf("startClient");
		var startPartner = url.lastIndexOf("/")+1;
		var endPartner = url.length;
		// 2) get type of chat: user or group
		var isChat = (url.indexOf("@") > 0 ? true : false);
		// 3) calculate new chat url depending on type
		var newUrl = url.substring(startUrl, endUrl);
		if (isChat) newUrl += "doChat";
		else newUrl += "joinRoom/";
		newUrl += url.substring(startPartner, endPartner);
		if (isChat) newUrl += "/";
		// 4) launch new url if not in a dirty form 
		if (o2cl()) {
			document.location.replace(newUrl);
		}
	}
}

function o_imOpenUserList(url){
	// opens the instant messaging user list window
	listWindow = window.open(url, "listWindow", "height=600, width=600, left=100, top=100, location=no, menubar=no, resizable=yes, status=no, scrollbars=yes, toolbar=no");
	listWindow.focus();
}	

function o_openPopUp(url, windowname, width, height, menubar) {
	// generic window popup function
	attributes = "height=" + height + ", width=" + width + ", resizable=yes, scrollbars=yes, left=100, top=100, ";
	if (menubar) {
		attributes += "location=yes, menubar=yes, status=yes, toolbar=yes";
	} else {
		attributes += "location=no, menubar=no, status=no, toolbar=no";
	}
	var win = window.open(url, windowname, attributes);
	win.focus();
}


function o_openClose(iconId, divId) {
	var div = document.getElementById(divId);
	if (div != null) {
		if (div.style != null && div.style.display == "none") {
			var icon = document.getElementById(iconId);
			if (icon != null) {
				icon.className = "o_opened_div";
				// make div visible
				o_showDiv(divId);
			}
		} else {
			// change opener icon
			var icon = document.getElementById(iconId);
			if (icon != null) {
				icon.className = "o_closed_div";
				// make div invisible
				o_hideDiv(divId);
			}
		}
	
	}
}