// lmtracker.js -- this should be included on all pages.
function LMTrackingClass() {
    this._pageTitle = document.title;
    this._pageTag = null;
    this._pageURL = _safeTruncate(document.URL.toString());
    this._referrer = (null == document.referrer) ? null : _safeTruncate(document.referrer);
    this._events = new Array();
    this._eventCounter = 0;
    this._tracked = false;
    
    this._buildImgURL = function() {
        var theURL = []; // string buffer inplace of lots of string concats
        theURL.push("/home/metrics/metrics.gif?pURL="+escape(this._pageURL));
        if( null != this._referrer ) {
            theURL.push("referrer="+escape(this._referrer));
        }
        if( null != this._pageTag ) {
            theURL.push("pTag="+escape(this._pageTag));
        }
        if( null != this._pageTitle ) {
            theURL.push("pTitle="+escape(this._pageTitle));
        } else {
            theURL.push("pTitle="+escape("no title"));
        }
        
        // presently adds Google params
       	this._pushQueryString(theURL);

        if( this._eventCounter > 0 ) {
            // the list if events looks like this: 
            //  "e0=eventName^name1~value1^name2~value2^namen~valueN&e1=eventName^name1&e2=eventName^name1&e3=eventName"
            // where the token "^" seperates values 
            var eIdx = 0;
            for( var eventName in this._events ) {
                var serial = this._events[eventName].serialize();
                theURL.push("e"+eIdx+"="+serial);
                eIdx++;
            }
            
        }
        
        return theURL.join("&");
    };
    
    function _safeTruncate( theURL ) {
       if( null == theURL ) {
          return "";
       }

       if( theURL.length <= 250 ) {
          return theURL;
       }

       var trunc = theURL.substr(0,250);
       var lastPerc = trunc.lastIndexOf('%');
       return lastPerc > 247 ? trunc.substr(0,lastPerc) : trunc;
    }
    
    this._parseParameter = function( key ) {
        var cleanedKey = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regex = new RegExp("[\\?&]"+cleanedKey+"=([^&#]*)","i");
	var qs = regex.exec(this._pageURL);
        return (null == qs) ? null : qs[1];
    };
    
    this._pushQueryString = function( theURL ) {
    	var cr = this._parseParameter("cr");
    	if( null != cr ) {
    	    theURL.push("cr="+cr);
    	}
    	var kw = this._parseParameter("kw");
    	if( null != kw ) {
    	    theURL.push("kw="+kw);
    	}
    	var nw = this._parseParameter("nw");
    	if( null != nw ) {
    	    theURL.push("nw="+nw);
    	}
    	var pl = this._parseParameter("pl");
    	if( null != pl ) {
    	    theURL.push("pl="+pl);
    	}
    	var acct = this._parseParameter("acct");
    	if( null != acct ) {
    	    theURL.push("acct="+acct);
    	}
    };
    
    this.areCookiesEnabled = function() {
    	if( 'undefined' != typeof navigator.cookiesEnabled ) {	
    		return navigator.cookieEnabled;
    	} else {
    		document.cookie = "lmtestcookie=yes";
    		return null != document.cookie && document.cookie.indexOf("lmtestcookie") >= 0;
    	}
    };
    
    // API call    
    this.setpagetag = function( tag ) {
        this._pageTag = tag;
    };

    // API call    
    this.setpagetitle = function( title ) {
        if( null != title && title.length > 0 ) {
        	this._pageTitle = title;
       	}
    };

    // API call    
    this.addevent = function( eventName, dataName, dataValue ) {
        if( null == eventName || 0 == eventName.length ) {
            alert("lmtracker error: The method addevent was called without an event name.");
            return null;
        }
        
        var MAX_EVENTS = 5;
        if( this._eventCounter >= MAX_EVENTS ) {
            alert("lmtracker error: This service only supports "+MAX_EVENTS+" events.  This amount has been exceeded.");
            return null;
        }
        
        var oEvent = this._events[eventName];
        if( null == oEvent ) {
            oEvent = new LMEventClass(eventName);
            this._events[eventName] = oEvent;
            this._eventCounter++;
        }
        if( null != dataName ) {
	    oEvent.adddata(dataName, dataValue);
	}
	return oEvent;
    };
    
    // API call    
    this.trackpage = function() {
    	if( this._tracked ) {
    		return;
    	}
        
        this._tracked = true;
        document.getElementById('lmtrk').src=this._buildImgURL();
    };
    
    // API call
    this.trackpageview = function() {
    	this.trackpage();
    };
}

function LMEventClass( eventName ) {
    this._name = eventName;
    this._data = new Array();

    //API CALL: intentionally all lowercase, as was requested.
    this.adddata = function( dataName, dataValue ) {
        this._data[dataName] = dataValue;
        return this;
    };

    this.getdata = function() {
        return this._data;
    };

    this.serialize = function() {
        var serialized = [];
        serialized.push(escape(this._name));
        for( var dataName in this._data ) {
            var dataValue = this._data[dataName];
            if( null == dataValue || 0 == dataValue.length ) {
	        // there is no data value.
	        serialized.push(escape(dataName));
            } else {
	        serialized.push(escape(dataName)+"~"+escape(dataValue));
            }
        }
        
        // when serialized each event parameter looks like this: 
        //   "e0=eventName^name1~value1^name2~value2^nameN~valueN"
        return serialized.join("^");
    };
}

var lmtracker = new LMTrackingClass();

function defaultTrack() {
	lmtracker.trackpage();
}

// only track visitors that have cookies enabled.  if cookies are disabled, it would skew the unique-visitor count metrics.
if( lmtracker.areCookiesEnabled() ) {
	document.write("<img src='/images/ffffff.gif' width='1' height='1' id='lmtrk' name='lmtrk'>");
	if(window.attachEvent) { 
		window.attachEvent( "onload" , defaultTrack);
	} else if(window.addEventListener)  { 
		window.addEventListener("DOMContentLoaded", defaultTrack, false);
	} 
} 
