/*
	Copyright (c) 2007 Galdos Systems, Inc. All Rights Reserved.

    You shall use this software only in accordance with the terms of the license  agreement you entered into with Galdos.

	GALDOS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT  OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.

*/

/*********************************************************
	file: client_controller.js
	author: Roger Lee
	desc: This javascript module contains all the system level
		events for interaction with the registry.  The content
		is business specific, but the interfaces most likely 
		can be reused in a framework.
***********************************************************/
// This method is needed at load time to see if a user is directly linking to a particular
// urn.  It detects the urn and attempts to load the entity.
function loadBookmark(){
	var val = "urn";
	var q  = unescape(document.location.search.substr(1)).split('&');
	
	var urn = ""
	for(var i=0; i<q.length; i++){
		var t=q[i].split('=');
		if(t[0].toLowerCase()==val.toLowerCase()) {
			urn = t[1];
			break;
		}
	}
	
	if (urn != "") {
		display_entity(null, urn, dojo.byId("entity_details"));
	}
};
		
var currentViewContext = null;
var currentEntityContextWidget = null;
var currentContext = null;
var accordionID = null;
var debugConsoleOn = false;

var groupFilterContentParams = null;
var urlReference = "";

var currentCR = null;

function init() {
	preferences = new ClientPreferences();
	ping();
	currentCR = "";
	//setup handlers for events
	queryStats = new ResultStats();
	queryParams = new TableListParams(
		dojo.byId("topPrevNextBar"),
		dojo.byId("bottomPrevNextBar"),
		dojo.byId("resultCount"),
		"loadLastQuery",
		queryStats
		);
	var search = dojo.widget.byId("byNameSearch");
	preferences.registerRoleListener(search);
	var retrieve = dojo.widget.byId("byIDSearch");
	preferences.registerRoleListener(retrieve);

	var admin = dojo.byId("admin_view");
	admin.style.display = "none";
	var queue = dojo.byId("queue_view");
	queue.style.display = "none";
	var details = dojo.byId("details_view");
	details.style.display = "none";
		
	dojo.undo.browser.setInitialState(new Checkpoint('show_title',null));
	
	var tab = dojo.widget.byId("byName");
	dojo.event.connect("before", tab, "show", 
		function() { dojo.widget.byId("byNameSearch").resetName(); });
				
	var tab = dojo.widget.byId("byID");
	dojo.event.connect("before", tab, "show", 
		function() { dojo.widget.byId("byIDSearch").resetID(); });
		
	dojo.io.bind({
		url: "user.htm?login_path" + "&random=" + genSeed(),
		method: "post",
		load: function(type, data, event) {
		              isErrorReceived(type,data);
			if (data.indexOf("https://") > -1) {
				preferences.sslLoginPath = data.replace(/(^\s*|\s*$)/g, "");
				dojo.debug("ssl login path: " + data.replace(/(^\s*|\s*$)/g, ""));
			}
		}
	});
	
	dojo.event.connect("after", dojo.widget.byId("splitDetails"), "endSizing", 
		function(e) {
			refreshContent();
		});
	dojo.event.connect("before", dojo.byId("bodyTag"), "onclick", closeHelp);
		
	var loadingDlg = dojo.widget.byId("waiting");
	loadingDlg.domNode.style.zIndex = 996;
	loadingDlg.shared.bg.zIndex = 995;
}

function refreshContent() {
	dojo.widget.byId("splitDetails").resizeSoon();
	if (accordionID != null) {
		dojo.widget.byId(accordionID).onResized();
	}
	dojo.byId("main_view").focus();
}

function genSeed() {
	return Math.floor(Math.random()*100000000001);
}

function postSystemMessage(message, type) {
	if (message.indexOf("Access is denied") != -1) {
		logout(this);
		message = "Your session has expired!";
	}
	
	if (type == "WARNING") 
		dojo.event.topic.publish("messageTopic", {message: message, type: "WARNING", delay: 1500});
	else if (type == "ERROR")
		dojo.event.topic.publish("messageTopic", {message: message, type: "ERROR", delay: 2000});
	else
		dojo.event.topic.publish("messageTopic", {message: message, type: "MESSAGE", delay: 1000});
}

function context_changed(event, /* id of entity to display */ urn,
					/* Calling widget */ source) {
	var url;
	if (event == "dojo") {
		url = "../../../entity.htm?display=metadata&urn=" + urn;
	}
	else {
		url = "entity.htm?display=metadata&urn=" + urn;
	}

	if (this.currentViewContext != "details"){
		this.swapView("details");
	}
		
	if (this.currentEntityContextWidget != null) {
		this.currentEntityContextWidget.loseContext();
		this.currentEntityContextWidget = source;
	}
		
	var target = dojo.html.getElementsByClass("metadata")[0];
	
	this.getReplacementContent(url, target, true);
	this.currentEntityContextWidget = source;
	this.currentContext = urn;
}

function display_entity(event, 
				/* id of entity to display */ urn, 
				/*target div to populate*/ target) {
				
	// adding a check to see if the entity is geoentity or user login
	if (urn.indexOf("urn:ogc:def:") > -1) {
		var next = queryStats.nextRecord()*1;
		if (next == 0)
			next = queryStats.maxResultSize()*1 - queryStats.getResultsCount()*1;
		else 
			next = queryStats.nextRecord()*1 - queryStats.getResultsCount()*1 ;
				
		var url = "entity.htm?display=entity&next=" + next + "&urn=" + urn;
		var checkpoint = new Checkpoint("display_entity",url);
		dojo.undo.browser.addToHistory(checkpoint);
		
		execute_display(url);		
	} else {
		user_dlg.showUser(urn);
	}
}

function execute_display(url) {
	if (this.currentViewContext != "details"){
		this.swapView("details");
		this.currentEntityContextWidget = null;
		this.currentContext = urn;
	}
	
	var details = dojo.html.getElementsByClass("entity_details")[0];
	this.getReplacementContent(url, details);
	var urn = url.substring(url.indexOf("urn=")+4);
	if (url.substring(0,2) == "..") {
		this.context_changed("dojo", urn, null);
	}
	else {
		this.context_changed(null, urn, null);
	}
	
	refreshContent();
}

function loadLastQuery(event, nextIndex) {
	if (nextIndex == null) {
		nextIndex = queryParams.stats.nextRecord();
	} else if (nextIndex == -1) {
		nextIndex = queryParams.stats.nextRecord() - queryParams.stats.getResultsCount();
	}
	this.make_query(event, preferences.lastQuery, nextIndex);
}

function showAdmin() {
	if (this.currentViewContext != "admin" ) {
		var checkpoint = new Checkpoint("show_admin",null);
		dojo.undo.browser.addToHistory(checkpoint);
		show_admin();
	}
}

function show_admin() {
	if (this.currentViewContext != "admin"  && preferences != null && 
		preferences.role() == 'RegistryAdministrator') {
		if (dojo.byId("uploadButton") == null) {
			lockTransport();
			dojo.io.bind({
				url: "view.htm?admin&random=" + genSeed(),
				method: "POST",
				error: function(type, error) {
					unlockTransport();
					isErrorReceived(type,error.message);
				},
				load: function(type, data, event) {
					unlockTransport();
					isErrorReceived(type,data);
					swapView("admin");
					currentEntityContextWidget = null;
					currentContext = null;

					dojo.byId("admin_view").innerHTML = data;
					var parser = new dojo.xml.Parse();
					var frag = parser.parseElement(dojo.byId("admin_view"), null, true);
					dojo.widget.getParser().createComponents(frag);
			
					var button = dojo.byId("uploadButton");
					button.onclick = function() {
						alert("The css file is being uploaded");
						var bindArgs = {
							formNode: dojo.byId("cssUploadForm"),
							mimetype: "text/html",
							load: function(type,data,evt) {
		                                         	var widget = dojo.widget.byId("cssList");
								widget.refresh();
								widget = dojo.widget.byId("reportWidget1");
								widget.refreshCSSList();
								widget = dojo.widget.byId("reportCRWidget1");
								widget.refreshCSSList();
							},
							error: function(type, error) {
		                                        	dojo.debug("Type:", type);
								dojo.debug("Response:", error.message);
							},
							method: "POST",
							multipart: true
						};
						dojo.io.bind(bindArgs);
					}
										
					button = dojo.byId("importButton");
					if (button != null) {
						button.onclick = function() {
							alert("The import file is being uploaded");
							var bindArgs = {
								formNode: dojo.byId("importGMLDictionary"),
								mimetype: "text/html",
								load: function(type,data,evt) {
									unlockTransport();
									var navToolbar = dojo.widget.byId("navToolbar");
									navToolbar.updateVersionNumber();	
									navToolbar.updateSyncList();
									alert("Registry updated");
								},
								error: function(type, error) {
									unlockTransport();
									dojo.debug("Type:", type);
									dojo.debug("Response:", error.message);
								},
								method: "POST",
								multipart: true
							};
							lockTransport();
							dojo.io.bind(bindArgs);
						}
					}
									
					button = dojo.byId("updateButton");
					if (button != null) {
						button.onclick = function() {
							alert("The synch archive file is being uploaded");
							var bindArgs = {
								formNode: dojo.byId("synchRegistry"),
								mimetype: "text/html",
								load: function(type,data,evt) {
									unlockTransport();
									var navToolbar = dojo.widget.byId("navToolbar");
									navToolbar.updateVersionNumber();	
									navToolbar.updateSyncList();
									alert("Registry Updated");
								},
								error: function(type, error) {
									unlockTransport();
									dojo.debug("Type:", type);
									dojo.debug("Response:", error.message);
								},
								method: "POST",
								multipart: true
							};
							lockTransport();
							dojo.io.bind(bindArgs);
						}
					}
					
					var tab = dojo.widget.byId("userManagement");
					dojo.event.connect("before", tab, "show", loadUsers);
				
					refreshContent();
					
					groupFilterStats = new ResultStats();
					groupFilterParams = new TableListParams(
						dojo.byId("gfTopPrevNextBar"),
						dojo.byId("gfBottomPrevNextBar"),
						dojo.byId("gfResultCount"),
						"loadLastBriefQuery",
						groupFilterStats
						);
						
					groupFilterContentStats = new ResultStats();
					groupFilterContentParams = new TableListParams(
						dojo.byId("gfContentTopPrevNextBar"),
						dojo.byId("gfContentBottomPrevNextBar"),
						dojo.byId("gfContentResultCount"),
						"loadLastBriefContentQuery",
						groupFilterContentStats
						);
						
					
					userStats = new ResultStats();
					userParams = new TableListParams(
						dojo.byId("userTopPrevNextBar"),
						dojo.byId("userBottomPrevNextBar"),
						dojo.byId("userResultCount"),
						"loadPrevUsers",
						userStats
						);
				}
			});
		} else {
			swapView("admin");
			dojo.widget.byId("gfWidget").cancel();
			loadUsers();
			currentEntityContextWidget = null;
			currentContext = null;
			
			refreshContent();
		}
	}
}

