var agt=navigator.userAgent.toLowerCase();
var is_major = parseInt(navigator.appVersion);
var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_ie6 = (is_ie && (is_major == 4) && (agt.indexOf("msie 6.")!=-1) );

var	dragging = false;

var Resizer = Class.create();

Resizer.prototype = {
	
	initialize: function() {
		this.browserWidth = 0;
		this.browserHeight = 0;
		this.headerHeight = 0;
		this.footerHeight = 0;
	},
	
	toString: function() {
		var sp = "\n";
		return ("width: " + this.browserWidth + sp + "height: " + this.browserHeight + sp + "headerHeight: " + this.headerHeight + sp + "footerHeight: " + this.footerHeight);
	},

	getBrowserSize: function() {
		if (is_ie6) 
		{
			this.browserWidth = document.documentElement.clientWidth;
			this.browserHeight = document.documentElement.clientHeight;
		}
		else 
		{
			this.browserHeight = ($("pageContainer"))?(($("pageContainer").style.display != "none")? $("pageContainer").offsetHeight: 0): 0;
			this.browserWidth = ($("pageContainer"))?(($("pageContainer").style.display != "none")? $("pageContainer").offsetWidth: 0): 0;
		}
		if (this.browserHeight <= 250 )
		{
			this.browserHeight = 250;
		}
		this.headerHeight = ($("pageHeader"))?(($("pageHeader").style.display != "none")? $("pageHeader").offsetHeight: 0): 0;
		this.footerHeight = ($("pageFooter"))?(($("pageFooter").style.display != "none")? $("pageFooter").offsetHeight: 0): 0;
	},

	setElementHeight: function(elementId, height, updateCss) {
		height = (height < 50)? 50: height;
		if ($(elementId)) 
		{ 
			$(elementId).style.height = height + "px"; 
			if (updateCss && typeof addCSSRule !== "undefined") {
				addCSSRule("#" + elementId).style.height = height + "px";
			}
		}
	},
	
	update: function() {
		this.getBrowserSize();
		
		var columnHeights = new Array ();
		//alert('browser hoogte '+browserHeight+' browser breedte '+browserWidth);
		for (i = 1; i < 4; i++)
		{
			var columnHeaderHeight = ($("column"+i+"Header"))?(($("column"+i+"Header").style.display != "none")? $("column"+i+"Header").offsetHeight: 0): 0;
			var columnTabRowHeight = ($("column"+i+"TabRow"))?(($("column"+i+"TabRow").style.display != "none")? $("column"+i+"TabRow").offsetHeight: 0): 0;
			var columnPanelToolbarHeight = ($("column"+i+"PanelToolbar"))?(($("column"+i+"PanelToolbar").style.display != "none")? $("column"+i+"PanelToolbar").offsetHeight: 0): 0;
			var columnPanelTabRowHeight = ($("column"+i+"PanelTabRow"))?(($("column"+i+"PanelTabRow").style.display != "none")? $("column"+i+"PanelTabRow").offsetHeight: 0): 0;
			var columnPanelFooterHeight = ($("column"+i+"PanelFooter"))?(($("column"+i+"PanelFooter").style.display != "none")? $("column"+i+"PanelFooter").offsetHeight: 0): 0;
			columnHeights[i] = columnHeaderHeight + columnTabRowHeight + columnPanelToolbarHeight + columnPanelTabRowHeight + columnPanelFooterHeight;
		}
		columnHeights.sort();

		/* de hoogte van de columnPanelContent div moet dan worden gezet*/
		var columnPanelContentHeight = this.browserHeight - this.headerHeight - this.footerHeight - 98;
		columnPanelContentHeight = (columnPanelContentHeight < 90)? 90: columnPanelContentHeight;
//		var panelHeightOffsets = [0, 89, 89, 87];
		var panelHeightOffsets = [0, 66, 66, 64];
		for (i = 1; i < 4; i++)
		{
			/*
			if ($("column" + i + "PanelContent"))
			{ 
				$("column" + i + "PanelContent").style.height = columnPanelContentHeight + "px"; 
				addCSSRule("#column" + i + "PanelContent").style.height = columnPanelContentHeight + "px";
			}
			if ($("column" + i + "PanelContentContainer"))
			{ 
				$("column" + i + "PanelContentContainer").style.height = (columnPanelContentHeight - panelHeightOffsets[i]) + "px"; 
				addCSSRule("#column" + i + "PanelContentContainer").style.height = (columnPanelContentHeight - panelHeightOffsets[i]) + "px";
			}
			*/
			this.setElementHeight("column" + i + "PanelContent", columnPanelContentHeight, true); 
			this.setElementHeight("column" + i + "PanelContentContainer", columnPanelContentHeight - panelHeightOffsets[i], true); 
			this.setElementHeight("slider" + i, columnPanelContentHeight + 69); 
		}

		if ($("pageFooter"))
		{
			if (is_ie6) 
			{ 
				$("pageFooter").style.top = -20 + "px"; 
			}
			$("pageFooter").style.width = this.browserWidth - 8 + "px";
		}

		// column 1
		this.setElementHeight("treeContainer", columnPanelContentHeight - 66, true); 
		this.setElementHeight("listContainer", columnPanelContentHeight - 66, true);
		// column 2 viewers
		this.setElementHeight("viewArticleField", columnPanelContentHeight - 66);
		this.setElementHeight("skosViewer", columnPanelContentHeight - 70); 

		// column 2 editors
		if ($("txaEditableContent_ifr"))
		{
			$("txaEditableContent_ifr").style.height = columnPanelContentHeight - 100 + "px"; 
			if ($("column2PanelContentContainer")) 
			{
				$("column2PanelContentContainer").style.height = columnPanelContentHeight - 23 + "px";
			}
		}
		this.setElementHeight("chibaxform", ((columnPanelContentHeight > 68)? columnPanelContentHeight - 66: 107));
		// column 3
		this.setElementHeight("searchCriteriaPanel", columnPanelContentHeight - 112);
		this.setElementHeight("emptySliderDiv", columnPanelContentHeight + 50);

		// structurelist for facet and field search
		this.setElementHeight("structereSelectionListv2", columnPanelContentHeight - 155);

		this.setElementHeight("structereSelectionList", columnPanelContentHeight - 151);
		this.setElementHeight("facetList", columnPanelContentHeight - 167);
		this.setElementHeight("fieldSearchSelectionList", columnPanelContentHeight - 206);

		this.setElementHeight("searchResults", columnPanelContentHeight - 104);
	}

}


function dynamicLayout()
{
	resizer.update();
}

function debug(msg, clear)
{
	var output = $("debug");
	if (output)
	{
		if (clear == true	|| output.innerHTML == "debugging...")
		{
			output.innerHTML = "<p>" + msg + "</p>";
		}
		else 
		{
			output.innerHTML += "<p>" + msg + "</p>";
		}
		setTimeout('$("debugContent").scrollTop = $("debugContent").scrollHeight', 100);
	}
}

