// ----------------------------- Begin - Mobular reporting functions -------------------------------------//

function mobularTracking() {

    var tracking = eengine.reporting.getLatest();
	var pos = parseInt(tracking.action, 10);
	
	var imgRef = '';
	switch ( pos ) {
		case -915:
			// because reporting is loaded after the first pair of doc viewed open events fire.. hack a workaround here.
			// for the opening of the e-document/e-kit
			
			// launch an engineload first			
			fireTrackingImage(tracking, 'engineload.gif');			
			
			// now process engineview
			imgRef = 'engineview.gif';			
			break;	
	   case 0:
	     imgRef = 'nomatch.gif';
	     break;	   
	   case 1:
	     imgRef = 'searchtop.gif';
	     break;	   
	   case 2:
	     imgRef = 'itemview.gif';
	     break;	   
	   case 3:
	     imgRef = 'helppixel.gif';
	     break;	   
	   case 4:
	     imgRef = 'aboutpixel.gif';
	     break;	   
	   case 5:
	     imgRef = 'showtop.gif';
	     break;	   
	   case 7:
	     imgRef = 's2f.gif';
	     break;	   
	   case 10:
	     imgRef = 's2d.gif';
	     break;	   
	   case 12:
	     imgRef = 'printview.gif';
	     break;	   
	   case 13:
	     imgRef = 'pageview.gif';
	     break;	   
	   case 14:
	     imgRef = 'engineload.gif';
	     break;	   
	   case 15:
	     imgRef = 'engineview.gif';
	     break;	   
	   case 16:
	     imgRef = 'redir.gif';
	     break;	   
	   case 21:
	     imgRef = 'error.gif';
	     break;
	}
    
    if ( imgRef != '' ) {      
       // generate new image request.
	   fireTrackingImage(tracking, imgRef);
    }
}

function fireTrackingImage(tracking, imgRef) {
   // generate new image request.
   var trackImg = new Image();
   var queryString = tracking.details;
   var div = '';
   if ( queryString != '' ) {
	 div = '&';
   }
   if ( tracking.query != '' ) {
	 queryString += div + tracking.query;
   }
   var tImgRef = eengine.qualifyUrl( addTracking( eengine.getIPath(imgRef,0), queryString, tracking.clickNumber ), 1 );	   
   // render tracking image
   trackImg.src = tImgRef;     
}

function buildTracking(imgRef, miscParam, clickNo) {
   return ('\n<IMG SRC="'+eengine.qualifyUrl( addTracking( eengine.getIPath(imgRef,0), miscParam, clickNo ), 1 )+'" width="1" height="1">');
}

function addTracking(sourceImage, addPrm, clickNo) {

     if ( addPrm != "" ) addPrm = "&" + addPrm;
     var _si = sourceImage+"?id="+uniqueId+addPrm+miscTrackParam+"&vid="+vendorId+"&lid="+listId+"&vertid="+verticalId+"&cno="+clickNo+"&tid=0&sid="+sourceId+"&cid="+eengine.serialNumber;
     return _si;
}

// ----------------------------- End - Mobular reporting functions ---------------------------------------//

// ----------------------------- Begin - Coremetrics reporting functions ---------------------------------//

// This assumes that the Coremetrics source javascript has already been sourced into the base page.
//
// The actual code to be included in the index.html for Coremetrics reporting to work is as follows
// (minus the js comment (//) identifiers of course):
//
//		<!-- Copyright Coremetrics, Inc. 2006 -->
//		<script language="JavaScript1.1" type="text/JavaScript"> var SA_ID="mobular;mobular";</script>
//		<script language="JavaScript1.1" type="text/JavaScript" src="//stats.surfaid.ihost.com/sacdcg1p_mobular_mobular.js"></script>
//		<noscript>
//		<img src="//stats.surfaid.ihost.com/crc/images/uc.GIF?1.20&amp;mobular&amp;mobular&amp;noscript" height="1" width="1" alt="" border="0"/>
//		</noscript>	   