function make_query(event, queryUrl, nextIndex) {
	window.focus();
	
	var widget = dojo.widget.byId("reportWidget1");
	if (widget != null) {
		widget.reset();
	}
		
	dojo.byId("page_size").blur();
	preferences.lastQuery = queryUrl;
	if (nextIndex != null) queryUrl += "&next=" + nextIndex;
	var checkpoint = new Checkpoint("make_query", queryUrl);
	dojo.undo.browser.addToHistory(checkpoint);
	execute_query(event, queryUrl);
}

var gfQuery = function(event, url, nextIndex) {
	make_brief_query(event,url,nextIndex,"groupFilterSearch");
}

function make_brief_query(event, queryUrl, nextIndex, target, pagesize) {
	if (queryUrl.indexOf("brief") == -1) {
		queryUrl += "&brief";
	}

	if (target == "groupFilterContent") {
		preferences.lastFilterQuery = queryUrl;
		groupFilterContentParams.top.innerHTML = "";
		groupFilterContentParams.bottom.innerHTML = "";
		
		list_view = dojo.widget.byId("gfPalette").filterContentNode;
		groupFilterContentParams.stats.newResultSet();
		updateCountDisplay(groupFilterContentParams.stats, groupFilterContentParams.count);
	} else if (target == "groupFilterSearch") {
		preferences.lastQuery = queryUrl;
		groupFilterParams.top.innerHTML = "";
		groupFilterParams.bottom.innerHTML = "";
		
		list_view = dojo.widget.byId("gfPalette").searchResultNode;
		groupFilterParams.stats.newResultSet();
		updateCountDisplay(groupFilterParams.stats, groupFilterParams.count);
	}

	if (nextIndex != null) queryUrl += "&next=" + nextIndex;
	var list_view;
	
	//need to clear the list view
	var params = "";
	if (pagesize == null) {
		pagesize = 10;
	}
	params += "&pagesize=" + pagesize;

	getReplacementContent(queryUrl+params, list_view);
}

function loadLastBriefQuery(event, nextIndex) {
	if (nextIndex == null) {
		nextIndex = groupFilterParams.stats.nextRecord();
	}
	this.make_brief_query(event, preferences.lastQuery, nextIndex, "groupFilterSearch");
}

function loadLastBriefContentQuery(event, nextIndex) {
	if (nextIndex == null) {
		nextIndex = groupFilterContentParams.stats.nextRecord();
	}
	this.make_brief_query(event, preferences.lastFilterQuery, nextIndex, "groupFilterContent");
}

function execute_query(event, queryUrl) {
	//need to update view
	if (this.currentViewContext != "list"){
		this.swapView("list");
		this.currentEntityContextWidget = null;
		this.currentContext = null;
	}
	
	//need to clear the list view
	dojo.byId("topPrevNextBar").innerHTML = "";
	dojo.byId("bottomPrevNextBar").innerHTML = "";
	
	var pagesize = dojo.byId("page_size").options[dojo.byId("page_size").selectedIndex].text;
	var params = "";
	//params += "&pagesize=" + pagesize;
	params += "&pagesize=5";
	
	var list_view = dojo.byId("list");
	queryStats.newResultSet();
	updateCountDisplay(queryStats, dojo.byId("resultCount"));
	
	getReplacementContent(queryUrl+params, list_view, true);
}

var duringLogin = false;
function login(event, /*String*/ login, /*string*/ password, /*ssl auth path*/ path) {
	var urlTarget = preferences.sslLoginPath;
	window.location = urlTarget + "?index";
	//~ duringLogin = true;
	//~ loop = true;
	//~ try {
		//~ var bind = dojo.io.bind({
			//~ url: urlTarget,
			//~ content: {
				//~ "login" : login,
				//~ "password": password
			//~ },
			//~ load: function (type, data, event) {
				//~ dojo.debug("login recieved args: " + data);
				//~ polling.call(dojo.global());
			//~ },
			//~ error: function(type, error) {
				//~ postSystemMessage(error.message,"ERROR")
			//~ },
			//~ transport: "IframeTransport",
			//~ mimetype: "text/html"
		//~ }); 
	//~ } catch (ex) {
		//~ dojo.debug("login error: " + ex);
	//~ }
	//~ polling();
}

function update_user() {
	var urlTarget = preferences.sslLoginPath;
	window.location = urlTarget + "?update_user";
}

var pollCount = 0;
var pollMax = 20;
function polling() {
	
	ping();
	pollCount++;
	
	if (pollCount < pollMax) { 
		dojo.lang.setTimeout(dojo.global(), polling, 1000);
	} else {
		pollCount = 0;
		duringLogin = false;
		return;
	}
}

function ping() {

	var urlTarget = urlReference + "user.htm?ping=true&random=" + genSeed();
	dojo.debug("ping url:" + urlTarget);
	var bind = dojo.io.bind({
		url: urlTarget,
		error: function(type, error) {
		              isErrorReceived(type,error.message);
			postSystemMessage(error.message,"ERROR")
		},
		mimetype: "text/html"
	});
	dojo.event.connect(bind,"load","ping_load");
}

function ping_load(type, data, event) {
	try {
	
	               isErrorReceived(type,data);
		dojo.debug("ping recieved args: " + data.replace(/(^\s*|\s*$)/g, ""));
		var args = data.replace(/(^\s*|\s*$)/g, "").split(';');

		if (args[1] == 'true') {
			var widget = dojo.widget.byId('navToolbar');
			if (args[3] != "[]") {
				widget.updateMessage("Welcome " + args[2]);
				preferences.userName = args[2];
				widget.updateRole(args[3]);
				preferences.roleUpdated();
				pollCount = pollMax+1;
				duringLogin = false;
				postSystemMessage("You are logged in");
			} else {
				postSystemMessage("Account error. Cannot log in.");
			}
		}
		else if (args[1] == 'false') {
			if (pollCount == pollMax-1) {
				postSystemMessage("Sorry your credentials are invalid, try again","ERROR");
				getDialog('login');
				duringLogin = false;
			}
		}
		else
			alert("|" + args[1] + "|");
	}
	catch (ex) 
	{ 
		dojo.debug(ex);
	}
}

function logout(event) {
	try {
		var urlTarget = "user.htm?logout=true&seed=" + genSeed();
		
		dojo.io.bind({
			url: urlTarget,
			load: function(type, data, evt) { 
				//~ var widget = dojo.widget.byId('navToolbar');
				//~ widget.updateMessage("Goodbye");
				//~ widget.updateRole("RegistryGuest");
				//~ preferences.roleUpdated();
				window.location.reload();
				//postSystemMessage("You are logged out now","MESSAGE");
			},
			error: function(type, error) {
				//~ var widget = dojo.widget.byId('navToolbar');
				//~ widget.updateMessage("Goodbye");
				//~ widget.updateRole("RegistryGuest");
				//~ preferences.roleUpdated();
				window.location.reload();
				//postSystemMessage(error.message,"ERROR")
			},
			//transport: "IframeTransport",
			mimetype: "text/html"
		});
	
	//~ var checkpoint = new Checkpoint("show_title", null);
	//~ dojo.undo.browser.addToHistory(checkpoint);
	//~ show_title();
	} catch (ex) {
	}
}

function show_title() {
	swapView("intro");
}

function swapView(/*Context type*/ viewContext) {
	if (viewContext != this.currentViewContext) {
		cleanUpIds();
	
		var intro = dojo.byId("intro_view");
		intro.style.display = "none";
		var admin = dojo.byId("admin_view");
		admin.style.display = "none";
		var queue = dojo.byId("queue_view");
		queue.style.display = "none";
		var details = dojo.byId("details_view");
		details.style.display = "none";
		
		var target = dojo.byId("main_view");
		
		if (this.currentViewContext != null) {
			dojo.byId(this.currentViewContext + "_view").style.display = "none";
		}
		dojo.byId(viewContext + "_view").style.display = "block";
		
		this.currentViewContext = viewContext;
	}
}

// Asynchronous call to a content system (registry), this expects formated HTML
// in the XmlHTTPResponse
function getReplacementContent(/*target method url*/ urlTarget, 
					/* Target node for replacement */ targetNode, 
					/* show waiting animation */animDelay,
					/* flush cache */ flush,
					/*retrival args*/ args){
	// need to reset widgets such as the report widget
	// there is only one report widget instance so far
	//~ var reportWidget = dojo.widget.byId("reportWidget1");
	//~ if (reportWidget != null) {
		//~ reportWidget.reset();
	//~ }
	targetNode.style.visibility = "hidden";
	if (animDelay == true) {
		lockTransport();
	}
	
	dojo.io.bind({
		url: urlTarget + "&random=" + genSeed(),
		load: function(type, data, evt) { 
			unlockTransport();
			isErrorReceived(type,data);
			targetNode.innerHTML = data;
			var parser = new dojo.xml.Parse();
			var frag = parser.parseElement(targetNode, null, true);
			dojo.widget.getParser().createComponents(frag);
			
			targetNode.style.visibility = "visible";
			refreshContent();
		},
		error: function(type, error) {
			unlockTransport();
			isErrorReceived(type,error.message);
			postSystemMessage(error.message,"ERROR");
			targetNode.style.visibility = "visible";
		},
		method: "POST",
		mimetype: "text/html"
	// and many more options!
	});
}

function Checkpoint(method, arg) {
	this.methodName = method;
	this.arg = arg;
	this.changeUrl = false;
}

Checkpoint.prototype.back = function() {
	this.execute("back");
}

Checkpoint.prototype.forward = function() {
	this.execute("forward");
}

Checkpoint.prototype.execute = function(direction) {
	var path_prefix = "";
	try {
		var y=document.createElement('option');
		y.text='Kiwi';
		var x = dojo.byId("ietest_select");
		x.add(y,null);
		x.remove(0);
		path_prefix = "../../../";
	} catch (ex) {
		path_prefix = "";
	}
	
	if (this.methodName == "make_query") {
		closeAllDialogs();
		execute_query(this, path_prefix + this.arg);
	}
	else if (this.methodName == "display_entity") {
		closeAllDialogs();
		execute_display(path_prefix + this.arg);
		
	}
	else if (this.methodName == "show_title") {
		closeAllDialogs();
		show_title();
	}
	else if (this.methodName == "show_admin") {
		closeAllDialogs();
		show_admin();
	}
	else if (this.methodName == "show_queue") {
		closeAllDialogs();
		execute_queue_query(path_prefix + this.arg);
	}
	dojo.debug(direction + " executing:[" + this.methodName + "] with: " + this.arg);
}

function closeAllDialogs() {
	queueState.canLoadQueue = false;
	if (crPalette != null) {
		crPalette.cancel();
	}
	if (help_dlg != null) {
		help_dlg.cancel();
	}
	if (dojo.widget.byId("gfPalette") != null) {
		dojo.widget.byId("gfPalette").cancel();
	}
	cleanUpIds();
}

/*************** Start of Client preferences ************/

var preferences = null;