function applicationShowError(status, params) {
	if ("" + params == "undefined") 
	{
		var params = {};
	}
	params.infoType = "Error";
	applicationShowInfo(status, params)
}

function applicationShowHint(status, params)
{
	if ("" + params == "undefined") 
	{
		var params = {};
	}
	params.infoType = "Hint";
	applicationShowInfo(status, params)
}

function applicationShowInfo(status, params)
{
	var prefix = "column" + ((params.column)? params.column: 2);
	var infoType = ((params.infoType)? params.infoType: "Hint");

	if ($(prefix + "PanelContent")) 
	{
		if (!$(prefix + infoType)) 
		{
			$(prefix + "PanelContent").innerHTML += '<div id="' + prefix + infoType + '" class="column' + infoType + '" style="display: none; "><div id="' + prefix + infoType + 'Text" class="column' + infoType + 'Text">' + status + '</div></div>';
		}
		else 
		{
			$(prefix + infoType + "Text").innerHTML = status;
		}

		new Effect.Appear(prefix + infoType, { duration: 0.5, queue: { position: 'end', scope: 'info', limit: 3 } });
		Effect.Queues.get('info').interval = 4500;
		new Effect.Pulsate(prefix + infoType, {	duration: 2.0, from: 0.9, pulses: 3, queue: { position: 'end', scope: 'info', limit: 3 } });
		new Effect.Fade(prefix + infoType, {	duration: 0.8, queue: { position: 'end', scope: 'info', limit: 3 } });
	}

}

function applicationUpdateStatus(status, params)
{
	if ($('column2Status')) 
	{
		$('column2Status').innerHTML = status;
		$('column2Status').appear({duration: 0.5});
	}
}

function applicationStartWait() 
{
	if (document.body) {
		if (document.body.addClassName) {	
			document.body.addClassName('waiting');
		}
	}
}

function applicationEndWait() 
{
	if (document.body) {
		if (document.body.addClassName) {	
			document.body.removeClassName('waiting');
		}
	}
}

function applicationToggle(index)
{
	var otherIndex = (index == "1") ? "3" : "1";
	if ($("column" + index).style.display == "none")
	{
		$("column" + index).style.display = "block";
		//$("column" + otherIndex).style.display = "none";
		$("showColumn" + index).hide();
		$("hideColumn" + index).show();
		//$("showColumn" + otherIndex).show();
		//$("hideColumn" + otherIndex).hide();
	}
	else
	{
		$("column" + index).style.display = "none";
		$("column" + otherIndex).style.display = "block";
		$("showColumn" + otherIndex).hide();
		$("hideColumn" + otherIndex).show();
		$("showColumn" + index).show();
		$("hideColumn" + index).hide();
	}

//	var otherIndex = (index == "1")? "3": "1";
//	$("slider" + index).innerHTML = "<div id='emptySliderDiv'>&#160;</div><a href=\"#\" onclick=\"applicationToggle('" + index + "')\">&lt;&gt;</a>";
//	$("slider" + otherIndex).innerHTML = "x";
//	if ($("column" + index).style.display == "none") 
//	{
//		$("column" + index).style.display = "block";
//		$("slider" + index).style.display = "none";
//	}
//	else 
//	{
//		$("column" + index).style.display = "none";
//		$("slider" + index).style.display = "block";
//		// auto show the 'other' panel
//		$("column" + otherIndex).style.display = "block";
//		$("slider" + otherIndex).style.display = "none";
//	}
	dynamicLayout();
}

function applicationUpdateTitle(s)
{
	application.updateTitle(s);
}

var keepAliveTimer = -1;

function actionReload()
{
	applicationKeepAlive();
	var myAjax = new Ajax.Request(application.keepAliveUrl, { method: 'get', parameters: {code: Math.random()}, asynchronous: false, evalScripts: true});
}

function applicationKeepAlive()
{
	if (keepAliveTimer!=-1) clearTimeout(keepAliveTimer);
	keepAliveTimer = window.setTimeout("actionReload()", 2*60*1000);
}

function applicationShowLogin()
{
	document.location.href = "/login.aspx?message=lostconnection&requestUrl=default.aspx";
}

var historyListener = function(newLocation, historyData) {
	debug("A history change has occurred: " + "newLocation="+newLocation + ", historyData=" + Object.toJSON(historyData), false);
	if (historyData != null) 
	{
		historyBlock = true;
		if (newLocation.slice(0, 19) == "applicationShowData") 
		{
			if (historyData.nodeContext != '' && ((selection.selectionData() != null)? selection.selectionData().nodeId: "") != historyData.nodeContext) 
			{
				if (selection.elementExists(historyData.uri, historyData.nodeContext)) 
				{
					debug("changing selection to: " + historyData.uri + ", " + historyData.nodeContext);
					selection.reset();
					selection.add(null, {uri: historyData.uri, nodeId: historyData.nodeContext});
					applicationShowData(historyData.uri, historyData.sysTab, historyData.mode, historyData.nodeContext);
				}
				else 
				{
					debug("changing tree to: " + historyData.uri + ", " + historyData.nodeContext);
					applicationShowTree({uri: historyData.uri, nodeId: historyData.nodeContext});
				}
				
			}
			else 
			{
				if (historyData.uri != "") 
				{
					applicationShowData(historyData.uri, historyData.sysTab, historyData.mode, historyData.nodeContext);
				}
			}
			
		}

		historyBlock = false;
	}
}

var historyCount = 0;
var historyBlock = false;

function initHistory()
{
	dhtmlHistory.initialize();
	dhtmlHistory.addListener(historyListener);
	
	// respond to refresh of page with history in url
	var url = document.location;
	if (url.hash.slice(0, 20) == "#applicationShowData") {
		actions = url.hash.slice(21).split("|");
		applicationShowTree({uri: actions[0]});//, actions[1], actions[2]);
	}
	
	/*	
	if (historyStorage.hasKey("showData")) 
	{
		debug("getting history for showData");
		var showDataData = historyStorage.get("showData");
		applicationShowData(showDataData.uri, showDataData.sysTab, showDataData.mode, showDataData.nodeContext);
	}
	else 
	{
		debug("no history for showData");
	}
	//debug(Object.toJSON(historyStorage.get("showData")), false);
	*/
}

function applicationShowAllStructures()
{
	debug("applicationShowAllStructures()");
	application.showAllStructures();
	application.showData("", "content", "view", "", "");
}


function applicationNodeMoveStructure(source, target)
{
	debug("applicationMoveStructure()");
	application.updateNodeMoveStructure(source, target, "");
	application.showData("", "content", "view", "", "");
}


