/****** wwWebAnalyzer/wwWebAnalyzer.js
* DESCRIPTION
*  Contains functions to do basic analysis
* 
* AUTHOR
*  ddorothy
*  
* CREATION DATE
*  7/24/2007
* 
* HISTORY
*  
* NOTES
* 
*****/

function wwWebAnalyzer() {}
  
/****f* wwWebAnalyzer/readCookie()
* DESCRIPTION
*  Reads the value of a cookie
* 
* PARAMETERS
*  name - string - the name of the cookie to get
*
* RETURN VALUE
*  string - null if cookie does not exist, otherwise cookie value
* 
* NOTES
*  taken from: http://www.quirksmode.org/js/cookies.html
*****/
wwWebAnalyzer.prototype.readCookie = function(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') { c = c.substring(1,c.length); }
    if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length,c.length); }
  }
  return null;
};

/****f* wwWebAnalyzer/createCookie()
* DESCRIPTION
*  This creates a cookie
* 
* PARAMETERS
*  name - string - the name of the cookie to make
*  value - string - the value of the cookie to set
*  days - float - the length of time in days to create the cookie for
*
* RETURN VALUE
*  None
* 
* NOTES
*  taken from: http://www.quirksmode.org/js/cookies.html
*****/
wwWebAnalyzer.prototype.createCookie = function(name,value,days) {
  var expires = "";
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    expires = "; expires="+date.toGMTString();
  }
  document.cookie = name+"="+value+expires+"; path=/";
};

/****f* wwWebAnalyzer/getQSVars()
* DESCRIPTION
*  Retrieves the query string variables
* 
* PARAMETERS
*  url - string - the url to parse the qs vars from (designed from perspective of GET but should work with a post string as well if needed)
*
* RETURN VALUE
*  dictionary - name/value array of querystring variables
* 
* NOTES
*  
*****/
wwWebAnalyzer.getQSVars = function(url) {
  try {
    //attempt to get an array of "name=value" values from the query string 
    //(if there is no ? then this will fail, thus the try...catch)
    //(may also fail if there are no names on the query string)
    var tmp = url.split("?")[1].split("&");
    var qs = [];
    
    //build the dictionary
    for( var i = 0; i < tmp.length; i++ ) {
      qs[tmp[i].split("=")[0]] = tmp[i].split("=")[1];
    }
    return qs;
  } catch(e) {
    return [];
  }
};

/****v* wwWebAnalyzer/Referrer
* DESCRIPTION
*  An object containing details about the referrer url
*  * QueryString - a dictionary of name value pairs from the querystring
*  * Host - the domain name of the referrer (may include port)
* 
* NOTES
*  an object
*****/
wwWebAnalyzer.prototype.Referrer = {
  QueryString : wwWebAnalyzer.getQSVars(document.referrer),
  Host : document.referrer.split("?")[0].replace("http://", "").replace("https://", "")
};

/****f* wwWebAnalyzer/setCookieSearchTerms()
* DESCRIPTION
*  Sets a cookie containing the search terms and a cookie containing the referring engine (ignores current domain)
* 
* PARAMETERS
*  None
*
* RETURN VALUE
*  None
* 
* NOTES
*  
*****/
wwWebAnalyzer.prototype.setCookieSearchTerms = function() {
  if(document.referrer && document.referrer.length > 0) {
    //get the domain name, remove http(s)://
    var domain = wwWebAnalyzer.prototype.Referrer.Host;
    var qs = wwWebAnalyzer.prototype.Referrer.QueryString;
    var searchterms = null;
    var googleOrganic = false;
    
    //look for search terms in two common variables
    if( qs.q !== undefined ) {
      searchterms = qs.q;
    } else if( qs.p !== undefined ) {
      searchterms = qs.p;
    }
    
    //look for queues for google organic search (warning this depends on google analytics)
    if( wwWebAnalyzer.prototype.readCookie('__utmz') !== null && wwWebAnalyzer.prototype.readCookie('__utmz').indexOf('organic') != -1 ) {
      googleOrganic = true;
    }
    
    //set the cookies if we were not referred by the current site
    if( domain.indexOf(window.location.host) == -1 && searchterms !== null) {
      wwWebAnalyzer.prototype.createCookie("wwWAdomain", domain, 1);
      wwWebAnalyzer.prototype.createCookie("wwWAterms", decodeURI(searchterms.replace("+", " ")), 1);
      wwWebAnalyzer.prototype.createCookie("wwWAgoogleOrganic", googleOrganic, 1);
    }
  }
};