/* Cached query information to aid in usability */
function ClientPreferences() {
	this.userName = "";
	this._isHoverContextOn = true;
	this._viewDeprecated = false;
	this._navToolbar = dojo.widget.byId("navToolbar");
	this._roleListeners = [];
	this.lastQuery = "";
	this.lastFilterQuery = "";
	this.sslLoginPath= "";
	
	this.isHoverContextOn = function() {
		return this._isHoverContextOn;
	}
	
	this.setHoverContext = function(flag) {
		this._isHoverContextOn = flag;
	}
	
	this.canViewDeprecated = function() {
		return this._viewDeprecated;
	}
	
	this.setViewDeprecated = function(flag) {
		this._viewDeprecated = flag;
	}
	
	this.role = function() {
		return this._navToolbar.role;
	}
	
	this.registerRoleListener = function(widget) {
		this._roleListeners.push(widget);
	}
	
	this.roleUpdated = function() {
		dojo.debug("global role updated");
		for (var i=0; i<this._roleListeners.length; i++) {
			this._roleListeners[i].roleUpdated();
		}
	}
}

/*************** End of Client preferences **************/

function isErrorReceived(type,data) {
	if (help_dlg != null) {
		help_dlg.cancel();
	}
	
	if (debugConsoleOn) {
		if (data != null && typeof(data) == "string") {
			if (data.indexOf("Session has expired") > -1) {
				alert("Session has expired.  You will be logged off");
				window.location.reload();
				return true;
			} else if (data.indexOf("Registry is offline") > -1) {
				if (preferences.role() != "RegistryGuest") {
					alert("Registry is offline.  You will be logged off");
					var urlTarget = "user.htm?logout=true&seed=" + genSeed();
					dojo.io.bind({url: urlTarget});
					window.location.reload();
				}
				return true;
			} else if (data.indexOf("Error:") > -1) {
				dojo.debug("Error:" + data);
				if (data.indexOf("object") > -1) {
				} else if (crPalette != null && crPalette.isShowing()) {
					alert(data);
				} else {
					//postSystemMessage(data,"ERROR");
				}
				return true;
			}
		}
	}
	
	return false;
}

function exportDataset(type) {
	if (type == null) {
		type = "WithEPSG";
	}
	
	try {
		window.open("export.htm?contentType=" + type,'export dataset');
	} catch (ex) {
		window.open("export.htm?contentType=" + type);
	}
}


var loadingCount = 0;
function registerLoad() {
	loadingCount++;
	if (loadingCount == 1 && dlg != null)
		dlg.show();
}

function deregisterLoad() {
	loadingCount--;
	if (loadingCount <= 0  && dlg != null) {
		dlg.hide();
		loadingCount = 0;
	}
}

function lockTransport(/*boolean*/ showWait) {
	if (showWait == null) showWait = true;
	
	if (isTransportLocked == false) {
		if (help_dlg != null) {
			help_dlg.cancel();
		}
		
		isTransportLocked = true;
		if (showWait) {
			registerLoad();
		}
		return true;
	}
	return false;
}

var isTransportLocked = false;
function unlockTransport() {
	if (isTransportLocked == true) {
		deregisterLoad() ;
		isTransportLocked = false;
	}
}

function closeHelp() {
	if (help_dlg != null && help_dlg.cancellable()) {
		help_dlg.cancel();
	}
}

/*************** Comes from EntitySelectionWidget IE hack ******************/
function entitySelectionLoadLastQuery(widgetId, index) {
	var widget = dojo.widget.byId(widgetId);
	if (widget != null) {
		widget.loadLastQuery(null, index);
	}
}

/**************** Memory management clean up *******************************/
function cleanUpIds() {
	// we can remove all the content based ids because they only exist from one screen
	// to the next.
	var widgets = dojo.widget.manager.getAllWidgets();
	var index = widgets.length - 1;
	for (;index >= 0; index--) {
		var type = widgets[index].widgetType.toLowerCase();
		var id = widgets[index].widgetId.toLowerCase();
		if (id.indexOf("param") > -1) {
			widgets[index].destroy();
		} else if (id.indexOf("dontdestroy") > -1) {
		} else if (type.indexOf("component") > -1 ||
			//~ type.indexOf("accordion") > -1 ||
			//~ type.indexOf("input") > -1 ||
			//~ type.indexOf("form") > -1 ||
			//~ ((type.indexOf("input") > -1 || type.indexOf("form") > -1) 
				//~ && type.indexOf("css") == -1
				//~ && type.indexOf("wizard") == -1) ||
			//~ type.indexOf("comment") > -1 ||
			//~ type.indexOf("textbox") > -1) ||
			type.indexOf("sexagesimal") > -1) {
			widgets[index].destroy();
		}
	}
}

function cleanInactiveUsers() {
	lockTransport();
	dojo.io.bind({
		url: "user.htm?clean&random=" + genSeed(),
		load: function(type, data, evt) { 
			unlockTransport();
			isErrorReceived(type,data);
			loadUsers();
			var message = dojo.byId("usermanMessage");
			if (message != null) message.innerHTML = data;
		},
		error: function(type, error) {
			unlockTransport();
			isErrorReceived(type,error.message);
			var message = dojo.byId("usermanMessage");
			if (message != null) message.innerHTML = "";
		},
		method: "POST",
		mimetype: "text/html"
	});
}

/*****************************************************
Section for managing the dialogs.  This includes dialog retrieval
and dialog storage within hidden fields.  
******************************************************/
var loadedDialogList = [];
loadedDialogList.push('login');
loadedDialogList.push('registration');
	
function loadDialog(/*String*/ dialogName, 
			/*target container*/ container) {
			
	for (var i=0; i<this.loadedDialogList.length; i++) {
		if (this.loadedDialogList[i] == dialogName) {
			return 1;
		}
	}
	
	dojo.io.bind({
		url: "dialogFactory.htm?name=" + dialogName + "&random=" + genSeed(),
		load: function(type, data, evt) { 
		              isErrorReceived(type,data);
			container.innerHTML += data;
			var parser = new dojo.xml.Parse();
			var frag = parser.parseElement(container, null, true);
			dojo.widget.getParser().createComponents(frag);
		},
		error: function(type, error) {
		              isErrorReceived(type,error.message);
			alert(error.message);
		},
		mimetype: "text/html"
	// and many more options!
	});
	
	this.loadedDialogList.push(dialogName);
	
	//currently returning an artibratry value for the wait time, this should 
	// at least be set in a global variable
	return 500;
}

var retryCount = 0;
function getDialog(/*String*/ dialogName,/*event*/ event) {
	var container = dojo.byId("dialog_container");
	var waitTime = this.loadDialog(dialogName, container);

	setTimeout(function() {
		var widget = dojo.widget.byId(dialogName);
		if (widget){
			if (!widget.isShowing()) {
				widget.show(event);
			}
		}
		else {
			retryCount++;
			if (retryCount < 3) {
				getDialog(dialogName, event);
			}
			else {
				postSystemMessage("Login service is down try again later","ERROR");
			}
		}
	}, waitTime);
}

//should be moved to widget
function showStandardReports(event) {
	getDialog("standardreport",event);
}

/***************** end of dialog section *************/

/*************** Start of help dialogs ******************/

var help_blue = "#CCCCFF";
var help_green = "#CCFFCC";
var help_red = "#FFCCCC";
var help_white = "#FFFFFF";

/* For a list of keys refer to the WebApp layer constants.
    Specifically: com.galdosinc.egpd.common.ClientHelpKey and com.galdosinc.egpd.common.EntityHelpKey
*/
function viewHelp(source, key, color, mode) {
	
	if (mode == null) mode = "client";
	var urlTarget = "entity.htm?display=help&mode=" + mode + getKeyParams(key);
	// setting color to always white
	help_dlg.setColor(help_white);
	help_dlg.setSize(600);
	
	dojo.io.bind({
		url: urlTarget + "&random=" + genSeed(),
		load: function(type, data, evt) { 
			help_dlg.replaceContent(data);
			help_dlg.show(source);
		},
		error: function(type, error) {
		        isErrorReceived(type,error.message);
			//help_dlg.replaceContent(error.message);
		},
		mimetype: "text/html"
	// and many more options!
	});
}

function getKeyParams(key) {
	if (key instanceof Array) {
		var params = "";
		for (var i=0; i<key.length; i++) {
			params += "&key=" + key[i];
		}
		return params;
	} else {
		return "&key=" + key;
	}
}

function hideHelp() {
	help_dlg.hide();
}

function launchHelp() {
	var url = "help/index.html";
	window.open(url);
}

/*************** End of help dialogs ********************/

/**********************************************
Section pertaining to maintaining selection information.
For every row from a result set the widget is registered 
here so that it can be managed through events.
***********************************************/
var queryStats = null;
var queryParams = null;

/* Cached query information to aid in usability */
function ResultStats() {
	this.results = [];
	this._maxResultSize = 0;
	this._nextRecord = 0;
	this.pagesize = 5;
	this.widgetId = "this"; 
	this.listType = "";
	
	this.getResultsCount = function() {
		return this.results.length;
	}
	
	this.countNewResult = function(widget) {
		this.results.push(widget);
		this._nextRecord += 1;
		return this.results.length;
	}
	
	this.newResultSet = function () {
		this.results = [];
		this._nextRecord = 0;
		this._maxResultSize = 0;
		return this.results.length;
	}
	
	this.toggleSelection = function(checked) {
		if (checked) {
			for (var i=0; i<this.results.length; i++) {
				this.results[i].toggleSelected(null,checked);
			}
		}
		else {
			for (var i=0; i<this.results.length; i++) {
				this.results[i].toggleSelected(null,checked);
			}
		}
	}
	
	this.maxResultSize = function () {
		return this._maxResultSize;
	}
	
	this.setResultSetCount = function(count) {
		this._maxResultSize = count;
	}
	
	this.nextRecord = function() {
		return this._nextRecord;
	}
	
	this.setNextRecord = function(index) {
		this._nextRecord = index;
	}
	
	this.getSelected = function() {
		var list = [];
		for (var i=0; i<this.results.length; i++) {
			if (this.results[i].selected) {
				list.push(this.results[i]);
			}
		}
		return list;
	}
}

function TableListParams(topNode, bottomNode, countNode, prevMethodName, statsObj) {
	this.top = topNode;
	this.bottom = bottomNode;
	this.count = countNode;
	this.method = prevMethodName;
	this.stats = statsObj;
}

function registerResultTotal(count) {
	queryStats.setResultSetCount(count);
}

function registerNextRecord(index) {
	queryStats.setNextRecord(index);
	updateCountDisplay(queryStats, dojo.byId("resultCount"));
	updatePrevNext(queryStats,"loadLastQuery",
			dojo.byId("topPrevNextBar"),
			dojo.byId("bottomPrevNextBar"));
}

/* this method is used in ComponentPropertyGroup */
//~ function registerResult(result) {
	//~ queryStats.countNewResult(result);
	//~ updateCountDisplay(queryStats, dojo.byId("resultCount"));
	//~ return queryStats.getResultsCount();
//~ }

//~ function resultCount() {
	//~ return queryStats.getResultsCount();
//~ }

function updateCountDisplay(resultStats, target) {
	if (resultStats.maxResultSize() != 0) {
		if (resultStats.nextRecord() != 0) {
			var x = resultStats.nextRecord()*1 - resultStats.getResultsCount()*1;
			var y = resultStats.nextRecord()*1 - 1;
			target.innerHTML = "Search Results  (" + x + " - " + y + " of " +
				resultStats.maxResultSize() + " possible results)";
		} 
		else {
			var x = resultStats.maxResultSize()*1 - resultStats.getResultsCount()*1 + 1;
			target.innerHTML = "Search Results (" + x + " - " +
				resultStats.maxResultSize() + " of " +
				resultStats.maxResultSize() + " possible results)";
		}
	}
	else {
		target.innerHTML = "";
	}
}