function applicationShowTree(params)
{
	debug("applicationShowTree(" + Object.toJSON(params) + ")");

	if (dragging) {
		debug("canceled");
		return;
	}
	application.referenceStructureId = ((params.referenceStructureId)? params.referenceStructureId: application.referenceStructureId);
	application.rootNodeId = ((params.rootNodeId || params.rootNodeId == '')? params.rootNodeId: application.rootNodeId);
	application.nodeId = ((params.nodeId || params.nodeId == '')? params.nodeId: application.nodeId);
	application.uri = ((params.uri || params.uri == '')? params.uri: application.uri);
	application.subUri = ((params.subUri || params.subUri == '')? params.subUri: application.subUri);
	application.mode = ((params.mode)? params.mode: application.mode);
	application.showTreeOnly = ((typeof params.showTreeOnly == "boolean")? params.showTreeOnly: application.showTreeOnly);

	var showItemInOwnContext = ((typeof params.showItemInOwnContext == "boolean")? params.showItemInOwnContext: false);

	/*
	if (!historyBlock)
	{
		dhtmlHistory.add("applicationShowTree:" + "", {params: params});
	}
	*/
	application.showTree(showItemInOwnContext)
}

function applicationSetTreeSelection()
{

	if (application.uri != '')
	{
		selection.reset();
		// there still is some incorrect use of uri/subUri!
		if (!selection.elementExists(application.uri, application.nodeId))
		{
			if (application.annexNodeId)
			{
				// selected node is placed as annex item
				applicationSelect(undefined, application.uri, 'annex', application.annexNodeId, false, false, true);
			}
			else
			{
				selection.add(null, {uri: application.subUri, nodeId: application.nodeId});
			}
			
		}
		else 
		{
			selection.add(null, {uri: application.uri, nodeId: application.nodeId});
		}
		
		if (application.showTreeOnly)
		{
			// do not show data
		}
		else
		{

			if (application.subUri != '')
			{
				applicationShowData(application.subUri, "content", application.mode, application.nodeId);
			}
			else
			{
				applicationShowData(application.uri, "content", application.mode, application.nodeId);
			}
		}
		
		applicationToggleMoveItemToolbar(application.nodeId, application.isReferred, application.isReferredNode, application.rootNodeId);
	}
}

function applicationSetTreeLabelDisplay(referenceStructureId, treeViewMode)
{
	treeEditor.viewModes[referenceStructureId] = treeViewMode;
	applicationShowTree({});
}

function applicationShowExpandData(uri, sysTab, mode, nodeContext, pageNumber, targetNodeId)
{
	if ($("div_" + targetNodeId).visible()) 
	{
		$("div_" + targetNodeId).hide();
		$("btn_" + targetNodeId).innerHTML = "v";
	}
	else 
	{
		$("div_" + targetNodeId).show();
		$("btn_" + targetNodeId).innerHTML = "^";
		application.showExpandData(uri, sysTab, mode, nodeContext, pageNumber, "div_" + targetNodeId);
	}
}

function applicationShowData(uri, sysTab, mode, nodeContext, pageNumber) {
	// applicationCheckEditorSave checks if the editor exists and is in edit mode; if so, it asks for save if the content has been changed.
	// if user wants to save true is returned, else false is returned.
	var checkEditorSave = applicationCheckEditorSave({ uri: uri, mode: mode });
	var editorSavesAsynchronously = (activeItemEditor != null)? activeItemEditor.isSavedAsynchronous: false;
	
	if (!(checkEditorSave && editorSavesAsynchronously))
	{
		// if the editor content does not need to be saved or if the data has been saved synchronously; continue to show data
		debug("applicationShowData(\"" + uri + "\", \"" + sysTab + "\", \"" + mode + "\", \"" + nodeContext + "\", \"" + pageNumber + "\")");

		if (mode == '') {
			mode = ((application.persistentMode) ? application.mode : 'view');
		}
		activeEditorMode = mode;

		nodeContext = ("" + nodeContext != "undefined") ? nodeContext : "";

		if (mode == 'edit' && nodeContext != "" && nodeContext.indexOf("_", 1) != -1) {
			mode = 'view'
		}

		pageNumber = ("" + pageNumber != "undefined") ? pageNumber : "";

		if (nodeContext != '' && selection.selectionData().nodeId != nodeContext) {
			if (selection.elementExists(uri, nodeContext)) {
				debug("changing selection to: " + uri + ", " + nodeContext);
				selection.reset();
				selection.add(null, { uri: uri, nodeId: nodeContext });
			}
		}

		if (dhtmlHistory && !historyBlock && uri != "" && uri != null) {
			dhtmlHistory.add("applicationShowData:" + uri + "|" + sysTab + "|" + mode, { uri: uri, sysTab: sysTab, mode: mode, nodeContext: nodeContext })
		}

		window.focus();
		applicationRemoveTinyMCEControl();
		activeSubItemEditor = null;
		activeItemEditor = null;
		application.mode = mode;
		application.showData(uri, sysTab, mode, nodeContext, pageNumber);
	}
}

function applicationReloadData()
{
	applicationShowTree({});
}

function applicationShowSelectionTree(referenceStructureId, rootNodeId, nodeId, uri, allowedRdfTypes, predicateUri){
	application.referenceStructureId = referenceStructureId;
	application.rootNodeId = rootNodeId;
	application.nodeId = nodeId;
	application.uri = uri;

	application.showSelectionTree(allowedRdfTypes, predicateUri);
	
	selection.reset();
	selection.options.addMode = 'select';
	//marco : do not select the root node	
	//selection.add(null, {uri: uri, nodeId: application.nodeId});
}

function applicationCheckEditorSave(params)
{
	return applicationAskForSave(params);
}

