DetailsPane = function () {};

Object.extend(DetailsPane.prototype, {
	
	internalLinkClickEvent : new YAHOO.util.CustomEvent("InternalLinkClickEvent", this),
	speciesComparisonChangeEvent :  new YAHOO.util.CustomEvent("SpeciesComparisonChangeEvent", this),
	
	participatingMolecules: 'participatingMolecules',
	participatingMoleculesMatches: 'participatingMoleculesMatches',
	
	eventTracker : new EventTracker({
    	category: "Details"
    }),
    
	loadDetails: function(dbid) {
		var sUrl = '/cgi-bin/entitylevelview/details?DB=' + this.db + "&FOCUS_SPECIES_ID=" + 
			this.focus_species_id + "&ID=" + dbid;
		var details = this.getDetailsDiv();
	    var ol = overlayElementWithTimeIndicator(details, 40);
		var callback = {
			scope: this,
			customevents:{
				onSuccess: function(eventType, args) {
					var o = null; 
					try{
						//o = eval('(' + args[0].responseText + ')');
						o = getJsonFromRawText(args[0].responseText);
					}catch(err){
						
					}
					this.processDetails(o.details);
					this.current_instance_id = dbid;
					this.createParticipatingMoleculesButton(dbid);
				}, 
				onFailure: function(eventType, args) {
					$('details').innerHTML = "<PRE>There was a problem loading the details of instance with DB_ID " +dbid+ ":\n" + args[0].statusText + "</PRE>";
				},
				onComplete: function(eventType, args) {
					if (ol) ol.remove();
				}
			}
		};
		YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
	},
	tweakInternalLinks: function(links) {
	    var re = new RegExp("ID=(\\d+)");
	    var matchStableIdScript = new RegExp(".*control_panel_st_id.*");
	    for (var i = 0, l = links.length; i < l; ++i) {
			var href = links[i].readAttribute('href');
			if (href) {
				if(href.match(matchStableIdScript)){
					links[i].pathname       = links[i].pathname.replace("entitylevelview", "cgi-bin");
				}
		    	var matches = href.match(re);
		    	if (matches) {
		    		try{
		    			var parent = links[i].parentNode;
		    			// If one of these links is clicked on activate species switching
		    			if(parent.className == "inferredFromRev" || parent.className == "orthologousEvent" || parent.className == "inferredFrom"){
		    				links[i].setAttribute("href","javascript:pba.detailsPane.fireInternalLinkClickEvent(" + matches[1] + ",\"switchspecies\")");
		    			}else{
		    				links[i].setAttribute("href","javascript:pba.detailsPane.fireInternalLinkClickEvent(" + matches[1] + ")");
		    			}
		    		}catch(err){
	
		    		}
		    	}
			}
	    }
	},
	processDetails: function(details) {
		//log("processDetails");
	    var ds = this.getDetailsDiv();
	    if (details) {
			var html = decodeURIComponent(details[0]);
			var script = decodeURIComponent(details[1]);
			/*
			 * eval script is not nice - refactor to server side includes if possible.
			 */
			ds.innerHTML = html.replace(/<script.*?>(\n|\r|.)*?<\/script>/,eval(script));
			var links = ds.getElementsBySelector('a');
			this.tweakInternalLinks(links);
			
			/* ######################### Next lines are for the GOOGLE ANALYTICS event tracking ######################### */
			/* This way is not the best one, but allows us to use the common eventTrack object        */
			_SBML_handler = this.eventTracker.track.bind(this.eventTracker, "Download SMBL", this.focus_pathway_id);
			_BioPAX2_handler = this.eventTracker.track.bind(this.eventTracker, "Download BioPAX2", this.focus_pathway_id);
			_BioPAX3_handler = this.eventTracker.track.bind(this.eventTracker, "Download BioPAX3", this.focus_pathway_id);
			_PDF_handler = this.eventTracker.track.bind(this.eventTracker, "Download PDF", this.focus_pathway_id);
			_Protege_handler = this.eventTracker.track.bind(this.eventTracker, "Download Protege", this.focus_pathway_id);
			/* ########################################################################################################## */
			
			/*
			 * Add species comparison drop down and download links
			 */
			ds.innerHTML = ds.innerHTML + "<table class=\"SpeciesComparisonDetails\" cellspacing=\"0\" border=\"0\"><tbody><tr><th class=\"speciesComparisonDetailsPane\" style='width:305px;'>Compare human pathway to</th><td>" 
										+ "<select id=\"speciescomparisondropdowndetails\"  name=\"speciescomparedropdowndetails\">" 
										+ $("speciescomparedropdown").innerHTML
										+ "</select></td></tr></tbody></table>"
			
										+ "<table class=\"Pathway\" cellspacing=\"0\" border=\"0\"><tbody><tr><th onmouseover=\"ddrivetip('Download the current pathway in one of these formats.','#DCDCDC', 250)\" onmouseout=\"hideddrivetip()\" class=\"downloadLinks\">Download pathway in one of the formats</th><td>" 
			 							+ "<a onClick=\"_SBML_handler()\" target=\"_blank\" href=\"/ReactomeGWT/entrypoint/sbmlRetrieval?ID=" + this.focus_pathway_id + "\">[SBML]</a>"
			 							
			 							+ "<a onClick=\"_BioPAX2_handler()\" target=\"_blank\" href=\"/cgi-bin/biopaxexporter?DB=" + this.db + "&amp;level=2&amp;ID=" + this.focus_pathway_id +   "\" onmouseout=\"hideddrivetip()\"" 
			 							+ "onmouseover=\"ddrivetip('Download process in BioPAX level 2 format.','#DCDCDC', 250)\">[BioPAX2]</a>"
			 							
			 							+ "<a onClick=\"_BioPAX3_handler()\" target=\"_blank\" href=\"/cgi-bin/biopaxexporter?DB=" + this.db + "&amp;level=3&amp;ID=" + this.focus_pathway_id +   "\" onmouseout=\"hideddrivetip()\""
			 							+ "onmouseover=\"ddrivetip('Download process in BioPAX level 3 format.','#DCDCDC', 250)\">[BioPAX3]</a>"
			 							
			 							+ "<a onClick=\"_PDF_handler()\" target=\"_blank\" href=\"/cgi-bin/pdfexporter?DB=" +this.db + "&amp;ID=" + this.focus_pathway_id +   "\" onmouseout=\"hideddrivetip()\" " 
			 							+ "onmouseover=\"ddrivetip('View/Download process in PDF format.','#DCDCDC', 250)\">[PDF]</a>"
			 							
			 							+ "<a onClick=\"_Protege_handler()\" target=\"_blank\" href=\"/cgi-bin/protegeexporter?DB=" + this.db +  "&amp;ID=" + this.focus_pathway_id +   "\" onmouseout=\"hideddrivetip()\" " 
			 							+ "onmouseover=\"ddrivetip('Download process as Protege project.','#DCDCDC', 250)\">[Protege]</a>"
			 							+ "</td></tr><tr>"
										+ "<th class='"+ this.participatingMolecules +"' class=\"downloadLinks\">Participating Molecules <span id='"+ this.participatingMoleculesMatches +"'></span></th>"
										+ "<td class='"+ this.participatingMolecules +"'><div id='"+ this.participatingMolecules +"' class='" + this.participatingMolecules +"'>"
										//+ "       <img src=\"icons/ajax-loader.gif\"/>&nbsp;<span style=\"color:#3B6ACC\">Loading participating molecules...</span>"
										+ "</div></td></tr></tbody></table>";
										try{
											this.updateSpeciesDropDown($("speciescomparedropdown").selectedIndex);
										}catch(err){
				
										}
			//console.info(ds.innerHTML);										
			$("speciescomparisondropdowndetails").onchange= this.onSpeciesComparisonChange.bind(this);
	    } else {
			ds.innerHTML = "";
	    }
	},
	getDetailsDiv: function() {
		return $("details");
	},
	fireInternalLinkClickEvent : function (dbId, switchspecies) {
		this.internalLinkClickEvent.fire(dbId, switchspecies);
	},
	onSpeciesComparisonChange : function(e){
		if(e == undefined){
			e = window.event;
		}
		this.speciesComparisonChangeEvent.fire(e);
	},
	
	/*
	 * Used when species comparison has been activated in control panel. Synchronise dropdown in details pane with new selection
	 */
	updateSpeciesDropDown : function(selectedIndex){
		var dropdown = $("speciescomparisondropdowndetails");
		try{
			if(dropdown){
				if(dropdown.selectedIndex != selectedIndex){
					dropdown.selectedIndex = selectedIndex;
					/*
					 * If update is called the value is being set programmatically instead of by the user choosing from the dropdown.
					 * In this case don't handle the event.
					 */
					$("speciescomparisondropdowndetails").onchange= null;
					if(dropdown.onchange)
						dropdown.onchange();
					$("speciescomparisondropdowndetails").onchange= this.onSpeciesComparisonChange.bind(this);
				}
			}
		}catch(err){
			
		}
	},

	/**
	 * Creates the button for lauching the participating molecules request to
	 * the server in function of the item identifier and the participating
	 * molecules containers defined in this class
	 * 
	 * @param {Object} dbid item database identifier
	 */	
	createParticipatingMoleculesButton: function(dbid){
		var b = document.createElement('button');
		b.innerHTML = '&nbsp;Load participating molecules&nbsp;';
		$(this.participatingMolecules).appendChild(b);

		var pm = new ParticipatingMolecules(this.participatingMolecules,
											this.participatingMoleculesMatches,
											this.db,
											dbid);
		Event.observe(b,'click', pm.load.bindAsEventListener(pm));
	}
});