function waitPrevNext(topBar, bottomBar) {
	while (topBar.hasChildNodes()) {
		topBar.removeChild(topBar.firstChild);
	}
	while (bottomBar.hasChildNodes()) {
		bottomBar.removeChild(bottomBar.firstChild);
	}

	topBar.appendChild(document.createTextNode("loading..."));
	bottomBar.appendChild(document.createTextNode("loading..."));
}

function updatePrevNext(resultStats, methodName, topBar, bottomBar) {
	while (topBar.hasChildNodes()) {
		topBar.removeChild(topBar.firstChild);
	}
	while (bottomBar.hasChildNodes()) {
		bottomBar.removeChild(bottomBar.firstChild);
	}
	
	var pagesize;
	try {
		pagesize = dojo.byId("page_size").options[dojo.byId("page_size").selectedIndex].text;
	} catch (e) {
		pagesize = resultStats.pagesize;
	}
	
	var interval = 10;
	try {
		if (resultStats.listType != "user") {
			interval = parseInt(pagesize);
		} else {
			interval = 10;
		}
	} catch (ex) {
	}
	
	var x = resultStats.nextRecord()*1 - resultStats.getResultsCount()*1;
	var y = resultStats.nextRecord()*1 - resultStats.getResultsCount()*1 - interval;
	if ( resultStats.nextRecord()*1 == 0 ){
		y = resultStats.maxResultSize()*1 + 1 - resultStats.getResultsCount()*1 - interval;
	}
	var z = resultStats.maxResultSize()*1 - resultStats.getResultsCount()*1
	if (resultStats.maxResultSize()*1 <= interval) {
		var prev = document.createElement("div");
		prev.style.display = "inline";
		prev.innerHTML = "&lt;&lt;prev";
		var next = document.createElement("div");
		next.style.display = "inline";
		next.innerHTML = "next&gt;&gt;";
		
		topBar.appendChild(prev.cloneNode(true));
		topBar.appendChild(document.createTextNode(" | "));
		topBar.appendChild(next.cloneNode(true));

		bottomBar.appendChild(prev);
		bottomBar.appendChild(document.createTextNode(" | "));
		bottomBar.appendChild(next);
	}
	else if (resultStats.nextRecord()*1 == 0 || 
		resultStats.nextRecord()*1 > resultStats.maxResultSize()*1) {
		var prev = document.createElement("a");
		if (y <= 0) {
			y = 1;
		}
		prev.href = "javascript:" + methodName + "(" + resultStats.widgetId + "," + y + ")";
		prev.innerHTML = "&lt;&lt;prev";
		var next = document.createElement("div");
		next.style.display = "inline";
		next.innerHTML = "next&gt;&gt;";
		
		topBar.appendChild(prev.cloneNode(true));
		topBar.appendChild(document.createTextNode(" | "));
		topBar.appendChild(next.cloneNode(true));

		bottomBar.appendChild(prev);
		bottomBar.appendChild(document.createTextNode(" | "));
		bottomBar.appendChild(next);
	}
	else if (resultStats.nextRecord()*1 != 0) {
		if (x == 1) {
			var prev = document.createElement("div");
			prev.style.display = "inline";
			prev.innerHTML = "&lt;&lt;prev";
			var next = document.createElement("a");
			next.href = "javascript:" + methodName + "(" + resultStats.widgetId + ")";
			next.innerHTML = "next&gt;&gt;";
			
			topBar.appendChild(prev.cloneNode(true));
			topBar.appendChild(document.createTextNode(" | "));
			topBar.appendChild(next.cloneNode(true));

			bottomBar.appendChild(prev);
			bottomBar.appendChild(document.createTextNode(" | "));
			bottomBar.appendChild(next);

		}
		else {
			var prev = document.createElement("a");
			if (y <= 0) {
				y = 1;
			}
			prev.href = "javascript:" + methodName + "(" + resultStats.widgetId + "," + y + ")";
			prev.innerHTML = "&lt;&lt;prev";
			var next = document.createElement("a");
			next.href = "javascript:" + methodName + "(" + resultStats.widgetId + ")";
			next.innerHTML = "next&gt;&gt;";

			topBar.appendChild(prev.cloneNode(true));
			topBar.appendChild(document.createTextNode(" | "));
			topBar.appendChild(next.cloneNode(true));

			bottomBar.appendChild(prev);
			bottomBar.appendChild(document.createTextNode(" | "));
			bottomBar.appendChild(next);
		}
	}
	else if (z > 0) {
		var next = document.createElement("div");
		next.style.display = "inline";
		next.innerHTML = "next&gt;&gt;";
		var prev = document.createElement("a");
		var nextIndex = z-interval+1;
		if (nextIndex <= 0) {
			nextIndex = 1;
		}
		prev.href = "javascript:" + methodName + "(" + resultStats.widgetId + "," + nextIndex + ")";
		prev.innerHTML = "prev";
						
		topBar.appendChild(prev.cloneNode(true));
		topBar.appendChild(document.createTextNode(" | "));
		topBar.appendChild(next.cloneNode(true));

		bottomBar.appendChild(prev);
		bottomBar.appendChild(document.createTextNode(" | "));
		bottomBar.appendChild(next);
	}
}

function notifySelectionWarning(/* queryStats */ stats, /*ComponentTable*/ widget) {
	if (stats != null) {
		var list = stats.getSelected();
		if (list.length > 0) {
			widget.showWarning();
		} else {
			widget.hideWarning();
		}
	}
}
/************* End of selection section *************/

var queueState = new QueueState();

function QueueState() {
	this.canLoadQueue = true;
	this.url = "";
	this.inLazyLoadSequence = false;
	this.resultCount = 0;
	this.interval = 2;
	this.container = null;
	
	this.getUrl = function() {
		return this.url + "&next=" + (this.resultCount+1) + "&interval=" + this.interval;
	};
};

function showQueue(filter_arg) {

	if (preferences.role() == "DataOwner" || 
		preferences.role() == "RegistryAdministrator") {
		dojo.html.replaceClass(dojo.byId("addCRLink"),'show','hide');		
	} else {
		dojo.html.replaceClass(dojo.byId("addCRLink"),'hide','show');	
	}

	if (dojo.byId("crPalette") == null) {
		dojo.byId("global_widget_container").innerHTML = 
			"<div dojoType=\"TreeLoadingController\" widgetId=\"treeController\" RPCUrl=\"local\"></div>" +
			"<div id=\"crPalette\" dojoType=\"galdos:ChangeRequestPaletteDialog\"></div>" + 
			"<div id=\"approvalDlg\" dojoType=\"galdos:ApproveChangeRequestDialog\"></div>";
		var parser = new dojo.xml.Parse();
		var frag = parser.parseElement(dojo.byId("global_widget_container"), null, true);
		dojo.widget.getParser().createComponents(frag);
		
		crPalette = dojo.widget.byId("crPalette");
		crTypeMenu = dojo.widget.byId("crTypesSelectionMenu");
		muTypeMenu = dojo.widget.byId("muTypesSelectionMenu");
		
		dojo.require("dojo.widget.TreeControllerExtension");
		dojo.lang.mixin(dojo.widget.byId('treeController'), 
			dojo.widget.TreeControllerExtension.prototype);
	}

	var filter = dojo.byId("cr_filter");
	var filterToApply = "outstanding";
	if (filter_arg != null && filter_arg != "load")
		filterToApply = filter_arg;
	else if (filter != null) {
		filterToApply = filter.options[filter.selectedIndex].text;
	}
	var url = "changerequest.htm?list=json&filter=" + filterToApply;
	queueState.url = url;
	queueState.resultCount = 0;
	queueState.container = null;
	queueState.interval = 5;
	
	execute_queue_query();
}

function execute_queue_query() {
	var url = queueState.getUrl();
	if (preferences != null && 
				(preferences.role() == 'Reviewer' || 
				preferences.role() == 'DataOwner' || 
				preferences.role() == 'RegistryAdministrator')) {

		if (currentViewContext != "queue"){
			swapView("queue");
			currentEntityContextWidget = null;
			currentContext = null;
			var checkpoint = new Checkpoint("show_queue",url);
			dojo.undo.browser.addToHistory(checkpoint);
		}
	
		var filterToApply = url.substring(url.indexOf("filter=")+7);
		//populateFilter(filterToApply);
		var list = dojo.byId("queue");
		getJSONContent(url,list,processJSONQueue);	
	}
}

function populateFilter(arg) {
	var filter = dojo.byId("cr_filter");
	var available_filters = ["outstanding", "owner of", "reviewer of", "work in progress","reviewing", "reviewed", "pre-release"];
	
	var length = filter.options.length
	for (var i=0; i < length; i++) {
		if (filter.options[i].text == arg) {
			filter.selectedIndex = i;
		}
	}
}

function getJSONContent(urlTarget, targetNode, callback) {
	//targetNode.style.visibility = "hidden";
	
	lockTransport(false);
	var bind = dojo.io.bind({
		url: urlTarget + "&random=" + genSeed(),
		error: function(type, error) {
			unlockTransport();
			isErrorReceived(type,error.message);
			postSystemMessage(error.message,"ERROR");
			targetNode.style.visibility = "visible";
		},
		method: "POST",
		mimetype: "text/html"
	// and many more options!
	});
	dojo.event.connect(bind,"load",callback);
}

function processJSONQueue(type, data, event) {
	unlockTransport();
	isErrorReceived(type,data);
	
	crList = dojo.json.evalJson(data);
	
	var target = dojo.byId("queue");
	processJSON(crList, target);
	//target.style.visibility = "visible";
	
	if (!dojo.lang.isArray(crList) || crList.length < queueState.interval) {
		queueState.inLazyLoadSequence = false;
	} else {
		if (queueState.canLoadQueue) {
		
			queueState.interval += 2;
			queueState.resultCount += crList.length;
			dojo.lang.setTimeout(dojo.global(), execute_queue_query, 100);
		}
	}
}

function processJSON(json, targetContainer) {
	if (!queueState.inLazyLoadSequence || queueState.container == null) {
		targetContainer.innerHTML = "";
		var widgetBProps = { "isContainer": true }
		queueState.container = dojo.widget.createWidget("dojo:HtmlWidget", widgetBProps, targetContainer);
	}
	
	if (json instanceof Array) {
		for (var i=0; i<json.length; i++) {
			var widget = buildJSON(json[i]);
			queueState.container.addWidgetAsDirectChild(widget);
                        queueState.container.registerChild(widget);
			queueState.inLazyLoadSequence = true;
		}
	} 
	else if (queueState.inLazyLoadSequence) {
	}
	else {
		var widget = buildJSON(json);
		queueState.container.addWidgetAsDirectChild(widget);
                queueState.container.registerChild(widget);
	}
}

