/*
 * Fix Prototype's Element.getOffsetParent for IE6/7
 * This bug only occurs when opening a dialog in IE6/7.
 * See: http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/XHTML/Q_24447434.html
 */
Element.addMethods({
	 getOffsetParent: function(element) {
		if (element.offsetParent) return $(element.offsetParent);
		if ((element == document.body) || (element == document.documentElement)) return $(element);

		while ((element = element.parentNode) && element != document.body)
			if (Element.getStyle(element, "position") != "static")
				return $(element);

		return $(document.body);
  }
});

var log = window.log || function() {
	try {
		console.log.apply(console, arguments);
	} catch (e) { }
}

// JScript File
function dynamicDialogLayout(){
	$("rnaDialog_row2").style.height = 500;
	$("rnaDialog").style.height = 500;
	var dialogContentHeight = $("rnaDialog_row2").style.height;
	//alert('huidige hoogte '+$("rnaDialog").style.height+' en benodigde hoogte = '+dialogContentHeight);
	//if ($("rnaDialog")) { $("rnaDialog").style.height = "1000px"; }
}

var myDialog;

var pleaseWaitMessage = '<div id="rnaDialog_PleaseWaitMessage"><img src="/lib/window/1.3/themes/rna/busy.gif" alt="please wait"/><br />waiting for server<br/>please wait...</div>';

