/**
 * =========================================
 * @author Graphic Language, Inc. 2006 - 2007 
 * (SmartMetrics 2: Language Agnostic Data Miner)
 * ----------------------------------------------------
 * problems? contact: dperez@graphiclanguage.net
 * =========================================
 **/

	

	function init(){
		
		//main variables load the SMGL Account into the URL before anything else happens.
		_SMRootURL = 'http://74.52.231.109/smartmetrics2/?SMGLAcct=' + _SMGLAcct;
	
		
		/** 
		 * This function will decide the basic state of the user.
		 * Here are the possible states:
		 * 
		 * NEW VISITOR------------------------------------
		 * Will create SMCookie cookie which will determine that they
		 * have never been to this site before. Will also create
		 * SMSession cookie which will initalize this visitor as now an internal
		 * visitor of the site. gathers_external_entry_point_data after initalization
		 * of new user. (and keywords if available)
		 * 
		 * RETURNING VISITOR------------------------------
		 * Will create only the SMSession cookie which will initialize this visitor
		 * as now an internal visitor of the site. 
		 * gathers external_entry_point_data (and keywords if available)
		 * 
		 * INTERNAL VISITOR--------------------------------
		 * Creates no cookies, just gathers information regarding the users
		 * movements within the site via internal_marketing_data (and keywords if available)
		 **/

			
		if (getCookieValue('SMCookie') && getCookieValue('SMSession'))
		{
			
			//INTERNAL VISITOR SESSION
			
			//collect internal marketing
			collectInternalMarketingData();
			
			
			
			
			
			
			
		}
		
		else if (getCookieValue('SMCookie'))
		{
			//RETURNING VISITOR, INITIALIZE INTERNAL SESSION

			
			
			//collect entry point
			collectEntryPointData();

			
			
		}
		
		else
		{
		

				
				//create a new visitor
		  		createNewVisitor();
				



		}
		
		
		
			
	}	


	
	
	function collectEntryPointData(){
		
		var _referralURL = document.referrer;
		var _BaseQueryStr = new String(document.location.search);
				//mod
				_BaseQueryStr.replace("&","|");
		var _SMCookieValue = getCookieValue('SMCookie');
		
			
				var _collectExternalEntry= new JSONscriptRequest(_SMRootURL + '&method=EntryPoint' + '&refStr=' + _referralURL + '&uuid=' + _SMCookieValue + '&QryStr=' + _BaseQueryStr +  '&callback=entryPointHandler');
			  _collectExternalEntry.buildScriptTag();
			  _collectExternalEntry.addScriptTag();
		
		
		
	}
	
	
	
	function createNewVisitor(){
		
		 var _createNewVisitor= new JSONscriptRequest(_SMRootURL + '&method=newVisitor&callback=newVisitorHandler');
		  _createNewVisitor.buildScriptTag();
		  _createNewVisitor.addScriptTag();
		
	}
	
	
	
	function collectInternalMarketingData(){
		
		
		var _lastpage = document.referrer;
		var _currentpage = document.location;
		var _querystr = document.location.search;
		var _SMCookieValue = getCookieValue('SMCookie');
		
					var _internalMarketingData = new JSONscriptRequest(_SMRootURL + '&method=InternalMarketing' + '&lastLocStr=' + _lastpage + '&uuid=' + _SMCookieValue + '&currentLocStr=' + _currentpage + '&qryStr=' + _querystr + '&callback=internalMarketingHandler');
					 _internalMarketingData.buildScriptTag();
		 			 _internalMarketingData.addScriptTag();
	}
	
	
	
	
	
	
	
	
			
		
		/**
		 * EVENT HANDLERS FOR AJAX CALLS
		 **/
		
		

	
	function newVisitorHandler(result){
	
	//LETS WRITE THE PERSISTENT COOKIE WITH THE CUSTOMER UUID
	writePersistentCookie('SMCookie', result, 'years', 1);
	
				
				//Since they are new, lets collect their entry point stuff as well!
				collectEntryPointData();
		
	}
	
	
	
	function entryPointHandler(result){
		
	//NOW, LETS WRITE THE SESSION COOKIE TO DENOTE THEY ARE INTERNAL USERS
	writeSessionCookie('SMSession', 'isInitalizedSession: ' + result);
	
	}
	
	
	function internalMarketingHandler(result){
		
		//HANDLER FOR INTERNAL MARKETING DATA

	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * ==============================================================================
	 * IMPORTED DEPENDENCIES: BELOW THIS LINE IS THIRD PARTY IMPLIEMNTATIONS THAT CREATE MAGIC
	 * ==============================================================================
	 */
	

	
	
	/**
	 * Cookie Library, handles all cookie things
	 */
	
	
/*==============================================================================

    Routines written by John Gardner - 2003 - 2005

    See www.braemoor.co.uk/software for information about more freeware
    available.

/*==============================================================================

Routine to write a session cookie

    Parameters:
        cookieName        Cookie name
        cookieValue       Cookie Value
    
    Return value:
        true              Session cookie written successfullly
        false             Failed - persistent cookies are not enabled

   e.g. if (writeSessionCookie("pans","drizzle") then
           alert ("Session cookie written");
        else
           alert ("Sorry - Session cookies not enabled");
*/

function writeSessionCookie (cookieName, cookieValue) {
  if (testSessionCookie()) {
    document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
    return true;
  }
  else return false;
}

/*==============================================================================

Routine to get the current value of a cookie

    Parameters:
        cookieName        Cookie name
    
    Return value:
        false             Failed - no such cookie
        value             Value of the retrieved cookie

   e.g. if (!getCookieValue("pans") then  {
           cookieValue = getCoookieValue ("pans2);
        }
*/

function getCookieValue (cookieName) {
  var exp = new RegExp (escape(cookieName) + "=([^;]+)");
  if (exp.test (document.cookie + ";")) {
    exp.exec (document.cookie + ";");
    return unescape(RegExp.$1);
  }
  else return false;
}

/*==============================================================================

Routine to see if session cookies are enabled

    Parameters:
        None
    
    Return value:
        true              Session cookies are enabled
        false             Session cookies are not enabled

   e.g. if (testSessionCookie())
           alert ("Session coookies are enabled");
        else
           alert ("Session coookies are not enabled");
*/

function testSessionCookie () {
  document.cookie ="testSessionCookie=Enabled";
  if (getCookieValue ("testSessionCookie")=="Enabled")
    return true 
  else
    return false;
}

/*==============================================================================

Routine to see of persistent cookies are allowed:

    Parameters:
        None
    
    Return value:
        true              Session cookies are enabled
        false             Session cookies are not enabled

   e.g. if (testPersistentCookie()) then
           alert ("Persistent coookies are enabled");
        else
           alert ("Persistent coookies are not enabled");
*/

function testPersistentCookie () {
  writePersistentCookie ("testPersistentCookie", "Enabled", "minutes", 1);
  if (getCookieValue ("testPersistentCookie")=="Enabled")
    return true  
  else 
    return false;
}

/*==============================================================================

Routine to write a persistent cookie

    Parameters:
        CookieName        Cookie name
        CookieValue       Cookie Value
        periodType        "years","months","days","hours", "minutes"
        offset            Number of units specified in periodType
    
    Return value:
        true              Persistent cookie written successfullly
        false             Failed - persistent cookies are not enabled
    
    e.g. writePersistentCookie ("Session", id, "years", 1);
*/       

function writePersistentCookie (CookieName, CookieValue, periodType, offset) {

  var expireDate = new Date ();
  offset = offset / 1;
  
  var myPeriodType = periodType;
  switch (myPeriodType.toLowerCase()) {
    case "years":
      expireDate.setYear(expireDate.getFullYear()+offset);
      break;
    case "months":
      expireDate.setMonth(expireDate.getMonth()+offset);
      break;
    case "days":
      expireDate.setDate(expireDate.getDate()+offset);
      break;
    case "hours":
      expireDate.setHours(expireDate.getHours()+offset);
      break;
    case "minutes":
      expireDate.setMinutes(expireDate.getMinutes()+offset);
      break;
    default:
      alert ("Invalid periodType parameter for writePersistentCookie()");
      break;
  } 
  
  document.cookie = escape(CookieName ) + "=" + escape(CookieValue) + "; expires=" + expireDate.toGMTString() + "; path=/";
}  

/*==============================================================================

Routine to delete a persistent cookie

    Parameters:
        CookieName        Cookie name
    
    Return value:
        true              Persistent cookie marked for deletion
    
    e.g. deleteCookie ("Session");
*/    

function deleteCookie (cookieName) {

  if (getCookieValue (cookieName)) writePersistentCookie (cookieName,"Pending delete","years", -1);  
  return true;     
}

	
	
	
	
	
	/**
	 * JSONRequest Library, handles all JSON Request things
	 */
	
	
	// JSONscriptRequest -- a simple class for accessing Yahoo! Web Services
// using dynamically generated script tags and JSON
//
// Author: Jason Levitt
// Date: December 7th, 2005
//
// A SECURITY WARNING FROM DOUGLAS CROCKFORD:
// "The dynamic <script> tag hack suffers from a problem. It allows a page 
// to access data from any server in the web, which is really useful. 
// Unfortunately, the data is returned in the form of a script. That script 
// can deliver the data, but it runs with the same authority as scripts on 
// the base page, so it is able to steal cookies or misuse the authorization 
// of the user with the server. A rogue script can do destructive things to 
// the relationship between the user and the base server."
//
// So, be extremely cautious in your use of this script.
//

// Constructor -- pass a REST request URL to the constructor
//
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl; 
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'SMJscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");
    
    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}
 
// removeScriptTag method
// 
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);  
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}