function applicationSelect(e, uri, type, selectedNodeId, isReferred, isReferredNode, isPlacedAsAnnexItem)
{
	// show the annex item list of the current selected content-item, hide all other annex item lists
	var objId = 'a_' + selectedNodeId + '_' + uri;
	var isAnnexItem = ($(objId) && $(objId).hasClassName('annex')) ? true : false;
	var ulNodeId = (isAnnexItem) ? $('li_' + selectedNodeId).parentNode.id.substring(9) : selectedNodeId;
	var all = $A($('treeContainer').select('div.annexItemList')).each(function(Obj)
	{
		if (Obj.id != 'annexList_' + ulNodeId || !(isAnnexItem)) { Obj.hide(); }
	})

	
	if (selection.options.addMode == 'new')	
	{
		application.uri = uri;
		
		isReferred = (isReferred == null)? '' : isReferred;
		isReferredNode = (isReferredNode == null) ? '' : isReferredNode;
		application.isReferred = isReferred;
		application.isReferredNode = isReferredNode;
		
		selection.reset();
		selection.add(null, { uri: uri, nodeId: selectedNodeId });
		//applicationRemoveTinyMCEControl();
		if (isPlacedAsAnnexItem == undefined || !isPlacedAsAnnexItem)
		{
			application.annexNodeId = undefined;
			applicationShowData(application.uri, "content", '', selectedNodeId);
		}
		applicationToggleMoveItemToolbar(selectedNodeId, isReferred, isReferredNode, application.rootNodeId, type);
	}

	if (selection.options.addMode == 'append' && application.mergeMode == true) {
		mergeAllowed = true;
		if (mergeAllowed) 
		{
			if (confirm(strings.applicationConfirmMergeNodeInto)) 
			{
				selection.add(null, { uri: uri, nodeId: selectedNodeId });
				applicationMergeItem();
			}
			else 
			{
				if (application.mergeMode == true) applicationClickMergeButton('btnMergeNodeInto');
			}
		}
		else 
		{
			alert(strings.applicationErrorMessageCannotMergeItems);
		}
	}
	else if (selection.options.addMode == 'append')
	{	
		isReferred = (isReferred == null)? '' : isReferred;
		isReferredNode = (isReferredNode == null)? '' : isReferredNode;

		if ((selectedNodeId.indexOf("_", 1) != -1) && (selectedNodeId.indexOf("_") == selectedNodeId.lastIndexOf("_")) && (isReferredNode))
		{
			//directly linked
			if(application.moveMode == 'into')
			{
				alert(strings.applicationErrorMessageIllegalMoveIntoReferedNode);
			} 
			else 
			{
				if (confirm(strings.applicationConfirmMoveNode))
				{
					selection.add(null, {uri: uri, nodeId: selectedNodeId});
					applicationMoveNode();
				} 
				else
				{
					if (application.moveMode == 'below') applicationClickMoveButton('btnMoveNodeBelow', 'below');
					else if (application.moveMode == 'above') applicationClickMoveButton('btnMoveNodeAbove', 'above');
					else if (application.moveMode == 'into') applicationClickMoveButton('btnMoveNodeInto', 'into');
				}
			}

		} 
		else if ((selectedNodeId.indexOf("_",1) != -1) && isReferred)
		{
			//indirectly linked
			alert(strings.applicationErrorMessageIllegalMoveIntoReferedNode);
		} 
		else if ((selectedNodeId == application.rootNodeId) && (application.moveMode == "above" || application.moveMode == "below"))
		{
			alert(strings.applicationErrorMessageAboveOrBelowRootnode );
		} 
		else
		{
			//unlinked en geen rootnode
			if (confirm(strings.applicationConfirmMoveNode))
			{
				selection.add(null, {uri: uri, nodeId: selectedNodeId});
				applicationMoveNode();
			} 
			else
			{
				if (application.moveMode == 'below') applicationClickMoveButton('btnMoveNodeBelow', 'below');
				else if (application.moveMode == 'above') applicationClickMoveButton('btnMoveNodeAbove', 'above');
				else if (application.moveMode == 'into') applicationClickMoveButton('btnMoveNodeInto', 'into');
			}
		}
	}

	if (selection.options.addMode == 'select') 
	{
		selection.reset();
		selection.add(null, {uri: uri, nodeId: selectedNodeId});
	}
	return false;
}


function applicationBuildNode(params)
{
	application.nodeId = params.nodeId;

	var showAnnexItem = false;

	if (params.showAnnexItem != undefined)
	{
		showAnnexItem = params.showAnnexItem;
	}
	
	var annexItemUri = params.annexItemUri;
	
	treeEditor.buildNode(params);
	// calls applicationUpdateNode onComplete
	
	if (showAnnexItem)
	{
		applicationShowData(annexItemUri, "content", "view");
		applicationSelect(undefined, params.annexItemUri, 'annex', params.annexNodeId, '', '', true);
	}
}

function applicationToggleNode(nodeId)
{
	if ($('ul_' + nodeId))
	{
		applicationUpdateNode(nodeId, true, false);
	}
	else {
		applicationBuildNode({nodeId: nodeId});
	}
}

function applicationNewReferenceStructure(referenceStructureName , selectedLanguages, selectedContentItemTypes)
{
	treeEditor.newReferenceStructure(referenceStructureName, selectedLanguages, selectedContentItemTypes);
}

function applicationOnNewReferenceStructure(referenceStructureId, rootNodeId, rootUri)
{
	applicationShowTree({referenceStructureId: referenceStructureId, rootNodeId: rootNodeId, nodeId: rootNodeId, uri: rootUri});
}

function applicationDeleteReferenceStructure(referenceStructureId)
{
	if (confirm(strings.applicationConfirmDeleteStructure))
	{
		treeEditor.deleteReferenceStructure(referenceStructureId);
	}
}

function applicationOnDeletedReferenceStructure()
{
	applicationShowAllStructures();
}


function applicationUpdateNode(nodeId, show, onBuildNode)
{
	application.nodeId = nodeId;

	var nodeButton = $('tb_' + nodeId);
	
	
	if (onBuildNode)
	{
		if ($('ul_' + nodeId))
		{
			// node has children; show them
			nodeButton.className = 'min';
			nodeButton.href = "javascript:applicationToggleNode('" + nodeId + "')";
			applicationToggleNodeClass(nodeId);
		}
		else
		{
			// node has no children; don't show them
			nodeButton.className = 'connector';
			nodeButton.href = '#';
		}

		selection.refreshClassName();
	}
	else
	{
		nodeButton.className = (nodeButton.className == 'min' || show == false)? 'plus': 'min';
		nodeButton.href = "javascript:applicationToggleNode('" + nodeId + "')";
		
		applicationToggleNodeClass(nodeId);
		applicationToggleNodeUl(nodeId);
		applicationToggleNodePagination(nodeId);
	}
}

function applicationShowSearch(mode, searchTab)
{
	application.showSearch(mode, searchTab);
}

function applicationNewConcept(conceptName, onSameLevel)
{
	conceptEditor.newConcept(conceptName, onSameLevel);
}

function applicationOnNewConcept(newUri, newNodeId, parentNodeId)
{
	// rebuild parent node
	applicationBuildNode( {nodeId: parentNodeId } );

	// select new node
	applicationSelect( null, newUri, 'content_item', newNodeId );
}


function applicationSaveAndViewConcept(uri)
{
	conceptEditor.saveConcept();
	applicationShowData(uri, "content", "view");
}

function applicationSaveConcept()
{
	conceptEditor.saveConcept();
}

function applicationSaveAndViewSkosConcept(uri)
{
	conceptEditor.saveSkosConcept();
	applicationShowData(uri, "content", "view");
}

function applicationSaveSkosConcept()
{
	conceptEditor.saveSkosConcept();
}