var DialogList = new Array();
DialogList["newItem"] = { window: null, allowMultiple: false, allowOthers: false };
DialogList["newAnnexItem"] = { window: null, allowMultiple: false, allowOthers: false };
DialogList["newStructure"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["userInfoWin"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["viewSettings"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["structureSettings"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["contentValidation"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["userManagement"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["groupManagement"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["authorisationManagement"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["linkManagerV2"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["linkNode"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["LinkNodeTo"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["linkNodeIn"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["moveNode"] = { window: null, allowMultiple: false, allowOthers: false };
DialogList["selectNodeForNewItem"] = { window: null, allowMultiple: false, allowOthers: false};
DialogList["selectNodeForChiba"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["selectTargetNodeForImport"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["confirmDeleteItem"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["facetValueSelection"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["selectPropertyValue"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["import"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["importOai"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["importDetermination"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["importExcel"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["importSkos"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["newStructureFolder"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["renameStructureFolder"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["statusManagement"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["systemManagement"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["MappingDialog"] = {window: null, allowMultiple: false, allowOthers: false};
DialogList["aboutDialog"] = { window: null, allowMultiple: false, allowOthers: false };
DialogList["passwordDialog"] = { window: null, allowMultiple: false, allowOthers: false };
DialogList["valueMapperSaveAs"] = { window: null, allowMultiple: false, allowOthers: false };
DialogList["metadataSuggest"] = { window: null, allowMultiple: false, allowOthers: false };
DialogList["valueMappingManager"] = { window: null, allowMultiple: false, allowOthers: false };
DialogList["valueMappingSaveAsDialog"] = { window: null, allowMultiple: false, allowOthers: false };

// detemines whether we can create a new dialog with id dialogId
function CanCreateDialog(dialogId) {
	var windows = Windows.windows;
		
	for (var i = 0, len = windows.length; i < len; i++) {
		if (DialogList[dialogId].window == windows[i]) {
			return false;
		}
	}
	return true;
}

// closes the dialog with id dialogId and fixes focus
function CloseDialog(dialogId) {
	if (typeof dialogId == "string") {
		DialogList[dialogId].window.close();
		window.focus();
		DialogList[dialogId].window = null;
	}
	else {
		dialogId.close();
		window.focus();
	}
}


// New item dialog
// **************************************************************************************************
function CreateNewItemDialog(sourceUri)
{
	if (CanCreateDialog("newItem")) 
	{
		cursor.wait();
		DialogList["newItem"].window = new Window('rnaDialog',{id: "rnaDialog", className: "clean", width: 500, height: 287, maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true,recenterAuto: true, title: strings.dialogTitleCreateNewItem});
		var myAjax = new Ajax.Updater( {success: 'rnaDialog_content' }, application.dialogWithoutTreeUrl + '?dialogType=newItem' + '&uri=' + sourceUri, { method: 'post', asynchronous: false, evalScripts: true, onComplete: function(t) { cursor.reset();}  });
		DialogList["newItem"].window.setCloseCallback(checkForClose_CreateNewItemWin);
		DialogList["newItem"].window._center();
		DialogList["newItem"].window.show(true);
		
		EnterTrap = function(e) {return false;};
	}
}

function checkForClose_CreateNewItemWin()
{
	EnterTrap = null;
	return true;
}

var NewItemDialogCntrl = Class.create();
NewItemDialogCntrl.prototype =
{
	selectedItemType: undefined,
	selectedNodePlacement: undefined,
	creatingNewItem: false,
	initialize: function()
	{
		var thisClass = this;

		var radioBtns = $A($('d1').select('input:radio')).each(function(obj)
		{
			var thisValue = obj.value;
			switch (obj.name)
			{
				case "contentItemTypeSelection":
					$(obj).observe("change", thisClass.onChangeItemType.bind(thisClass, obj));
					$(obj).observe("click", thisClass.onChangeItemType.bind(thisClass, obj));
					obj.next(0).observe("click", thisClass.onChangeItemType.bind(thisClass, obj, true));
					break;
				case "nodePlacement":
					$(obj).observe("change", thisClass.onChangeNodePlacement.bind(thisClass, obj));
					$(obj).observe("click", thisClass.onChangeNodePlacement.bind(thisClass, obj));
					obj.next(0).observe("click", thisClass.onChangeNodePlacement.bind(thisClass, obj, true));
					break;
			}
		});

		if ($('selectItemBtn'))
		{
			$('selectItemBtn').observe("click", thisClass.onSelectItemType.bind(thisClass));
		}

		if ($('subItemTypeField'))
		{
			$('subItemTypeField').observe("click", thisClass.onSelectItemType.bind(thisClass));
		}

		if ($('dialogSubmitButton'))
		{
			$('dialogSubmitButton').observe("click", thisClass.onSubmit.bind(thisClass));
		}

		if ($('dialogCancelButton'))
		{
			$('dialogCancelButton').observe("click", thisClass.onCancel.bind(thisClass));
		}

		this.onChangeItemType($('preselectedItemType'), true);
		this.onChangeNodePlacement($('createAsChild'), true);
	},

	onChangeItemType: function(obj, onLblClick)
	{
		if ($(obj) && $(obj).tagName == 'INPUT' && !(obj.disabled))
		{
			$(obj).checked = (onLblClick) ? true : $(obj).checked;

			if (obj.hasClassName('itemType'))
			{
				this.setFormElement($('subItemType'), true);
			} else {
				this.setFormElement($('subItemType'), false);
			}
		}
	},

	onChangeNodePlacement: function(obj, onLblClick)
	{
		if ($(obj) && $(obj).tagName == 'INPUT' && !(obj.disabled))
		{
			$(obj).checked = (onLblClick) ? true : $(obj).checked;
		}
	},

	onCancel: function()
	{
		CloseDialog("newItem");
	},

	onSubmit: function()
	{
		if (this.creatingNewItem == false)
		{
			this.creatingNewItem = true;

			if (Form.getInputs('d1', 'radio', 'contentItemTypeSelection').find(function(radio) { return radio.checked; }) == undefined)
			{
				$('errorField').replace('<p id="errorField"><strong>' + strings.errorMessage + '</strong> ' + strings.errorMessageNoItemTypeSelected + '</p>');
				this.creatingNewItem = false;
			}
			else if (Form.getInputs('d1', 'radio', 'nodePlacement').find(function(radio) { return radio.checked; }) == undefined)
			{
				$('errorField').replace('<p id="errorField"><strong>' + strings.errorMessage + '</strong> ' + strings.errorMessageNoItemSpecified + '</p>');
				this.creatingNewItem = false;
			}
			else if ($('titleField').getValue() == '')
			{
				$('errorField').replace('<p id="errorField"><strong>' + strings.errorMessage + '</strong> ' + strings.errorMessageEmptyTitleField + '</p>');
				this.creatingNewItem = false;
			}
			else if (!($('subItemTypeField').disabled == true) && ($('subItemTypeField').getValue() == '' || $('subItemTypeUriField').getValue() == ''))
			{
				$('errorField').replace('<p id="errorField"><strong>' + strings.errorMessage + '</strong> ' + strings.errorMessageNoItemSpecified + '</p>');
				this.creatingNewItem = false;
			}
			else
			{
				$('errorField').replace('<p id="errorField">&#160;</p>');
				this.createNewItem(Form.getInputs('d1', 'radio', 'nodePlacement').find(function(radio) { return radio.checked; }).getValue());
			}
		}
	},

	createNewItem: function(placement)
	{
		var title = $('titleField').getValue();
		var contentItemTypeSelection = Form.getInputs('d1', 'radio', 'contentItemTypeSelection').find(function(radio) { return radio.checked; }).getValue();
		var itemTypeUri = $('subItemTypeUriField').getValue();
		if (placement == '1')
		{
			applicationNewContentItem(title, contentItemTypeSelection, 'false', itemTypeUri);
			CloseDialog("newItem");
		}
		else if (placement == '2')
		{
			applicationNewContentItem(title, contentItemTypeSelection, 'true', itemTypeUri);
			CloseDialog("newItem");
		}
		else
		{
			$('errorField').replace('<p id="errorField"><strong>' + strings.errorMessage + '</strong> could not create new item' + strings.errorMessageNoItemSpecified + '</p>');
			this.creatingNewItem = false;
		}
	},

	onSelectItemType: function()
	{
		if (!($('subItemType').hasClassName('disabled')))
		{
			CreateSelectNodeForNewItemDialog();
		}
	},

	setFormElement: function(obj, status)
	{
		if (obj.hasClassName("radioElement") || obj.hasClassName("inputElement"))
		{
			if (status) { obj.removeClassName('disabled'); }
			else { obj.addClassName('disabled'); }
		}

		$A(obj.select('input')).each(function(input)
		{
			input.disabled = (status) ? false : true;
			input.checked = (input.checked) ? false : input.checked;
		})
	}
}


// New Annex Item dialog
// **************************************************************************************************

function CreateNewAnnexItemDialog(uri)
{
	if (CanCreateDialog("newAnnexItem"))
	{
		cursor.wait();
		DialogList["newAnnexItem"].window = new Window('rnaDialog', { id: "rnaDialog", className: "clean", width: 500, height: 160, maximizable: false, minimizable: false, hideEffect: Element.hide, showEffect: Element.show, resizable: false, destroyOnClose: true, recenterAuto: true, title: strings.dialogTitleCreateAnnexNewItem });
		var params = "dialogType=newAnnexItem&uri="+uri;
		var myAjax = new Ajax.Updater({ success: 'rnaDialog_content' }, application.dialogWithoutTreeUrl + "?" +params, { method: 'post', asynchronous: false, evalScripts: true, onComplete: function(t) { cursor.reset(); } });
		DialogList["newAnnexItem"].window.setCloseCallback(checkForClose_CreateNewAnnexItemWin);
		DialogList["newAnnexItem"].window._center();
		DialogList["newAnnexItem"].window.show(true);
		EnterTrap = function(e) { return false; };

		var cntrl = new NewAnnexItemDialogCntrl();
	}
}

function checkForClose_CreateNewAnnexItemWin()
{
	EnterTrap = null;
	return true;
}

var NewAnnexItemDialogCntrl = Class.create();
NewAnnexItemDialogCntrl.prototype =
{
	locked: false,
	initialize: function()
	{
		var me = this;
		$('predicateSelector').observe('change', me.onSelectPredicate.bind(me));
		$('itemTypeSelector').observe('change', me.onSelectitemType.bind(me));
		$('dialogSubmitButton').observe('click', me.onSubmit.bind(me));
		$('dialogCancelButton').observe('click', me.close.bind(me));
		this.onSelectPredicate();
	},

	onSelectPredicate: function()
	{
		switch ($('predicateSelector').getValue())
		{
			case '0':
				this.enablefield('formSection_itemType', false);
				break;
			default:
				new Ajax.Updater('formSection_itemType', '/pages/nodeDialog.aspx', {
					parameters: { uri: this.uri, predicateUri: $('predicateSelector').getValue(), dialogType: 'newAnnexItem' }
				});
				this.enablefield('formSection_itemType', true);
		}
		this.setErrorMessage('', '', false);
	},

	onSelectitemType: function()
	{
		this.setErrorMessage('', '', false);
	},

	enablefield: function(id, bln)
	{
		if ($(id))
		{
			if (bln) { $(id).removeClassName('disabled'); }
			else { $(id).addClassName('disabled'); }

			var a = $A($(id).select('select')).each(function(obj)
			{
				obj.disabled = (bln) ? false : true;
				obj.setValue('0');
			});
		}
	},

	onCancel: function() {
		CloseDialog("newAnnexItem");
	},

	onSubmit: function()
	{
		if (this.locked)
		{
			// already saving
		} else
		{
			this.locked = true;

			if ($('predicateSelector').getValue() == '0')
			{
				this.setErrorMessage(strings.applicationErrorMessageSelectPredicate, 'predicate', true);
				this.locked = false;
			} else if ($("itemTypeSelector").getValue() == '0')
			{
				this.setErrorMessage(strings.applicationErrorMessageSelectItemType, 'itemType', true);
				this.locked = false;
			} else if ($("itemTypeSelector").disabled == true)
			{
				this.setErrorMessage(strings.applicationErrorMessageSelectItemType, 'predicate', true);
				this.locked = false;
			} else
			{
				this.setErrorMessage('', false);
				var predicateUri = $('predicateSelector').getValue();
				var itemTypeUri = $('itemTypeSelector').getValue();
				applicationNewAnnexContentItem(predicateUri, itemTypeUri);
				this.close();
			}
		}
	},

	close: function()
	{
		CloseDialog("newAnnexItem");
	},

	setErrorMessage: function(string, placement, bln)
	{
		$('predicateErrorField').hide();
		$('itemTypeErrorField').hide();

		var obj = (placement == 'predicate') ? $('predicateErrorField') : $('itemTypeErrorField');

		if (bln)
		{
			obj.innerHTML = string;
			obj.show();
		} else
		{
			obj.innerHTML = '&#160;';
			obj.hide();
		}
	}
}


// New structure dialog
// **************************************************************************************************

function CreateNewStructureDialog()
{
	if (CanCreateDialog("newStructure"))
	{
		cursor.wait();
		DialogList["newStructure"].window = new Window('rnaDialog_newstructure',{id: "rnaDialog_newstructure", className: "clean", width: 500, height: 542, maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, recenterAuto: true, title: strings.dialogTitleCreateNewStructure});
		var myAjax = new Ajax.Updater( {success: 'rnaDialog_newstructure_content' }, application.dialogWithoutTreeUrl + '?dialogType=newStructure', { method: 'post', asynchronous: false, evalScripts: true, onComplete: function(t) { cursor.reset();} });
		DialogList["newStructure"].window.setCloseCallback(checkForClose_CreateNewStructureWin);
		DialogList["newStructure"].window._center();
		DialogList["newStructure"].window.show();
		EnterTrap = function(e)	{return false;};
		var nsDialogCntrl = new newStructureDialogCntrl();
	}
}

function checkForClose_CreateNewStructureWin()
{
	EnterTrap = null;
	return true; 
}

var newStructureDialogCntrl = Class.create();
newStructureDialogCntrl.prototype =
{
	itemTypes: null,

	initialize: function()
	{
		if ($('formSection6'))
		{
			this.itemTypes = $A($('formSection6').select("input[type=radio]"));
		}
		this.itemTypes[0].checked = true;
		this.itemTypes[1].checked = true;
		var thisClass = this;
		this.itemTypes.each(function(obj)
		{
			if ($(obj.value + "_lbl"))
			{
				$(obj.value + "_lbl").observe("click", thisClass.onClickLbl.bind(thisClass, obj.value));
			}
		});
	},

	onClickLbl: function(value)
	{
		$(value + "_radioBtn").checked = true;
	}
}


function onSubmitStructure ()
{

	var numberOfSelectedLanguages = Selectbox.selectAllOptionsElements('selectedLanguages','SELECT');
	var numberOfSelectedTypes = Selectbox.selectAllOptionsElements('selectedContentItemTypes','SELECT');
	var errorCnt = 0;
	
//	if (numberOfSelectedTypes < 1)
//	{
//		$('errorField').replace('<p id="errorField"><strong>'+strings.errorMessage+'</strong>&#160;'+strings.applicationErrorMessageAtLeastOnEntry+'</div>');
//		$('selectedContentItemTypes').setStyle({borderColor:'red'});
//		errorCnt++;
//	} else
//	{
//		$('selectedContentItemTypes').setStyle({borderColor:'black'});
//	}
	
	if (numberOfSelectedLanguages < 1)
	{
		$('errorField').replace('<p id="errorField"><strong>'+strings.errorMessage+'</strong>&#160;'+strings.applicationErrorMessageAtLeastOnEntry+'</div>');
		$('selectedLanguages').setStyle({borderColor:'red'});
		errorCnt++;
	} else
	{
		$('selectedLanguages').setStyle({borderColor:'black'});
	}

	if ($('structureTitle').getValue().split(' ').join('') == "" )
  {
    $('errorField').replace('<p id="errorField"><strong>'+strings.errorMessage+'</strong>&#160;'+strings.errorMessageEmptyTitleField+'</div>');
		$('structureTitle').setStyle({borderColor:'red'});
		errorCnt++;
  } else 
  {
		$('structureTitle').setStyle({borderColor:'black'});
  }
	
	if (errorCnt == 0 && $('d3'))
	{
		// create a string of selected languages
		var selectedLanguagesString = '';
		var selectedLanguagesElement = $('selectedLanguages');
		if (selectedLanguagesElement)
		{
			var Items = selectedLanguagesElement.childElements();
			var languageList = $A(Items);
			languageList.each(function(item) 
			{
				selectedLanguagesString += ','+item.value;
			});
		}
    selectedLanguagesString = selectedLanguagesString.substr(1);
    var selectedContentItemTypes = $$('input:checked[type="radio"][name="selectedContentItemTypes"]').pluck('value');
    selectedContentItemTypes += ',' + $('ContentItemCheckBoxSimpleNode').getValue();
		
    var result = applicationNewReferenceStructure($('structureTitle').getValue(), selectedLanguagesString, selectedContentItemTypes);
		CloseDialog("newStructure");
	
	} else
	{
		numberOfSelectedTypes = Selectbox.selectAllOptionsElements('selectedContentItemTypes','DESELECT');
		numberOfSelectedLanguages = Selectbox.selectAllOptionsElements('selectedLanguages','DESELECT');
	}
	
}	

function onCancelStructure ()
{
	CloseDialog("newStructure");
}





// userInfo dialog
// **************************************************************************************************

function CreateNewUserInfoDialog() {
	if (CanCreateDialog("userInfoWin")){
		cursor.wait();
		DialogList["userInfoWin"].window = new Window('rnaDialog_userinfo',{id: "rnaDialog_userinfo", className: "clean", width: 380, height: 95, maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, recenterAuto: true, title: strings.dialogTitleUserInfo});
		var myAjax = new Ajax.Updater( {success: 'rnaDialog_userinfo_content' }, application.dialogWithoutTreeUrl + '?dialogType=userInfo', { method: 'post', asynchronous: false, evalScripts: true, onComplete: function(t) { cursor.reset();} });
		DialogList["userInfoWin"].window.setCloseCallback(checkForClose_CreateNewUserInfoWin);
		DialogList["userInfoWin"].window._center();
		DialogList["userInfoWin"].window.show();
		EnterTrap = function(e) { return false; };
	}
}

function checkForClose_CreateNewUserInfoWin(){
	EnterTrap = null;
	return true; 
 }

function onCloseUserInfo (){
	CloseDialog("userInfoWin");
}


// view settings dialog
// **************************************************************************************************
function CreateViewSettingsDialog() {
	if (CanCreateDialog("viewSettings")) {
		cursor.wait();
		DialogList["viewSettings"].window = new Window('rnaDialog02',{id: "rnaDialog02", className: "clean", width: 500, height: 470, maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, recenterAuto: true, title: strings.dialogTitleViewSettings});
		var myAjax = new Ajax.Updater( {success: 'rnaDialog02_content' }, application.dialogWithoutTreeUrl + '?dialogType=viewSettings', { method: 'post', asynchronous: false, evalScripts: true, onComplete: function(t) { cursor.reset();} });
		DialogList["viewSettings"].window.setCloseCallback(checkForClose_viewSettingsWin);
		DialogList["viewSettings"].window._center();
		DialogList["viewSettings"].window.show(true);
		EnterTrap = function(e) { return false;};
	}
}

function checkForClose_viewSettingsWin(){
	EnterTrap = null;
	return true; 
 }

function onSaveViewSettings(){
	var numberOfSelectedLanguages = Selectbox.selectAllOptionsElements('selectedLanguages','SELECT');
	var errorMessage = '';
	
	if (numberOfSelectedLanguages >= 0 && $("d2"))
	{
		var postData = Form.serialize($("d2"));
		var myAjax = new Ajax.Updater( {success: 'extraField' }, application.dialogActionUrl + '?action=saveViewSettings', { method: 'post', parameters: postData, asynchronous: false, evalScripts: true });
		
		if (myAjax)
		{
			CloseDialog("viewSettings");
		} else
		{
			var numberOfSelectedLanguages = Selectbox.selectAllOptionsElements('selectedLanguages','DESELECT');
			alert(strings.editorErrorMessageDocumentNotSaved);
		}
	} 
}

function onCancelViewSettings (){
	CloseDialog("viewSettings");
}


// structure settings dialog
// **************************************************************************************************

function CreateStructureSettingsDialog(referenceStructureId) {
	if (CanCreateDialog("structureSettings")) {
		cursor.wait();
		DialogList["structureSettings"].window = new Window('rnaDialog_structuresettings',{id: "rnaDialog_structuresettings", className: "clean", width: 500, height: 440, maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, recenterAuto: true,title: strings.dialogTitleStructureSettings});
		var myAjax = new Ajax.Updater( {success: 'rnaDialog_structuresettings_content'}, application.dialogWithoutTreeUrl + '?dialogType=structureSettings&referenceStructureId=' + referenceStructureId, { method: 'post', asynchronous: false, evalScripts: true, onComplete: function(t) { cursor.reset();} });
		DialogList["structureSettings"].window.setCloseCallback(checkForClose_StructureSettingsWin);
		DialogList["structureSettings"].window._center();
		DialogList["structureSettings"].window.show(true);
		EnterTrap = function(e) {
			return false;
		};
	}
}


function onSaveStructureSettings()
{
	// in order to save, at least one language should be selected
	// select all option elements in 'selectedLanguages'
	var numberOfSelectedLanguages = Selectbox.selectAllOptionsElements('selectedLanguages','SELECT');
	var errorCnt = 0;

	if (numberOfSelectedLanguages < 1)
	{
		$('errorField').replace('<p id="errorField"><strong>'+strings.errorMessage+'</strong>&#160;'+strings.applicationErrorMessageAtLeastOnEntry+'</div>');
		$('selectedLanguages').setStyle({borderColor:'red'});
		errorCnt++;
	} else
	{
		$('selectedLanguages').setStyle({borderColor:'black'});
	}
	
	if (errorCnt == 0 && $("d2"))
	{
		var postData = Form.serialize($("d2"));
		var myAjax = new Ajax.Updater( {success: 'extraField' }, application.dialogActionUrl + '?action=saveStructureSettings', { method: 'post', parameters: postData, asynchronous: false, evalScripts: true });

		if (myAjax)	CloseDialog("structureSettings");
		else	alert(strings.editorErrorMessageDocumentNotSaved);
	
	} else
	{
		numberOfSelectedTypes = Selectbox.selectAllOptionsElements('selectedContentItemTypes','DESELECT');
		numberOfSelectedLanguages = Selectbox.selectAllOptionsElements('selectedLanguages','DESELECT');
	}
}

function checkForClose_StructureSettingsWin(){
	EnterTrap = null;
	return true; 
}
 
function onCancelStructureSettings () {
  CloseDialog("structureSettings");
}


// Validation Report Dialog
// **************************************************************************************************
function CreateValidationDialog(content) {
	if (CanCreateDialog("contentValidation")) {
		DialogList["contentValidation"].window = new Window('rnaDialog',{id: "rnaDialog_validationreport", className: "clean", width: 570, height: 271, maximizable: false, minimizable: false, hideEffect:Effect.SwitchOff, showEffect:Effect.BlindDown, resizable: true, destroyOnClose: true, recenterAuto: true, title: strings.dialogTitleValidationErrors});
		DialogList["contentValidation"].window.setHTMLContent(content);
		DialogList["contentValidation"].window._center();
		DialogList["contentValidation"].window.show();
	}
}

function HideValidationDialog() {
	DialogList["contentValidation"].window.hide();
}

// User Management Dialog
// **************************************************************************************************
function CreateUserManagementDialog()
{
	if (CanCreateDialog("userManagement"))
	{
		DialogList["userManagement"].window = new Window('rnaDialog_usermanagement',{id: "rnaDialog_usermanagement", className: "clean", width: 505, height: 612, maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, recenterAuto: true,title: strings.dialogTitleUserManagement});
		$('rnaDialog_usermanagement_content').innerHTML = "<iframe id='linkManagement_iframe' src='" + application.userManagementUrl + "' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["userManagement"].window.setCloseCallback(checkForClose_UserManagement);
		DialogList["userManagement"].window._center();
		DialogList["userManagement"].window.show(true);
		EnterTrap = function(e)
		{

//			if (e == 'closeDialog')
//			{
//				onCancelUserManagement();
//			}		
			return false;
		};
	}
}

function checkForClose_UserManagement(){
	EnterTrap = null;
	return true; 
}
 
function onCancelUserManagement(){
	CloseDialog("userManagement");
}

// Status Management Dialog
// **************************************************************************************************
function CreateStatusManagementDialog()
{
	if (CanCreateDialog("statusManagement"))
	{
		DialogList["statusManagement"].window = new Window('rnaDialog_statusmanagement',{id: "rnaDialog_statusmanagement", className: "clean", width: 505, height: 270, maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, recenterAuto: true,title: strings.dialogTitleStatusManagement});
		$('rnaDialog_statusmanagement_content').innerHTML = "<iframe id='linkManagement_iframe' src='" + application.statusManagementUrl + "' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["statusManagement"].window.setCloseCallback(checkForClose_StatusManagement);
		DialogList["statusManagement"].window._center();
		DialogList["statusManagement"].window.show(true);
		EnterTrap = function(e)
		{	
			return false;
		};
	}
}

function checkForClose_StatusManagement(){
	EnterTrap = null;
	return true; 
}
 
function onCancelStatusManagement(){
	CloseDialog("statusManagement");
}


// Group Management Dialog
// **************************************************************************************************
function CreateGroupManagementDialog() {
	if (CanCreateDialog("groupManagement")) {
		DialogList["groupManagement"].window = new Window('rnaDialog_groupmanagement',{id: "rnaDialog_groupmanagement", className: "clean", width: 505, height: 540, recenterAuto: true,  maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, title: strings.dialogTitleGroupManagement});
		$('rnaDialog_groupmanagement_content').innerHTML = "<iframe id='linkManagement_iframe' src='" + application.groupManagementUrl + "' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["groupManagement"].window.setCloseCallback(checkForClose_GroupManagement);
		DialogList["groupManagement"].window._center();
		DialogList["groupManagement"].window.show(true);
		EnterTrap = function(e)
		{

//			if (e == 'closeDialog')
//			{
//				onCancelGroupManagement();
//			}			
			return false;
		};
	}
}

function checkForClose_GroupManagement(){
	EnterTrap = null;
	return true; 
}

function onCancelGroupManagement(){
	CloseDialog("groupManagement");
}


// Authorization Management
// **************************************************************************************************
function CreateAuthorizationManagementDialog()
{
	if (CanCreateDialog("authorisationManagement"))
	{
		DialogList["authorisationManagement"].window = new Window('rnaDialog_authorization',{id: "rnaDialog_authorization", className: "clean", width: 830, height: 630, recenterAuto: true,  maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, title: strings.dialogTitleAuthorisationManagement});
		$('rnaDialog_authorization_content').innerHTML = "<iframe id='linkManagement_iframe' src='" + application.authorizationManagementUrl + "' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["authorisationManagement"].window.setCloseCallback(checkForClose_AuthorizationManagement);
		DialogList["authorisationManagement"].window._center();
		DialogList["authorisationManagement"].window.show(true);
		EnterTrap = function(e){ return false; };
	}
}

function checkForClose_AuthorizationManagement()
{
	EnterTrap = null;
	return true; 
}

function updateHeightWindowAuthorizaiotnManagement()
{
	DialogList["authorisationManagement"].window.updateHeight();
}
 
function onCloseAuthorizationManagement()
{
	CloseDialog("authorisationManagement");
}




// Link Manager Dialog V2 NEW
// **************************************************************************************************
function CreateLinkManagerv2Dialog() {
	if (CanCreateDialog("linkManagerV2")) {
		DialogList["linkManagerV2"].window = new Window('rnaDialog_linkManagerV2',{id: "rnaDialog_linkManagerV2", className: "clean", width: 510, height: 624, recenterAuto: true,  maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, title: 'link manager'});
		$('rnaDialog_linkManagerV2_content').innerHTML = "<iframe id='linkManagement_iframe' src='"+application.dialogWithTreeUrl+"?dialogType=linkManager"+selection.toRequest()+"' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["linkManagerV2"].window.setCloseCallback(checkForClose_LinkManager);
		DialogList["linkManagerV2"].window._center();
		DialogList["linkManagerV2"].window.show(true);
		EnterTrap = function(e)
		{

			return false;
		};
	}
}

function refreshLinkManagerWindow()
{
	$('rnaDialog_linkManagerV2_content').innerHTML = "<iframe id='linkManagement_iframe' src='"+application.dialogWithTreeUrl+"?dialogType=linkManager"+selection.toRequest()+"' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
}

function deleteLink(nodeId, type)
{
	applicationDeleteLinkNode(nodeId, type);
	dialogType = type;
	refreshLinkManagerWindow();
	return false;
}

function checkForClose_LinkManager()
{
	EnterTrap = null;
	return true;
}

function onCloseLinkManagerV2()
{
	parent.CloseDialog("linkManagerV2");
}




// Move Node IN Other Structure dialog
// **************************************************************************************************

function CreateLinkNodeInDialog()
{
	if (CanCreateDialog("linkNodeIn"))
	{
		var windowTitle = strings.dialogTitleLinkIn;
		var linkNodeURL = application.dialogWithTreeUrl+'?dialogType=linknode_in';
		
		DialogList["linkNodeIn"].window = new Window('rnaDialog_linknode',{id: "rnaDialog_linknode", className: "clean", width: 520, height: 571, recenterAuto: true,  maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, title: windowTitle});
		$('rnaDialog_linknode_content').innerHTML = "<iframe id='linkNode_iframe' src='"+linkNodeURL+"' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["linkNodeIn"].window.setCloseCallback(checkForClose_linkNodeIn);
		DialogList["linkNodeIn"].window._center();
		DialogList["linkNodeIn"].window.show(true);	
		EnterTrap = function(e)
		{
		
			return false;
		};
	}
}

function LinkSelectedNodeIn(nodeId)
{
	applicationNewLinkNode(nodeId, 'in');
	CloseDialog("linkNodeIn");
	// this selectbox should only be used by the linkmanager dialog. After selection, the linkmanager is updated:
	$('rnaDialog_linkManagerV2_content').innerHTML = "<iframe id='linkManagement_iframe' src='"+application.dialogWithTreeUrl+"?dialogType=linkManager"+selection.toRequest()+"' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
}

function checkForClose_linkNodeIn()
{
	EnterTrap = null;
	return true;
}

function onCloseLinkNodeInDialog()
{
	parent.CloseDialog("linkNodeIn");
}




// Move Node TO Other Structure dialog
// **************************************************************************************************

function CreateLinkNodeToDialog()
{
	if (CanCreateDialog("LinkNodeTo")) {
		var windowTitle = strings.dialogTitleLinkTo;
		var linkNodeURL = application.dialogWithTreeUrl+'?dialogType=linknode_to';
				
		DialogList["linkNodeTo"].window = new Window('rnaDialog_linknode',{id: "rnaDialog_linknode", className: "clean", width: 520, height: 571, recenterAuto: true,  maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, title: windowTitle});
		$('rnaDialog_linknode_content').innerHTML = "<iframe id='linkNode_iframe' src='"+linkNodeURL+"' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["linkNodeTo"].window.setCloseCallback(checkForClose_linkNodeTo);
		DialogList["linkNodeTo"].window._center();
		DialogList["linkNodeTo"].window.show(true);
		EnterTrap = function(e)
		{

			return false;
		};
	}
}

function checkForClose_linkNodeTo()
{
	EnterTrap = null;
	return true;
}

function LinkSelectedNodeTo(nodeId)
{
	applicationNewLinkNode(nodeId, 'to');
	CloseDialog("linkNodeTo");
	// this selectbox should only be used by the linkmanager dialog. After selection, the linkmanager is updated:
	$('rnaDialog_linkManagerV2_content').innerHTML = "<iframe id='linkManagement_iframe' src='"+application.dialogWithTreeUrl+"?dialogType=linkManager"+selection.toRequest()+"' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
}

function onCloseLinkNodeToDialog()
{
	parent.CloseDialog("linkNodeTo");
}


// Move Node to Other Structure dialog
// **************************************************************************************************
function CreateMoveNodeDialog() 
{
	if (CanCreateDialog("moveNode")) 
	{
		DialogList["moveNode"].window = new Window('rnaDialog_movenode',{id: "rnaDialog_movenode", className: "clean", width: 520, height: 571, recenterAuto: true,  maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, title: strings.dialogTitleMoveNode});
		$('rnaDialog_movenode_content').innerHTML = "<iframe id='linkManagement_iframe' src='"+application.dialogWithTreeUrl+"?dialogType=movenode' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["moveNode"].window._center();
		DialogList["moveNode"].window.setCloseCallback(checkForClose_MoveNodeWin);
		DialogList["moveNode"].window.show(true);
		EnterTrap = function(e)
		{

			return false;
		};
	}
}

function MoveNodeToOtherStructure(uri, type, selectedNodeId)
{
	applicationMoveNodeToOtherStructure(uri, type, selectedNodeId);
	CloseDialog("moveNode");
}

function checkForClose_MoveNodeWin()
{
	EnterTrap = null;
	return true; 
}

function updateHeightWindowMoveNodeWin()
{
	DialogList["moveNode"].window.updateHeight();
}

function onCloseLinkNodeToDialog()
{
	parent.CloseDialog("moveNode");
}


// Select Node For New Item Dialog
// **************************************************************************************************
function CreateSelectNodeForNewItemDialog()
{
	if (CanCreateDialog("selectNodeForNewItem"))
	{
		DialogList["selectNodeForNewItem"].window = new Window('rnaDialog_selectnode', { id: "rnaDialog_selectnode", className: "clean", width: 520, height: 581, recenterAuto: true, maximizable: false, minimizable: false, hideEffect: Element.hide, showEffect: Element.show, resizable: false, destroyOnClose: true, title: strings.dialogTitleSelectItemType });
		$('rnaDialog_selectnode_content').innerHTML = "<iframe id='linkManagement_iframe' src='" + application.dialogWithTreeUrl + "?dialogType=selectNodeForNewItemDialog&allowedRdfTypes=http%3A%2F%2Fwww%2Ernaproject%2Eorg%2Fdata%2Frnax%2FrnaxItemType' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["selectNodeForNewItem"].window._center();
		DialogList["selectNodeForNewItem"].window.setCloseCallback(checkForClose_SelectNodeForNewItemDialog);
		DialogList["selectNodeForNewItem"].window.show(true);
		EnterTrap = function(e) { return false; };
	}
}

function setContentItemType (uri, label)
{ 
	$('subItemTypeField').value = "";
}

function closeNewItemNodeSelectDialog()
{
	CloseDialog("selectNodeForNewItem");
}

function checkForClose_SelectNodeForNewItemDialog()
{
	EnterTrap = null;
	return true; 
}


// Select Node For Chiba Dialog
// **************************************************************************************************
function CreateSelectNodeForChibaDialog(allowedRdfTypes)
{
	if (CanCreateDialog("selectNodeForChiba")) 
	{
		DialogList["selectNodeForChiba"].window = new Window('rnaDialog_selectnode',{id: "rnaDialog_selectnode", className: "clean", width: 520, height: 571, recenterAuto: true,  maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, title: strings.dialogTitleSelectNode});
		$('rnaDialog_selectnode_content').innerHTML = "<iframe id='linkManagement_iframe' src='"+application.dialogWithTreeUrl+"?dialogType=selectnodeforchiba&allowedRdfTypes="+ allowedRdfTypes +"' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["selectNodeForChiba"].window._center();
		DialogList["selectNodeForChiba"].window.setCloseCallback(checkForClose_SelectNodeForChibaWin);
		DialogList["selectNodeForChiba"].window.show(true);
		EnterTrap = function(e){return false;};
	}
}

function CreateSelectNodeForChibaDialogStatement(allowedRdfTypes, uri, predicateUri, dialogCntrl) {
	if (CanCreateDialog("selectNodeForChiba")) {

		// get the literal filled in to use it for instant value mapping / search
		var ChibaFrame = getFrameNumber('chibaxform');
		var literal = ChibaFrame.dialogArgs.objectLabel.value;
		
		DialogList["selectNodeForChiba"].window = new Window('rnaDialog_selectnode', { id: "rnaDialog_selectnode", className: "clean", width: 520, height: 571, recenterAuto: true, maximizable: false, minimizable: false, hideEffect: Element.hide, showEffect: Element.show, resizable: false, destroyOnClose: true, title: strings.dialogTitleSelectNode });
		$('rnaDialog_selectnode_content').innerHTML = "<iframe id='linkManagement_iframe' src='" + application.dialogWithTreeUrl + "?dialogType=selectnodeforchiba&allowedRdfTypes=" + allowedRdfTypes + "&literal=" + literal + "&subContentItemUri=" + uri + "&predicateUri=" + predicateUri + "' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["selectNodeForChiba"].window._center();
		DialogList["selectNodeForChiba"].window.setCloseCallback(checkForClose_SelectNodeForChibaWin);
		DialogList["selectNodeForChiba"].window.show(true);
		EnterTrap = function(e) { return false; };

		if (dialogCntrl != undefined)
		{
			top.editPredicateDialogCntrl = dialogCntrl;
		}
	}
}


function getFrameNumber(frameName)
{
	var i=0;
	while (frames[i])
	{
		if (frames[i].name == frameName)
			return frames[i];
		else
			i++;	
	}	
	return '';
}


function setDialogArgsInRoot(aObjectUri, aObjectLabel)
{

	if (top.cntrl != undefined && top.cntrl.isOpen == true)
	{
		// send result to edit dialog control class
		top.editPredicateDialogCntrl.setRangeSelection(aObjectUri, aObjectLabel);
		CloseDialog("selectNodeForChiba");
	} else {
		// send result directly to chiba
		var ChibaFrame = getFrameNumber('chibaxform');

		if (typeof ChibaFrame.dialogArgs == 'object') {
			dialogArgsCopy = ChibaFrame.dialogArgs;
			dialogArgsCopy.objectLabel.value = "" + aObjectLabel;
			dialogArgsCopy.objectUri.value = "" + aObjectUri;
		  
			ChibaFrame.setXFormsValue(dialogArgsCopy.objectLabel);
			ChibaFrame.setXFormsValue(dialogArgsCopy.objectUri);
			//dialogArgsCopy.objectLabel.focus(); // gaat niet goed in ie omdat de focus op een (nog?) niet zichtbaar object wordt gezet
			
			CloseDialog("selectNodeForChiba");
		} else
		{
			alert(strings.applicationErrorMessageCouldNotSetSelection);
			CloseDialog("selectNodeForChiba");
		}
	}
}

function checkForClose_SelectNodeForChibaWin()
{
	EnterTrap = null;
	return true; 
}

function updateHeightWindowSelectNodeForChibaWin()
{
	DialogList["selectNodeForChiba"].window.updateHeight();
}

function onCloseSelectNodeForChibaDialog()
{
	
	CloseDialog("selectNodeForChiba");
}

// Select Target Node For Import Dialog
// **************************************************************************************************

function CreateSelectTargetNodeForImportDialog()
{
	if (CanCreateDialog("selectTargetNodeForImport")) 
	{
		DialogList["selectTargetNodeForImport"].window = new Window('rnaDialog_selectTargetNodeForImport',{id: "rnaDialog_selectTargetNodeForImport", className: "clean", width: 520, height: 571, recenterAuto: true,  maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, title: strings.dialogTitleSelectParentForImport});
		$('rnaDialog_selectTargetNodeForImport_content').innerHTML = "<iframe id='selectTargetNodeForImport_iframe' src='"+application.dialogWithTreeUrl+"?dialogType=selectTargetNodeForImport' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["selectTargetNodeForImport"].window._center();
		DialogList["selectTargetNodeForImport"].window.setCloseCallback(checkForClose_SelectTargetNodeForImportDialog);
		DialogList["selectTargetNodeForImport"].window.show(true);
		EnterTrap = function(e)
		{
			return false;
		};
	}
}

function SelectTargetUri(uri, uriLabel)
{
	// wijzig in UserControls/ImportManagement.ascx >> parent.parent.tbTargetUriId = '<%= tbTargetUri.ClientID %>';
	
	// get label element	
	var iframeEl = document.getElementById('linkManagement_iframe');
	if (iframeEl.contentDocument)				// DOM
		var labelElement = iframeEl.contentDocument.getElementById(this.tbTargetUriLabel);
	else if (iframeEl.contentWindow)		// IE win
		var labelElement = iframeEl.contentWindow.document.getElementById(this.tbTargetUriLabel);
	
	// get input element
	if (iframeEl.contentDocument)				// DOM
		var inputElement = iframeEl.contentDocument.getElementById(this.tbTargetUriId);
	else if (iframeEl.contentWindow)		// IE win
		var inputElement = iframeEl.contentWindow.document.getElementById(this.tbTargetUriId);
	
	if (labelElement != '') labelElement.value = uriLabel;
	if (inputElement != '')	inputElement.value = uri;
}


function checkForClose_SelectTargetNodeForImportDialog()
{
	EnterTrap = null;
	return true; 
}

function updateHeightWindowSelectTargetNodeForImportDialog()
{
	DialogList["selectTargetNodeForImport"].window.updateHeight();
}


// Confirm Delete Item
// **************************************************************************************************

function CreateConfirmDeleteItemDialog(uri)
{
	if (CanCreateDialog("confirmDeleteItem")) 
	{
		cursor.wait();
		DialogList["confirmDeleteItem"].window = new Window('rnaDialog_confirmDeleteItem',{id: "rnaDialog_confirmDeleteItem", className: "clean", width: 420, height: 303, maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, recenterAuto: true, title: strings.dialogTitleDeleteItem});
		var myAjax = new Ajax.Updater( {success: 'rnaDialog_confirmDeleteItem_content' }, application.dialogWithoutTreeUrl + '?dialogType=confirmDeleteItem&uri=' + uri, { method: 'post', asynchronous: false, evalScripts: true, onComplete: function(t) {cursor.reset();}  });
		DialogList["confirmDeleteItem"].window.setCloseCallback(checkForClose_ConfirmDeleteItemDialog);
		DialogList["confirmDeleteItem"].window._center();
		DialogList["confirmDeleteItem"].window.show(true);
		EnterTrap = function(e)
		{
			return false;
		};
	}
}

function onConfirmDeleteItem()
{
	applicationRemoveItem();
	CloseDialog("confirmDeleteItem");
}

function checkForClose_ConfirmDeleteItemDialog()
{
	EnterTrap = null;
	return true;
}

function onCancelDeleteItem()
{
	CloseDialog("confirmDeleteItem");
}





// Select Property Value Dialog
// **************************************************************************************************

var currentPropertyValueSelection = new Array();

function CreateSelectPropertyValueDialog(facetName, facetID, updateFacetsAfterwards, mode, facetType)
{
	if (CanCreateDialog("selectPropertyValue"))
	{
		cursor.wait();
		var dialogHeight = (facetType == "integer-range" || facetType == "float-range" || facetType == "date-range") ? 160 : 560;
		
		currentPropertyValueSelection = new Array();
		var paras = $A($('selectedValues_' + facetID).childElements());
		paras.each(function(item) {
			currentPropertyValueSelection.push(item.value);
		});
		DialogList["selectPropertyValue"].window = new Window('rnaDialog_facetValueSelection', { id: "rnaDialog_facetValueSelection", className: "clean", width: 420, height: dialogHeight, maximizable: false, minimizable: false, hideEffect: Element.hide, showEffect: Element.show, resizable: false, destroyOnClose: true, recenterAuto: true, title: strings.dialogTitleSelectFacetValues + ': ' + facetName });
		var postData = Form.serialize($("searchForm"));
		postData = postData.replace(/%2C/g, "%7C%7C"); // replace , by ||
		var myAjax = new Ajax.Updater({ success: 'rnaDialog_facetValueSelection_content' }, application.dialogWithoutTreeUrl + '?action=showFacet&dialogType=selectPropertyValues&search=dynamicfacet&facet=true&rows=0&facet.sort=false&facetPage=1&facet.mincount=1&facet.field=' + facetID + '&facetName=' + facetName + "&updateFacetsAfterwards=" + updateFacetsAfterwards + "&facetType=" + facetType, { method: 'post', parameters: postData, asynchronous: false, evalScripts: true, onComplete: function(t) { cursor.reset(); } });
		DialogList["selectPropertyValue"].window.setCloseCallback(checkForClose_selectPropertyValueDialog);
		DialogList["selectPropertyValue"].window._center();
		DialogList["selectPropertyValue"].window.show(true);
		EnterTrap = function(e)
		{
			return false;
		};
	}
}

function RefillSelectPropertyValueDialog(facetName, facetID, updateFacetsAfterwards, mode, facetType, facetPage, facetPrefix) {
	cursor.wait();
	var postData = Form.serialize($("searchForm"));
	postData = postData.replace(/%2C/g, "%7C%7C"); // replace , by ||
	var myAjax = new Ajax.Updater({ success: 'rnaDialog_facetValueSelection_content' }, application.dialogWithoutTreeUrl + '?action=showFacet&dialogType=selectPropertyValues&search=dynamicfacet&facet=true&rows=0&facet.sort=false&facetPage=' + facetPage + '&facet.mincount=1&facet.field=' + facetID + '&facetName=' + facetName + "&updateFacetsAfterwards=" + updateFacetsAfterwards + "&facetType=" + facetType + '&facet.prefix=' + facetPrefix, { method: 'post', parameters: postData, asynchronous: false, evalScripts: true, onComplete: function(t) { cursor.reset(); } });
}

function onSelectNewPropertyValue(facetName, facetId, facetLabel, facetValue) {
	currentPropertyValueSelection.push(facetLabel);
	var optionId = facetId + '_' + facetValue;
	onSelectLineItem(optionId, false, '', '', '')
}

function onDeselectPropertyValue(facetName, facetId, facetLabel, facetValue) {
	var i = 0;
	while (i < currentPropertyValueSelection.length) {
		if (currentPropertyValueSelection[i] == facetLabel) {
			currentPropertyValueSelection. splice(i, 1);
			break;
		}
		i++;
	}
	var optionId = facetId + '_' + facetValue;
	onDeselectLineItem(optionId, false, '', '', '');
}


function onOkFacetValueSelectionDialog(optionId, moveable, selectBox, searchType, currentFacetName, currentFacetId) {
	
	if (currentPropertyValueSelection.length == 0) {
		// nothing selected
		onDeselectLineItem(currentFacetId, true, 'select_properties', 'selectFacet');
	} else {
		// remove inputfields from searchFrame
		$('selectedValues_' + currentFacetId).replace('<div style="display: none;" id="selectedValues_' + currentFacetId + '">&#160;</div>');

		// replace lineItem in searchframe to selection
		onSelectLineItem(optionId, true, 'select_properties', 'selectFacet');

		// add inputfields for selected property values
		for (var i = 0; i < currentPropertyValueSelection.length; i++) {
			var inputElement = '<input id="item_' + currentPropertyValueSelection[i] + '_facet" name="item_' + currentFacetId + '_facet" value="' + currentPropertyValueSelection[i] + '">';
			$('selectedValues_' + currentFacetId).insert(inputElement);
			$(currentFacetId + '_editBtn').show();
		}

		// update searchframe
		rebuildFacetValueString(currentFacetId, currentFacetName);
	}

	CloseDialog("selectPropertyValue");
	updatePropertyList(true);
}


function validateRangeValue(str, dataType) {
	if ((dataType == "integer") && (str.match(/^[1-9][0-9]*$/))) {
		return (true);
	}
	else if ((dataType == "float") && (str.match(/^[1-9][0-9]*(\.[0-9]+)?$/))) {
		return (true);
	}
	else if ((dataType == "date") && (str.match(/^([-+])?(((\d{4})-?(0[13578]|10|12)-?(0[1-9]|[12][0-9]|3[01]))|((\d{4})-?(0[469]|11)-?([0][1-9]|[12][0-9]|30))|((\d{4})-?(02)-?(0[1-9]|1[0-9]|2[0-8]))|(([02468][048]00)-?(02)-?(29))|(([13579][26]00)-?(02)-?(29))|(([0-9][0-9][0][48])-?(02)-?(29))|(([0-9][0-9][2468][048])-?(02)-?(29))|(([0-9][0-9][13579][26])-?(02)-?(29))|(0000-?00-?00)|(8888-?88-?88)|(9999-?99-?99))?$/))) {
		return (true);
	}

	alert('invalid ' + dataType + ': ' + str);
	return (false);
}

function onOkFacetRangeSelectionDialog(optionId, moveable, selectBox, searchType, currentFacetName, currentFacetId) {
	
	if ($('rangeValue').value == "") {
		onDeselectLineItem(currentFacetId, true, 'select_properties', 'selectFacet');
	}
	else {
		// remove inputfields from searchFrame
		$('selectedValues_' + currentFacetId).replace('<div style="display: none;" id="selectedValues_' + currentFacetId + '">&#160;</div>');

		// replace lineItem in searchframe to selection
		onSelectLineItem(optionId, true, 'select_properties', 'selectFacet');
	
		// add inputfields for selected property values
		var inputElement = '<input id="item_' + $('rangeValue').value + '_facet" name="item_' + currentFacetId + '_facet" value="' + $('rangeValue').value + '">';
		$('selectedValues_' + currentFacetId).insert(inputElement);
		$(currentFacetId + '_editBtn').show();

		// update searchframe
		rebuildFacetValueString(currentFacetId, currentFacetName);
	}

	CloseDialog("selectPropertyValue");
	updatePropertyList(true);
}




function onCancelPropertyValueSelection(id)
{
	//$('lineitem_'+id).remove();
	CloseDialog("selectPropertyValue");
	updatePropertyList(true);
}


function updatePropertyList(updateFacetsAfterwards)
{
	if (updateFacetsAfterwards) {
		cursor.wait();
		updateSelectionList('propertyValue');
		var postData = Form.serialize($("searchForm"));
		postData = postData.replace(/%2C/g, "%7C%7C"); // replace , by ||
		var myAjax = new Ajax.Updater( {success: 'SelectionList_select_properties' }, application.solrResultsUrl + '?facetsonly=true&facet=true&rows=0&facet.sort=false&facet.limit=5&facet.mincount=1', { method: 'post', parameters: postData, asynchronous: false, evalScripts: true, onComplete: function(t) {cursor.reset();}  });
	}
}

function onCloseSelectPropertyValueDialog(updateFacetsAfterwards)
{
	CloseDialog("selectPropertyValue");
	updatePropertyList(updateFacetsAfterwards);
}

function checkForClose_selectPropertyValueDialog()
{
	EnterTrap = null;
	return true;
}


// Facet Values dialog Box / not in use
// **************************************************************************************************

function CreateShowFacetValueSelectionDialog(facetName, facetID, updateFacetsAfterwards)
{
	if (CanCreateDialog("facetValueSelection"))
	{
		cursor.wait();
		DialogList["facetValueSelection"].window = new Window('rnaDialog_facetValueSelection',{id: "rnaDialog_facetValueSelection", className: "clean", width: 420, height: 262, maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true,recenterAuto: true, title: strings.dialogTitleSelectFacetValues +' '+ facetName});
		var postData = Form.serialize($("searchForm"));
		postData = postData.replace(/%2C/g, "%7C%7C"); // replace , by ||
		var myAjax = new Ajax.Updater( {success: 'rnaDialog_facetValueSelection_content' }, application.dialogWithoutTreeUrl + '?action=showFacet&dialogType=selectFacetValues&search=dynamicfacet&facet=true&rows=0&facet.sort=false&facet.limit=500&facet.mincount=1&facet.field='+facetID+'&facetName=' + facetName + "&updateFacetsAfterwards=" + updateFacetsAfterwards, { method: 'post', parameters: postData, asynchronous: false, evalScripts: true, onComplete: function(t) {cursor.reset();}  });
		DialogList["facetValueSelection"].window.setCloseCallback(checkForClose_FacetValueSelectionDialog);
		DialogList["facetValueSelection"].window._center();
		DialogList["facetValueSelection"].window.show(true);
		EnterTrap = function(e)
		{
			
			return false;
		};
	}
	return false;
}

function onCloseShowFacetValueSelectionDialog (updateFacetsAfterwards)
{
	CloseDialog("facetValueSelection");

	// update available facets
	updatePropertyList(updateFacetsAfterwards);
}

function checkForClose_FacetValueSelectionDialog()
{
	EnterTrap = null;
	return true;
}


// Import Excel dialog
// **************************************************************************************************
//DialogList["importExcel"] = {window: null, allowMultiple: false, allowOthers: false};
//http://rnatoolset.local/pages/importmanagement.aspx
function CreateExcelImportDialog()
{
	if (CanCreateDialog("importExcel"))
	{
		DialogList["importExcel"].window = new Window('rnaDialog_importExcel',{id: "rnaDialog_importExcel", className: "clean", width: 505, height: 410, recenterAuto: true,  maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, title: 'import items'});
		$('rnaDialog_importExcel_content').innerHTML = "<iframe name='importDialogIframe' class='datamanagementiframe' id='linkManagement_iframe' src='" + application.importManagementUrl+"?ImportType=excel' class='importExcel' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["importExcel"].window.setCloseCallback(checkForClose_importExcel);
		DialogList["importExcel"].window._center();
		DialogList["importExcel"].window.show(true);
		EnterTrap = function(e){return false};
	}
}

function checkForClose_importExcel()
{
	EnterTrap = null;
	return true; 
}

function onCancelImportExcel()
{
	CloseDialog("importExcel");
}




// New StructureFOLDER dialog
// **************************************************************************************************
function CreateNewStructureFolderDialog() {
	if (CanCreateDialog("newStructureFolder")) {
		cursor.wait();
		DialogList["newStructureFolder"].window = new Window('rnaDialognewStructureFolder',{id: "rnaDialognewStructureFolder", className: "clean", width: 500, height: 110, maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, recenterAuto: true, title: strings.dialogTitleCreateStructureFolder});
		var myAjax = new Ajax.Updater( {success: 'rnaDialognewStructureFolder_content' }, application.dialogWithoutTreeUrl + '?dialogType=newStructureFolder', { method: 'post', asynchronous: false, evalScripts: true, onComplete: function(t) { cursor.reset();} });
		DialogList["newStructureFolder"].window.setCloseCallback(checkForClose_CreateNewStructureFolderDialog);
		DialogList["newStructureFolder"].window._center();
		DialogList["newStructureFolder"].window.show(true);
		EnterTrap = function(e) { return false;};
	}
}

function checkForClose_CreateNewStructureFolderDialog()
{
	EnterTrap = null;
	return true; 
}

function onSubmitNewStructureFolder()
{
	var form = $('newStructureFolderForm');
	var input = form['folderName'];
	var newName = $(input).getValue();
	//alert('onSubmitNewStructureFolder' + newName);

	if (newName != "") 
	{
		if (structureListEditor) {
			structureListEditor.newFolder(newName);
		}
		CloseDialog("newStructureFolder");
	}
	else {
		alert(strings.dialogFolderNameError);
	}
}

function onCloseNewStructureFolder()
{
	CloseDialog("newStructureFolder");
}


// rename Structurefolder dialog
// **************************************************************************************************
function CreateRenameStructureFolderDialog(folderName) {
	if (CanCreateDialog("renameStructureFolder"))
	{
		cursor.wait();
		DialogList["renameStructureFolder"].window = new Window('rnaDialogrenameStructureFolder',{id: "rnaDialogrenameStructureFolder", className: "clean", width: 500, height: 130, maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, recenterAuto: true, title: strings.dialogTitleRenameStructureFolder});
		var myAjax = new Ajax.Updater( {success: 'rnaDialogrenameStructureFolder_content' }, application.dialogWithoutTreeUrl + '?dialogType=renameStructureFolder&currentFolderName='+folderName, { method: 'post', asynchronous: false, evalScripts: true, onComplete: function(t) { cursor.reset();} });
		DialogList["renameStructureFolder"].window.setCloseCallback(checkForClose_CreateRenameStructureFolderDialog);
		DialogList["renameStructureFolder"].window._center();
		DialogList["renameStructureFolder"].window.show(true);
		EnterTrap = function(e) { return false;};
	}
}

function checkForClose_CreateRenameStructureFolderDialog()
{
	EnterTrap = null;
	return true; 
}

function onSubmitRenameStructureFolder()
{
	var form = $('renameStructureFolderForm');
	var input = form['folderName'];
	var newName = $(input).getValue();
	//alert('onSubmitRenameStructureFolder' + newName);
	if (newName != "") 
	{
		if (structureListEditor) 
		{
			structureListEditor.renameFolder(newName);
		}
		CloseDialog("renameStructureFolder");
	}
	else 
	{
		alert(strings.dialogFolderNameError);
	}
}

function onCloseRenameStructureFolder()
{
	CloseDialog("renameStructureFolder");
}

// Import dialog
// **************************************************************************************************

function CreateImportDialog()
{
	DialogList["import"].window = new Window('rnaDialog_import',{id: "rnaDialog_import", className: "clean", width: 505, height: 530, recenterAuto: true,  maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, title: strings.dialogTitleImportExcel});
	$('rnaDialog_import_content').innerHTML = "<iframe name='importDialogIframe' class='datamanagementiframe' id='linkManagement_iframe' src='" + application.importManagementUrl+"?ImportType=excel' class='importExcel' frameborder='no' border='0' style='width:100%;'></iframe>";
	DialogList["import"].window.setCloseCallback(checkForClose_importExcel);
	DialogList["import"].window._center();
	DialogList["import"].window.show(true);
	EnterTrap = function(e){return false};
}

function CreateExcelImportDialog()
{
	if (CanCreateDialog("import"))
	{
		DialogList["import"].window = new Window('rnaDialog_import',{id: "rnaDialog_import", className: "clean", width: 505, height: 530, recenterAuto: true,  maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, title: strings.dialogTitleImportExcel});
		$('rnaDialog_import_content').innerHTML = "<iframe name='importDialogIframe' class='datamanagementiframe' id='linkManagement_iframe' src='" + application.importManagementUrl+"?ImportType=excel' class='importExcel' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["import"].window.setCloseCallback(checkForClose_importExcel);
		DialogList["import"].window._center();
		DialogList["import"].window.show(true);
		EnterTrap = function(e){return false};
	}
}

function CreateOaiImportDialog()
{
	if (CanCreateDialog("import"))
	{
		DialogList["import"].window = new Window('rnaDialog_import',{id: "rnaDialog_import", className: "clean", width: 505, height: 530, recenterAuto: true,  maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, title: strings.dialogTitleImportOai});
		$('rnaDialog_import_content').innerHTML = "<iframe name='importDialogIframe' class='datamanagementiframe' id='linkManagement_iframe' src='" + application.importManagementUrl+"?ImportType=oai' class='importOai' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["import"].window.setCloseCallback(checkForClose_importOai);
		DialogList["import"].window._center();
		DialogList["import"].window.show(true);
		EnterTrap = function(e){return false};
	}
}

function CreateDeterminationImportDialog()
{
	if (CanCreateDialog("import"))
	{
		DialogList["import"].window = new Window('rnaDialog_import',{id: "rnaDialog_import", className: "clean", width: 505, height: 530, recenterAuto: true,  maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, title: strings.dialogTitleImportDetermination});
		$('rnaDialog_import_content').innerHTML = "<iframe name='importDialogIframe' class='datamanagementiframe' id='linkManagement_iframe' src='" + application.importManagementUrl+"?ImportType=determination' class='importDetermination' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["import"].window.setCloseCallback(checkForClose_importDetermination);
		DialogList["import"].window._center();
		DialogList["import"].window.show(true);
		EnterTrap = function(e){return false};
	}
}

function CreateRnaImportDialog()
{
	if (CanCreateDialog("import"))
	{
		DialogList["import"].window = new Window('rnaDialog_import',{id: "rnaDialog_import", className: "clean", width: 505, height: 530, recenterAuto: true,  maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, title: strings.dialogTitleImportRna});
		$('rnaDialog_import_content').innerHTML = "<iframe name='importDialogIframe' class='datamanagementiframe' id='linkManagement_iframe' src='" + application.importManagementUrl+"?ImportType=rna' class='importRna' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["import"].window.setCloseCallback(checkForClose_importRna);
		DialogList["import"].window._center();
		DialogList["import"].window.show(true);
		EnterTrap = function(e){return false};
	}
}

function CreateSkosImportDialog ()
{
	if (CanCreateDialog("import"))
	{
		DialogList["import"].window = new Window('rnaDialog_import',{id: "rnaDialog_import", className: "clean", width: 505, height: 530, recenterAuto: true,  maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, title: strings.dialogTitleImportSkos});
		$('rnaDialog_import_content').innerHTML = "<iframe name='importDialogIframe' class='datamanagementiframe' id='linkManagement_iframe' src='" + application.importManagementUrl+"?ImportType=skos' class='importSkos' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["import"].window.setCloseCallback(checkForClose_importSkos);
		DialogList["import"].window._center();
		DialogList["import"].window.show(true);
		EnterTrap = function(e){return false};
	}
}

function onSelectItemTypeInImportDialog() {

	// this function is used by import Excel dialog
	if ($(ddlAvailableContentTypesId)) {

		var url = '/pages/ExcelTemplate.aspx?action=getExcelForContentItemType&contentItemTypeId=' + $(ddlAvailableContentTypesId).getValue();
		
		window.open(url,'','');
	}
}

function checkForClose_importExcel()
{
	EnterTrap = null;
	return true; 
}

function checkForClose_importOai()
{
	EnterTrap = null;
	return true; 
}

function checkForClose_importDetermination()
{
	EnterTrap = null;
	return true; 
}

function checkForClose_importRna()
{
	EnterTrap = null;
	return true; 
}

function checkForClose_importSkos()
{
	EnterTrap = null;
	return true; 
}

function onCancelImportDialog()
{
	CloseDialog("import");
} 




// system Management dialog
// **************************************************************************************************

function CreateSystemManagementDialog(uri)
{
	if (CanCreateDialog("systemManagement")) 
	{
		cursor.wait();
		DialogList["systemManagement"].window = new Window('rnaDialog_systemManagement',{id: "rnaDialog_systemManagement", className: "clean", width: 420, height: 340, maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, recenterAuto: true, title: strings.dialogTitleSystemManagement});
		var myAjax = new Ajax.Updater( {success: 'rnaDialog_systemManagement_content' }, application.dialogWithoutTreeUrl + '?dialogType=systemManagement&uri=' + uri, { method: 'post', asynchronous: false, evalScripts: true, onComplete: function(t) {cursor.reset();}  });
		DialogList["systemManagement"].window.setCloseCallback(checkForClose_systemManagement);
		DialogList["systemManagement"].window._center();
		DialogList["systemManagement"].window.show(true);
		EnterTrap = function(e){return false;};
	}
}


function checkForClose_systemManagement()
{
	EnterTrap = null;
	return true;
}

function onCloseSystemManagement()
{
	CloseDialog("systemManagement");
}

// mapping management dialog
// **************************************************************************************************

function CreateMappingDialog(sourceUri)
{
	
	sourceUri = (!sourceUri || sourceUri=="")? "none": sourceUri;
	
	DialogList["MappingDialog"].window = new Window('rnaDialog_MappingDialog',{id: "rnaDialog_MappingDialog", className: "clean", width: 605, height: 770, recenterAuto: true,  maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, title: strings.dialogTitleMappingManagement});
	$('rnaDialog_MappingDialog_content').innerHTML = "<iframe name='MappingDialogIframe' class='datamanagementiframe' id='MappingDialog_iframe' src='" + application.mappingUrl+"?sourceUri="+sourceUri+"' class='importExcel' frameborder='no' border='0' style='width:100%;'></iframe>";

	DialogList["MappingDialog"].window.setCloseCallback(checkForClose_MappingDialog);
	DialogList["MappingDialog"].window._center();
	DialogList["MappingDialog"].window.show(true);
	EnterTrap = function(e){return false;};
}

function checkForClose_MappingDialog()
{
	EnterTrap = null;
	return true;
}

function onCloseMappingDialog()
{
	CloseDialog("MappingDialog");
}


// about dialog
// **************************************************************************************************

function CreateaboutDialog()
{
	if (CanCreateDialog("aboutDialog")) 
	{
		cursor.wait();
		DialogList["aboutDialog"].window = new Window('rnaDialog_aboutDialog',{id: "rnaDialog_aboutDialog", className: "clean", width: 480, height: 340, maximizable: false, minimizable: false, hideEffect:Element.hide, showEffect:Element.show, resizable: false, destroyOnClose: true, recenterAuto: true, title: strings.dialogTitleAbout});
		var myAjax = new Ajax.Updater( {success: 'rnaDialog_aboutDialog_content' }, application.dialogWithoutTreeUrl + '?dialogType=aboutDialog', { method: 'post', asynchronous: false, evalScripts: true, onComplete: function(t) {cursor.reset();}  });
		DialogList["aboutDialog"].window.setCloseCallback(checkForClose_aboutDialog);
		DialogList["aboutDialog"].window._center();
		DialogList["aboutDialog"].window.show(true);
		EnterTrap = function(e){return false;};
	}
}

function checkForClose_aboutDialog()
{
	EnterTrap = null;
	return true;
}

function onCloseAboutDialog()
{
	CloseDialog("aboutDialog");
}


// password dialog
// **************************************************************************************************

function CreatePasswordDialog(sourceUri) {
	if (CanCreateDialog("passwordDialog")) {
		cursor.wait();
		DialogList["passwordDialog"].window = new Window('rnaDialog', { id: "rnaDialog", className: "clean", width: 500, height: 170, maximizable: false, minimizable: false, hideEffect: Element.hide, showEffect: Element.show, resizable: false, destroyOnClose: true, recenterAuto: true, title: strings.dialogTitlePassword });
		var myAjax = new Ajax.Updater({ success: 'rnaDialog_content' }, application.dialogWithoutTreeUrl + '?dialogType=passwordDialog', { method: 'post', asynchronous: false, evalScripts: true, onComplete: function (t) { cursor.reset(); } });
		DialogList["passwordDialog"].window.setCloseCallback(checkForClose_passwordDialog);
		DialogList["passwordDialog"].window._center();
		DialogList["passwordDialog"].window.show(true);

		EnterTrap = function (e) { return false; };
	}
}

function checkForClose_passwordDialog() {
	EnterTrap = null;
	return true;
}


var PasswordDialogCntrl = Class.create({
	initialize: function (passwordOld, passwordNew, passwordCheck, challenge, loginName) {
		this.passwordOld = passwordOld || $('passwordOld');
		this.passwordNew = passwordNew || $('passwordNew');
		this.passwordCheck = passwordCheck || $('passwordCheck');
		this.challenge = challenge || $('challenge');
		/* new for sha512 passwords */
		this.loginName = loginName || $('loginName');

		this.addEventHandlers();
	},

	addEventHandlers: function () {
		if ($('dialogSubmitButton')) {
			$('dialogSubmitButton').observe("click", this.onSubmit.bind(this));
		}

		if ($('dialogCancelButton')) {
			$('dialogCancelButton').observe("click", this.onCancel.bind(this));
		}
	},

	onCancel: function () {
		CloseDialog("passwordDialog");
	},

	onSubmit: function () {
		this.changePassword();
	},

	changePassword: function () {
		if (this.passwordNew.getValue() != this.passwordCheck.getValue()) {
			$('extraField').replace('<div id="extraField"><b>error: you have entered two different passwords</b></div>');
			return;
		}

		if (this.passwordNew.getValue() == "") {
			$('extraField').replace('<div id="extraField"><b>error: no password entered</b></div>');
			return;
		}

		if (this.passwordNew.getValue().length < 5) {
			$('extraField').replace('<div id="extraField"><b>error: password should contain at least 5 characters</b></div>');
			return;
		}

		var username = this.loginName.getValue().toLowerCase().reverse();
		var password = this.passwordOld.getValue();
		var challenge = this.challenge.getValue();

		var shaObj = new jsSHA(password, "ASCII");
		var shaSecObj = new jsSHA(shaObj.getHMAC(username, "ASCII", "SHA-512", "HEX").toUpperCase(), "ASCII");
		var hash = shaSecObj.getHMAC(challenge, "ASCII", "SHA-512", "HEX").toUpperCase();

		var newPasswordHash = new jsSHA(this.passwordNew.getValue(), "ASCII");
		var newPasswordCheck = new jsSHA(this.passwordCheck.getValue(), "ASCII");

		var newPass = newPasswordHash.getHMAC(username, "ASCII", "SHA-512", "HEX").toUpperCase();
		var newPassCheck = newPasswordCheck.getHMAC(username, "ASCII", "SHA-512", "HEX").toUpperCase();

		var pageURL = application.dialogActionUrl;
		var parameters = {
			'action': 'changePassword',
			'old': hash,
			'new': newPass,
			'check': newPassCheck,
			'challenge': challenge
		};

		var myAjax = new Ajax.Updater({ success: 'extraField' }, pageURL, { method: 'get', parameters: parameters, asynchronous: false, evalScripts: true, onComplete: this.onCheckStatus });
	},

	onCheckStatus: function (e) {
		var dollar = e.responseText.match(/success/i);
		if (dollar != null) {
			CloseDialog("passwordDialog");
		}
	}

});

if (typeof String.prototype.reverse !== 'function') {
	String.prototype.reverse = function () { return this.split("").reverse().join(""); }
}

/*
var PasswordDialogCntrl = Class.create();
PasswordDialogCntrl.prototype =
{
	initialize: function () {
		var thisClass = this;

		if ($('dialogSubmitButton')) {
			$('dialogSubmitButton').observe("click", thisClass.onSubmit.bind(thisClass));
		}

		if ($('dialogCancelButton')) {
			$('dialogCancelButton').observe("click", thisClass.onCancel.bind(thisClass));
		}
	},

	onCancel: function () {
		CloseDialog("passwordDialog");
	},

	onSubmit: function () {
		console.log('onsubmit', this);
		this.changePassword();
	},

	changePassword: function () {
		var passwordOld = hex_md5($('passwordOld').getValue());
		var passwordNew = hex_md5($('passwordNew').getValue());
		var passwordNewRepeated = hex_md5($('passwordRepeatNew').getValue());

		var pageURL = application.dialogActionUrl;
		var action = 'changePassword';
		var parameters = 'action=' + action + '&old=' + passwordOld + '&new=' + passwordNew + '&newRepeated=' + passwordNewRepeated;
		var myAjax = new Ajax.Updater({ success: 'extraField' }, pageURL, { method: 'get', parameters: parameters, asynchronous: false, evalScripts: true, onComplete: function (e) { alert("zzz"); thisClass.onCheckStatus(e) } });
		//applicationNewContentItem(title, contentItemTypeSelection, 'false', itemTypeUri);


		//				onFailure: function(e) { me.onError( strings.entityCheckerErrorMessageServerError); },
		//				onException: function(e) { me.onError(strings.entityCheckerErrorMessageServerError); }
	},

	onCheckStatus: function (e) {
		alert("---" + e);
		var dollar = e.responseText.match(/error:/i);
		if (dollar == null) {
			CloseDialog("passWordDialog");
		}
		else {
		}
	}
}
*/

// save valueMapper definition dialog
// **************************************************************************************************

function createValueMapperSaveAsDialog()
{
	if ($('ddlReferencingReferenceStructure').getValue() == '' || $('ddlReferencingItemType').getValue() == '' || $('ddlReferencingPredicate').getValue() == '' || $('ddlReferencedReferenceStructure').getValue() == '' || $('ddlReferencedItemType').getValue() == '' || $('referencedLabelType').getValue() == '')
	{
		alert('cannot save this definition\n\nselect all structures, item types, predicates and label types first');
	}	
	else
	{
		if (top.CanCreateDialog("valueMappingSaveAsDialog"))
		{
			top.DialogList["valueMapperSaveAs"].window = new Window('rnaDialogvalueMapperSaveAs', { id: "rnaDialogvalueMapperSaveAs", parent: "form", className: "clean", width: 450, height: 117, top: 75, left: 52, maximizable: false, minimizable: false, hideEffect: Element.hide, showEffect: Element.show, resizable: false, destroyOnClose: true, recenterAuto: false, title: strings.dialogTitleSaveDefinitionAs });
			top.DialogList["valueMapperSaveAs"].window.setContent($('dialogContainer_SaveAs'), false, false);
			//DialogList["valueMapperSaveAs"].window.setCloseCallback(checkForClose_CreateRenameStructureFolderDialog);
			top.DialogList["valueMapperSaveAs"].window.show(false);
			EnterTrap = function(e) { return false; };
		}
	}	
}

function checkForClose_CreateRenameStructureFolderDialog()
{
	EnterTrap = null;
	return true;
}

function onCloseValueMapperSaveAsDialog()
{
	top.CloseDialog("valueMapperSaveAs");
}






// Metadata Suggest dialog
// **************************************************************************************************

var metadataSuggestSubUri = ""; 
function CreateMetadataSuggestDialog(subUri)
{
	var metadataSuggestSubUri = subUri;	
	if (CanCreateDialog("metadataSuggest"))
	{
		cursor.wait();
		DialogList["metadataSuggest"].window = new Window('rnaDialog_metadataSuggest', { id: "rnaDialog_MetadataSuggest", className: "clean", width: 603, height: 700, maximizable: false, minimizable: false, hideEffect: Element.hide, showEffect: Element.show, resizable: false, destroyOnClose: true, recenterAuto: true, title: strings.dialogTitleSuggestMetadata });
		$('rnaDialog_metadataSuggest_content').innerHTML = "<iframe id='metadataSuggest_iframe' name='metadataSuggest_iframe' src='" + application.dialogWithoutTreeUrl + "?dialogType=metadataSuggest&dialogPage=1&suggestMetadataSubUri=" + metadataSuggestSubUri+"' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["metadataSuggest"].window.setCloseCallback(checkForClose_MetadataSuggest);
		DialogList["metadataSuggest"].window._center();
		DialogList["metadataSuggest"].window.show(true);
		EnterTrap = function(e) { return false; };
	}
}

function metadataSuggestDialogCntrl(pageNR)
{
	var formElement = $("DialogMetadataSuggestForm");
	switch (pageNR)
	{
		case 2:
			var formParams = $(formElement).serialize();
			self.location.href = "/Pages/entityCheckerAction.aspx?action=start&" + formParams;
			break;
		case 3:
			var formParams = $('DialogMetadataSuggestForm').serialize({ hash: false })+"&action=save";
			self.location.href = "/Pages/entityCheckerAction.aspx?" + formParams;
		default:
			var formParams = "dialogType=metadataSuggest&dialogPage=1&suggestMetadataSubUri=" + $('uri').getValue();
			self.location.href = parent.parent.application.dialogWithoutTreeUrl + "?" + formParams;
	}
}


function checkForClose_MetadataSuggest()
{
	EnterTrap = null;
	return true;
}

function onCloseMetadataSuggest()
{
	CloseDialog("metadataSuggest");
}

var treeSelectCntrl = Class.create();
treeSelectCntrl.prototype = {
	initialize: function(treeContainerId) { this.treeContainer = ($(treeContainerId)) ? $(treeContainerId) : null; this.setLblClickObservers(); },
	toggle: function(chkBx) { if (chkBx.checked) { this.selectAll() } else { this.deselectAll(); } },
	selectAll: function() { if (this.treeContainer) { this.setState(true); } },
	deselectAll: function() { if (this.treeContainer) { this.setState(false); } },
	setState: function(state) { this.treeContainer.select('input[type="checkbox"]').each(function(checkBox) { checkBox.checked = (state) ? true : false; }) },
	setLblClickObservers: function()
	{
		var me = this;
		var labels = $A($('suggestList').select('li label')).each(function(obj)
		{
			$(obj).observe("click", me.onClickLbl.bind(this, obj.id));
		});
	},

	onClickLbl: function(obj)
	{
		if ($(obj.substring(4)))
		{
			$(obj.substring(4)).checked = ($(obj.substring(4)).checked) ? false : true;
		}
	}
}

var metadataSuggestPoller = Class.create();
metadataSuggestPoller.prototype = {
	guid: null,
	uri: null,
	status: 'disabled',

	initialize: function()
	{
		// zoek in pagina naar de guid van de huidige entitychecker id
		this.uri = ($('uri') && $('uri').value != '') ? $('uri').value : null;
		this.guid = ($('guid') && $('guid').value != '') ? $('guid').value : null;
		if (this.guid != null && this.uri != null)
		{
			this.status = "enabled"
		};
	},

	start: function()
	{
		if (this.status == "enabled")
		{
			//start periodical updater
			var statusParams = "?action=status&guid=" + this.guid;
			var me = this;

			this.StatusChecker = new Ajax.PeriodicalUpdater('hiddenResults', '/pages/entityCheckerAction.aspx', {
				parameters: statusParams,
				evalScripts: true,
				onSuccess: function(e) { me.onCheckStatus(e) },
				onFailure: function(e) { me.onError( strings.entityCheckerErrorMessageServerError); },
				onException: function(e) { me.onError(strings.entityCheckerErrorMessageServerError); }
			});
		} 
		else
		{
			this.onError(strings.entityCheckerErrorMessageServerError);
		}
	},

	onCheckStatus: function(e)
	{
		var dollar = e.responseText.match(/<status>(.*)<\/status>/);
		if (dollar == null)
		{
			this.onError(strings.entityCheckerErrorMessageServerError);
			if (this.StatusChecker) { this.StatusChecker.stop(); }
		} else
		{
			var status = dollar[1];

			switch (status)
			{
				case "running":
					// just let the periodical updater do its work
					break;
				case "ok":
					this.StatusChecker.stop();
					var resultParams = "?action=result&guid=" + this.guid + "&uri=" + this.uri;
					self.location.href = "/pages/entityCheckerAction.aspx" + resultParams;
					break;
				case "error":
					this.StatusChecker.stop();
					this.onError(strings.entityCheckerErrorMessageCannotCheckDocument);
					break;
				default:
					this.onError(strings.entityCheckerErrorMessageServiceUnavailable);
					this.StatusChecker.stop();
					break;
			}
		}
	},

	onError: function(message)
	{
		this.StatusChecker.stop();
		$('indicatorLbl').hide();
		if (message != "")
		{
			$('indicatorErrorLbl').innerHTML = message;
		}
		$('indicatorErrorLbl').show();
	}

}

var suggestListControl = Class.create();
suggestListControl.prototype = {
	currentlyActivated: 'listItem_1',
	previsoulyActivated: 0,
	suggestListId: "suggestList",
	propertySelectorId: "propertySelector",

	initialize: function()
	{
		this.conText = ($('conText')) ? $('conText') : null;
		this.conTextTitle = ($('conTextTitle')) ? $('conTextTitle') : null;
		this.propertySelector = ($('propertySelector')) ? $('propertySelector') : null;
		this.suggestList = ($(this.suggestListId)) ? $(this.suggestListId) : null;

		if (this.suggestList != null && this.conText != null && this.propertySelector != null && this.conTextTitle)
		{
			this.activate($(this.suggestList.firstDescendant().id));
			this.setKeyListener();
			this.preSetProperties();
		}
	},

	activate: function(obj)
	{
		if (obj != null && obj.id != null)
		{
			this.previouslyActivated = this.currentlyActivated;
			this.currentlyActivated = obj.id;
			this.deActivate(this.previouslyActivated);
			$(obj.id).addClassName('active');
			this.updateDashBoard(obj.id.slice(9));
		}
	},

	activateNext: function()
	{
		try
		{
			eval($(this.currentlyActivated).next().onclick());
			$('suggestionsListContainer').scrollTop = $(this.currentlyActivated).positionedOffset()[1] - 50;
		} catch (e) { }
	},

	activatePrevious: function()
	{
		try
		{
			eval($(this.currentlyActivated).previous().onclick());
			$('suggestionsListContainer').scrollTop = $(this.currentlyActivated).positionedOffset()[1] - 50;
		} catch (e) { }
	},

	deActivate: function(id)
	{
		if ($(id)) { $(id).removeClassName('active') }
	},

	updateDashBoard: function(id)
	{
		this.conText.innerHTML = "-";
		this.propertySelector.innerHTML = "<ul><li>-</li></ul>";
		this.tempElement = "";
		$('conTextTitle').innerHTML = "-";

		if ($('listItem_' + id).select('[class="entity"]')[0].innerHTML != '') { $('conTextTitle').innerHTML = $('listItem_' + id).select('[class="entity"]')[0].innerHTML }
		if ($('listItem_' + id).select('[class="conText"]').size() >= 1) { this.conText.innerHTML = $('listItem_' + id).select('[class="conText"]')[0].innerHTML }
		if ($(id))
		{
			$A($(id).childElements()).each(function(property, position)
			{
				if (position != 0)
				{
					var js = "sl.onClickPropertyLabel(this, 'propertyCheckBox_" + property.id + "', '" + id + "');";
					var selectedAttr = (property.selected) ? "checked='true'" : "";
					var isBounded = (property.hasClassName('unbounded')) ? false : true;
					var uriEnabled = (property.hasClassName('reference')) ? true : false;
					var isUsed = $A($('suggestList').select('li.' + property.value)).size();
					var disableThis = (isBounded && isUsed && !(property.selected)) ? "disabled='disabled'" : "";

					this.tempElement += '<li><input name="DONT_USE" id="propertyCheckBox_' + property.id + '" value="' + property.id + '" ' + disableThis + ' onclick="' + js + '" type="checkbox" ' + selectedAttr + '  /><label  onclick="' + js + '">' + property.innerHTML + '</label></li>'
				}
			} .bind(this));
			this.propertySelector.innerHTML = "<ul>" + this.tempElement + "</ul>";
			new Effect.Opacity(this.propertySelector.select('UL')[0], { from: 0, to: 1, duration: 0.35 });
		}
		new Effect.Opacity(this.conText, { from: 0, to: 1, duration: 0.35 });
	},

	onChangeProperty: function(propertyId, id)
	{
		if ($('propertyCheckBox_' + propertyId))
		{
			$(propertyId).selected = $('propertyCheckBox_' + propertyId).checked
		};

		// if nothing is selected, select the 'none' option
		if ($(id).getValue() == '') { $(id + '_none').selected = true; }
		else { $(id + '_none').selected = false; }

		this.TempSubstract = "";

		$A($(id).childElements()).each(function(property, position)
		{
			if (position != 0 && property.selected)
			{
				this.TempSubstract += "<li class='" + property.value + "'>" + property.innerHTML + "</li>";
			}
		} .bind(this));

		if (this.TempSubstract != '') { $('listItem_' + id).select('div.propertylist ul')[0].innerHTML = this.TempSubstract; }
		else if ($('listItem_' + id)) { $('listItem_' + id).select('div.propertylist ul')[0].innerHTML = "<li>-</li>"; }
	},

	setKeyListener: function()
	{
		document.onkeydown = function(e)
		{
			var evt = e || window.event;
			this.onPressKey(evt.keyCode);
		} .bind(this);
	},

	onPressKey: function(keycode)
	{
		switch (keycode)
		{
			case 38: this.activatePrevious(); break;
			case 40: this.activateNext();
		}
	},

	onClickPropertyLabel: function(obj, inputId, id)
	{
		switch (obj.tagName)
		{
			case "LABEL":
				$(inputId).checked = ($(inputId).checked) ? false : true;
				this.onChangeProperty($(inputId).value, String(id));
			case "INPUT":
				this.onChangeProperty(obj.value, String(id));
		}
	},

	preSetProperties: function()
	{
		$A($(this.suggestList).childElements()).each(function(property, position)
		{
			this.TempSubstract = "";
			var thisId = property.id.slice(9);
			if ($(thisId))
			{
				$A($(thisId).childElements()).each(function(property, position)
				{
					if (position != 0 && property.selected) { this.TempSubstract += "<li>" + property.innerHTML + "</li>" }
				} .bind(this));

				if (this.TempSubstract != '') { $('listItem_' + thisId).select('div.propertylist ul')[0].innerHTML = this.TempSubstract; }
				else if ($('listItem_' + thisId)) { $('listItem_' + thisId).select('div.propertylist ul')[0].innerHTML = "<li>-</li>"; }
			}
		} .bind(this))
	},

	onSaveMetadataSuggest: function()
	{
		metadataSuggestDialogCntrl(3);
	}
}

// value mapping manager dialog
// **************************************************************************************************

function CreateValueMappingManagerDialog() {
	if (CanCreateDialog("valueMappingManager")) {
		cursor.wait();
		DialogList["valueMappingManager"].window = new Window('rnaDialog_valuemappingmanager', { id: "rnaDialog_valuemappingmanager", className: "clean", width: 605, height: 730, recenterAuto: true, maximizable: false, minimizable: false, hideEffect: Element.hide, showEffect: Element.show, resizable: false, destroyOnClose: true, title: strings.dialogTitleValueMappingManager });
		$('rnaDialog_valuemappingmanager_content').innerHTML = "<iframe id='rnaDialog_valuemappingmanager_iframe' name='rnaDialog_valuemappingmanager_iframe' src='" + application.dialogWithoutTreeUrl + "?dialogType=valueMappingManager' class='datamanagementiframe' frameborder='no' border='0' style='width:100%;'></iframe>";
		DialogList["valueMappingManager"].window.setCloseCallback(checkForClose_ValueMappingManagerWin);
		DialogList["valueMappingManager"].window._center();
		DialogList["valueMappingManager"].window.show(true);
		EnterTrap = function(e) {
			return false;
		};
	}
}

function checkForClose_ValueMappingManagerWin() {
	EnterTrap = null;
	return true;
}

function onCancelValueMappingManager() {
	CloseDialog("valueMappingManager");
	cursor.reset();
}

var valueMapperDialogControl = Class.create();
valueMapperDialogControl.prototype = {
	valueMappingId: undefined,
	pageUrl: '/pages/nodeDialog.aspx?dialogType=valueMappingManager',
	baseUrl: '/pages/nodeDialog.aspx',
	valueMappingMatchStrategy: undefined,

	referencingReferenceStructureId: undefined,
	referencingItemTypeUri: undefined,
	referencingPredicateUri: undefined,

	referencedReferenceStructureId: undefined,
	referencedItemTypeUri: undefined,
	referencedLabelType: undefined,

	statusChecker: undefined,

	initialize: function()
	{

	},

	onChangeValueMappingDefinition: function(valueMappingId)
	{
		if (valueMappingId)
		{
			this.valueMappingId = valueMappingId;
			top.DialogList["valueMappingManager"].window.setURL(this.pageUrl + '&valueMappingId=' + this.valueMappingId);
		}
		else
		{
			top.DialogList["valueMappingManager"].window.setURL(this.pageUrl);
		}
	},

	onDeleteValueMappingDefinition: function()
	{
		var answer = confirm("Do you really want to delete this value mapping definition and all its matches?")
		if (answer)
		{
			this.updateWindow(this.pageUrl + '&valueMappingId=' + this.valueMappingId + '&action=delete');
		}
	},

	onClickReset: function()
	{
		this.updateWindow(this.pageUrl);
	},

	onSaveValueMappingDefinition: function(title)
	{
		if (title == '')
		{
			$('saveAsDialog_ValidationMessage').innerHTML = "&#160;title field is empty";
		}
		else
		{
			this.definitionTitle = title;
			this.valueMappingMatchStrategy = $('valueMappingMatchStrategy').getValue();
			this.referencedItemTypeUri = $('ddlReferencedItemType').getValue()
			this.referencedLabelType = $('referencedLabelType').getValue()

			var url = this.pageUrl + '&action=saveValueMappingDefinition&definitionName=' + this.definitionTitle + '&strategyName=exact&referencingReferenceStructureId=' + this.referencingReferenceStructureId + '&referencingItemTypeUri=' + encodeURIComponent(this.referencingItemTypeUri) + '&referencingPredicateUri=' + encodeURIComponent(this.referencingPredicateUri) + '&referencedReferenceStructureId=' + this.referencedReferenceStructureId + '&referencedItemTypeUri=' + encodeURIComponent(this.referencedItemTypeUri) + '&referencedLabelType=' + this.referencedLabelType;
			this.updateWindow(url);
		}
	},

	updateValueMappingDefinition: function(referencingReferenceStructureId, referencingItemTypeUri, referencingPredicateUri, referencedReferenceStructureId, referencedItemTypeUri, referencedLabelType)
	{
		if (referencingReferenceStructureId)
		{
			this.referencingReferenceStructureId = referencingReferenceStructureId;
		}
		if (referencingItemTypeUri)
		{
			this.referencingItemTypeUri = referencingItemTypeUri;
		}
		if (referencingPredicateUri)
		{
			this.referencingPredicateUri = referencingPredicateUri;
		}
		if (referencedReferenceStructureId)
		{
			this.referencedReferenceStructureId = referencedReferenceStructureId;
		}
		if (referencedItemTypeUri)
		{
			this.referencedItemTypeUri = referencedItemTypeUri;
		}
		if (referencedLabelType)
		{
			this.referencedLabelType = referencedLabelType;
		}

		if (referencedLabelType == undefined && referencedItemTypeUri == undefined && referencedReferenceStructureId != undefined && referencingPredicateUri != undefined && referencingItemTypeUri != undefined && referencingReferenceStructureId != undefined)
		{
			this.updateWindow(this.pageUrl + '&referencingReferenceStructureId=' + referencingReferenceStructureId + '&referencingItemTypeUri=' + referencingItemTypeUri + '&referencingPredicateUri=' + referencingPredicateUri + '&referencedReferenceStructureId=' + referencedReferenceStructureId);
		}
		else if (referencedLabelType == undefined && referencedItemTypeUri == undefined && referencedReferenceStructureId == undefined && referencingPredicateUri != undefined && referencingItemTypeUri != undefined && referencingReferenceStructureId != undefined)
		{
			this.updateWindow(this.pageUrl + '&referencingReferenceStructureId=' + referencingReferenceStructureId + '&referencingItemTypeUri=' + referencingItemTypeUri + '&referencingPredicateUri=' + referencingPredicateUri);
		}
		else if (referencedLabelType == undefined && referencedItemTypeUri == undefined && referencedReferenceStructureId == undefined && referencingPredicateUri == undefined && referencingItemTypeUri != undefined && referencingReferenceStructureId != undefined)
		{
			this.updateWindow(this.pageUrl + '&referencingReferenceStructureId=' + referencingReferenceStructureId + '&referencingItemTypeUri=' + referencingItemTypeUri);
		}
		else if (referencedLabelType == undefined && referencedItemTypeUri == undefined && referencedReferenceStructureId == undefined && referencingPredicateUri == undefined && referencingItemTypeUri == undefined && referencingReferenceStructureId != undefined)
		{
			this.updateWindow(this.pageUrl + '&referencingReferenceStructureId=' + referencingReferenceStructureId);
		}
	},

	onClickFindMatches: function(cmd)
	{
		this.updateValueMatchList('action=findMatches');
		this.updateValueMatchListperiodical();
	},

	checkStatusOfFindMatches: function()
	{
		var me = this;
		setTimeout(function(obj) { me.updateValueMatchList(); }, 2000);
	},

	updateWindow: function(url)
	{
		parent.parent.DialogList["valueMappingManager"].window.setURL(url);
	},

	updateValueMatchList: function(params)
	{
		defaultParams = 'dialogType=valueMappingManagerMatchList&valueMappingId=' + this.valueMappingId;
		if (params)
		{
			defaultParams += '&' + params;
		}
		new Ajax.Updater('LinkManager', this.baseUrl, { parameters: defaultParams, evalScripts: true });
	},

	updateValueMatchListperiodical: function(params)
	{
		defaultParams = 'dialogType=valueMappingManagerMatchList&valueMappingId=' + this.valueMappingId+'&action=refresh' + "&caller=valueMapperDialogControl.updateValueMatchListperiodical";

		if (params)
		{
			defaultParams += '&' + params;
		}
		
		var me = this;

		this.statusChecker = new Ajax.PeriodicalUpdater('LinkManager', this.baseUrl, {
			parameters: defaultParams,
			//frequency: 5,
			evalScripts: true,
			onFailure: function(e) { alert("Value mapper was stopped because of a server error."); },
			onException: function(e) { alert("Value mapper was stopped because of a server error."); }
		});
	},
	
	stopStatusChecker: function()
	{
		if (this.statusChecker)
		{
			this.statusChecker.stop();
		}
	}
}


var valueMapperMatchListControl = Class.create();
valueMapperMatchListControl.prototype = {
	children: null,
	pageSize: 1,
	pageNumber: 1,
	baseUrl: '/pages/nodeDialog.aspx',
	valueMappingId: undefined,
	statusChecker: undefined,

	initialize: function(valueMappingId, currentPageNumber)
	{
		this.children = $('scrollContainer');
		this.valueMappingId = valueMappingId;
		this.pageNumber = (currentPageNumber != undefined) ? currentPageNumber : 1;
		//if ($('pageSizeSelector')) { this.pageSize = $('pageSizeSelector').getValue(); }
		
		if (this.children != null)
		{
			this.children = $A(this.children.getElementsByTagName('INPUT'));
		}
	},

	toggleSelection: function()
	{
		if (this.children != null)
		{
			if ($('selectionToggleBox').checked)
			{
				for (var i = 0; i <= this.children.length - 1; i++)
				{
					if (this.children[i].type == "checkbox" && $(this.children[i].id).disabled == false)
					{
						$(this.children[i].id).checked = true;
					}
				}
			}
			else
			{
				for (var i = 0; i <= this.children.length - 1; i++)
				{
					if (this.children[i].type == "checkbox" && $(this.children[i].id).disabled == false)
					{
						$(this.children[i].id).checked = false;
					}
				}
			}
		}
	},

	onChangePageSize: function()
	{
		this.pageSize = $('pageSizeSelector').getValue();
		params = 'action=showList';
		this.updateValueMatchList(params);
	},

	setPageNumber: function(pageNumber)
	{
		if (pageNumber != this.pageNumber)
		{
			this.pageNumber = pageNumber;
			params = 'action=refresh&caller=setPageNumber';
			this.updateValueMatchList(params);
		}
	},

	onRefreshList: function()
	{
		this.updateValueMatchList('action=refresh&caller=onRefreshList');
	},

	onLinkAllMatches: function()
	{
		params = 'action=linkAllMatches';
		this.updateValueMatchList(params);
		//alert(this.pageNumber);
		dialogCntrl.updateValueMatchListperiodical('pageNumber=' + this.pageNumber + '&pageSize=' + this.pageSize);
		//this.updateValueMatchListperiodical();
		//this.startupStatusPanel();
	},

	onLinkSelectedMatches: function()
	{
		var params = 'action=linkSelectedMatches';

		for (var i = 0; i <= this.children.length - 1; i++)
		{
			if (this.children[i].checked)
			{
				params = params + '&valueMatchId=' + this.children[i].name
			}
		}
		this.updateValueMatchList(params);
		dialogCntrl.updateValueMatchListperiodical('pageNumber=' + this.pageNumber + '&pageSize=' + this.pageSize);
		//this.startupStatusPanel();
	},

//	startupStatusPanel: function()
//	{
//		var formData = '';
//		var me = this;
//		var statusPanelUrl = this.baseUrl + 'dialogType=valueMappingManagerMatchList&action=refresh&caller=startupStatusPanel&valueMappingId=' + this.valueMappingId;
//		this.statusChecker = new Ajax.PeriodicalUpdater('statusMessage', this.baseUrl, {
//			parameters: formData,
//			evalScripts: true,
//			onFailure: function(e) { alert("Value mapper was stopped because of a server error."); },
//			onException: function(e) { alert("Value mapper was stopped because of a server error."); }
//		});
//	},

	stopStatusPanel: function()
	{
		if (this.statusChecker)
		{
			this.statusChecker.stop();
		}
	},

	updateValueMatchList: function(params)
	{
		defaultParams = 'dialogType=valueMappingManagerMatchList&valueMappingId=' + this.valueMappingId + '&pageNumber=' + this.pageNumber + '&pageSize=' + this.pageSize;
		if (params)
		{
			defaultParams += '&' + params;
		}

		new Ajax.Updater('LinkManager', this.baseUrl, { parameters: defaultParams, evalScripts: true });
	},

	updateValueMatchListperiodical: function(params)
	{
		defaultParams = 'dialogType=valueMappingManagerMatchList&valueMappingId=' + this.valueMappingId + '&action=refresh&caller=valueMapperMatchListControl.updateValueMatchListperiodical&pageNumber=' + this.pageNumber + '&pageSize=' + this.pageSize;
		if (params)
		{
			defaultParams += '&' + params;
		}

		var me = this;

		this.StatusChecker = new Ajax.PeriodicalUpdater('LinkManager', this.baseUrl, {
			parameters: defaultParams,
			evalScripts: true,
			onFailure: function(e) { alert("Value mapper was stopped because of a server error."); },
			onException: function(e) { alert("Value mapper was stopped because of a server error."); }
		});
		this.StatusChecker.start();
	}
}

