//Each time we add a new company that we advertise with (ie. Adwords), we need
// to add a new advertiser to the advertiser array. There's no harm in adding
// or keeping advertisers that are not actually being actively used.

var advertiser=[];
advertiser[0]="googleadwords";
advertiser[1]="Bing";
advertiser[2]="Yahoo";
advertiser[3]="LinkedIn";
advertiser[4]="Ask";
advertiser[5]="Banner";
advertiser[6]="LookSmart";

var searchdomain_keys=[];
searchdomain_keys[0]={
  'engine' : 'Google',    
  'domain_key' : 'google.',       
  'divider' : 'q'
};
searchdomain_keys[1]={
  'engine' : 'Yahoo',     
  'domain_key' : 'search.yahoo.', 
  'divider' : 'p'
};
searchdomain_keys[2]={
  'engine' : 'Bing',      
  'domain_key' : 'bing.',         
  'divider' : 'q'
};
searchdomain_keys[3]={
  'engine' : 'AOL',       
  'domain_key' : 'search.aol.',   
  'divider' : 'q'
};
searchdomain_keys[4]={
  'engine' : 'Ask',       
  'domain_key' : 'ask.',          
  'divider' : 'q'
};
searchdomain_keys[5]={
  'engine' : 'Altavista', 
  'domain_key' : 'altavista.',    
  'divider' : 'q'
};
searchdomain_keys[6]={
  'engine' : 'Lycos',     
  'domain_key' : 'search.lycos.', 
  'divider' : 'query'
};

var the_source = "";
var the_keyword = "";
var http_referrer=document.referrer;

/* function for getting the value of a parameter from the URL.
Regex finds text between either ? or & and = to be param, and between = and other chars 
to be value. If null result, convert null to empty string*/
function get_value( key,location )
{
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+key+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( location );
  if( results == null )
    return "";
  else
    return results[1];
}

/* general function for setting cookies. */
function setCookie(c_name,value,expiredays)
{
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie=c_name+ "=" +escape(value)+
  ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()) + "; path=/";
}

/* general function for getting value of cookie */
function getCookie(c_name)
{
  if (document.cookie.length>0)
  {
    c_start=document.cookie.indexOf(c_name + "=");
    if (c_start!=-1)
    {
      c_start=c_start + c_name.length+1;
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length;
      return unescape(document.cookie.substring(c_start,c_end));
    }
  }
  return "";
}

/*Let's use these functions to either get and reset the cookies, or set a brand-new cookies
The cookies have two names: referral_source (source of the traffic) and referral_keyword (usually keywords
passed by an ad or a search term.) */

function setReferrer() {
  var found = false;
  
  //if the cookie called "referral_source" has an empty value (no cookie) then we should try to set one.
  if(getCookie("referral_source") == "") { 
      
    //first, let's check for advertisers in the query string
    for (var i in advertiser) {
      value = get_value(advertiser[i],window.location.href);
      
      //set a cookie of an advertiser is found
      if (value != "") {
        the_source = advertiser[i];
        the_keyword = value;
        found = true;        
        break;        
      } 
    }
  
    // If no advertiser was found, let's try for a search engine in the HTTP header's referrer 
    if (!found) { 
        
      for (var j in searchdomain_keys) {
        match=http_referrer.indexOf(searchdomain_keys[j].domain_key);
          
        //if we find a match, let's set a cookie.
        if (match != -1){
          the_source = searchdomain_keys[j].engine;
          value=get_value(searchdomain_keys[j].divider,http_referrer);
          // there could be a domain match but no query string
          if (value != "") {
            the_keyword = value;
          } else {
            the_keyword = "unknown" 
          }
          found = true;
        }
      }
    }
    
    // Getting a touch desperate, let's see if we can at least parse out a referral domain
    if (!found) {
      try {
        the_source = http_referrer.match(/:\/\/(.[^/?]+)/)[1];
        the_keyword = "unknown";
        found = true;
      } catch(e) {
        the_source = "";
        the_keyword = "";
      }
    }
    
    // If we found -something- let's set the cookies
    if (found) {
      setCookie("referral_source",the_source,365);
      setCookie("referral_keyword",the_keyword,365);
    }
    

  // The second half of the original conditional. If we DID find a cookie, let's just reset
  } else { 
    setCookie("referral_source",getCookie("referral_source"),365);
    setCookie("referral_keyword",getCookie("referral_keyword"),365);
  }
}

/**** This function is only used on the "Request Trial" form ****/

function hideForm() {
  // get the value of the fcadvertiser cookie.
  var thecookie = getCookie('referral_source');

  // Let's check for cookie. A cookie being present means an fcadvertiser is used.
  // Use that as the referral source ("How did you hear of us?") and hide that part of the form.
  if(thecookie != "") {

    var referral_source = thecookie;
    var referral_keyword = getCookie('referral_keyword');

    // Next, we'll translate the cookie value into a more plain-English value for any that need it
    if(referral_source == 'googleadwords') {
      referral_source = 'Google Adwords';
    }

    // concatenate the source plus the keyword into one new variable
    var full_referral = referral_source + " - " + referral_keyword;
    
    // Add a new option to the "how did you hear about us" drop-down, at position zero, populated with values. Select it. Then hide it.
    // TODO: swap these out for jQuery methods since we use jQuery throughout web app
    if(document.getElementById('00N70000001yCHe')) {
      document.getElementById('00N70000001yCHe').options[0]=new Option('Detected Referral', full_referral); 
      document.getElementById('00N70000001yCHe').selectedIndex=0; 
      document.getElementById('referral').style.display='none'; 
    }
  }
}