function applicationOnSavedConcept()
{
	applicationShowTree({});
}

// merge node into
function applicationClickMergeButton(buttonId) {
	var button = $(buttonId);

	if (button != null) {
		if (button.className == 'pending') {
			// button is released (dus min of meer cancel)
			button.removeClassName('pending');
			selection.options.addMode = 'new';
			application.mergeMode = false;
			application.mergeButtonId = null;
		}
		else {
			if (application.mergeButtonId == null) {
				// no move button is pressed yet
				button.addClassName('pending');
				selection.options.addMode = 'append';
				application.mergeMode = true;
				application.mergeButtonId = buttonId;
			}
		}
	}


}

// node move

function applicationClickMoveButton(buttonId, moveMode)
{
	var button = $(buttonId);

	if (button != null)
	{
		if (button.className == 'pending')
		{
			// button is released
			button.removeClassName('pending');
			selection.options.addMode = 'new';
			application.moveMode = 'noMove';
			application.moveButtonId = null;
		}
		else {
			if (application.moveButtonId == null)	{
				// no move button is pressed yet
				button.addClassName('pending');
				selection.options.addMode = 'append';
				application.moveMode = moveMode;
				application.moveButtonId = buttonId;
			}
		}
	}
}

function applicationMoveNode()
{
	treeEditor.moveItem();
}

function applicationOnMovedItem(movedNodeId, movedUri, isLegalMove, errorCode)
{
	applicationClickMoveButton(application.moveButtonId, application.moveMode);
	selection.pop();

	if (isLegalMove == 'true')
	{
		// show moved node in tree
		applicationShowTree({nodeId: movedNodeId, uri: movedUri});
	}
	else
	{
		var message;
		switch(errorCode)
		{
			case "nodeToMoveIsAncestorOfTargetNode":
					message= strings.applicationErrorMessageCannotMoveToOwnChilds;
				break;
			case "targetNodeNotFound":
					message= strings.applicationErrorMessageUnknownError;
				break;
			case "notAuthorized":
					message= strings.applicationErrorMessageNoMoveItemRights;
				break;
			case "NodeToMoveIsRecycleBin":
					message= strings.applicationErrorMessageCannotMoveRecycleBin;
				break;
			case "NodeToMoveIsRootNode": 
					message= strings.applicationErrorMessageCannotMoveRootNode;
				break;
			default:
					message= strings.applicationErrorMessageUnknownError;
				break;
		}
		alert(message);
	}
}

function applicationMoveNodeToOtherStructure(uri, type, selectedNodeId)
{
	selection.options.addMode = 'append';
	application.moveMode = 'into';
	application.mode = 'view';
	applicationSelect(null, uri, type, selectedNodeId);
}

function applicationOnMovedNodeToOtherStructure(parentNodeId, parentUri, isLegalMove)
{
	selection.pop();

	if (isLegalMove == 'true')
	{
		// show previous parent of moved node in tree
		applicationShowTree({nodeId: parentNodeId, uri: parentUri});
	}
	else
	{
		alert(strings.applicationErrorMessageIllegalMove);
	}
}


/* node removal and restore */

function applicationRemoveItem()
{
	treeEditor.removeItem();
}

function applicationOnRemovedItem( parentNodeId, parentUri )
{
	selection.reset();
	// rebuild parent node
	applicationBuildNode( {nodeId: parentNodeId } );
	// select parent concept
	applicationSelect( null, parentUri, 'content_item', parentNodeId);
}

function applicationRestoreItem(){
	treeEditor.restoreItem();
}

function applicationOnRestoredItem(parentNodeId, parentUri)
{
	selection.reset();
	// rebuild parent node
	applicationBuildNode( {nodeId: parentNodeId } );
	// select parent concept
	applicationSelect( null, parentUri, 'content_item', parentNodeId);
}

function applicationDeleteItem()
{
	treeEditor.deleteItem();
}

function applicationOnDeletedItem(parentNodeId, parentUri)
{
	selection.reset();
	// rebuild parent node
	applicationBuildNode( {nodeId: parentNodeId } );
	// select parent concept
	applicationSelect( null, parentUri, 'content_item', parentNodeId);
}

function applicationMergeItem() {
	treeEditor.mergeItem();
}

function applicationOnMergedItem(sourceParentNodeId, targetNodeId, targetUri, isLegalMove, errorCode) {
	if (isLegalMove == 'true') {
		// show moved node in tree
		selection.reset();
		// rebuild parent node of the source concept (disappeared)
		applicationBuildNode({ nodeId: sourceParentNodeId });
		// refresh and select target concept
		applicationBuildNode({ nodeId: targetNodeId });
		applicationSelect(null, targetUri, 'content_item', targetNodeId);
		applicationClickMergeButton('btnMergeNodeInto');
	}
	else {
		var message;
		switch (errorCode) {
			case "notAuthorized":
				message = strings.applicationErrorMessageNotAuthorizedToMerge;
				break;
			case "itemsNotFound":
				message = strings.applicationErrorMessageCannotMergeItemsNotFound;
				break;
			case "cannotMergeRootItem":
				message = strings.applicationErrorMessageCannotMergeRootItem;
				break;
			case "cannotMergeIncompatibleItems":
				message = strings.applicationErrorMessageCannotMergeIncompatibleItems;
				break;
			case "cannotMergeIntoChildItem":
				message = strings.applicationErrorMessageCannotMergeIntoChildItem;
				break;
			default:
				message = strings.applicationErrorMessageCannotMerge;
				break;
		}
		alert(message);
	}
}

// Web Page *****

function applicationValidateWebPage(uri)
{
	articleEditor.validateWebPage(uri);
}

function applicationSaveWebPage()
{
	articleEditor.saveWebPage();
}

function applicationSaveAndViewWebPage(uri)
{
	articleEditor.saveWebPage();
	applicationShowData(uri, "content", "view");
}


// Object Record *****

function applicationSaveObjectRecord(params)
{
	objectRecordEditor.saveObjectRecord();
	objectRecordEditor.evalOnSaveObjectRecordSuccess = "applicationShowData('" + params.uri + "', 'content', '" + params.mode + "');";
}

function applicationSaveAndViewObjectRecord(uri)
{
	objectRecordEditor.saveObjectRecord();
	objectRecordEditor.evalOnSaveObjectRecordSuccess = "applicationShowData('" + uri + "', 'content', 'view');";
}

function applicationSaveObjectRecordSuccess()
{
	applicationUpdateMd5ForForm();
	applicationShowHint(strings.applicationMessageRecordSaved);
	objectRecordEditor.onSaveObjectRecordSuccess();
}

function applicationSaveObjectRecordError()
{
	applicationShowError(strings.applicationErrorMessageRecordNotSaved)
}


