/**
 * eventLogger.js
 * @description Logs library guide events
 * @author Rebecca Younes
 * @date September 2007
 */

ILR.namespace("library.guides");

/**
 * @namespace ILR.library.guides
 * @class AjaxEventLogger
 */

ILR.library.guides.AjaxEventLogger = {

	init : function() {

		// NB local vars used only within the current function. Properties of "this" may be 
		// accessed from other functions.
		var  requiredScripts = [	
				// RY 11/7/07 scriptLoader works for scripts needed by event listeners, but not
				// for those needed on page load.
				// ILR.js.yui + "connection/connection-min.js",
				ILR.js.ilr + "prototype/String.js",
				ILR.js.ilr + "dom/dom.js"
			], 
			dropDown = document.getElementById("dropDownResourceSelect"),
			subjectNavLinks = document.getElementById("catherwoodGuideSubjectNavigation").getElementsByTagName("a"),
			guideLinks = YAHOO.util.Dom.getElementsByClassName("guideLink", "a", "catherwoodGuide"),
			resource = "/library/customcf/guides/logging/initPage.cfm",
			query; 
		
		// Load required scripts			
		ILR.util.scriptLoader.loadScripts(requiredScripts);

		// Attach event listeners for logging
		YAHOO.util.Event.addListener(dropDown, "change", this.handleGuideEvent, this, true);		
		YAHOO.util.Event.addListener(subjectNavLinks, "click", this.handleGuideEvent, this, true);
		YAHOO.util.Event.addListener(guideLinks, "click", this.handleGuideEvent, this, true);	
				
		// Set up guide/page-level information
		this.page = window.location;
		this.guideName = encodeURIComponent(document.getElementById("guideName").firstChild.nodeValue);
		this.taxonomyId = document.getElementById("taxonomyId").firstChild.nodeValue;
		
		query = query = "?tid=" + this.taxonomyId + "&page=" + this.page + "&guide=" + this.guideName;
		YAHOO.util.Connect.asyncRequest("GET", resource + query, null, null); 
		// Debugging version
		// YAHOO.util.Connect.asyncRequest("GET", resource + query, { success: function(o) {alert(o.responseText)}}, null);				

	},		
	
			 
	handleGuideEvent : function(event) {
		
		var eventTarget = YAHOO.util.Event.getTarget(event);

		this.setTargetTerm(eventTarget);
		this.setTaxonomyPath(eventTarget);			
		this.log();
		
	},
		
    // We pass the server the following pieces of information: 
	// 1. tid: taxonomy Id. Output on the page by the renderhandler and determined from the DOM. Alternatively
	// could query the database in the cfc init() function, but then need to hard-code the taxonomy name.
	// 2. page: url of the guide page.
	// 3. guideName: name of the current guide. This is determined from the DOM rather than looked up 
	// in the taxonomy table based on the first term of the path, so that we can use the alternative
	// guide name that has been assigned to the page, if one exists.
	// 4. target: The item clicked/selected
	// 5. targetType: The type of item clicked/selected (subject nav link, guide link, or dropdown)
	// 6. taxPath: A sequence of numbers that can be used to identify the path through the taxonomy
	// leading to this item
	// 1, 2, and 3 are specific to the page/guide rather than the event, but we cannot store them in session
	// scope at page load time only, because then logging won't work when the session expires. 
	log : function() {
		
		var	resource = "/library/customcf/guides/logging/logGuideEvent.cfm",
			query = "?tid=" + this.taxonomyId + "&page=" + this.page + "&guide=" + this.guideName + "&target=" + encodeURIComponent(this.target) + "&targetType=" + this.targetType + "&taxPath=" + this.taxPath;

		this.reset();
		
		YAHOO.util.Connect.asyncRequest("GET", resource + query, null, null);
		// Debugging version
		// YAHOO.util.Connect.asyncRequest("GET", resource + query, { success: function(o) {alert(o.responseText)}}, null);		
	},
	
	reset :  function() {
		this.targetType = "";
		this.target = "";
		this.taxPath = "";
	},
	
	setTargetTerm : function(eventTarget) {
		
		// the dropdown of all guide resources
		if (eventTarget.tagName == "SELECT") {
			this.targetType = "dropDown";
			this.target = eventTarget.options[eventTarget.selectedIndex].text;
		}
		
		// subject nav links 
		else if (YAHOO.util.Dom.isAncestor("catherwoodGuideSubjectNavigation", eventTarget)) {
			this.targetType = "subjectNavLink";
			this.target = eventTarget.href.match("Heading[\\d_]+")[0];
			// The target here is the path through the navigation menu, leaving out the top term
			// for the guide name. Because the navigation can be multiple levels deep, we
			// can't use this.target = eventTarget.firstChild.nodeValue.trim() as for guide links
			this.target = this.trimPath(this.target);
		}
		
		// guide links
		else { // if (YAHOO.util.Dom.hasClass(eventTarget, "guideLink")) {
			this.targetType = "guideLink";

			// For library holdings, the link text is just "Cornell University Library Holdings", which 
			// isn't revealing to log. We can't store the item's title as the link id, because, though
			// whitespace could be replaced with underscores, it can also contain punctuation, which
			// isn't allowed in xhtml identifiers. We need to get the item name from the dt which is the
			// previous sibling of the enclosing dd.				
			if (YAHOO.util.Dom.hasClass(eventTarget, "libraryHoldingLink")) {
				eventTarget = YAHOO.util.Dom.getPreviousSibling(YAHOO.util.Dom.getAncestorByTagName(eventTarget, "DD"));
			}
			this.target = eventTarget.firstChild.nodeValue.trim();				
		}	
	},
		
	setTaxonomyPath : function(eventTarget) {
		
		var taxPath,
			activeSectionIds = [],
			numActiveSections,
			i;
	
		if (this.targetType == "subjectNavLink") {
			// When the taxonomy is 3 or more levels deep, coordinate terms can be displayed on the page
			// simultaneously. In this case, we want the taxonomyPath to exclude the coordinate terms.
			// For example, in International/Global, click on Statistics/Data, and all subsections of
			// Statistics/Data are displayed. 
			activeSectionIds = getAttributes(YAHOO.util.Dom.getElementsByClassName("activeSection", "span", "catherwoodGuide"), "id");			
			numActiveSections = activeSectionIds.length;
			for (i = 0; i < numActiveSections; i++) {
				if (i == 0 || activeSectionIds[i].indexOf(activeSectionIds[i-1]) >= 0) {
					taxPath = activeSectionIds[i];
				}
				else {
					taxPath = activeSectionIds[i-2];
					break;
				}
			}
		}
		// dropdown or guide link
		else {
			// NB Not: YAHOO.util.Dom.getElementsByClassName("activeSection", "span", "catherwoodGuide").pop().id
			// When there are more than two tiers in the taxonomy, coordinate subsections can be displayed on the page.
			// simultaneously. We need to get the path to the link that was clicked, not a list of all active subsections.
			taxPath = YAHOO.util.Dom.getAncestorByClassName(eventTarget, "activeSection").id;	
		}
		
		this.taxPath = this.trimPath(taxPath);
	},
	
	trimPath : function(taxPath) {
		return taxPath.replace(/Heading_/, "").replace(/_$/, "");
	}
	
};

YAHOO.util.Event.addListener(window, "load", ILR.library.guides.AjaxEventLogger.init, ILR.library.guides.AjaxEventLogger, true);