function buildJSON(json) {
	var widgetBProps;
	if (json.widgetType == "galdos:ExpandableComponentTree") {
		var widget = dojo.widget.createWidget(json.widgetType, json.args);
		for (var i=0; i<json.container.length; i++) {
			var component = buildJSON(json.container[i]);
			widget.addWidgetAsDirectChild(component);
                        widget.registerChild(component);
		}
		return widget;
	}
	else if (json.widgetType == "galdos:ExpandableComponentJSONProxy") {
		var widget = dojo.widget.createWidget(json.widgetType, json.args);
		for (var i=0; i<json.container.length; i++) {
			var component = buildJSON(json.container[i]);
			widget.addWidgetAsDirectChild(component);
                        widget.registerChild(component);            
		}
		if(json.args.urn == this.currentCR){
		    widget.toggleExpansion();
		}
		return widget;
	}
	else if (json.widgetType == "galdos:ComponentProperty") {
		return dojo.widget.createWidget(json.widgetType, json.args);
	}
	else if (json.widgetType == "galdos:ComponentTable") {
		var widget = dojo.widget.createWidget(json.widgetType, json.args);
		for (var i=0; i<json.container.length; i++) {
			var row = buildJSON(json.container[i]);
			widget.addPropertyGroup(row);
		}
		return widget;
	}
	else if (json.widgetType == "galdos:ComponentPropertyGroup") {
		var widget = dojo.widget.createWidget(json.widgetType, json.args);
		for (var i=0; i<json.container.length; i++) {
			var property = buildJSON(json.container[i]);
			widget.addProperty(property);
		}
		widget.addMenu();
		return widget;
	}
	else {
		dojo.debug("json.widgetType");
	}
}

/*************** Start of Reports **********************/

function showCustomReport() {
	var reportWidget = dojo.widget.byId("reportWidget1");
	reportWidget.launch();
}

function cancelCustomReport() {
	var reportWidget = dojo.widget.byId("reportWidget1");
	reportWidget.reset();
}

function showCRReport() {
	var reportWidget = dojo.widget.byId("reportCRWidget1");
	reportWidget.launch();
}

function cancelCRReport() {
	var reportWidget = dojo.widget.byId("reportCRWidget1");
	reportWidget.reset();
}

/***************** End of Reports **********************/

/******  START OF REMOVE SECTION *********/
var typeMenu;
var crTypeMenu;
var muTypeMenu;
var exportMenu;

function testAroundPlace(e){
	typeMenu.aroundBox = "content-box";
	typeMenu.open(e.currentTarget, null, e.currentTarget);
}

function showExportOption(e){
	exportMenu.aroundBox = "content-box";
	exportMenu.open(e.currentTarget, null, e.currentTarget);
}

function crTestAroundPlace(e){
	crTypeMenu.aroundBox = "content-box";
	crTypeMenu.open(e.currentTarget, null, e.currentTarget);
}
	
function muTestAroundPlace(e){
	muTypeMenu.aroundBox = "content-box";
	muTypeMenu.open(e.currentTarget, null, e.currentTarget);
}
	
var typeSelect;
typeSelect = new TypeSelection("searchType");
		
var crTypeSelect;
crTypeSelect = new TypeSelection("crType");

var muTypeSelect;
muTypeSelect = new TypeSelection("muType");

/* Cached query information to aid in usability */
function TypeSelection(name) {
	this._name = name;
	this._selectedType = "";
	this._isTypeSearchOn = false;
	this._listeners = [];
	
	this.updateListeners = function() {
		for (i=0; i<this._listeners.length; i++) {
			this._listeners[i].typeSelected(this._selectedType);
		}
	}
	
	this.registerListener = function(listener) {
		this._listeners.push(listener);
	}
	
	this.isTypeSearchOn = function() {
		return this._isTypeSearchOn;
	}
	
	this.turnTypeSearchOff = function() {
		this._isTypeSearchOn = false;
		this._selectedType = "";
		this.updateListeners();
	}
	
	this.selectedType = function() {
		if (this.isTypeSearchOn == true) {
			return this._selectedType;
		}
		else
		{	
			return "any";
		}
	}
	
	this.reflectSelection = function(value) {
		this.isTypeSearchOn = true;
		this._selectedType = value;
		this.updateListeners();
	}
	
	this.reflectSelection = function(div) {
		this.isTypeSearchOn = true;
		this._selectedType = div.caption;
		this.updateListeners();
	}
}

/************** END OF REMOVE SECTION ***************/

var userStats = null;

function list_users(event, queryUrl, nextIndex) {
	//need to update view
	if (this.currentViewContext != "admin"){
		dojo.debug("list_users: not correct view in focus");
	}
		
	//need to clear the list view
	dojo.byId("userTopPrevNextBar").innerHTML = "";
	dojo.byId("userBottomPrevNextBar").innerHTML = "";

	var params = "";
	if (queryUrl.indexOf('?') == -1) {
		alert(queryUrl);
		params += "?";
	}
	if (nextIndex != null) params += "&next=" + nextIndex;
	params += "&interval=" + 10;
	
	var list_view = dojo.byId("userList");
	userStats.newResultSet();
	updateCountDisplay(userStats, dojo.byId("userResultCount"));
	this.getReplacementContent(queryUrl+params, list_view,true);
}

function loadPrevUsers(event, nextIndex) {
	var url = "user.htm?list";
	if (nextIndex == null) {
		nextIndex = userParams.stats.nextRecord();
	}else if (nextIndex == 1) {
		if (userParams.stats.nextRecord() == 0 ){
			nextIndex = userParams.stats.maxResultSize() + 1 - userParams.stats.getResultsCount() - 10;
		}		
	}
	this.list_users(event, url, nextIndex);
}

function loadNextUsers(event, nextIndex) {
	var url = "user.htm?list";
	this.list_users(event, url, nextIndex);
}

function loadUsers() {
	var message = dojo.byId("usermanMessage");
	if (message != null) message.innerHTML = "";
			
	var url = "user.htm?list";
	this.list_users(null, url, 1);
}

function roleChangeSelected(event) {
	alert(event.fromElement);
}

function cancel() {
	resetSystemWizard();
	crPalette.refresh();
}

function done() {
	help_dlg.cancel();
	if (wizardState.action == "new") {
		if (wizardState.entityType == "") {
			return;
		} else {
			crPalette.newEntity(wizardState.entityType);
		}
	}
	else if (wizardState.action == "clone") {
		if (wizardState.focusUrn == "") {
			return;
		} else {
			crPalette.clone(wizardState.focusUrn);
		}
	}
	else if (wizardState.action == "update") {
		if (wizardState.focusUrn == "") {
			return;
		} else {
			crPalette.minorUpdate(wizardState.focusUrn);
		}
	}
	else if (wizardState.action == "retire") {
		if (wizardState.focusUrn == "") {
			return;
		} else {
			crPalette.retire(wizardState.focusUrn);
		}
	}
	else if (wizardState.action == "deprecate") {
		if (wizardState.focusUrn == "") {
			return;
		} else {
			crPalette.deprecate(wizardState.focusUrn);
		}
	}
	else if (wizardState.action == "supersede") {
		if (wizardState.focusUrn == "") {
			return;
		} else {
			crPalette.supersede(wizardState.focusUrn);
		}
	}
	else {
		dojo.debug("wizard state not correct");
	}
	
dojo.debug("done: done");
	resetSystemWizard();
}

function resetSystemWizard() {
	help_dlg.cancel();
	var wizard = dojo.widget.byId("wizard1");
	wizard.reset();
	wizard.getPanels()[1].doneFunction = null;
	wizard.getPanels()[1].hideNext = false;
	wizard.getPanels()[1].reset();
	wizard.getPanels()[2].doneFunction = null;
	wizard.getPanels()[2].hideNext = false;
	//~ wizard.getPanels()[2].reset();
	wizardState.reset();
	crPalette.resetWizard();
	crPalette.wizardWidget.reset();
	crPalette.isLocked = false;
}

var wizardState = new WizardState();
function WizardState() {
	this.action = "";
	this.entityType = "";
	this.focusUrn = "";
	this.isInTargetCycle = false;
	this.isTargetNew = false;
	this.relationshipName = "";
	this.relationshipType = "";
	this.completeTheFormLock = false;
	
	this.lockOnForm = function() {
		this.completeTheFormLock = true;
	}
	
	this.isLockedOnForm = function() {
		return this.completeTheFormLock;
	}
	
	this.releaseLockOnForm = function() {
		this.completeTheFormLock = false;
	}
	
	this.setAction = function(action) {
		this.action = action;
	}
	
	this.setType = function(type) {
		this.entityType = type;
	}
	
	this.setUrn = function(urn) {
		this.focusUrn = urn;
	}
	
	this.addTarget = function() {
		var objectList = dojo.widget.byId("relationshipTargetList");
		objectList.addRow();
	}
	
	this.setTargetCycleFlag = function() {
		this.isInTargetCycle = true;
	}
	
	this.setTargetNew = function() {
		this.isTargetNew = true;
	}
	
	this.releaseTargetNew = function() {
		this.isTargetNew = false;
	}
	
	this.setRelationshipName = function(name) {
		this.relationshipName = name;
	}
	
	this.setRelationshipType = function(name) {
		this.relationshipType = name;
	}
	
	this.reset = function() {
		this.action="";
		this.entityType = "";
		this.focusUrn = "";
		this.isInTargetCycle = false;
		this.isTargetNew = false;
		this.relationshipName = "";
		this.relationshipType = "";
		this.completeTheFormLock = false;
		
	}
	
	this.printState = function() {
		dojo.debug("Wizard State: ");
		dojo.debug(this.action);	
		dojo.debug(this.entityType);
		dojo.debug(this.focusUrn);
		dojo.debug(this.isInTargetCycle);
		dojo.debug(this.isTargetNew);
		dojo.debug(this.relationshipName);
		dojo.debug(this.relationshipType);
	}
}

function actionStepCheckPass() {
	help_dlg.cancel();
	var form = dojo.byId("actionForm");
	var typeStepPane = dojo.widget.byId("typeStep");
	var entitySelectStepPane = dojo.widget.byId("entitySelectStep");
	
	if (form.elements[0].checked == true) {
		typeStepPane.doneFunction = done;
		typeStepPane.hideNext = true;
		crPalette.wizardWidget.setAuthorityControl("false");
		crPalette.wizardWidget.showStandardTypeList();
		wizardState.setAction(form.elements[0].value);
	}
	else if (form.elements[1].checked == true) {
		entitySelectStepPane.doneFunction = done;
		entitySelectStepPane.hideNext = true;
		crPalette.wizardWidget.setAuthorityControl("true");
		crPalette.wizardWidget.showStandardTypeList();
		wizardState.setAction(form.elements[1].value);
	}
	else if (form.elements[2].checked == true) {
		entitySelectStepPane.doneFunction = done;
		entitySelectStepPane.hideNext = true;
		crPalette.wizardWidget.setAuthorityControl("false");
		crPalette.wizardWidget.showMinorUpdateTypeList();
		wizardState.setAction(form.elements[2].value);
	}
	else if (form.elements[3].checked == true) {
		crPalette.wizardWidget.setAuthorityControl("false");
		crPalette.wizardWidget.showStandardTypeList();
		wizardState.setRelationshipName("deprecated-by");
		wizardState.setRelationshipType("deprecate");
		wizardState.setAction(form.elements[3].value);
	}
	else if (form.elements[4].checked == true) {
		crPalette.wizardWidget.setAuthorityControl("false");
		crPalette.wizardWidget.showStandardTypeList();
		wizardState.setRelationshipName("retired-by");
		wizardState.setRelationshipType("retire");
		wizardState.setAction(form.elements[4].value);
	}	
	else {
		return false;
	}
}