function applicationNewContentItem(title, contentItemTypeId, onSameLevel, itemTypeUri)
{
	if (activeItemEditor)
	{
		activeItemEditor.newContentItem(title, contentItemTypeId, onSameLevel, itemTypeUri);
	}
	else
	{
		alert(strings.applicationErrorMessageNoActiveEditor);
	}
}

function applicationOnNewContentItem(newUri, newNodeId, parentNodeId) 
{
	// rebuild parent node
	applicationBuildNode( {nodeId: parentNodeId, showAnnexItem: true, annexItemUri : newUri, annexNodeId : newNodeId } );

	// select new content item
	applicationSelect( null, newUri, 'content_item', newNodeId );
}

function applicationNewAnnexContentItem(predicateUri, itemTypeUri) {
	if (activeItemEditor) {
		activeItemEditor.newAnnexContentItem(predicateUri, itemTypeUri);
	}
	else {
		alert(strings.applicationErrorMessageNoActiveEditor);
	}
}

// System Data *****

function applicationSaveSystemData()
{
	systemDataEditor.saveSystemData();
}

function applicationSaveAndViewSystemData(uri)
{
	systemDataEditor.saveSystemData(
		{onSucces: function() {
			//alert(uri + "systemdata" + "view");
			applicationShowData(uri, "systemdata", "view");
			}
		}
	);
	
}

function applicationNewLinkNode(referredNodeId, linkType)
{
	treeEditor.newLinkNode(referredNodeId, linkType);
}

function applicationOnNewLinkNode(parentReferrerNodeId, parentReferrerUri, isUpdated)
{
	if (isUpdated == 'true')
	{
		// rebuild parent node
	  applicationBuildNode( {nodeId: parentReferrerNodeId } );
		// select new node
		applicationSelect( null, parentReferrerUri, 'content_item', parentReferrerNodeId );
	}
	else
	{
		alert(strings.applicationErrorMessageIllegalLink);
	}
}

function applicationDeleteLinkNode( referrerNodeId , linkType)
{
	treeEditor.deleteLinkNode( referrerNodeId, linkType );
}

function applicationOnDeletedLinkNode(isDeleted, parentNodeId, parentUri)
{
	if (isDeleted == 'true')
	{
		// rebuild parent node
	  applicationBuildNode( {nodeId: parentNodeId } );

		// select new node
		applicationSelect( null, parentUri, 'content_item', parentNodeId );
	}
}

function applicationPostComment(uri)
{
	commentsEditor.postComment(uri);
}

function applicationAcceptComment(uri, commentId)
{
	commentsEditor.acceptComment(uri, commentId);
}

function applicationHideComment(uri, commentId)
{
	commentsEditor.hideComment(uri, commentId);
}

function applicationShowComment(uri, commentId)
{
	commentsEditor.showComment(uri, commentId);
}

function applicationDeleteComment(uri, commentId)
{
	if (confirm(strings.applicationConfirmDeleteComment))
	{
		commentsEditor.deleteComment(uri, commentId);
	}
}

// utility functions - start

function applicationToggleNodeClass( nodeId )
{
	var nodeLI = $('li_' + nodeId);
	switch (nodeLI.className) {
		case 'open':
			nodeLI.className = 'closed';
			break;
		case 'openNoConnect':
			nodeLI.className = 'noConnect';
			break;
		case 'closed':
			nodeLI.className = 'open';
			break;
		case 'noConnect':
			nodeLI.className = 'openNoConnect';
			break;
	}
}

function applicationToggleNodeUl( nodeId )
{
	var nodeUl = $('ul_' + nodeId);
	if (nodeUl)
	{
		nodeUl.style.display = (nodeUl.style.display == 'none')? 'block': 'none';
	}
}

function applicationToggleNodePagination(nodeId)
{
	var nodePagination = $('pb_' + nodeId);
	if (nodePagination)
	{
		if (nodePagination.visible())
			nodePagination.hide();
		else
			nodePagination.show();
	}
}

function applicationEnableInputsAndSelects()
{
	var inputNodes = $$('input');

	for (var i = 0; i < inputNodes.length; i++)
	{
		inputNodes[i].removeAttribute("disabled", 0);
	}

	var selectNodes = $$('select');

	for (var i = 0; i < selectNodes.length; i++)
	{
		selectNodes[i].removeAttribute("disabled", 0);
	}
}

function applicationUpdateMd5ForForm()
{
	if (activeSubItemEditor)
	{
		activeSubItemEditor.notDirty();
	}
}

function applicationAskForSave(params)
{
	debug("activeEditorMode: " + activeEditorMode + "; activeSubItemEditor: " + activeSubItemEditor);
	if (activeEditorMode == "edit" && activeSubItemEditor)
	{
		return activeSubItemEditor.askForSave(params);
	}
	
	return false;
}

// custom alert dialog
// **************************************************************************************************

function applicationAlert(s)
{
	Dialog.alert("<textarea style='height:300px; width:100%'>" + s + "</textarea>", {id: "alert", className: "clean", width: 510, height: 354, maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: true, destroyOnClose: true, title: "RNA Toolset"});
}

function applicationInitTinyMCE()
{
	articleEditor.initTinyMCE();
}


function applicationAddTinyMCEControl()
{
	applicationRemoveTinyMCEControl();

	if ($('txaEditableContent'))
	{
		//alert("adding tinyMCE");
		tinyMCE.execCommand('mceAddControl', false, 'txaEditableContent');
	}
}

function applicationRemoveTinyMCEControl(){
	if ($('txaEditableContent') && tinyMCE.activeEditor)
	{
		debug("removing tinyMCE");
		tinyMCE.execCommand('mceRemoveControl', false, 'txaEditableContent');
		tinyMCE.activeEditor = null;
	}
}

function applicationChibaLoaded()
{
	activeItemEditor = objectRecordEditor;
	activeSubItemEditor = objectRecordEditor;
	activeSubItemEditor.notDirty();
}

function applicationOnSelectRecycleBin()
{
	Element.toggleClassName('btnRecycleBin', 'active');
	$('btnCurrentStructure').removeClassName('active');
}