function cmTracking() {

	this.getDocName = function() {
		// grab current status and doc handle
		var pgStatus = eengine.kitData.current;
		var docs = eengine.kitData.documents;
		return escape(docs[pgStatus.doc].title) + ":";
	};
	
	this.prependDocName = function(msg) {
		// If its a kit, prepend the document name to the page information
		if ( eengine.kitData.documents.length > 1 ) {
			msg += this.getDocName();
		}		
		return msg;
	};

	// get a handle to the latest item recorded by the tracking object
    var tracking = eengine.reporting.getLatest();
	
	// get the number of the action recorded
	var pos = parseInt(tracking.action, 10);
	
	// sift through actions... only process the ones we want, ignore the rest
	var msg = '';
	switch ( pos ) {
		case -915:
			// because reporting is loaded after the first pair of doc viewed open events fire.. hack a workaround here.
			// for the opening of the e-document/e-kit
			if ( eengine.trackLoad == 1 ) {
				msg = "action=SiteOpened";		
				eengine.trackLoad = 2;
			}			
			break;
		case 0:		
			// declare object to capture the keyword to use
			var re =/keywords=([^&]*)/gi;
			tracking.details.match(re);
			
			// capture a failed search
			var kwd = RegExp.$1;
			if ( kwd != '' ) {
				// only record action if a keyword was entered.
				msg = "action=SearchFailure&details="+escape(kwd);
			}
			break;
			
		case 1:		
			// declare object to capture the keyword to use
			var re =/keywords=([^&]*)/gi;
			tracking.details.match(re);
			
			// capture a successful search
			var kwd = RegExp.$1;
			if ( kwd != '' ) {
				// only record action if a keyword was entered.
				msg = "action=SearchSuccess&details="+escape(kwd);
			}
			break;
			
		case 3:
			// capture the display of a help page
			msg = "action=DisplayHelp";
			break;
			
		case 4:
			// capture the display of the about page
			msg = "action=DisplayAbout";
			break;
			
        case 5:
			// capture the display of a cover page
			msg = "action=DisplayCover";
			break;	
			
		case 6:
			// capture the display of a send to friend page
			msg = "action=DisplaySendToFriend";
			break;
			
		case 7:
			// capture the completion of a send to friend operation
			msg = "action=SendToFriendShortcut";
			break;			
			
		case 8:
			// capture the 'go to page' action
			var pg =/page=([^&]+)/gi;
			tracking.details.match(pg);
						
			var pgnum = RegExp.$1;
			if ( pgnum != '' ) {
				msg = "action=GoToPage&details=";
				// If its a kit, prepend the document name to the page information
				msg = this.prependDocName(msg);
				msg += pgnum;
			}
			break;
			
		case 9:
			// capture the display of 'save to desktop' page
			msg = "action=DisplaySaveToDesktop"; 
			break;
			
		case 10:
			// capture the execution of the 'save to desktop' operation
			msg = "action=SaveToDesktopComplete"; 
			break;

		case 11:
			// capture the display of the print form
			msg = "action=DisplayPrint";
			break;
			
		case 12:
			// capture the printing of a page or pages
			
			// For PDF printing, set the clickthrough type so that you can eat the clickthrough when 
			// doClickThrough fires a tracking id: 16.
			g_clickthroughType = "print";		
			
			// strip off the prtid
			var t_details = "";
			var print_id = "";
			var print_rng = "";
			var print_png2 = "";

			//var obj = /prtid=([0-9])&rng=([^&]+)&png2=(.+)/ig;
			var obj = /prtid=([0-9])&rng=([^&]+)&png2=(.*)/ig;
			if (tracking.details.match(obj)) { 		
				print_id = RegExp.$1;
				print_rng = RegExp.$2;
				print_png2 = RegExp.$3;				
			} else {
			//	alert("Invalid tracking call for printing.  This message should never appear (" + tracking.details + ")");
			}
			
			// get the pages printed
			var s_pg = 0;
			var e_pg = 0;
			
			var pg = /(.+),(.+)/gi;
			if (print_rng.match(pg)) {
				s_pg = RegExp.$1;
				e_pg = RegExp.$2;
			} else {
				s_pg = print_rng;
			}
			
			// get the pages printed
			var start_page = "";
			var end_page = "";
	
			if (print_png2.match(pg)) {
				start_page = RegExp.$1;
				end_page = RegExp.$2;
			} else {
				start_page = print_png2;
			}

			msg = "action=PrintPage&details=";
			
			// If its a kit, prepend the document name to the page information
			msg = this.prependDocName(msg);

			// Add the page information			
			msg += start_page;
			if (end_page != "") { msg += "-" + end_page }
			break;

		case 13:
			// capture the display of a page or pages
			var left_page = "";
			var right_page = "";
			
			var pg = /page=([^&]+),([^&]+)/gi;
			if (tracking.details.match(pg)) {
				left_page = RegExp.$1;
				right_page = RegExp.$2;
			} else {
				pg =/page=([^&]+)/gi;
				if (tracking.details.match(pg)) {
					left_page = RegExp.$1;
				} else {
				//	alert("Invalid tracking call for writePage.  This message should never appear (" + tracking.details + ")");
				}
			}
			if (right_page != "") { msg = "action=TwoPageSpread&details=" } else { msg = "action=SinglePageSpread&details=" }
			
			// If its a kit, prepend the document name to the page information
			msg = this.prependDocName(msg);

			// Add the page information			
			msg += left_page;
			if (right_page != "") { msg += "-" + right_page }
			break;
			
		case 15:
			// capture the opening of the e-document/e-kit		
			msg = "action=SiteOpened";
			break;
			
		case 16:
			// capture the click through/redirection event
			var obj =/url=([^&]+)/gi;
			tracking.details.match(obj);
						
			var url = RegExp.$1;
			if ( url != '' ) {
				if (url.indexOf('about:blank') == -1)
				{
					if (url.indexOf(baseUrl) >= 0 && url.indexOf("/print/") >= 0)
					{
						// If the clickthrough is coming from the printing operation, eat it because
						// the print operation has already been recorded and the doClickThrough is 
						// simply a means to an end.  If the click through is coming from S2D, 
						// record it as such.
						if (g_clickthroughType != "print")
						{
							msg = "page=SaveToDesktopPDF&qkwd=" + escape(url);
						}
						// Reset the clickthrough type for future use.
						g_clickthroughType = "";
					} else {
						msg = "page=ClickThrough&qkwd=" + escape(url);
					}
				}
			}
						
			break;
	}
		
    if ( msg != '' ) {    	
		var query = "";
		if (tracking.query != "") {
			// Strip out either function that initializes tracking debugging
			var obj =/(.*)(?:where=cmDebug\(.*\)|where=fullDebug\(.*\))(.*)/gi;
			if (tracking.query.match(obj)) { 		
				query = RegExp.$1 + RegExp.$2; 
			} else {
				query = tracking.query;
			}
		
			// Strip off a trailing ampersand, if necessary
			obj = /(.*)\&$/gi;
			if (query.match(obj)) { query = RegExp.$1 }
	
			// Prepend the remaining query string to the tracking variables
			if (query != "") { msg = query + "&" + msg }
		}
		
		// Add any miscellaneous tracking parameters as well as the engine information
		msg += "&cid=" + cid + "&campid=" + campid + "&engineid=" + engineid + miscTrackParam;
  
		// SA_Message for Surfaid 
		SA_Message=msg;

		if (g_cmDebug) { 
			alert("window.SA_Message = " + window.SA_Message);

			//Temporary hijack of the global div tag...
			var gRC = document.getElementById("globalRC");
			if ( gRC ) {
				document.getElementById("globalRC").innerHTML = "window.SA_Message='" + window.SA_Message + "'";
			}
		}

		try {
			sa_onclick(tracking.url);  
		} catch(e){
			if (g_cmDebug) { 
				alert('Unable to successfully call the Coremetrics sa_onclick function for usage tracking.\n\nIs the stats.js file being loaded in the index.html file? '+e.message);
			}
		}	
		
		if ( ( eengine.trackLoad == 2 ) && ( msg.indexOf("action=SiteOpened") != -1 ) ) {
			eengine.trackLoad = 3;
			// hack to force a DisplayCover at this point in time
			msg = msg.replace("action=SiteOpened", "action=DisplayCover");
			
			// SA_Message for Surfaid 
			SA_Message=msg;
			try {
				sa_onclick(tracking.url);  
			} catch(e){
				if (g_cmDebug) { 
					alert('Unable to successfully call the Coremetrics sa_onclick function for usage tracking.\n\nIs the stats.js file being loaded in the index.html file?');
				}
			}
		}		
    }
}

// This function is used to turn on debug alert boxes for Coremetrics reporting.  If desired,
// the function is called through a query string on any URL deploying this reporting.js file.
//
// For example:  http://preview.mobular.net/mobularshow/69/234/388/index.html?where=cmDebug()
//
var g_cmDebug = 0;
function cmDebug() {
	g_cmDebug = 1;
}

try {
	var _q = location.search;
	_q = _q.replace(/^\?/i, '');
	if ( _q.toLowerCase().indexOf('=cmdebug()') != -1 ) {
		cmDebug();
	}
} catch (e) {}

// Global variable used to distinguish a PDF S2D and a PDF print operation.
var g_clickthroughType = "";

// ----------------------------- End - Coremetrics reporting functions -----------------------------------//


// ----------------------------- Begin - Registration of any reporting functions -------------------------//

// register Mobular tracking with the parametric reporting object
eengine.reporting.addEvent("mobularTracking()");

// register Coremetrics tracking with the parametric reporting object
eengine.reporting.addEvent("cmTracking()");

// ----------------------------- End - Registration of any reporting functions ---------------------------//

