/** NOTE:	this file exists purely for backward compatibility reason for old embed charts.  
 *			We SHOULD NOT develop this file any further.  All additional code for WebMetrics
 *			should be done in common/javascript/Resource.js file instead.
 *
 *			all work for embedded charts tracking shoudl be done in Chart.js file.
 */

if ( typeof( Wikinvest ) == 'undefined' ) 
{
	// if Wikinvest is not defined, create the namespace
	Wikinvest = {};
}

if ( typeof( Wikinvest.WebMetrics ) == 'undefined' )
{
	// if WebMetrics is not defined, create the namespace
	Wikinvest.WebMetrics = {};
}

Wikinvest.WebMetrics.Tracker = function()
{
	this._uniqueUserKey = "Wikinvest_Plugin_UniqueUserKey";
	this._testKey = "Wikinvest_Plugin_TestKey";
	this._cookiePath = "/";
	this._url = "http://plugins.wikinvest.com/plugin/api.php?";
	this._urlDelimiter = "&";
};

Wikinvest.WebMetrics.Tracker.prototype._uniqueUserKey;
Wikinvest.WebMetrics.Tracker.prototype._testKey;
Wikinvest.WebMetrics.Tracker.prototype._cookiePath;
Wikinvest.WebMetrics.Tracker.prototype._url; 
Wikinvest.WebMetrics.Tracker.prototype._urlDelimiter;

/** this function sends an end time visit signal to server for a given user.  
 *  This function takes in a tracking type and a value, extracts the UU from cookie, and constructs 
 *  a server API to increment page view counter. 
 *
 *  params:
 *      trackingType    this will match a #define action and dictates what server API to call
 *      value           value will correspond to the tracking type (id for charts, url for page, etc)  

 */
Wikinvest.WebMetrics.Tracker.prototype._endTime = function(trackingType, value)
{
	//var hostUrl = document.location;
	var uidParameter = "uid=";
	var pageUrlParameter = "page_url=";
	var actionType = this._getActionString(trackingType);
	if (actionType.length != 0)
	{
		var url = this._url + actionType + this._urlDelimiter +
				pageUrlParameter + escape(value) + this._urlDelimiter +
				uidParameter;

		url = url + this._getOrSetUUIdFromCookie(false);
		this._makeUrlCall(url);
	}
};

/** this method is a wrapper call that makes a server call to track a user click.  This method 
 *  will be invoked if user clicks on a link in the blogger network. 
 * 
 *  @parameter:
 *      trackingType    this will match a #define action and dictates what server API to call
 *  	srcUrl			URL that the user is currently at
 *    	destUrl         URL that the user clicked on
 */ 
Wikinvest.WebMetrics.Tracker.prototype._trackUrlClick = function(trackingType, srcUrl, destUrl)
{
    //var hostUrl = document.location;
    var srcUrlParameter = "src_page_url=";
    var destUrlParameter = "dest_page_url=";
    var actionType = this._getActionString(trackingType);
	if (actionType.length != 0)
	{
		var url = this._url + actionType + this._urlDelimiter + 
                srcUrlParameter + escape(srcUrl) + this._urlDelimiter + 
                destUrlParameter + escape(destUrl);
		this._makeUrlCall(url);
	}
};

/** This function tracks an user view for a given type.  It takes in a tracking type and a value,  
 *  extracts the UU from cookie, and constructs a server API to increment page view counter. 
 *
 *  params:
 *		trackingType    this will match a #define action and dictates what server API to call
 *      value           value will correspond to the tracking type (id for charts, url for page, etc)  
 */
Wikinvest.WebMetrics.Tracker.prototype._trackPageView = function(trackingType, value)
{
	var uidParameter = "uid=";
	var pageUrlParameter = "page_url=";
	var actionType = this._getActionString(trackingType);
	if (actionType.length != 0)
	{
		var url = this._url + actionType + this._urlDelimiter + 
				pageUrlParameter + escape(value) + this._urlDelimiter + 
				uidParameter;

		url = url + this._getOrSetUUIdFromCookie(true); 
		this._makeUrlCall(url);
	}
};

/** this helper function takes in a tracking type enum and returns the string action for server.
 *  will return the right action string if enum is valid, or an empty string to denote an 
 *  unrecognized enum. 
 */
Wikinvest.WebMetrics.Tracker.prototype._getActionString = function(trackingType)
{
	var actionString = "action=";
	switch(trackingType)
	{
		case 1: //this is a url action 
			actionString = actionString + "metricpv";
			break;
		case 2: //this is a chart view
			actionString = actionString + "metriccv"; 
			break;
		case 3: //this is a end time action
			actionString = actionString + "metricEnd";
			break;
		case 4: //this is a click action
			actionString = actionString + "metriclc";
			break;
		case 5: // this is a chart action 
			//actionString = actionString;
			break;
		default: 
			actionString = "";
			break;
	}
	return actionString;
};