function jumpToRelationshipTarget(urn, type) {
	help_dlg.cancel();
	var form = dojo.byId("actionForm");
	var typeStepPane = dojo.widget.byId("typeStep");
	var entitySelectStepPane = dojo.widget.byId("entitySelectStep");
	
	if (type == "Deprecation") {
		crPalette.wizardWidget.setAuthorityControl("false");
		wizardState.setRelationshipName("deprecated-by");
		wizardState.setRelationshipType("deprecate");
		wizardState.setAction(form.elements[3].value);
		wizardState.setUrn(urn);
		switchPanel(3);
	}
	else if (type == "Retirement") {
		crPalette.wizardWidget.setAuthorityControl("false");
		wizardState.setRelationshipName("retired-by");
		wizardState.setRelationshipType("retire");
		wizardState.setAction(form.elements[4].value);
		wizardState.setUrn(urn);
		switchPanel(3);
	}	
	else {
		return false;
	}
}

function entityTypeCheckPass() {
	help_dlg.cancel();
	var wizard = dojo.widget.byId("wizard1");
	if (crPalette.wizardWidget.typeSelect.value == "") {
		return "Type cannot be empty";
	}
	else if (wizardState.isInTargetCycle == true 
		&& wizardState.isTargetNew == true) {
		crPalette.newEntity(wizardState.entityType);
		switchPanel(4);
		return true;
	}
	else {
	}
}


function entitySelectCheckPass() {
	dojo.debug("EntitySelectCheckpass called");
	help_dlg.cancel();
	var wizard = dojo.widget.byId("wizard1");
	dojo.debug("EntitySelectCheckpass: " + crPalette.wizardWidget.selectorInput.value);
	if (crPalette.wizardWidget.selectorInput.value == "") {
		return "You must select an entity first";
	}
	else if (wizardState.isInTargetCycle == true) {
		crPalette.wizardWidget.addTarget();
		crPalette.wizardWidget.reset();
		switchPanel(4);
		return true;
	}
	else {
	}
}

function addMoreCheckPass() {
	help_dlg.cancel();
	var form = dojo.byId("addTargetForm");
	
	if (wizardState.isLockedOnForm()) {
		alert("Form needs to be saved");
		return "Form needs to be saved";
	}
	
	var wizard = dojo.widget.byId("wizard1");
	if (form.elements[1].checked == true) {
		switchPanel(3);
		return true;
	}
	else {
	}
}

function relationshipCheckPass() {
	help_dlg.cancel();
	var form = dojo.byId("targetForm");
	var wizard = dojo.widget.byId("wizard1");
		
	wizardState.setTargetCycleFlag();
	if (form.elements[0].checked == true) {
		wizardState.setTargetNew();
		crPalette.clone(wizardState.focusUrn);
		wizardState.lockOnForm();
	}
	else if (form.elements[1].checked == true) {
		wizardState.setTargetNew();
		crPalette.newEntity(wizardState.entityType);
		wizardState.lockOnForm();
		switchPanel(4);
		return true;
	}
	else if (form.elements[2].checked == true) {
		crPalette.wizardWidget.updateEntityList(wizardState.entityType);
		switchPanel(2);
		return true;
	}
	else if (form.elements[3].checked == true) {
		switchPanel(4);
		return true;
	}
	else {
		return true;
	}
}

function switchPanel(index) {
	help_dlg.cancel();
	var wizard = dojo.widget.byId("wizard1");
	var size = wizard.getPanels().length;
	if (index < 0 || index >= size) 
		return;
	
	var target = wizard.getPanels()[index];
	wizard.selected.hide();
	target.show();
	wizard.selected = target;
	wizard.checkButtons();
}



