function trim(str) {
	return str.replace(/^\s + |\s + $/g, "");
}


/**
 * Displays the treeview for Nesstar categories tree
 * @param browse_key French or English phrase to browse ODESI/CORA
 * @param posDiv div id on the display page for the treeview
 * @return Treeview of ODESI Nesstar categories
 */
function displayNesstarTree(browse_key, posDiv, lang){
	var tree, currentIconMode;
	var nesstar_uri = "http://142.150.190.11/obj/fCatalog/Catalog609@children";
	var cora_uri = "http://130.15.161.127:82/obj/fCatalog/CORA@children";
	

	Treeview = (function () {

		//load alphabet nodes
		function loadCategories(node, fnLoadComplete){
			var nodeLabel = node.label;
			var nodeData = node.data.customData;
			var nodeID = node.data.customID;
			
			var vUrl = "/nesstar-details.xqy?uri=" + node.data.customData;
			var callback = {

				success: function (oResponse) {
					
					var data = [];       
					var oResults = oResponse.responseText;
					
					var split_Result = oResults.split("|"); //Split each catalog
						
					for (var i = 0, len = split_Result.length - 1; i < len; ++i){
	
						var m = split_Result[i];
						
						var nodeInfo = m.split("-->"); //Split each catalog's name and url
						var survey = nodeInfo[1].split("=");

						//Survey nodes or No entry nodes
						if (nodeInfo[1].match("/details/view.html")!= null || nodeInfo[0].match("No entries found.")!= null) {
							nodeInfo[0] = nodeInfo[0] + 
											"&nbsp;&nbsp;<br/><a class='notips' href='" + 
											"" + nodeInfo[1] + "'>View Survey</a> | " +
											"<a href=javascript:MarkedRecords.toggleMark('" + survey[1] + "','" + lang + "')>Add to My List</a>" + "<br/><br/>";
							var tmpNode = new YAHOO.widget.TextNode({label: nodeInfo[0], customData: nodeInfo[1]}, node, false);
							tmpNode.isLeaf = true;
							tmpNode.labelStyle = "ygtvlabel2";
							
						}
						else  { //Category nodes
							var tmpNode = new YAHOO.widget.TextNode({label: nodeInfo[0], customData: nodeInfo[1]}, node, false);
							tmpNode.title = "Click to Expand";
							tmpNode.labelStyle = "notips"; //notips to override default behaviour by yui tooltip
						}
						

					}
	
					oResponse.argument.fnLoadComplete();
				},

				failure: function (oResponse) 
				{
					YAHOO.log("Failed to process XHR transaction.", "info", "example");
					oResponse.argument.fnLoadComplete();
				},
	
				argument: {
					"node" : node,
					"fnLoadComplete" : fnLoadComplete
				},
	
				timeout: 7000
			};
			
			YAHOO.util.Connect.asyncRequest('GET', vUrl, callback);
		
		}

		//Function creates the tree
		function buildTree() {
			
			//instantiate the tree:
			tree = new YAHOO.widget.TreeView(posDiv);
			
			tree.setDynamicLoad(loadCategories, currentIconMode); 
			
			var root = tree.getRoot();
			
			
			if (trim(browse_key).length > 0){
				temp = browse_key.split("|");

				for (i = 0; i < temp.length-1; i++){
					label = temp[i];
					uri = nesstar_uri;
					
					var tmpNode = new YAHOO.widget.TextNode({
						label: trim(label), customData: uri, customID: trim(label)
					}, root, false);
					
					tmpNode.title = "Click to Expand";
					tmpNode.labelStyle = "notips";
					
				}
			}
			else {
			}
		

			   
			//The tree is not created in the DOM until this method is called:
			tree.draw();
		}

		return {
			init: function () {
			currentIconMode = 0;
			buildTree();
		}
		}

	})();

	YAHOO.util.Event.onDOMReady(Treeview.init, Treeview, true)
}



/**
 * Displays treeview for browsing keywords, series & survey title names
 * @param browse_key This specifies which element to browse - Keyword/series/title
 * @param posDiv Div tag where the treeview will be displayed
 * @return Treeview display to browse
 */