function applicationToggleMoveItemToolbar(nodeId, isReferred, isReferredNode, rootNodeId, type)
{
	if (rootNodeId == nodeId)
	{
		// root node
		if ($('moveUnlinkedItemsToolbar')) $('moveUnlinkedItemsToolbar').hide();
		if ($('moveDirectlyLinkedItemsToolbar')) $('moveDirectlyLinkedItemsToolbar').hide();
		if ($('structureMoveToolBarLabel')) $('structureMoveToolBarLabel').hide();
		if ($('moveItemsToolbarLabel')) $('moveItemsToolbarLabel').show();
		if ($('linkItemsToolbar')) $('linkItemsToolbar').show();
		if ($('mergeItemsToolbar')) $('mergeItemsToolbar').hide();

	} else if (nodeId == undefined)
	{
		// geen selectie
		if ($('moveUnlinkedItemsToolbar')) $('moveUnlinkedItemsToolbar').hide();
		if ($('moveDirectlyLinkedItemsToolbar')) $('moveDirectlyLinkedItemsToolbar').hide();
		if ($('structureMoveToolBarLabel')) $('structureMoveToolBarLabel').hide();
		if ($('moveItemsToolbarLabel')) $('moveItemsToolbarLabel').hide();
		if ($('linkItemsToolbar')) $('linkItemsToolbar').hide();
		if ($('mergeItemsToolbar')) $('mergeItemsToolbar').hide();

	} else if ((nodeId.indexOf("_", 1) != -1) && (nodeId.indexOf("_") == nodeId.lastIndexOf("_")) && (isReferredNode))
	{
		// directly linked node
		if ($('moveUnlinkedItemsToolbar')) $('moveUnlinkedItemsToolbar').show();
		if ($('moveDirectlyLinkedItemsToolbar')) $('moveDirectlyLinkedItemsToolbar').hide();
		if ($('structureMoveToolBarLabel')) $('structureMoveToolBarLabel').show();
		if ($('moveItemsToolbarLabel')) $('moveItemsToolbarLabel').show();
		if ($('linkItemsToolbar')) $('linkItemsToolbar').hide();
		if ($('mergeItemsToolbar')) $('mergeItemsToolbar').hide();

	} else if ((nodeId.indexOf("_", 1) != -1) && isReferred)
	{
		// indirectly linked node
		if ($('moveUnlinkedItemsToolbar')) $('moveUnlinkedItemsToolbar').hide();
		if ($('moveDirectlyLinkedItemsToolbar')) $('moveDirectlyLinkedItemsToolbar').hide();
		if ($('structureMoveToolBarLabel')) $('structureMoveToolBarLabel').hide();
		if ($('moveItemsToolbarLabel')) $('moveItemsToolbarLabel').hide();
		if ($('linkItemsToolbar')) $('linkItemsToolbar').hide();
		if ($('mergeItemsToolbar')) $('mergeItemsToolbar').hide();

	} else if (type == 'annex')
	{
		// annex item
		if ($('moveUnlinkedItemsToolbar')) $('moveUnlinkedItemsToolbar').hide();
		if ($('moveDirectlyLinkedItemsToolbar')) $('moveDirectlyLinkedItemsToolbar').hide();
		if ($('structureMoveToolBarLabel')) $('structureMoveToolBarLabel').hide();
		if ($('moveItemsToolbarLabel')) $('moveItemsToolbarLabel').hide();
		if ($('linkItemsToolbar')) $('linkItemsToolbar').hide();
		if ($('mergeItemsToolbar')) $('mergeItemsToolbar').hide();

	} else
	{
		// normal item
		if ($('moveUnlinkedItemsToolbar')) $('moveUnlinkedItemsToolbar').show();
		if ($('moveDirectlyLinkedItemsToolbar')) $('moveDirectlyLinkedItemsToolbar').hide();
		if ($('structureMoveToolBarLabel')) $('structureMoveToolBarLabel').show();
		if ($('moveItemsToolbarLabel')) $('moveItemsToolbarLabel').show();
		if ($('linkItemsToolbar')) $('linkItemsToolbar').show();
		if ($('mergeItemsToolbar')) $('mergeItemsToolbar').show();
	}
}

// utility functions - end
// Trap Backspace(8) and Enter(13) -
// Except bksp on text/textareas, enter on textarea/submit

EnterTrap = null;

if (typeof window.event != 'undefined')
{
	// IE
	document.onkeydown = function() {
		var t = event.srcElement.type;
		var id = event.srcElement.id;
		var kc = event.keyCode;
		var tinyMceBullitTest = "" + t + kc + event.srcElement.parentElement;
		
		//Batch editor || quicksearch
		if ($(event.srcElement).up(".batch-editor") || $(event.srcElement).up(".quick-search")) {
			return true
		} 
		else if ((kc != "keyCode" && kc != 13) || ( t == 'text' &&	kc != 13 ) || (t == 'textarea') || ( t == 'submit' &&	kc == 13) || ( tinyMceBullitTest == 'undefined13javascript:;'))
		{
			return true
		}
		else {
			if (kc == 13 && EnterTrap != null) {
				return EnterTrap();
			} 
			else if (kc == 13 && id == 'searchField' && $('searchSubmit')) {
				eval($('searchSubmit').onclick());
				return false;
			}
			else {
				alert(strings.applicationErrorMessageBackspaceNotAllowed); // demo
				return false;
			}
		}
	}
}
else {
	// FireFox/Others
	document.onkeypress = function(e) {
		var t = e.target.type;
		var id = e.target.id;
		var kc = e.keyCode;
				
		//Batch editor || quicksearch
		if ($(e.target).up(".batch-editor") || $(e.target).up(".quick-search")) {
			return true
		}
		else if ((kc != "keyCode" && kc != 13) || ( t == 'text' &&	kc != 13 ) || (t == 'textarea') || ( t == 'submit' &&	kc == 13))
		{
			return true
		}
		else
		{
			if (kc == 13 && EnterTrap != null) {
				return EnterTrap();
			} 
			else if (kc == 13 && id == 'searchField' && $('searchSubmit')) {
				eval($('searchSubmit').onclick());
				return false;
			}
			else {
				alert(strings.applicationErrorMessageBackspaceNotAllowed); // demo
				return false
			}
		}
	}
}


/**
 * Copyright (c)2005-2008 Matt Kruse (javascripttoolbox.com)
 * 
 * Dual licensed under the MIT and GPL licenses. 
 * This basically means you can use this code however you want for
 * free, but don't claim to have written it yourself!
 * Donations always accepted: http://www.JavascriptToolbox.com/donate/
 * 
 * Please do not link to the .js files on javascripttoolbox.com from
 * your site. Copy the files locally to your server instead.
 * 
 */
/* $VERSION: 1.1 */
var Selectbox = {};

Selectbox.hasOptions = function(obj) {
  return (obj!=null && typeof(obj.options)!="undefined" && obj.options!=null);
};

Selectbox.selectUnselectMatchingOptions = function(obj,regex,which,only) {
  if (window.RegExp) {
    if (!this.hasOptions(obj)) { return false; }
    var only = !(typeof(only)=="undefined" || only==null);
    var re = new RegExp(regex);
    for (var i=0; i<obj.options.length; i++) {
      if (re.test(obj.options[i].text)) {
        obj.options[i].selected = (which=="select");
      }
      else if (only) {
        obj.options[i].selected = (which=="unselect");
      }
    }
    return true;
  }
  return false;
};