/****f* wwWebAnalyzer/storeSearchTerms()
* DESCRIPTION
*  Sends the search terms to the analytics service.
* 
* PARAMETERS
*  service - string - url to service to send to
*
* RETURN VALUE
*  None
* 
* NOTES
*  
*****/
wwWebAnalyzer.prototype.storeSearchTerms = function () {
  //check to see that we have engine and terms cookies
  var engine = wwWebAnalyzer.prototype.readCookie("wwWAdomain");
  var terms = wwWebAnalyzer.prototype.readCookie("wwWAterms");
  if( engine !== null && terms !== null ) {
    //we have an engine and search terms so send the info to the server.
    var service = new rpc.ServiceProxy(this.serviceUrl, { asynchronous: true });
    service.storeSearchTerms({params:[engine, terms]});
  }
};

/****f* wwWebAnalyzer/init()
* DESCRIPTION
*  Initializes wwWebAnalyzer class
*  Things it does:
*   * Check for new referrer
*     * Store search terms & engine in cookie
*     * Send search terms & engine to analyzer service
*   * Populate specially named form fields
* 
* PARAMETERS
*  None
*
* RETURN VALUE
*  None
* 
* NOTES
*  Run during window.onload() or later;
*  Available Options
*   * serviceUrl - string - the location of the Analyzer service.
*   * formfields - named array - the name of the form fields to populate
*     * referringDomain - string - the field name to populate the search engine in
*     * referringKeyWords - string - the field name to populate the search terms in
*     * googleOrganic - string - the field name to populate if google thinks it is an organic search or not
*****/
wwWebAnalyzer.prototype.init = function (options) {
  //set some defaults
  this.serviceUrl = '/wwWebAnalyzer.php';
  this.formfields = {
    referringDomain : 'referringDomain',
    referringKeyWords : 'referringKeyWords',
    googleOrganic : 'googleOrganic'
  };
  //add in user supplied values
  if( typeof options == "object" ) {
    if( options.serviceUrl ) {
      this.serviceUrl = options.serviceUrl;
    }
    if( options.formfields && typeof options.formfields == "object" ) {
      if( options.formfields.referringDomain ) {
        this.formfields.referringDomain = options.formfields.referringDomain;
      }
      if( options.formfields.referringKeyWords ) {
        this.formfields.referringKeyWords = options.formfields.referringKeyWords;
      }
      if( options.formfields.googleOrganic ) {
        this.formfields.googleOrganic = options.formfields.googleOrganic;
      }
    }
  }
  //check for new referrer (ignore same domain)
  var engine = wwWebAnalyzer.prototype.readCookie("wwWAdomain");
  var terms = wwWebAnalyzer.prototype.readCookie("wwWAterms");
  if( wwWebAnalyzer.prototype.Referrer.Host.indexOf(window.location.host) == -1 ) {
    wwWebAnalyzer.prototype.setCookieSearchTerms();
  }
  if( terms != wwWebAnalyzer.prototype.readCookie("wwWAterms") || engine != wwWebAnalyzer.prototype.readCookie("wwWAdomain") ) {
    this.storeSearchTerms();
  }
  
  //attempt to populate form fields for collecting engine & terms data
  for( var i = 0; i < document.forms.length; i++ ) {
    try {
      document.forms[i][this.formfields.referringDomain].value = wwWebAnalyzer.prototype.readCookie("wwWAdomain");
      document.forms[i][this.formfields.referringKeyWords].value = wwWebAnalyzer.prototype.readCookie("wwWAterms");
      document.forms[i][this.formfields.googleOrganic].value = wwWebAnalyzer.prototype.readCookie("wwWAgoogleOrganic") ? 'Yes' : 'No';
    } catch(e) {/*ignore errors*/}
  }
};

