/**************
* Cookie Storage
* @author: Carter
* 1) Storing cookie for CloudShouter's transaction ID (affiliate program)
* 2) Storing cookie for general referral information
*
* REQUIRES: jquery.cookie.js
*/

jQuery(function() {
    
    /****
     CloudShouter Affiliate Tracking
     check the cstid (cloud shouter trainsaction id) and create a cookie for it
    ****/
    
    // Helper: get url params from query string
    var urlParam = function(name){
      var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
      return results ? (results[1] || null) : null;
    }
    
    var COOKIE_NAME = 'transid';
    var REQUEST_PARAM = 'transid'; // 'cstid'
    
    // read cookie and url params
    var cstid = urlParam(REQUEST_PARAM);
    var transid = jQuery.cookie(COOKIE_NAME);
    
    // check if the param exists
    if (cstid) {
      // make sure the cookie doesn't exist yet
      if (!transid) {
        transid = cstid;
        // set cookie for next time
        jQuery.cookie(COOKIE_NAME, transid, {path: '/', domain: '.unbounce.com', expires: 3});
      }
    }
    
    
    /****
     Store Referrer information in a Cookie as well along with timestamp and the transactionID if there is one
     cookie = ["datetime|referrer|transid,datetime|referrer|transid"]
     datetime is the time in seconds since the epoch (to retrieve in ruby: Time.at(datetime))
    ****/
    
    // find the URL that the user came from
    var referrer = document.referrer;
    
    // now make sure the referrer wasn't us (or direct)
    if (referrer != "" && referrer.indexOf("unbounce.com") == -1 ) {
     
      // check to see if they have our referrer cookie
      var cookie = jQuery.cookie("referrer");
      var items = cookie ? cookie.split(",") : new Array();
      
      // create a string of all the details
      // timestampe|referrer|transid
      var details = parseInt(new Date().getTime() / 1000) + "|";
      details += referrer + "|";
      details += cstid;
      
      items.push(details);
      
      // set the cookie with new info (delete the existing one first)
      if (cookie) jQuery.cookie('referrer', null, {path: '/', domain: '.unbounce.com'});
      jQuery.cookie('referrer', items.toString(), {path: '/', domain: '.unbounce.com', expires: 300});
      
    }
    

  
});