Selectbox.selectOptions = function(obj,regex) {
  return this.selectUnselectMatchingOptions(obj,regex,"select",false);
};

Selectbox.selectOnlyOptions = function(obj,regex) {
  return this.selectUnselectMatchingOptions(obj,regex,"select",true);
};

Selectbox.unselectOptions = function(obj,regex) {
  return this.selectUnselectMatchingOptions(obj,regex,"unselect",false);
};

Selectbox.sort = function(obj) {
  var o = [];
  if (!this.hasOptions(obj)) { return false; }
  for (var i=0; i<obj.options.length; i++) {
    o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
  }
  if (o.length==0) { return true; }
  o = o.sort( 
    function(a,b) { 
      if ((a.text+"") < (b.text+"")) { return -1; }
      if ((a.text+"") > (b.text+"")) { return 1; }
      return 0;
    } 
  );

  for (var i=0; i<o.length; i++) {
    obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
  }
  return true;
};

Selectbox.selectAllOptions = function(obj) {
  if (!this.hasOptions(obj)) { return false; }
  for (var i=0; i<obj.options.length; i++) {
    obj.options[i].selected = true;
  }
  return true;
};

Selectbox.moveSelectedOptions = function(from,to) {
  if (!this.hasOptions(from)) { return false; }
  // Unselect matching options, if required
  if (arguments.length>3) {
    var regex = arguments[3];
    if (regex != "") {
      if (!this.unselectOptions(from,regex)) {
        return false;
      }
    }
  }
  // Move them over
  for (var i=0; i<from.options.length; i++) {
    var o = from.options[i];
    if (o.selected) {
      var index = (!this.hasOptions(to))?0:to.options.length;
      to.options[index] = new Option(o.text, o.value, false, false);
    }
  }
  // Delete them from original
  for (var i=(from.options.length-1); i>=0; i--) {
    var o = from.options[i];
    if (o.selected) {
      from.options[i] = null;
    }
  }
  if ((arguments.length<3) || (arguments[2])) {
    this.sort(from);
    this.sort(to);
  }
  from.selectedIndex = to.selectedIndex = -1;
  return true;
};

Selectbox.copySelectedOptions = function(from,to) {
  if (!this.hasOptions(from)) { return false; }
  var options = new Object();
  if (this.hasOptions(to)) {
    for (var i=0; i<to.options.length; i++) {
      options[to.options[i].value] = to.options[i].text;
    }
  }
  for (var i=0; i<from.options.length; i++) {
    var o = from.options[i];
    if (o.selected) {
      if (typeof(options[o.value])=="undefined" || options[o.value]==null || options[o.value]!=o.text) {
        var index = (!this.hasOptions(to))?0:to.options.length;
        to.options[index] = new Option( o.text, o.value, false, false);
      }
    }
  }
  if ((arguments.length<3) || (arguments[2]==true)) {
    this.sort(to);
  }
  from.selectedIndex = to.selectedIndex = -1;
  return true;
};

Selectbox.moveAllOptions = function(from,to) {
  this.selectAllOptions(from);
  if (arguments.length==2) {
    this.moveSelectedOptions(from,to);
  }
  else if (arguments.length==3) {
    this.moveSelectedOptions(from,to,arguments[2]);
    }
  else if (arguments.length==4) {
    this.moveSelectedOptions(from,to,arguments[2],arguments[3]);
  }
};

Selectbox.copyAllOptions = function(from,to) {
  this.selectAllOptions(from);
  if (arguments.length==2) {
    this.copySelectedOptions(from,to);
  }
  else if (arguments.length==3) {
    this.copySelectedOptions(from,to,arguments[2]);
  }
};

Selectbox.swapOptions = function(obj,i,j) {
  if (!this.hasOptions(obj)) { return false; }
  var o = obj.options;
  if (i<0 || i>=o.length || j<0 || j>=o.length) { return false; }
  var i_selected = o[i].selected;
  var j_selected = o[j].selected;
  var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
  var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
  o[i] = temp2;
  o[j] = temp;
  o[i].selected = j_selected;
  o[j].selected = i_selected;
  return true;
};

Selectbox.moveOptionUp = function(obj) {
  if (!this.hasOptions(obj)) { return false; }
  for (i=0; i<obj.options.length; i++) {
    if (obj.options[i].selected) {
      if (i>0 && !obj.options[i-1].selected) {
        this.swapOptions(obj,i,i-1);
        obj.options[i-1].selected = true;
      }
    }
  }
  return true;
};

Selectbox.moveOptionDown = function(obj) {
  if (!this.hasOptions(obj)) { return false; }
  for (i=obj.options.length-1; i>=0; i--) {
    if (obj.options[i].selected) {
      if (i != (obj.options.length-1) && ! obj.options[i+1].selected) {
        this.swapOptions(obj,i,i+1);
        obj.options[i+1].selected = true;
      }
    }
  }
  return true;
};

Selectbox.removeSelectedOptions = function(from) { 
  if (!this.hasOptions(from)) { return false; }
  if (from.type=="select-one" && from.selectedIndex>=0) {
    from.options[from.selectedIndex] = null;
  }
  else {
    for (var i=(from.options.length-1); i>=0; i--) { 
      var o=from.options[i]; 
      if (o.selected) { 
        from.options[i] = null; 
      } 
    }
  }
  from.selectedIndex = -1; 
};

Selectbox.removeAllOptions = function(from) { 
  if (!this.hasOptions(from)) { return false; }
  for (var i=(from.options.length-1); i>=0; i--) { 
    from.options[i] = null; 
  } 
  from.selectedIndex = -1; 
  return true;
};

Selectbox.addOption = function(obj,text,value,selected) {
  if (obj!=null && obj.options!=null) {
    obj.options[obj.options.length] = new Option(text, value, false, selected);
  }
};

Selectbox.selectAllOptionsElements = function(selectBoxId, action) 
{
	// zelf toegevoegde functie
	var SelectBox = $(selectBoxId);
	var count = 0;
	var status = (action=='SELECT')?true:false;
	if (SelectBox)
	{
		for (var i=0; i<SelectBox.options.length; i++) {
			SelectBox.options[i].selected = status;
			count++;
		}
		return count;
	}	else 
	{
		return false;
	}
}

var Cursor = Class.create();

Cursor.prototype = {
	
	initialize: function() {
	},
	
	reset: function() {
		//document.body.style.cursor = 'default';
		$(document.body).removeClassName("waiting");
	},
	
	wait: function(){
		//document.body.style.cursor = 'wait';
		$(document.body).addClassName("waiting");
	}
		
};

var cursor = new Cursor();

var resizer = new Resizer();
var application = new Application();
var selection = new Selection();
var treeEditor = new TreeEditor();

var activeItemEditor = null;
var activeSubItemEditor = null;
var activeEditorMode = "view";