function Sexagesimal(param, uom) {
	this.degree = "";
	this.minute = "";
	this.second = "";
	this.hemi = "";
	this.param = param;
	this.unit = uom;
	
	this.decode = function(value) {
		var uom = this.extractCode(this.unit);
		
		if (uom == "9110") {
			
			
			/* 9110 encoding as follows: <sign> DDD.MMSSsss*/

			/* Populate the minutes from the encoded decimal
			    Need to check that the minutes are valid, if the user
			    only specifies the minutes there will be no decimal.  
			    The minutes also <= 3 digits.
			    The minutes also have to be <180 if longitude
			    The minutes must be <90 if latitdue
			*/
			var index = value.indexOf(".");
			var remainder = "";
			if (index == -1) {
				//if (value.length > 3) {
				//	dojo.debug("value too long");
				//	return "";
				//}
				this.degree = parseInt(value,10);
			} else if (index > 4) {
				dojo.debug("degrees are too long");
				return "";
			} else {
				var index = value.indexOf(".");
				this.degree = parseInt(value.substring(0, index),10);
				remainder = value.substring(index+1);
			}
		
			/* Handle extraction of minutes.
			    Minutes can be empty
			    Minutes must be <60
			    Minutes can be specified by one digit and then should be
			      padded with a zero on the end.  ex. 123.4 should have minutes
			      of "40" not "4".
			*/
			if (remainder.length == 0) {
				this.minute = "";
			} else if (remainder.length == 1) {
				this.minute = parseInt(remainder + "0");
				remainder = remainder.substring(1);
			} else if (remainder.indexOf("0") == 0) {
				this.minute = parseInt(remainder.substring(1,2));
				remainder = remainder.substring(2);
			} else {
				this.minute = parseInt(remainder.substring(0,2));
				remainder = remainder.substring(2);
			}
			
			/* Handle extraction of seconds
			    Seconds can be empty
			    Seconds before the decimal must be < 60
			    Seconds after two digits must be followed by a decimal
			    Seconds can have unlimited precision after decimal
			*/
			if (remainder.length == 0) {
				this.second = "";
			} else if (remainder.length == 1) {
				this.second = parseInt(remainder + "0", 10);
			} else if (remainder.length == 2) {
				this.second = parseInt(remainder,10);
			} else if (remainder.length > 2) {
				var sec1 = remainder.substring(0,2);
				var sec2 = remainder.substring(2);
				this.second = parseFloat(sec1 + "." + sec2,10);
			}
						
			var type = this.paramType(this.param);
			if (type == "angle") {
				this.hemi = "";
			} else if (type == "latlong") {
				var latlong = this.latLong(this.param);
				if (latlong == "latitude") {
					if (this.degree*1 % 180 == 0 && this.minute == 0 && this.second == 0) {
					} else if (value.indexOf("-") == 0) {
						this.hemi = "S";
					} else if ((this.degree*1 == 0 || Math.abs(this.degree*1) == 180) &&
						(this.minute*1 != 0 || this.second*1 != 0)) {
						this.hemi = "N";
					} else if (this.degree*1 == 0 || Math.abs(this.degree*1) == 180) {
						this.hemi = "";
					} else if (this.degree > 0) {
						this.hemi = "N";
					} else if (this.degree < 0) {
						this.hemi = "S";
					} else {
						this.hemi = "";
					}
				} else if (latlong == "longitude") {
					if (this.degree*1 % 180 == 0 && this.minute == 0 && this.second == 0) {
					} else if (value.indexOf("-") == 0) {
						this.hemi = "W";
					} else if ((this.degree*1 == 0 || Math.abs(this.degree*1) == 180) &&
						(this.minute*1 != 0 || this.second*1 != 0)) {
						this.hemi = "E";
					} else if (this.degree*1 == 0 || Math.abs(this.degree*1) == 180) {
					} else if (this.degree > 0) {
						this.hemi = "E";
					} else if (this.degree < 0) {
						this.hemi = "W";
					} else {
						this.hemi = "";
					}
				}
				this.degree = Math.abs(this.degree);
			} 
		} else if (uom == "9102") {
			var index = value.indexOf(".");
			if (index != -1) {
				this.degree = value.substring(0,index);
				var mFloat = "0." + value.substring(index+1);
				var minutes = mFloat * 60;
				minutes = minutes.toString();
				index = minutes.indexOf(".");
				if (index != -1) {
					this.minute = minutes.substring(0,index);
					var sFloat = "0." + minutes.substring(index+1);
					this.second = (Math.round(sFloat * 60 *100000)/100000).toString();
				} else {
					this.minute = minutes;
					this.second = "";
				}
			} else {
				this.degree = value;
				this.minute = "";
				this.second = "";
			}
			
			var type = this.paramType(this.param);
			if (type == "angle") {
				this.hemi = "";
			} else if (type == "latlong") {
				var latlong = this.latLong(this.param);
				if (latlong == "latitude") {
					if (this.degree*1 % 180 == 0 && this.minute == 0 && this.second == 0) {
					} else if (value.indexOf("-") == 0) {
						this.hemi = "S";
					} else if ((this.degree*1 == 0 || Math.abs(this.degree*1) == 180) &&
						(this.minute*1 != 0 || this.second*1 != 0)) {
						this.hemi = "N";
					} else if (this.degree*1 == 0 ||  Math.abs(this.degree*1) == 180) {
						this.hemi = "";
					} else if (this.degree*1 > 0) {
						this.hemi = "N";
					} else if (this.degree*1 < 0) {
						this.hemi = "S";
					} else {
						this.hemi = "";
					}
				} else if (latlong == "longitude") {
					if (this.degree*1 % 180 == 0 && this.minute == 0 && this.second == 0) {
					} else if (value.indexOf("-") == 0) {
						this.hemi = "W";
					} else if ((this.degree*1 == 0 || Math.abs(this.degree*1) == 180) &&
						(this.minute*1 != 0 || this.second*1 != 0)) {
						this.hemi = "E";
					} else if (this.degree*1 == 0 || Math.abs(this.degree*1) == 180) {
						this.hemi = "";
					} else if (this.degree*1 > 0) {
						this.hemi = "E";
					} else if (this.degree*1 < 0) {
						this.hemi = "W";
					} else {
						this.hemi = "";
					}
				}
				this.degree = Math.abs(this.degree);
			} 
			//~ dojo.debug("ARG: " + this.degree + " " + this.minute + " " + this.second + " " + this.hemi);
		}
	}
	
	this.encode = function() {
		var uom = this.extractCode(this.unit);
		if (uom == "9110") {
			/* 9110 encoding as follows: <sign> DDD.MMSSsss*/
			var type = this.paramType(this.param);
			var latlong = this.latLong(this.param);
			var encoding = "";
			var seconds = this.second;
			if (type == "angle") {
				encoding = this.createEncodedString(this.degree,this.minute,this.second,false);
			} else if (type == "latlong") {
				if (this.hemi == "S" || this.hemi == "W") {
					encoding = "-" + this.createEncodedString(this.degree,this.minute,this.second,true);
				} else {
					encoding = this.createEncodedString(this.degree,this.minute,this.second,true);
				}
			} 
			return encoding;
		} else if (uom == "9102") {
			var type = this.paramType(this.param);
			var latlong = this.latLong(this.param);
			
			var encoding = "";
			encoding = this.degree*1.0 + (this.minute*1.0/(60*1.0)) + Math.round((this.second*1.0/(3600*1.0))*100000)/100000;
			return encoding;
		}
		return "";
	}
	
	this.createEncodedString = function(degrees, minutes, seconds, isAbsoluteValue) {
		var encodedString = "";
		if (isAbsoluteValue) {
			var tempDegree = Math.abs(parseInt(degrees,10));
			if (tempDegree.toString().length == 1) {
				encodedString += "00" + tempDegree;
			} else if (tempDegree.toString().length == 2) {
				encodedString += "0" + tempDegree;
			} else {
				encodedString += tempDegree;
			}
		} else {
			var tempDegree = parseInt(degrees,10);
			if (tempDegree >= 0) {
				if (tempDegree.toString().length == 1) {
					encodedString += "00" + tempDegree;
				} else if (tempDegree.toString().length == 2) {
					encodedString += "0" + tempDegree;
				} else {
					encodedString += tempDegree;
				}
			} else {
				tempDegree = Math.abs(tempDegree);
				if (tempDegree.toString().length == 1) {
					encodedString += "-00" + tempDegree;
				} else if (tempDegree.toString().length == 2) {
					encodedString += "-0" + tempDegree;
				} else {
					encodedString += "-" + tempDegree;
				}
			}
		}
		
		if (minutes != "") {
			encodedString += ".";
			var tempMin = minutes;
			if (tempMin.toString().length == 1) {
				encodedString += "0" + tempMin;
			} else if (tempMin.toString().indexOf("0") == 0) {
				encodedString += tempMin;
			} else {
				encodedString += parseInt(minutes,10);
			}
		} else {
			encodedString += ".";
			encodedString += "00";
		}

		if (seconds != "") {
			//ensure the units are in double format
			var floatSeconds = seconds;
			if (typeof(seconds) == 'string') {
				floatSeconds = parseFloat(seconds,10);
			}
				
			//round to 4 decimal places
			floatSeconds = Math.round(floatSeconds*100000)/100000;
			
			// convert double into string and remove period
			var collapsedSecondEncoding = "00";
			var tempSeconds = floatSeconds.toString();
			var index = tempSeconds.indexOf(".");
			if (index == 1) {
				collapsedSecondEncoding = "0" + tempSeconds.substring(0,index) + tempSeconds.substring(index+1);
			} else if (index == -1 && tempSeconds.length == 1) {
				collapsedSecondEncoding = "0" + tempSeconds;
			} else if (index == -1) {
				collapsedSecondEncoding = tempSeconds;
			} else {
				collapsedSecondEncoding = tempSeconds.substring(0,index) + tempSeconds.substring(index+1);
			}
			encodedString += collapsedSecondEncoding;
		} 
		return encodedString;
	}
	
	this.paramType =  function(parameter) {
		var param = this.extractCode(parameter);

		if (param == "8614" ||
			param == "8615" ||
			param == "8616" ||
			param == "8813" ||
			param == "8814" ||
			param == "8831"
		) {
			return "angle";
		} else if (param == "8601" ||
			param == "8602" ||
			param == "8617" ||
			param == "8618" ||
			param == "8619" ||
			param == "8620" ||
			param == "8621" ||
			param == "8622" ||
			param == "8801" ||
			param == "8811" ||
			param == "8802" ||
			param == "8812" ||
			param == "8818" ||
			param == "8821" ||
			param == "8822" ||
			param == "8823" ||
			param == "8824" ||
			param == "8828" ||
			param == "8829" ||
			param == "8830" ||
			param == "8832" ||
			param == "8833" ||
			param == "8834" ||
			param == "8835") {
			return "latlong";
		} else {
			return "value";
		}
	}
	
	this.latLong = function(parameter) {
		var param = this.extractCode(parameter);

		if (param == "8601" ||
			param == "8617" ||
			param == "8619" ||
			param == "8621" ||
			param == "8801" ||
			param == "8811" ||
			param == "8818" ||
			param == "8821" ||
			param == "8823" ||
			param == "8824" ||
			param == "8828" ||
			param == "8832" ||
			param == "8834") {
			return "latitude";	
		} else if (param == "8602" ||
			param == "8618" ||
			param == "8620" ||
			param == "8622" ||
			param == "8802" ||
			param == "8812" ||
			param == "8822" ||
			param == "8829" ||
			param == "8830" ||
			param == "8833" ||
			param == "8835") {  
			return "longitude";
		} else {
			return "";
		}
	}
	
	this.extractCode = function(urn) {
		var buffer = urn;
		while (buffer.indexOf(":") > -1) {
			var indexOfColon = buffer.indexOf(":");
			var buffer2 = buffer.substring(indexOfColon + 1);
			buffer = buffer2;
		}
		return buffer;
	}
	
	this.uomFormat = function() {
		var uom = this.extractCode(this.unit);
		
		if (uom == "9110") {
			return "FORMAT: DDD.MMSSsss";
		} else if (uom == "9102") {
			return "FORMAT: decimal value";
		}
		return "";
	}
	
	this.isSexagesimalUnit = function(uom) {
		var unit = this.extractCode(uom);
			
		//~ if (unit == "9102" ||
			//~ unit == "9107" ||
			//~ unit == "9108" ||
			//~ unit == "9110" ||
			//~ unit == "9111" ||
			//~ unit == "9115" ||
			//~ unit == "9116" ||
			//~ unit == "9117" ||
			//~ unit == "9118" ||
			//~ unit == "9119" ||
			//~ unit == "9120" ||
			//~ unit == "9121") {
			
		if (unit == "9102" ||
			unit == "9110") {
			return true;	
		} else {
			return false;
		}
	}
	
	this.print = function() {
		dojo.debug("degrees: " + this.degree);
		dojo.debug("minutes: " + this.minute);
		dojo.debug("seconds: " + this.second);
		dojo.debug("hemi: " + this.hemi);
	}
	
	this.display = function() {
		if (this.degree*1 == 0 || this.degree != null && this.degree != "") {
			var uom = this.extractCode(this.unit);
			
			/* minutes, seconds and hemisphere can be optional so do not display
				them if they are not present */
			if (uom == "9110" ||
				uom == "9102") {
				var displayString = this.degree + "&deg";
				if (typeof(this.minute) == "number" && this.minute == 0 && (this.second == 0 || this.second == "")) {
				} else if (typeof(this.minute) != "number" && (this.minute == "0" || this.minute == "00" || this.minute == "")) {
				} else if (typeof(this.minute) == "number" || this.minute != "") {
					displayString += "&nbsp;" + this.minute + "'";
				}
				if (typeof(this.second) == "number" || this.second != "") {
					displayString += "&nbsp;" + this.second + "\"";
				}
				if (this.hemi != "" && this.degree == 0 
					&& this.minute != 0 && this.minute != "" 
					&& this.second != 0 && this.second != "") {
					displayString += "&nbsp;" + this.hemi;
				} else if (this.hemi != "" && (this.degree != 0 || this.minute != "")) {
					displayString += "&nbsp;" + this.hemi;
				}
				return displayString;
			}
		}
		return "";
		
	}
};


function validateEntityForm(form) {
	var secondValidCheck = true;
	if (dojo.byId("entityActionField").value != "partial") {
		//These validations are additional restricts that are applied to various special case entity types.
	
		if (form.elements["entityType"].value == "Compound CRS" && 
			form.elements["component-reference-system"] != null) {
			if (form.elements["component-reference-system"].length >= 2 &&
				form.elements["component-reference-system"][0].value.length > 0 &&
				form.elements["component-reference-system"][1].value.length > 0) {
				secondValidCheck = true;
			}
			else {
				crPalette.formWidget.postMessage("Must have at least two component CRS'");
				secondValidCheck = false;
			}
		}
		
		if (form.elements["entityType"].value == "Concatenated Coordinate Operation" && 
			form.elements["coord-operation"] != null) {
			if (form.elements["coord-operation"].length >= 2) {
				secondValidCheck = true;
			}
			else {
				crPalette.formWidget.postMessage("Must have at least two component operations");
				secondValidCheck = false;
			}
		}
		
		if (form.elements["entityType"].value == "Ellipsoid") {
			var radios = form.elements["second_defining_param_type"];
			if (radios[2].checked == true) {
				profile = {
					required: [ 	"identifier", 
							"name",
							"semi-major-axis", 
							"semi-major-axis.uom",
							"second_defining_param_type"
						],
					constraints: {
					}
				};
			}
		}
	}
	//check if it is a partial	
	var profile = getProfile(form.elements["entityType"].value, form);
	if (form.elements["entityType"].value == null) {
		dojo.debug("validateEntityForm: Not valid form type");
		return false;
	}
	if (dojo.byId("entityActionField").value == "partial") {
		profile = getProfile("", form);
	}
	
	var results = dojo.validate.check(form, profile);
	
	var message = "";
	if (results.hasInvalid()) {
		message = "<h4>These fields are invalid:</h4><ul>";
		var list = results.getInvalid();
		for (var i=0; i<list.length; i++) {
			message += "<li>" + list[i] + "</li>";
		}
		message += "</ul>";
	}
	if (results.hasMissing()) {
		message = "<h4>These fields are missing:</h4><ul>";
		var list = results.getMissing();
		for (var i=0; i<list.length; i++) {
			message += "<li>" + list[i] + "</li>";
		}
		message += "</ul>";
	}
	
	if (message != "") {
		crPalette.formWidget.postMessage(message);
	}
		
        return(results.isSuccessful() && secondValidCheck); // return true if it passed the validation
                                        // if false, then the form will not be submitted
};

function getElement(form, name) {
	var elem = form[name];
	
	if (elem == null) {
		for (var x=0; x < form.elements.length; x++) {
			if (name == form.elements[x].name) {
				elem = form.elements[x];
			}
		}
	}
	return elem;
};