function displayBrowseTree(browse_key, posDiv){
	var tree, currentIconMode;

	Treeview = (function () {

		function loadNodeDetails(node, fnLoadComplete){
			var nodeLabel = node.label;
			var nodeData = node.data.customData;
			var nodeID = node.data.customID;
			var mode;
			
			if (nodeData.match("serName") != null)
				mode = "serName";
			else if (nodeData.match("Keyword") != null)
				mode = "keyword";
			else 
				mode = "titl";

			
			var sUrl = "/browse/browse-tree-details.html?label=" + nodeLabel + "&mode=" + mode; 

			var callback = {

				success: function (oResponse) {
					var data = [];                                                                 
					var oResults = oResponse.responseText;   
					var split_Result = oResults.split("|");
	
					for (var i = 0, len = split_Result.length - 1; i < len; ++i){
	
						var m = split_Result[i];
						
						var tmpNode = new YAHOO.widget.TextNode({label: m, customData: m  }, node, false);
						
						if (mode.match("keyword") != null){
							tmpNode.href = "/search/search.html?q="+ m + "&field=KW&coll=all";
							tmpNode.title = "Click to search keyword";
							tmpNode.labelStyle = "notips";
						}
						else if (mode.match("serName") != null) {
							tmpNode.href = "/search/search.html?q=" + m + "&field=SE&coll=all";
							tmpNode.title = "Click to search series";
							tmpNode.labelStyle = "notips";
						}
						else {
							tmpNode.href = "/search/search.html?q=" + m + "&field=TI&coll=all";
							tmpNode.title = "Click to search titles";	
							tmpNode.labelStyle = "notips";
						}
					}
	
					oResponse.argument.fnLoadComplete();
				},

				failure: function (oResponse) 
				{
					YAHOO.log("Failed to process XHR transaction.", "info", "example");
					oResponse.argument.fnLoadComplete();
				},
	
				argument: {
					"node" : node,
					"fnLoadComplete" : fnLoadComplete
				},
	
				timeout: 7000
			};
			

			YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
		}

		//load alphabet nodes
		function loadAlphaNodes(node){
			var nodeLabel = node.label;
			var nodeData = node.data.customData;
			var nodeID = node.data.customID;
			
			
			//alphabet
			for ( var i = 1; i < 27 ; i++ ) { 
                var tmpNode = new YAHOO.widget.TextNode({label: String.fromCharCode(i+64), customData: nodeData}, node, false); 
                tmpNode.setDynamicLoad(loadNodeDetails, currentIconMode);
                tmpNode.title = "Click to Expand";
                tmpNode.labelStyle = "notips";
                
                tmpNode.subscribe("expand", function(node) {
                    node.labelStyle = "node-selected";
                    tree.draw();
                  });
                tmpNode.subscribe("collapse", function(node) {
                    node.labelStyle = "node-deselected";
                    alert("in collapse");
                    tree.draw();
                  });
            } 
			
            

		}

		//Function creates the tree
		function buildTree() {
			
			//instantiate the tree:
			tree = new YAHOO.widget.TreeView(posDiv);
			var root = tree.getRoot();
		
			if (trim(browse_key).length > 0){
				temp = browse_key.split("|");

				for (i = 0; i < temp.length-1; i++){
					label = temp[i].split("-");
							
					if (label[0].match("Series") != null)
						bmode = "serName";
					else if (label[0].match("Keyword") != null)
						bmode = "Keyword";
					else {
						bmode = "titl";
					}
	
					var tmpNode = new YAHOO.widget.TextNode({
						label: trim(label[1]), customData: bmode, customID: trim(label[0])
					}, root, false);
					
					tmpNode.title = "Click to Expand";
					tmpNode.labelStyle = "notips";
					
					loadAlphaNodes(tmpNode);
				}
			}
			else {
			}
			
			
			//The tree is not created in the DOM until this method is called:
			tree.draw();
		}

		return {
			init: function () {
			currentIconMode = 0;
			buildTree();
			}
		}

	})();

	YAHOO.util.Event.onDOMReady(Treeview.init, Treeview, true)
}


/* Treeview for all variables
 * parameters: URI to document, variable list, URI for each variable, div tag to display tree
 */
function displayVars(uri, var_list, var_uri_list, position){

	var tree, currentIconMode;

	Treeview = (function () {

		function loadNodeDetails(node, fnLoadComplete){
			var nodeLabel = node.label;
			var nodeData = node.data.customData;
			var nodeID = node.data.customID;
			
			var sUrl = "/browse/variable-details.html?uri=" + node.data.customData + "&varid=" + nodeID;

			var callback = {

				success: function (oResponse) {

					var data = [];                                                                 
					var oResults = oResponse.responseText;   
					var split_Result = oResults.split("|");

					for (var i = 0, len = split_Result.length - 1; i < len; ++i){
	
						var m = split_Result[i];
						var tmpNode = new YAHOO.widget.TextNode({label: m, customData: m }, node, false);
						
						if (var_uri_list.match("details")== null){
							tmpNode.isLeaf = true;
							tmpNode.labelStyle = "ygtvlabel3";
						}
					}
	
					oResponse.argument.fnLoadComplete();
				},

				failure: function (oResponse) 
				{
					YAHOO.log("Failed to process XHR transaction.", "info", "example");
					oResponse.argument.fnLoadComplete();
				},
	
				argument: {
					"node" : node,
					"fnLoadComplete" : fnLoadComplete
				},
	
				timeout: 7000
			};
			

			YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
		}


		//Function creates the tree
		function buildTree() {
		
			//instantiate the tree:
			tree = new YAHOO.widget.TreeView("treeDiv"+ position);
			var root = tree.getRoot();
			
			if (trim(var_list).length > 0){
				temp = var_list.split("|");
				uriList = var_uri_list.split("|");

				for (i = 0; i < temp.length-1; i++){
					tmplabel = temp[i];
					label = tmplabel.split("@ID");
					label[1] = label[1].replace(/&amp;apos;/g,"'");

					var tmpNode = new YAHOO.widget.TextNode({
						label: trim(label[1]), customData: uri, customID: trim(label[0])
					}, root, false);
					
					tmpNode.href = uriList[i];
					tmpNode.title = "Click to view in repository";
					tmpNode.labelStyle = "notips";
					
					if (uriList[i].match("details")== null) {
						tmpNode.target = "odesi_main";
						//override default label style - smaller font
						tmpNode.labelStyle = "ygtvlabel1";
					}
					else
						tmpNode.target = "_self";
					

					tmpNode.setDynamicLoad(loadNodeDetails, currentIconMode);
				}
			}
			else {
			}

			//The tree is not created in the DOM until this method is called:
			tree.draw();
		}

		return {
			init: function () {
			currentIconMode = 0;
			buildTree();
		}
		}

	})();

	YAHOO.util.Event.onDOMReady(Treeview.init, Treeview, true)
}
