PathwayBrowser = function () {};

Object.extend(PathwayBrowser.prototype, {
	
	pathwayDiagramPane : null,
	eventHierarchyPane : null,
	detailsPane : null,
	searchResults : null,
	tabView : null,
	lastSearchResults : null,
	default_focus_species_id : 48887,
	db : null,
	focus_pathway_id : null,
	current_instance_id : null,
	otherSpeciesDbId : 0,
	loadAndProcessDataUrl : '/cgi-bin/entitylevelview/pathwaybrowserdata',
    pathwayLoadedEvent : new YAHOO.util.CustomEvent(
        "pathwayLoadedEvent", this),
    new_current_instance_id : 0,
    firstTimeDetails : 1,
    eventTracker : new EventTracker({
    	category: "Diagram"
    }),
	
	setViewerSize: function() {
	    var oClipwindow = $("clipwindow");
	    var leftpanel = $("leftpanel");
	    var details = $("details");
	    var availableHeight = YAHOO.util.Dom.getViewportHeight() - 13 - Position.cumulativeOffset(oClipwindow)[1];
	    // 4 is the height of the little triangle for opening/closing details
	    var clipHeight;
	    /*
	     * Tabs in leftpanel are slightly smaller to allow room for scroll bars.
	     */
	    var tabHeight;
	    var tabHeightOffset = 60;
	    if ((details != null) && details.visible()) {
	    	details.style.height = Math.floor(availableHeight * 0.4) + "px";
	    	clipHeight = (Math.ceil(availableHeight * 0.6) - 4) + "px";
	    	tabHeight = (Math.ceil(availableHeight * 0.6) - tabHeightOffset) + "px";
            this.pathwayDiagramPane.resetExpressionKey(0.7);
	    } else {
	    	clipHeight = (availableHeight - 4) + "px";
	    	tabHeight = (availableHeight - tabHeightOffset) + "px";
            this.pathwayDiagramPane.resetExpressionKey(1);
	    }
	    oClipwindow.style.height = clipHeight;
	    this.pathwayDiagramPane.positionThumbnail();
	    if (leftpanel != null) {
	    	leftpanel.style.height = clipHeight;
	        leftpanel.style.overflow = "hidden";
	    }
	    
	    /*
	     * Set up tabs for scroll bar
	     */
	    var hierarchyTab = $("hierarchytab");
    	hierarchyTab.className += " leftpaneltab";
    	hierarchyTab.style.height = tabHeight;
	    var searchResultsTab = $("searchresultstab");
	    searchResultsTab.className += " leftpaneltab";
	    searchResultsTab.style.height = tabHeight;
	    var helpTab = $("helptab");
	    helpTab.className += " leftpaneltab";
	    helpTab.style.height = tabHeight;
	    var pos = Position.cumulativeOffset(document.getElementById("leftpaneltogglerplaceholder"));
        this.placeToggleArrow(pos[0], pos[1], "leftpaneltogglercontainer", "leftpaneltoggler");
        pos = Position.cumulativeOffset(document.getElementById("detailstogglerplaceholder"));
        this.placeToggleArrow(pos[0], pos[1] -6, "detailstogglercontainer", "detailstoggler");
	},
		
	initDisplayExpressionLevels: function(){
		 var details = $("details");
		 if((details != null ) && details.visible()){
			this.pathwayDiagramPane.initDisplayExpressionLevels(0.7);
		 }else{
			this.pathwayDiagramPane.initDisplayExpressionLevels(1);
		 }
	},
	
	handleMapsearchform: function(event) {
	    var query = document.forms["mapsearchform"].QUERY.value;
	    if ((query != null) && (query != "") && (query.length > 1)) {
	    	this.pathwayDiagramPane.clearHighlites();
			this.tabView.set('activeTab',this.tabView.getTab(0),true);    	
			this.doSearch(query);
	    }
	    if (event != null)
	    	Event.stop(event);
	},
	doExampleSearch: function(query) {
		document.forms["mapsearchform"].QUERY.value = query;
		this.handleMapsearchform();
	},
	doSearch: function(query) {
		query = decodeURIComponent(query);
		
			var sUrl = '/cgi-bin/entitylevelview/search' + '?DB=' + this.db + '&QUERY=' + query;
			if (this.focus_species_id) sUrl += '&FOCUS_SPECIES_ID=' + this.focus_species_id;
			if (this.focus_pathway_id) sUrl += '&FOCUS_PATHWAY_ID=' + this.focus_pathway_id;
		
		if (!$($('leftpanel').parentNode).visible()) {
			this.toggleLeftPanel();
		}
	    var ol = overlayElementWithTimeIndicator($("leftpanel"));
	    var lp = $("searchresultstab");
		var callback = {
			scope: this,
			customevents: {
				onSuccess: function(eventType, args) {
					var rtxt = args[0].responseText;
					if (rtxt && (rtxt != " ")) {
						var a = getJsonFromRawText(rtxt);
//					    var a = eval(rtxt);
						this.lastSearchResults = $H(a[0]);
						this.renderRemoteSearchResults(a[0], query);
					} else {
						lp.innerHTML = "No matches for query <B>" + query + "</B>";
					}
				}, 
				onFailure: function(eventType, args) {
					var uo = node.userObject;
					alert("failed");
					lp.innerHTML = "Search failed:<BR />" + req.statusText;
				},
				onComplete: function(eventType, args) {
					if (ol) ol.remove();
				}
			}
		};
		YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
		
		//YAHOO.util.Connect.asyncRequest("POST", "/ReactomeGWT/entrypoint/elv/ELVUtilsServlet", 
		//		callback, "action=search&QUERY=" + query + "&FOCUS_SPECIES_ID=" + parseInt(this.focus_species_id));

	},
	renderRemoteSearchResults: function(results, query) {
		var container = $("searchresultstab");
		results = $H(results);
		$("searchresultstab").innerHTML = "Found <B>" + results.size() + "</B> match(es) for query <B>" + query + "</B>:<BR />";
		var results_a = results.values();
		for (var j = 0, m = results_a.length; j < m; ++j) {
			var r = results_a[j];
			var d1 = Element.extend(document.createElement('div'));
			container.appendChild(d1);
			var img = Element.extend(document.createElement('img'));
			img.src = r.icon;
			d1.appendChild(img);
			var a = Element.extend(document.createElement('a'));
			a.setAttribute('href',"javascript:void(0)");
			a.appendChild(document.createTextNode(r.name));
			d1.appendChild(a);
			Event.observe(a, 'click', this.handleClickOnSearchResult.bindAsEventListener(this, r.id));
		}
	},
	handleClickOnSearchResult: function (e, rid) {
		this.loadAndProcessSearchResultsData(rid, false);
	},
	resize : function() {
		this.setViewerSize();
		this.pathwayDiagramPane.reposition(0,0);
	},
	handleToggleLeftPanel: function(event) {
		this.toggleLeftPanel();
	},
	toggleLeftPanel: function() {
	    var l = Position.cumulativeOffset($('clipwindow'))[0];
	    var n = $($('leftpanel').parentNode);
	    n.toggle();
	    var el = $('leftpaneltoggler');
	    
	    if (n.visible()) {
			el.src = "/icons/hide-arrow-large.png";
			el.title = "Hide Event Hierarchy Panel";
	    } else {
			el.src = "/icons/show-arrow-large.png";
			el.title = "Show Event Hierarchy Panel";
	    }
	    var pos = Position.cumulativeOffset(document.getElementById("leftpaneltogglerplaceholder"));
        this.placeToggleArrow(pos[0], pos[1], "leftpaneltogglercontainer", "leftpaneltoggler");
	    var canvas = $('canvas');
	    canvas.setStyle({left: (parseInt(canvas.style.left) + (l - Position.cumulativeOffset($('clipwindow'))[0]))+'px'});
	    this.pathwayDiagramPane.reposition(0,0);
	    /*
	     * Update the db out of date notification location.
	     */
	    try{
	    	this.pathwayDiagramPane.placeDbOutOfDataNotification();
	    }catch(err){
	    	
	    }
	    if(this.pathwayDiagramPane.paintExpressionData){
	    	this.pathwayDiagramPane.placeExperimentBrowser();
	    }
	    else if(this.pathwayDiagramPane.displayComparison==1){
	    	if(this.pathwayDiagramPane.speciesdata){
	            this.pathwayDiagramPane.placeSpeciesComparisonPanel(this.pathwayDiagramPane.speciesdata.name); 
	    	}else{
	    		this.pathwayDiagramPane.placeSpeciesComparisonPanel();
	        } 
	    }
	    var speciesNamePanel = $("speciesnamepanel");
	    if(speciesNamePanel && speciesNamePanel.style.display == "block"){
	    	this.pathwayDiagramPane.placeSpeciesNamePanel();
	    }
	    /* ##### Next line is for the GOOGLE ANALYTICS event tracking ##### */
		this.eventTracker.track("Hierarchy Pane Toggle", n.visible()?"Open":"Close");
		/* ################################################################ */
	},
	toggleDetails: function() {
	    var n = $('details');
	    n.toggle();
	    var el = $('detailstoggler');
	    
	    if (n.visible()) {
			el.src = "/icons/hide-arrow-large-v.png";
			el.title = "Hide Details";
			$('contentNorth').style.height = (YAHOO.util.Dom.getViewportHeight() * .6) + 10;
	    } else {
			el.src = "/icons/show-arrow-large-v.png";
			el.title = "Show Details";
			$('contentNorth').style.height = (YAHOO.util.Dom.getViewportHeight() - 20);
	    }
	    var pos = Position.cumulativeOffset(document.getElementById("detailstogglerplaceholder"));
        this.placeToggleArrow(pos[0], pos[1]-6, "detailstogglercontainer", "detailstoggler");

	    this.setViewerSize();
		this.pathwayDiagramPane.reposition(0,0);
		
		/* ##### Next lines are for the GOOGLE ANALYTICS event tracking ##### */
		this._isFirstDetailsToggle = typeof(this._isFirstDetailsToggle)=='undefined'; 
		if(!this._isFirstDetailsToggle){
			this.eventTracker.track("Details Pane Toggle", n.visible()?"Open":"Close");
		}
		/* ################################################################## */
	},
	processTitle: function(title) {
	    if (title) {
			document.title = title;
	    }
	},
	handleHome : function(){
		document.location.href = document.location.protocol + "//" + document.domain;
	},
	changeFocusPathway : function (pathway_id) {
		if (this.focus_species_id != null) {
			this.focus_pathway_id 			  = pathway_id;	
			this.detailsPane.focus_pathway_id = pathway_id;
			this.eventHierarchyPane.focus_pathway_id = pathway_id;
			this.pathwayDiagramPane.changeFocusPathway(pathway_id);
		}
	},
	updateLocationHref: function(vertexId) {
		var i = document.location.href.indexOf("#");
		var href = document.location.href;
		if (i != -1) {
			href = href.substring(0,i);
		}
		href += "#DB=" + this.db + "&FOCUS_SPECIES_ID=" + this.focus_species_id;
		if (this.focus_pathway_id) href += "&FOCUS_PATHWAY_ID=" + this.focus_pathway_id;
		if (this.current_instance_id) href += "&ID=" + this.current_instance_id;
		
		if(vertexId){
			this.vertexId = vertexId;
			href = href + "&VID="+this.vertexId;
		}
		
		document.location.href = href;
	},
	setDBandFocusSpecies: function() {
	    var params = this.extractParamsFromURI();
	    var db = '';
	    if (params['DB'] && (typeof(params['DB']) == 'string')) {
			db = params['DB'];
	    } else {
			var cv = getCookie('DB');
			if (cv) {
			    db = cv;
			}
	    }
	    this.setDB(db);
	    var focus_species_id;
	    if (params['FOCUS_SPECIES_ID'] && (typeof(params['FOCUS_SPECIES_ID']) == 'string')) {
	    	focus_species_id = params['FOCUS_SPECIES_ID'];
	    } else {
			var cv = getCookie('FOCUS_SPECIES_ID');
			if (cv) {
			    focus_species_id = cv;
			} else {
				// NOTE
				// Hopefully a reasonable default for the time being.
				focus_species_id = this.default_focus_species_id;
			}
	    }
	    this.setFocusSpecies(focus_species_id);
	},
	createLeftPanelTabs: function() {
		this.tabView = new YAHOO.widget.TabView('leftpanel');
	},
	init: function() {
		this.pathwayDiagramPane = new PathwayDiagramPane();
		this.eventHierarchyPane = new EventHierarchyPane();
		this.detailsPane = new DetailsPane();		
		// This has to happen before init_query_autocomplete as otherwise autocompleter wouldn't know the db.
		this.setDBandFocusSpecies();		
		//This has to happen early as doing it somehow makes the search bar lower
		this.init_query_autocomplete();
		this.setViewerSize();
		this.createLeftPanelTabs();
		this.init_handlers();	
		this.pathwayDiagramPane.init();
		this.eventHierarchyPane.speciesInitializedEvent.subscribe(this.onSpeciesListInitialized.bind(this), this);
		this.eventHierarchyPane.initSpeciesList();
		this.eventHierarchyPane.newSpeciesTreeLoadedEvent.subscribe(this.onNewSpeciesTreeLoaded.bind(this), this);
		this.eventHierarchyPane.buildEventHierarchy();
		this.eventHierarchyPane.treeNodeClickEvent.subscribe(this.onTreeNodeClick.bind(this), this);
		this.eventHierarchyPane.treeTrunkLoadedEvent.subscribe(this.onTreeTrunkLoaded.bind(this), this);
		this.eventHierarchyPane.searchResultsLoadedEvent.subscribe(this.onSearchResultsLoaded.bind(this), this);
		this.pathwayDiagramPane.diagramNodeClickedEvent.subscribe(this.onDiagramNodeClick.bind(this), this);
		this.pathwayDiagramPane.participatingProteinClickedEvent.subscribe(this.onParticipatingMoleculeClick.bind(this), this);
		// Menuitem clicked event for right-click menus. Used for other pathways functionality
        this.pathwayDiagramPane.menuItemClickedEvent.subscribe(this.onMenuItemClick.bind(this), this);
		this.detailsPane.internalLinkClickEvent.subscribe(this.onInternalLinkClick.bind(this), this);
		this.eventHierarchyPane.treeNodeMouseOverEvent.subscribe(
				this.pathwayDiagramPane.onTransientHighliteRequest.bind(this.pathwayDiagramPane)
		);
		this.eventHierarchyPane.treeNodeMouseOutEvent.subscribe(
				this.pathwayDiagramPane.onTransientHighliteRemovalRequest.bind(this.pathwayDiagramPane)
		);
		YAHOO.util.Event.addListener($("gohome"), 'click', 
				this.handleHome, this, true);
		
		YAHOO.util.Event.addListener($("closedboutofdatenotification"), 'mousedown', 
				this.closeDbOutOfDateNotification, this, true);
		
        this.disableContextMenu(document.getElementById("clipwindow"));
        
        if (! this.handleQueryInURI()) {
			this.toggleDetails();
		}
        this.tweakNavigationBarLinks();
        // If we are coming to the ELV from the expression analysis page, set up a handler
        // to request and process expression data from the server.
        this.pathwayDiagramPane.diagramLoadedEvent.subscribe(
				this.diagramLoadedEventHandler
						.bind(this),
				this);
      
        var pos = Position.cumulativeOffset(document.getElementById("leftpaneltogglerplaceholder"));
        this.placeToggleArrow(pos[0], pos[1], "leftpaneltogglercontainer", "leftpaneltoggler");
        $("expmodecheck").checked = false;
        /*
         * Hack to accommodate input type file in firefox on the mac. globalStorage is object unique to firefox. If this is detected
         * set the colspan of the td holding the input file to 2 so 'browse' button is not truncated.
         */
        if(window.globalStorage){
        	$("expressionfileuploadtd").colSpan = "2";
        	$("expressionpaintingontd").colSpan = "2";
        	$("interactionfileuploadtd").colSpan = "2";
        }
        try{
        	document.body.style.overflow = "hidden";
        }catch(err){

        }
        this.pathwayDiagramPane.hideDbOutOfDateNotification = 0;
        this.detailsPane.speciesComparisonChangeEvent.subscribe(this.onDetailsSpeciesComparisonChange.bind(this), this);
        this.pathwayDiagramPane.speciesComparisonChangeEvent.subscribe(this.onPathwayDiagramPaneSpeciesComparisonChange.bind(this), this);
        
        this.createResizablePanels();
	},
	/*
	 * Toggle arrows are used to hide/show event hierarchy and details pane.
	 */
	placeToggleArrow: function(x,y, placeHolderId, arrowId){
	   // Place hide arrow for left panel      
	   var hidearrowcontainer = document.getElementById(placeHolderId);
       if(hidearrowcontainer){
    	   // Set style directly. In IE, object returned does not have setStyle method (but does have style
    	   // property).
    	   hidearrowcontainer.style.top  = y + "px";
    	   hidearrowcontainer.style.left = x + "px";
		}	
	},
	
	/*
	 * Close the notification informing users they are viewing information from an out of date database.
	 * 
	 */
	closeDbOutOfDateNotification : function(){
		try{
			$("dboutofdatebanner").style.display="none";
			this.pathwayDiagramPane.hideDbOutOfDateNotification = 1;
		}catch(err){
			
		}
	},
	/*
	 * When the diagram has loaded, check is expression painting or species comparison mode
	 * is enabled. If so, retrieve relevant data from the server and paint the overlays.
	 * Used when user arrives at ELV from expression analysis/species comparison page.
	 * Diagram has to be loaded first so that necessary objects are initialized before trying to
	 * paint overlays.
	 */
	diagramLoadedEventHandler : function(){
		var t = this;
        var callback = {
				scope : this,
				customevents : {
					onSuccess : function(eventType, args) {
						
        			try{
        				if(args[0].responseText && args[0].responseText.replace(/^\s+|\s+$/g, '') == "error"){
       						throw("error");
        				}
						//var data = eval('(' + args[0].responseText + ')');
        				var data = getJsonFromRawText(args[0].responseText);
						if(data.action == "compare"){
							this.pathwayDiagramPane.displayComparison = 1;
							this.pathwayDiagramPane.getComplexComponentsForSpeciesComparison(data);
							this.pathwayDiagramPane.updateSpeciesComparisonDropDownBySpeciesId(this.pathwayDiagramPane.otherSpeciesDbId);
							
						}else if(data.action == "exp"){
							this.pathwayDiagramPane.paintExpressionData = 1;
							this.pathwayDiagramPane.expressionPainter.expressionCallback(args[0].responseText);
							this.setViewerSize();
							this.initDisplayExpressionLevels();
						}
        			}catch(err){
        				document.body.style.cursor = "default";
        				if (t.pathwayDiagramPane.displayComparisonFromGWT == 1 || t.pathwayDiagramPane.displayComparison == 1){
        					t.pathwayDiagramPane.onSpeciesComparisonClose();
        					alert("There was a problem retrieving species comparison data. Closing species comparison.");
        				}else if(t.pathwayDiagramPane.paintExpressionDataFromGWT == 1 || t.pathwayDiagramPane.paintExpressionData == 1){
        					t.pathwayDiagramPane.closeExperiment();
        					alert("There was a problem retrieving expresison data. Closing expression painter.");
        					
        				}
        			}
        			/* new_current_instance_id is used as a flag to indicate to the elv that the other pathways feature was selected
        			  by the user and now that the diagram is loaded, call onPathwayLoaded to scroll/select the user selected node.
        			*/
        			if(this.new_current_instance_id != null){
        				this.onPathwayLoaded();
        			}
				},
					onFailure : function(eventType, args) {
						alert("PathwayBrowser: Failed to receive data when processing exp painter or species comparison (new_current_instance_id)" + args[0]);
					}
				}
		};
        if(this.firstTimeDetails == 1){
        	this.toggleDetails();
        	this.firstTimeDetails = 0;
        }
        // Check if we need to repaint expression data when switching pathways.
        if(this.pathwayDiagramPane.paintExpressionDataFromGWT == 1 || this.pathwayDiagramPane.paintExpressionData == 1){
        	var postUrl =
        		"/ReactomeGWT/entrypoint/elv/PathwayExpressionDataServlet?FOCUS_PATHWAY_ID=" + this.focus_pathway_id;
        	YAHOO.util.Connect.asyncRequest("GET", postUrl, callback);
        }else if (this.pathwayDiagramPane.displayComparisonFromGWT == 1 || this.pathwayDiagramPane.displayComparison == 1){
        	var getUrl = "/ReactomeGWT/entrypoint/elv/SpeciesComparisonServlet?pathwayid=" + this.focus_pathway_id
        		+ "&ospeciesid=" + this.pathwayDiagramPane.otherSpeciesDbId;
        	YAHOO.util.Connect.asyncRequest("GET", getUrl, callback);
        }
		/* new_current_instance_id is used as a flag to indicate to the elv that the other pathways feature was selected
		  by the user and now that the diagram is loaded, call onPathwayLoaded to scroll/select the user selected node.
		*/
		else if(this.new_current_instance_id != null){
			this.onPathwayLoaded();
		}
	},
	
	init_query_autocomplete: function() {
		log("init_query_autocomplete()");
		var maxResultsDisplayed = 20;
		this.oACDS = new YAHOO.widget.DS_XHR("/cgi-bin/entitylevelview/searchtermautocomplete", ["\n", "\t"]);
		this.oACDS.scriptQueryParam = "QUERY";
		this.oACDS.scriptQueryAppend = "DB=" + this.db + "&MAXROWS=" + maxResultsDisplayed;
	    this.oACDS.responseType = YAHOO.widget.DS_XHR.TYPE_FLAT;
	    this.oACDS.maxCacheEntries = 0;
	    this.oACDS.queryMatchSubset = false;
	
	    this.oAutoComp = new YAHOO.widget.AutoComplete('query','querycontainer', this.oACDS);
	    this.oAutoComp.prehighlightClassName = "yui-ac-prehighlight";
	    this.oAutoComp.typeAhead = false;
	    this.oAutoComp.useShadow = true;
	    this.oAutoComp.minQueryLength = 2;
	    this.oAutoComp.maxResultsDisplayed = maxResultsDisplayed;
	    this.oAutoComp.queryDelay = 1; 
	    this.oAutoComp.formatResult = function(oResultItem, sQuery) {
	    	sQuery = decodeURIComponent(sQuery);
	   		sQuery = sQuery.replace(/\*/g, "");
	   		sQuery = '(' + sQuery + ')';
	    	var re = new RegExp(sQuery, "gi");
	        var sMarkup = oResultItem[0];
	        sMarkup = sMarkup.replace(re, "<span class=\"hl-substr-1\">$1</span>");
	        return (sMarkup);
	    };
	    // Need to specify the focus species
	    var t = this;
	    this.oAutoComp.doBeforeSendQuery = function(sQuery) {
	    	
	    	if (t.focus_species_id != null) 
	    		sQuery += "&FOCUS_SPECIES_ID=" + t.focus_species_id;
	    	log("doBeforeSendQuery(): " + sQuery);
	    	return sQuery;
	    };
	},
	tweakNavigationBarLinks: function() {
		var e = $("productsandservices");
		if (e) {
			var links = e.getElementsBySelector('a');
			var re = new RegExp("DB=\\w+");
	    	for (var i = 0, l = links.length; i < l; ++i) {
				var href = links[i].readAttribute('href');
				if (href) {
					href = href.replace(re, "DB="+this.db);
					links[i].setAttribute("href",href);
				}
	    	}
		}
	},
	goToOldUI: function() {
		var loc;
		if ((this.current_instance_id != null) && (this.current_instance_id != this.focus_species_id)) {
			loc = '/cgi-bin/eventbrowser?DB=' + this.db + '&ID=' + this.current_instance_id + '&FOCUS_SPECIES_ID=' + this.focus_species_id;
		} else {
			loc = '/cgi-bin/frontpage?DB=' + this.db + '&FOCUS_SPECIES_ID=' + this.focus_species_id;
		}
		window.location = loc;
	},
	init_handlers: function() {
		var t = this;
	    if ($('mapsearchform')) {
			Event.observe('mapsearchform', 'submit', this.handleMapsearchform.bindAsEventListener(this));
			Event.observe('querysubmitbutton', 'click', this.handleMapsearchform.bindAsEventListener(this));
	    }
	    Event.observe(window, 'resize', this.resize.bindAsEventListener(this));
	    Event.observe('leftpaneltoggler','mousedown',this.handleToggleLeftPanel.bindAsEventListener(this));
	    Event.observe('leftpaneltoggler','mouseover',this.highliteToggleLeftPanel.bindAsEventListener(this));
	    Event.observe('leftpaneltoggler','mouseout',this.hidehighliteToggleLeftPanel.bindAsEventListener(this));
	    Event.observe('detailstoggler','mousedown',this.toggleDetails.bindAsEventListener(this));
	    Event.observe('detailstoggler','mouseover',this.highliteToggleDetails.bindAsEventListener(this));
	    Event.observe('detailstoggler','mouseout',this.hidehighliteToggleDetails.bindAsEventListener(this));
	    
	    YAHOO.util.Event.addListener('specieslistdropdown', 'change',
				this.speciesSelectorChange, this, true);
	    YAHOO.util.Event.addListener('expmodecheck', 'click',
				this.toggleDisplayExpressionData, this, true);
	    
	},
	toggleDisplayExpressionData : function(eventType, o){
		var target = null;
		if(eventType.target){
			target = eventType.target;
		}else{
			target = eventType.srcElement;
		}
		try{
			if(target.checked == true){
		        var callback = {
						scope : this,
						customevents : {
							onSuccess : function(eventType, args) {
		        			try{
		        				if(args[0].responseText && args[0].responseText.replace(/^\s+|\s+$/g, '') == "error"){
		        					throw("error");
		        				}
								//var data = eval('(' + args[0].responseText + ')');
		        				var data = getJsonFromRawText(args[0].responseText);
								if(data == null){
									$("expmodecheck").checked = false;
									alert("No expression data found.");
								}else
								if(data.action == "exp"){
									this.pathwayDiagramPane.expressionPainter.expressionCallback(args[0].responseText);
									this.setViewerSize();
									this.initDisplayExpressionLevels();
								}
		        			}catch(err){
		        				document.body.style.cursor = "default";
		        				$("expmodecheck").checked = false;
		        				alert("There was a problem retrieving expression data. Have you submitted expression data?");
		        			}
							},
							onFailure : function(eventType, args) {
								alert("PathwayBrowser: Failed to receive data when processing exp painter or species comparison");
							}
						}
				};
				var getUrl =
	        		//"/ReactomeGWT/entrypoint/elv/ExpressionVisualizerServlet";
					"/ReactomeGWT/entrypoint/elv/PathwayExpressionDataServlet?FOCUS_PATHWAY_ID=" + this.focus_pathway_id;
	        	YAHOO.util.Connect.asyncRequest("GET", getUrl, 
	                    		 callback);
			}else if(target.checked == false){
				this.pathwayDiagramPane.closeExperiment();
				
			}
		}catch(err){
			alert("There was problem toggling the display of expression data.");
		}
		
	},
	/*
	 * This list below adds/hides highlights for the toggle arrows.
	 */
	highliteToggleDetails : function(){		
		$("detailstoggler").style.border="3px solid rgb(59,253,50)";
	},
	hidehighliteToggleDetails : function(){
		$("detailstoggler").style.border="";
	},
	highliteToggleLeftPanel: function(){
		$("leftpaneltoggler").style.border="3px solid rgb(59,253,50)";
	},
	hidehighliteToggleLeftPanel: function(){
		$("leftpaneltoggler").style.border="";		
	},
	/*
	 * end toggle highlight routines
	 */
	extractParamsFromURI: function() {
		var uri = String(document.location);
		var fragment = uri.substring(uri.indexOf("#")+1,uri.length);
		var params = fragment.toQueryParams();
		return params;
	},
	handleQueryInURI: function() {
		var params = this.extractParamsFromURI();
		// Z = set the zoom level
	    if (params['Z'] && (typeof(params['Z']) == 'string')) {
			this.pathwayDiagramPane.z = params['Z'];
			this.pathwayDiagramPane.zoomChange.fire(this.pathwayDiagramPane.z);
		}
	    /*
	     * FromGWT vars used in this case instead of paintExpressionData and displayComparison which are used in other parts of the
	     * code and were causing timing issues.
	     */
	    if(params['DATA_TYPE'] == "Expression"){
	    	this.pathwayDiagramPane.paintExpressionDataFromGWT = 1;
	    }
	    if(params['DATA_TYPE'] == "SpeciesComparison"){
	    	this.pathwayDiagramPane.otherSpeciesDbId = params['OTHER_SPECIES_DB_ID'];
	    	if(this.pathwayDiagramPane.otherSpeciesDbId == undefined){
	    		alert("Could not identify species to compare against.");
	    	} else {
	    		this.pathwayDiagramPane.displayComparisonFromGWT = 1;
	    	}
	    }
	    if (params['FOCUS_PATHWAY_ID'] && (typeof(params['FOCUS_PATHWAY_ID']) == 'string')) {	    	
	    	this.changeFocusPathway(params['FOCUS_PATHWAY_ID']);
	    }
	    if (params['ID'] && (typeof(params['ID']) == 'string')) {
	    	log("params[ID]=" + params['ID']);
	    	
	    	if(params['VID'] && (typeof(params['ID']) == 'string')){
	    		this.vertexId = params['VID'];
	    	}
	    	
			this.loadAndProcessData(params['ID'], true, false);
			return true;
	    } else if (this.focus_pathway_id) {
	    	log("this.focus_pathway_id=" + this.focus_pathway_id);
	    	this.loadAndProcessData(this.focus_pathway_id, true,false);
	    	return true;
	    }
	   
	    return false;
	},
	onDetailsSpeciesComparisonChange : function(type, args){
		try{
			if(this.checkSpeciesComparison() == false){
				this.detailsPane.updateSpeciesDropDown(0);
				
				return;
			}
			var e 		= args[0];
			var target 	= null;
			if(e.target){
				target = e.target;
			}else{
				target = e.srcElement;
			}
			var selectedIndex = target.selectedIndex;
			this.pathwayDiagramPane.updateSpeciesComparisonDropDown(e, selectedIndex);
		}catch(err){
			
		}
	},
	
	onSpeciesListInitialized : function(){
		this.pathwayDiagramPane.initControlPanel();
	},
	onPathwayDiagramPaneSpeciesComparisonChange : function(type, args){
		if(this.checkSpeciesComparison() == true){
			var data 			= args[0];
			var speciesId 		= args[1];
			var selectedIndex 	= args[2];
			this.pathwayDiagramPane.getComplexComponentsForSpeciesComparison(data);
			this.pathwayDiagramPane.otherSpeciesDbId = speciesId;
			this.detailsPane.updateSpeciesDropDown(selectedIndex);
		}else{
			this.pathwayDiagramPane.updateSpeciesComparisonDropDown(null, 0);
		}
	},
	setFocusSpecies : function (focus_species_id) {
		this.previousSpeciesId = this.focus_species_id;
		this.focus_species_id = focus_species_id;
		this.pathwayDiagramPane.focus_species_id = focus_species_id;
		this.eventHierarchyPane.focus_species_id = focus_species_id;
		this.detailsPane.focus_species_id = focus_species_id;
	},
	getCurrentFINodes : function(){
		return this.pathwayDiagramPane.getCurrentFINodes();
	},
	displayFIOverlay: function(node, json){
	    return this.pathwayDiagramPane.displayFIOverlay(node, json);
	},
	clearFIOverlay:function(){
	    this.pathwayDiagramPane.clearFIOverlay();
	},
	displayControlPanel: function(){
	    this.pathwayDiagramPane.displayControlDialog();
	},
	applyConfidenceColours: function(confthreshold, exceedColour, belowColour){
	    this.pathwayDiagramPane.applyConfidenceColours(confthreshold, exceedColour, belowColour);
	},
	resetColours:function(){
	    this.pathwayDiagramPane.resetColours();
	},
	setDB: function (db) {
		this.db = db;
		this.pathwayDiagramPane.db = db;
		this.eventHierarchyPane.db = db;
		this.detailsPane.db = db;
	},
	onTreeNodeClick: function(type, args, me) {
		var topNode = args[0];
		var clickedNode = args[1];
		var selectedEntity = parseInt(args[2]);
        this.focusOnTreeNode(topNode.data.name, topNode.data.dbid, clickedNode.data.dbid, selectedEntity);
	},
    focusOnTreeNode: function(name, pathwaydbid, nodedbid, selectedEntity){
    //	console.log("focusOnTreenode " + selectedEntity);
		this.processTitle(name);
		this.pathwayDiagramPane.clearHighlites();
		this.vertexId = null;
		try{
			this.pathwayDiagramPane.highliteNodesForRepresentedInstance(this.pathwayDiagramPane.representedInstances[nodedbid],false);
		}catch(er){

		}
		if (pathwaydbid != this.focus_pathway_id) {
			this.changeFocusPathway(pathwaydbid);
		}
		//if(selectedEntity) nodedbid = selectedEntity;
		this.loadAndProcessData(nodedbid, false, true, null, null, selectedEntity);
    },
	onDiagramNodeClick: function(type, args, me) {
		var node = args[0];
		this.current_instance_id = node.userObject.id;
		
		/* ##### Next line is for the GOOGLE ANALYTICS event tracking ##### */
		this.eventTracker.track(node.userObject.cls, node.userObject.name);
		/* ################################################################ */

	    this.detailsPane.loadDetails(node.userObject.id);
	    this.eventHierarchyPane.highliteNodeInEventHierarchy(node, true);
	    this.updateLocationHref(node.id);
	},
	onParticipatingMoleculeClick: function(type, args, me){
		var dbid = args[0];
		this.loadDetails(dbid);
	},
	
	loadDetails: function(dbid){
		var sUrl = this.loadAndProcessDataUrl + '?DB=' + this.db + 
		'&FOCUS_SPECIES_ID=' + this.focus_species_id + '&ID=' + dbid;
	
		var ol = overlayElementWithTimeIndicator(this.detailsPane.getDetailsDiv());
		var callback = {
			scope: this,
			customevents: {
				onSuccess: function(eventType, args) {
					this.current_instance_id = dbid;
	                //var h = eval('(' + args[0].responseText + ')');
					var h = getJsonFromRawText(args[0].responseText);
	                var o = new Object();
	                o.details = h.details;
	                o.map_highlites 	  = h.map_highlites;
	                o.hierarchy_highlites = h.hierarchy_highlites;
	                o.top_highlites 	  = h.top_highlites;
	    		    this.detailsPane.processDetails(o.details);
				}, 
				onFailure: function(eventType, args) {
				},
				onComplete: function(eventType, args) {
					if (ol) ol.remove();
				}
			}
		};
		YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
	},
	/*
	 * Currently handles other pathways functionality.
	 */
    onMenuItemClick: function(type, args, me) {
		var rootdbid 										= args[0];
        var nodedbid 										= args[1];
        this.new_current_instance_id 						= nodedbid;
        this.tabView.set('activeTab',this.tabView.getTab(1),true);
        //this.eventHierarchyPane.topNodeFull = rootdbid;
        this.eventHierarchyPane.topNodeFull = 0;
        if(this.eventHierarchyPane.selectPathway(rootdbid) == "false"){
        	this.loadAndProcessData(rootdbid, true, false, false, true);
        }
      
        this.processTitle(args[2]);
	},
	
    onPathwayLoaded : function(){
        this.pathwayDiagramPane.scrollToNode(this.new_current_instance_id);
        this.pathwayDiagramPane.highliteNodeWithId(this.pathwayDiagramPane.dbnodes[this.new_current_instance_id], false);
        this.pathwayDiagramPane.diagramNodeClickedEvent.fire(this.pathwayDiagramPane.nodes[this.pathwayDiagramPane.dbnodes[this.new_current_instance_id]]);
		this.new_current_instance_id=null;
    },
    disableContextMenu: function(element) {
        element.oncontextmenu = function() {
        return false;
        }
    },
    createResizablePanels: function(){
    		var r = new YAHOO.util.Resize("contentNorth",{
			proxy			: true,
			animate			: true,
			animateDuration	: .2,
			animateEasing	: YAHOO.util.Easing.backBoth, 
			handles			: ["b"],
			minHeight		: YAHOO.util.Dom.getViewportHeight() * 0.25,
	        maxHeight		: YAHOO.util.Dom.getViewportHeight() * 0.9
		});
		 
		r.on('beforeResize', function(ev){
			if(!$('details').visible())
				return false;
		})
		r.on('resize', function(ev){
			var totalHeight = YAHOO.util.Dom.getViewportHeight();
			$("clipwindow").style.height = (ev.height - 33) + 'px';	//Diagram
			$("leftpanel").style.height = (ev.height - 25) + 'px'; //Container left panel
			$("hierarchytab").style.height = (ev.height - 95) + 'px';
			$("searchresultstab").style.height = (ev.height - 95) + 'px';
			$("helptab").style.height = (ev.height - 95) + 'px';
			
			$('details').style.height = (totalHeight - ev.height - 15) + 'px';
			$("detailstogglercontainer").style.top  = (ev.height - 6) + "px";
			$("leftpaneltogglercontainer").style.top  = (ev.height/2) + "px";
		});
		
		
		var v = new YAHOO.util.Resize("leftpanel", {
			proxy			: true,
			animate			: true,
			animateDuration	: .2,
			animateEasing	: YAHOO.util.Easing.backBoth, 
			handles			: ["r"],
	        minWidth		: 290,
	        maxWidth		: YAHOO.util.Dom.getViewportWidth() * 0.6
		})
		v.on('beforeResize', function(ev){
			if(!$('leftpanel').visible())
				return false;
		})
		v.on('resize', function(ev){
			var newWidth = ev.width;
	
			$("leftpanel").style.width = newWidth + 'px';
			$("outerwrapper").style.width = (newWidth - 15)+ 'px';
			$("innerwrapper").style.width = (newWidth - 20)+ 'px';
			$("hierarchytab").style.width = (newWidth - 20)+ 'px';
			$("searchresultstab").style.width = (newWidth - 15) + 'px';
			$("helptab").style.width = (newWidth - 15) + 'px';
			
			$("leftpaneltogglercontainer").style.left  = newWidth + 'px';
		});
    },
    
    /*
     * Handler for when user clicks on link in the details pane.
     */
	onInternalLinkClick: function(type, args, me) {
		log("onInternalLinkClick " + args);
		var callback = {
				scope: this,
				customevents: {
					onSuccess: function(eventType, switchargs) {
						//var speciesData = eval('(' + switchargs[0].responseText + ')');
						var speciesData = getJsonFromRawText(switchargs[0].responseText);
						var speciesId = speciesData.speciesid;
						var present = speciesData.present;
						/*
						 * If the entity is not present in the orthologous pathway ask the user for confirmation
						 */
						if(present == false){
							var r = confirm("This entity is not present in the pathway orthologous to the current pathway. If you would like to view the orthologous pathway anyway click OK");
							if(r == false){
								return;
							}
						}
						this.switchSpecies(speciesId);
						this.new_current_instance_id = dbid;
						var dropdown = $("specieslistdropdown");
						var selectedindex=0;
						for(var optionsIndex=0;optionsIndex<dropdown.options.length; optionsIndex++){
							if(dropdown.options[optionsIndex].value== speciesId){
								selectedIndex = optionsIndex;
							}
						}
						
						$("specieslistdropdown").selectedIndex=selectedIndex;
						if($("specieslistdropdown").onchange)
							$("specieslistdropdown").onchange();
					}, 
					onFailure: function(eventType, args) {
			
					},
					onComplete: function(eventType, args) {
			
					}
				}
			};
		
		
		var dbid = args[0];
		var switchspecies = args[1];
		
		if(switchspecies){
			YAHOO.util.Connect.asyncRequest("POST", "/ReactomeGWT/entrypoint/elv/ELVUtilsServlet", 
				callback, "action=getspecies&dbid=" + dbid + "&pid=" + parseInt(this.focus_pathway_id));
		}else{
			this.vertexId = this.pathwayDiagramPane.dbnodes[dbid];
			this.loadAndProcessData(dbid, null, false, true);
		}

	},
	checkSpeciesComparison: function(){
		if(this.focus_species_id != "48887"){
			alert(this.pathwayDiagramPane.COMPARISON_NOT_ALLOWED_STRING);
			return false;
		}
		
		return true;
	},
	onTreeTrunkLoaded: function(type, args, me) {
		this.tabView.set('activeTab',this.tabView.getTab(1),true);
	},
    // FIX search results
	onSearchResultsLoaded: function(type, args, me) {
		//this.pathwayDiagramPane.clearHighlites();
	},
	toString: function() {
		return "PathwayBrowser";
	},
	/*
	 * Handler for species switching dropdown
	 */
	speciesSelectorChange : function(e){
		var target = null;
		if(e.target){
			target = e.target;
		}else{
			target = e.srcElement;
		}
		var speciesId = target.value;
		this.switchSpecies(speciesId);
	},
	switchSpecies:function(speciesId){
		if (this.pathwayDiagramPane.displayComparisonFromGWT == 1 || this.pathwayDiagramPane.displayComparison == 1){
			alert(this.pathwayDiagramPane.COMPARISON_NOT_ALLOWED_STRING);
			this.pathwayDiagramPane.onSpeciesComparisonClose();
		}
		var currentPathwayName = this.eventHierarchyPane.getPathwayName(this.focus_pathway_id);
		this.setFocusSpecies(speciesId);
		this.eventHierarchyPane.buildEventHierarchy(this.focus_pathway_id, currentPathwayName);
	},
	
	/* PathwayInfo is an array containing pathwayId and pathwayName.
	 * PathwayId is id of selected pathway in previous species. Now that the event hierarchy for the new species
	 * has been loaded, check to see if an orthologous pathway exists and switch to it if so.
	 * 
	 * pathwayName is the name of the pathway we are trying to find an orthologue for.
	 */
	onNewSpeciesTreeLoaded:function(eventType, pathwayInfo){
		var t = this;
		var callback = {
				scope: this,
				customevents: {
					onSuccess: function(eventType, args) {
						var rtxt = args[0].responseText;
						try{
							if (rtxt && (rtxt.length > 0)) {
								var data = getJsonFromRawText(args[0].responseText);
//								var data = eval('(' + rtxt + ')');
								var orthologousId = data.orthologousEventId;
								var path = data.path;
								t.speciesName = $("specieslistdropdown").options[$("specieslistdropdown").selectedIndex].text;
								if(orthologousId == undefined || orthologousId == "none"){
									t.pathwayDiagramPane.noPathwaySelected();
									t.focus_pathway_id=null;
									t.detailsPane.focus_pathway_id=null;
									t.current_instance_id=null;
									t.eventHierarchyPane.focus_pathway_id = null;
									t.detailsPane.getDetailsDiv().innerHTML="";
									t.updateLocationHref();
									t.processTitle(" ");
									var speciesName = $("specieslistdropdown").options[$("specieslistdropdown").selectedIndex].text;
									t.pathwayDiagramPane.placeSpeciesNamePanel(t.speciesName, "label");
									alert("The '" + pathwayInfo[1] + "' pathway does not exist in our orthology projection to " + speciesName + ", sorry.");
									return;
								}
								t.eventHierarchyPane.removeTreeNodeHilites();
								// Change pathway to orthologous pathway.
								//t.focusOnTreeNode(document.title, orthologousId, orthologousId);
								t.eventHierarchyPane.treehighlites1.push(parseInt(orthologousId));
								var pathHighlights = $A(path).without(parseInt(orthologousId));
								if(pathHighlights.length > 0){
									t.eventHierarchyPane.topNodeFull = parseInt(pathHighlights[0]);
								}else{
									t.eventHierarchyPane.topNodeFull = parseInt(orthologousId);
								}
								t.focusOnTreeNode(document.title, orthologousId, orthologousId);
								t.eventHierarchyPane.treehighlites2 = pathHighlights;
								t.eventHierarchyPane.scrollToFocusPathway();
								t.eventHierarchyPane.highliteTreeNodeToBeHighlited();
								t.eventHierarchyPane.expandNodeById(t.eventHierarchyPane.topNodeFull);
								t.pathwayDiagramPane.placeSpeciesNamePanel(t.speciesName, "label");
							}
						}catch(err){
						}
					}, 
					onFailure: function(eventType, args) {
						
					}
				}
			};
		YAHOO.util.Connect.asyncRequest("POST", "/ReactomeGWT/entrypoint/elv/ELVUtilsServlet", 
       		 callback, "pathwayid=" + parseInt(pathwayInfo[0]) + "&otherspeciesid=" + this.focus_species_id 
       		 + "&action=getortholog&prevspeciesid="+this.previousSpeciesId + "&topid=" + pathwayInfo[2]);
	},
	
	loadAndProcessData: function(dbid, forceCoordinates, treenodesAlreadyHandled, processDetails, otherPathway, selectedEntityId) {
		//console.log("load and process data");
		if(selectedEntityId) dbid = selectedEntityId;
		var sUrl = this.loadAndProcessDataUrl + '?DB=' + this.db + 
			'&FOCUS_SPECIES_ID=' + this.focus_species_id + '&ID=' + dbid;
	//	console.log("dbid " + dbid);
		if (this.focus_pathway_id) sUrl += '&FOCUS_PATHWAY_ID=' + this.focus_pathway_id;
	//	console.log("pathway id " + this.focus_pathway_id);
	//	console.log("surl " + sUrl);
		if (forceCoordinates) sUrl += '&COORDINATES=1';
		var ol = overlayElementWithTimeIndicator(this.detailsPane.getDetailsDiv());
		var callback = {
			scope: this,
			customevents: {
				onSuccess: function(eventType, args) {
					this.current_instance_id = dbid;
                  //  var h = eval('(' + args[0].responseText + ')');
					var h = getJsonFromRawText(args[0].responseText);
                    var o = new Object();
                    o.details = h.details;
                    o.map_highlites 	  = h.map_highlites;
                 //   console.log("map hilites " + o.map_highlites);
                    o.hierarchy_highlites = h.hierarchy_highlites;
                    o.top_highlites 	  = h.top_highlites;
                    if(h.coordinates){
                    	o.coordinates = h.coordinates;
                    }
					if (! treenodesAlreadyHandled) {
						this.eventHierarchyPane.removeTreeNodeHilites();
						if ($A(o.hierarchy_highlites).indexOf(dbid) >= 0) {
							this.eventHierarchyPane.treehighlites1 = [dbid];
							this.eventHierarchyPane.highliteTreeNodesByEventDbIds(this.eventHierarchyPane.treehighlites1,this.eventHierarchyPane.treehighlites1cls);
						}
						this.eventHierarchyPane.treehighlites2 = $A(o.hierarchy_highlites).without(this.eventHierarchyPane.treehighlites1, this.focus_pathway_id);
						this.eventHierarchyPane.treehighlites2 = new Array();
						this.eventHierarchyPane.highliteNodeInEventHierarchyById(dbid,this.eventHierarchyPane.treehighlites2cls)
					}
					if (o.focus_species_id) {
				    	this.setFocusSpecies(o.focus_species_id);
				    	this.eventHierarchyPane.buildEventHierarchy();
				    }
					// if focus change
					if ((otherPathway && otherPathway==true)  
							&& (processDetails == undefined || processDetails == false)) {
						this.changeFocusPathway(dbid);
						this.eventHierarchyPane.selectPathway(dbid);
					}
				    this.detailsPane.processDetails(o.details);
				    if (o.map_highlites && ( this.focus_pathway_id != dbid)) {
				    	/*
				    	 * if the dbid is not present in the dbnodes structure then the id is for a pathway, not an entity.
				    	 */
				    	if(this.pathwayDiagramPane.dbnodes[dbid]==undefined){
				    	//	console.log("node undefined");
				    		if(selectedEntityId){
				    			this.pathwayDiagramPane.getComplexComponentsForNodeHighlighting(o.map_highlites, selectedEntityId);
				    		}else{
				    			this.pathwayDiagramPane.processHighlites(o.map_highlites, null, selectedEntityId);
				    		}
				    	}else{
				    		if(this.vertexId){
				    			o.map_highlites = new Array();
				    			o.map_highlites[0]=this.vertexId;
				    		}else{
				    			o.map_highlites = new Array();
				    			o.map_highlites[0] = dbid;
				    		}
				    		/**
				    		 * Next lines are a patch for fiting the diagram
				    		 * to the available space when it is loaded from
				    		 * a search of the front page
				    		 */
				    		var centre = true;
				    		//this._isFirstLoad is not longer used in the rest
				    		//of the webapp
				    		if(this._isFirstLoad==undefined){
				    			centre = false;
				    			this._isFirstLoad = false;
				    			this.pathwayDiagramPane.fitPathway();
				    		}
				    		this.pathwayDiagramPane.processHighlites(o.map_highlites, this.vertexId, selectedEntityId, centre);
				    	}
				    }
				    this.updateLocationHref();
                    this.pathwayLoadedEvent.fire();
					
					this.detailsPane.createParticipatingMoleculesButton(dbid);
				}, 
				onFailure: function(eventType, args) {
				},
				onComplete: function(eventType, args) {
					if (ol) ol.remove();
				}
			}
		};
		YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
	},

	loadAndProcessSearchResultsData: function(dbid, forceCoordinates, treenodesAlreadyHandled) {
		var sUrl = this.loadAndProcessDataUrl + '?DB=' + this.db + 
			'&FOCUS_SPECIES_ID=' + this.focus_species_id + '&ID=' + dbid;
		if (this.focus_pathway_id) sUrl += '&FOCUS_PATHWAY_ID=' + this.focus_pathway_id;
		if (forceCoordinates) sUrl += '&COORDINATES=1';
		var ol = overlayElementWithTimeIndicator(this.detailsPane.getDetailsDiv());
		var leftpanelol = overlayElementWithTimeIndicator($("leftpanel"));
		var callback = {
			scope: this,
			customevents: {
				onSuccess: function(eventType, args) {
					this.current_instance_id = dbid;
					//var o = eval('(' + args[0].responseText + ')');
					var o = getJsonFromRawText(args[0].responseText);
					if (! treenodesAlreadyHandled) {
						this.eventHierarchyPane.removeTreeNodeHilites();
					}
				    this.eventHierarchyPane.buildSearchResultsHierarchy(o.hierarchy_highlites, leftpanelol, dbid);
				}, 
				onFailure: function(eventType, args) {
					if (leftpanelol) leftpanelol.remove();
				},
				onComplete: function(eventType, args) {
					if (ol) ol.remove();
					//if(leftpanelol) leftpanelol.remove();
				}
			}
		};
		YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
	}
});

YAHOO.util.Event.onDOMReady(function() {
	if (YAHOO.env.ua.ie > 0) {
		$('clipwrapper').setStyle({left:'0px'});
		$('thumbnailframe').setStyle({bottom:'0px',left:'0px'});
		/*
		 * To get horizontal scrollbar for the hierarchy tab as overflow: auto 
		 * and overflow:scroll does not have the desired effect in IE.
		 */
		$('hierarchytab').setStyle({width:'600px'});
	}
	
	//************************************************************************//
	//********** Shows an example of how to open the 'Diagram key' ***********//
	//************************************************************************//
	var value = YAHOO.util.Cookie.get("PathwayBrowserViews");
	value = (value==undefined || value==null) ? 1 : ++value;
	YAHOO.util.Cookie.set("PathwayBrowserViews", value);
	if (value <= 2) {
		new Effect.Pulsate('legend', {pulses: 10,duration: 4.0});
		setTimeout("new Effect.Appear('legend_img');", 1000);
		setTimeout("new Effect.Fade('legend_img');", 2500);
	}
	//************************************************************************//
});