/** this helper function will try to get the unique user id from the cookies.  if exist, it will
 *  return the id.  if the id does not exist in cookie, it will check to see if we should set the
 *  cookie and if we can set the cookie.  if so, it will generate a new id and set it in the cookie.
 *  if not, then it will return empty string to denote that the user does not have cookies enabled.
 *
 *  @parameter:
 * 		setCookie		true/false parameter that tells this function if it should generate a new
 * 						id to persist in the cookie or not. 
 */  
Wikinvest.WebMetrics.Tracker.prototype._getOrSetUUIdFromCookie = function(setCookie)
{
	var originalCookieUUId = this._getCookie(this._uniqueUserKey);
	if (originalCookieUUId.length == 0)
    {  // id does not exist, generate one and store in the cookie 
        if (setCookie && this._canSetCookie())
        { 
			var uniqueUserId = this._getUniqueId32();
        	var daysToExpire = 365;  
            this._setCookie(this._uniqueUserKey, uniqueUserId, daysToExpire, this._cookiePath);
            //return uniqueUserId; 
        }   
	// return either hte set cookie or an empty string if value cannot be set. 
		return this._getCookie(this._uniqueUserKey); 
    }   
    else
    {   // found the id in cookie, return it.
        return originalCookieUUId; 
    }   

};

Wikinvest.WebMetrics.Tracker.prototype._getUniqueId32 = function()
{
	return (this._random4digits() + this._random4digits() + this._random4digits() + 
			this._random4digits() + this._random4digits() + this._random4digits() + 
			this._random4digits() + this._random4digits());
};

/** Hack to call a URL on another domain
 *  The result from the url should be JS that can be executed
 *  @parameter:
 *    url          URL that needs to be called
 */
Wikinvest.WebMetrics.Tracker.prototype._makeUrlCall = function(url) 
{
	if ( (url != null) && (url.length != 0) )
	{
		//alert(url);
		var script = document.createElement('script');
		script.src = url;

		var addScript = function() 
		{	
			if(document.body) { document.body.appendChild( script ); }
		};
		setTimeout( addScript, 100 );
	}
};

Wikinvest.WebMetrics.Tracker.prototype._random4digits = function()
{
	return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};

Wikinvest.WebMetrics.Tracker.prototype._canSetCookie = function()
{
    var daysToExpire = 1;
    var randomValueBefore = this._getUniqueId32(); 
    this._setCookie(this._testKey, randomValueBefore, daysToExpire, this._cookiePath);
    var randomValueAfter = this._getCookie(this._testKey);
    return (randomValueBefore == randomValueAfter); 
};

/** this method provides a cleaner way to retrieve values from the cookie.  
 *  it breaks the cookie into an array of name/value pairs for all cookies, with each 
 *  cookie name/value pair to be an array itself (id = array[0], value = array[1]). 
 *  
 *  this method then scans through the array to look for matching id.  if found, return
 *  the associated value.  if not, this method returns empty string. 
 *
 livia.tam@gmail.com
 *  @parameter: 
 *		pKey           the id for the cookie value we want to retrieve.
 */
Wikinvest.WebMetrics.Tracker.prototype._getCookie = function(pKey)	
{
	var allCookies = document.cookie.split( ';' );
	var thisCookie = '';
	var cookieName = '';
	var cookieValue = '';
	
	for (i = 0; i < allCookies.length; i++)
	{
		thisCookie = allCookies[i].split('=');
				
		// trim left/right whitespace around the cookieName
		cookieName = thisCookie[0].replace(/^\s+|\s+$/g, '');
		if (cookieName == pKey)
		{
			// found cookie, see if a value exists
			if (thisCookie.length > 1) 
			{
				// get the unescaped value (will trim whitespace beforehand)
				cookieValue = unescape(thisCookie[1].replace(/^\s+|\s+$/g, ''));
				return cookieValue;
			}
		}
	}
	return "";
};

Wikinvest.WebMetrics.Tracker.prototype._setCookie = function(pKey, pValue, pExpirationDays, pPath)
{
	var expire = new Date();
    expire.setDate(expire.getDate() + pExpirationDays);
    var cookieString = pKey + "=" + pValue + 
		";expires=" + expire.toGMTString() + ";path=" + pPath;

	//alert("cookie set: " + cookieString);
    
	// this code will actually append the line to the end of the cookie since the only way to delete
	// a cookie is to set expiration_date <= current_date.
	document.cookie = cookieString; 
};