function getProfile(type, form) {

	var profile = {
		required: [ "identifier", "name" ],
		constraints: {
			//~ tx1: dojo.validate.isInteger,
			//~ tx2: dojo.validate.isInteger,
			//~ tx3: [dojo.validate.isValidDate, "MM/DD/YYYY"],
			//~ tx4: [dojo.validate.isValidDate, "YYYY.MM.DD"],
			//~ tx5: [dojo.validate.isEmailAddress],
			//~ tx6: [dojo.validate.isEmailAddress, {allowLocal: true}],
			//~ tx7: [dojo.validate.isEmailAddress, {allowCruft: true}],
			//~ tx8: dojo.validate.isURL,
			//~ tx12: [[dojo.validate.isRealNumber],[dojo.validate.isInRange, {max:100.00,min:5.0}]],
		}
	};
	
	if (type == "Projected CRS") {
		profile = {
			required: [ 	"identifier", 
					"name", 
					"domain-of-validity",
					"conversion",
					"cartesian-cs",
					"scope",
					"base-geodetic-crs",
					"epsg.type"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    scope: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}]
			}
		};
	} else if (type == "Geodetic CRS") {
		profile = {
			required: [ 	"identifier", 
					"name", 
					"epsg.type",
					"scope",
					"domain-of-validity",
					"coordinate-system",
					"geodetic-datum"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    scope: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}]
			}
		};
	} else if (type == "Vertical CRS") {
		profile = {
			required: [ 	"identifier", 
					"name", 
					"domain-of-validity",
					"scope",
					"vertical-cs",
					"vertical-datum"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    scope: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}]
			}
		};
	} else if (type == "Engineering CRS") {
		profile = {
			required: [ 	"identifier", 
					"name", 
					"domain-of-validity",
					"scope",
					"coordinate-system",
					"engineering-datum"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    scope: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}]
			}
		};
	} else if (type == "Compound CRS") {
		profile = {
			required: [ 	"identifier", 
					"name", 
					"domain-of-validity",
					"scope",
					"component-reference-system"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    scope: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}]
			}
		};
	} else if (type == "Coordinate Transformation") {
		profile = {
			required: [ 	"identifier", 
					"name", 
					"epsg.variant",
					"domain-of-validity", 
					"operation.version", 
					"scope",
					"_method",
					"source-crs", 
					"target-crs"
				],
			constraints: {
                name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    scope: [dojo.validate.isText, {maxlength: 254}],
                
                "parameter-value": [dojo.validate.isText, {maxlength: 254}],
                "operation.version": [dojo.validate.isText, {maxlength: 24}],
                
				"coordinate_operation_accuracy": dojo.validate.isRealNumber
			}
		};
	} else if (type == "Concatenated Coordinate Operation") {
		profile = {
			required: [ 	"identifier", 
					"name", 
					"epsg.variant",
					"source-crs", 
					"target-crs", 
					"scope",
					"domain-of-validity", 
					"coord-operation"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    scope: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}]
			}
		};
	} else if (type == "Coordinate Conversion") {
		profile = {
			required: [ 	"identifier", 
					"name", 
					"domain-of-validity",
					"scope",
					"_method"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    scope: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}]
			}
		};
	} else if (type == "Engineering Datum") {
		profile = {
			required: [ 	"identifier", 
					"name",
					"scope"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    scope: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}],
                
                "anchor-definition": [dojo.validate.isText, {maxlength: 254}], 
				realization_epoch: [dojo.validate.isValidDate, "YYYY-MM-DD"]
			}
		};
	} else if (type == "Vertical Datum") {
		profile = {
			required: [ 	"identifier", 
					"name",
					"scope"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    scope: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}],
                
                "anchor-definition": [dojo.validate.isText, {maxlength: 254}], 
				realization_epoch: [dojo.validate.isValidDate, "YYYY-MM-DD"]
			}
		};
	} else if (type == "Geodetic Datum") {
		profile = {
			required: [ 	"identifier", 
					"name",
					"scope",
					"prime-meridian", 
					"ellipsoid"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    scope: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}],
                
                "anchor-definition": [dojo.validate.isText, {maxlength: 254}],                
				realization_epoch: [dojo.validate.isValidDate, "YYYY-MM-DD"]
			}
		};
	} else if (type == "Prime Meridian") {
		profile = {
			required: [ 	
					"greenwich-longitude.uom",
					"greenwich-longitude",
					"identifier", 
					"name"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}]
			}
		};
	} else if (type == "Ellipsoid") {
		profile = {
			required: [ 	"identifier", 
					"name",
					"semi-major-axis", 
					"semi-major-axis.uom",
					"second_defining_param_type",
					"second_defining_param"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}]
			}
		};
	} else if (type == "Coordinate Operation Method") {
		profile = {
			required: [ 	"identifier", 
					"name", 
					"is_operation_reversible",
					"method-formula"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}],
                
                example: [dojo.validate.isText, {maxlength: 4000}],
                "method-formula": [dojo.validate.isText, {maxlength: 4000}],
                
				is_operation_reversible: dojo.validate.isBoolean
			}
		};
	} else if (type == "Coordinate Operation Parameter") {
		profile = {
			required: [ 	"identifier", 
					"name"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}]
			}
		};
	} else if (type == "Cartesian CS") {
		profile = {
			required: [ 	"identifier", 
					"name",
					"axis.description-reference",
					"axis.axis-abbrev",
					"axis.axis-direction",
					"axis.uom"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 254}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}],
                
                "axis.axis-abbrev": [dojo.validate.isText, {maxlength: 24}],
                "axis.axis-direction": [dojo.validate.isText, {maxlength: 24}]
			}
		};
	} else if (type == "Ellipsoidal CS") {
		profile = {
			required: [ 	"identifier", 
					"name",
					"axis.description-reference",
					"axis.axis-abbrev",
					"axis.axis-direction",
					"axis.uom"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 254}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}],
                
                "axis.axis-abbrev": [dojo.validate.isText, {maxlength: 24}],
                "axis.axis-direction": [dojo.validate.isText, {maxlength: 24}]
			}
		};
	} else if (type == "Vertical CS") {
		profile = {
			required: [ 	"identifier", 
					"name",
					"axis.description-reference",
					"axis.axis-abbrev",
					"axis.axis-direction",
					"axis.uom"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 254}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}],
                
                "axis.axis-abbrev": [dojo.validate.isText, {maxlength: 24}],
                "axis.axis-direction": [dojo.validate.isText, {maxlength: 24}]
			}
		};
	} else if (type == "Linear CS") {
		profile = {
			required: [ 	"identifier", 
					"name",
					"axis.description-reference",
					"axis.axis-abbrev",
					"axis.axis-direction",
					"axis.uom"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 254}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}],
                
                "axis.axis-abbrev": [dojo.validate.isText, {maxlength: 24}],
                "axis.axis-direction": [dojo.validate.isText, {maxlength: 24}]
			}
		};
	} else if (type == "Spherical CS") {
		profile = {
			required: [ 	"identifier", 
					"name",
					"axis.description-reference",
					"axis.axis-abbrev",
					"axis.axis-direction",
					"axis.uom"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 254}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}],
                
                "axis.axis-abbrev": [dojo.validate.isText, {maxlength: 24}],
                "axis.axis-direction": [dojo.validate.isText, {maxlength: 24}]			
			}
		};
	} else if (type == "Polar CS") {
		profile = {
			required: [ 	"identifier", 
					"name",
					"axis.description-reference",
					"axis.axis-abbrev",
					"axis.axis-direction",
					"axis.uom"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 254}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}],
                
                "axis.axis-abbrev": [dojo.validate.isText, {maxlength: 24}],
                "axis.axis-direction": [dojo.validate.isText, {maxlength: 24}]		
			}
		};
	} else if (type == "Cylindrical CS") {
		profile = {
			required: [ 	"identifier", 
					"name",
					"axis.description-reference",
					"axis.axis-abbrev",
					"axis.axis-direction",
					"axis.uom"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 254}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}],
                
                "axis.axis-abbrev": [dojo.validate.isText, {maxlength: 24}],
                "axis.axis-direction": [dojo.validate.isText, {maxlength: 24}]			
			}
		};
	} else if (type == "Affine CS") {
		profile = {
			required: [ 	"identifier", 
					"name",
					"axis.description-reference",
					"axis.axis-abbrev",
					"axis.axis-direction",
					"axis.uom"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 254}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}],
                
                "axis.axis-abbrev": [dojo.validate.isText, {maxlength: 24}],
                "axis.axis-direction": [dojo.validate.isText, {maxlength: 24}]
			}
		};
	} else if (type == "Change Request") {
		profile = {
			required: [ 	"identifier", 
					"name", 
					"report-date",
					"request",
					"reporter"
				],
			constraints: {
         "_action": [dojo.validate.isText, {maxlength: 4000}],		
         request: [dojo.validate.isText, {maxlength: 254}],
         reporter: [dojo.validate.isText, {maxlength: 254}],
         "codes-affected": [dojo.validate.isText, {maxlength: 254}],
         "tables-affected": [dojo.validate.isText, {maxlength: 254}],
         remarks: [dojo.validate.isText, {maxlength: 254}]
			}
		};
		
	} else if (type == "Area of Use") {
		profile = {
			required: [ 	"identifier", 
					"name", 
					"west_bound_longitude",
					"east_bound_longitude",
					"south_bound_latitude",
					"north_bound_latitude",
					"ex_extent.description"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}],
                
                "ex_extent.description": [dojo.validate.isText, {maxlength: 4000}],
                "iso-a2-country-code": [dojo.validate.isText, {maxlength: 2}],
                "iso-a3-country-code": [dojo.validate.isText, {maxlength: 3}],
                
				west_bound_longitude: dojo.validate.isRealNumber,
				east_bound_longitude: dojo.validate.isRealNumber,
				south_bound_latitude: dojo.validate.isRealNumber,
				north_bound_latitude: dojo.validate.isRealNumber
			}
		};
	} else if (type == "Axis Name") {
		profile = {
			required: [ 	"identifier", 
					"name"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}]
			}
		};
	} else if (type == "Naming System") {
		profile = {
			required: [ 	"identifier", 
					"name"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}]
			}
		};
	}  else if (type == "Base Unit") {
		profile = {
			required: [ 	"identifier", 
					"name",
					"units-system"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}]
			}
		};
	}  else if (type == "Derived Unit") {
		profile = {
			required: [ 	"identifier", 
					"name",
					"derivation-unit-term.uom",
					"derivation-unit-term.uom.exponent"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}]
			}
		};
	}  else if (type == "Conventional Unit") {
		profile = {
			required: [ 	"identifier", 
					"name",
					"conversion-to-preferred-unit.formula.b",
					"conversion-to-preferred-unit.formula.c",
					"conversion-to-preferred-unit.uom"
				],
			constraints: {
			    name: [dojo.validate.isText, {maxlength: 80}],			    
			    remarks: [dojo.validate.isText, {maxlength: 254}],
			    "epsg.information-source": [dojo.validate.isText, {maxlength: 254}]
			}
		};
	} 
	return profile;
};

function entitySelectionLoadLastQuery(widgetId, index) {
	var widget = dojo.widget.byId(widgetId);
	if (widget != null) {
		widget.loadLastQuery(null, index);
	}
};


function validateRegistrationForm(form) {
	var profile = null;
	if (form.elements['formType'].value == "normal") {
		profile = {
			required: [ "username", "password1","password2", "email", "phone", "contactName" ],
			constraints: {
			}
		};
	} else {
		if (form.elements['password1'].value.length == 0 && form.elements['password1'].value.length == 0) {
			profile = {
				required: [ "username", "email", "phone", "contactName" ],
				constraints: {
				}
			};
		} else {
			profile = {
				required: [ "username", "password1","password2", "email", "phone", "contactName" ],
				constraints: {
				}
			};
		}
	}

        var results = dojo.validate.check(form, profile);

	if (results.hasInvalid()) {
		dojo.widget.byId("registration").postMessage("Required: " + results.getInvalid());
	}
	if (results.hasMissing()) {
		dojo.widget.byId("registration").postMessage("Missing: " + results.getMissing());
	}
	
        return(results.isSuccessful()); // return true if it passed the validation
                                        // if false, then the form will not be submitted
};



