// marketoFormFields.js
//
//  When the current page is reached from an outside link, capture information about the referring site and any search string and/or
//  pay per click keywords that were used. The information is stored in cookies. When a page containing forms with specified .css classes 
//  is loaded, the saved cookie information is retrieved and put into the values in the form fields.
 function getQueryVariable(variable) {
  var query = document.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  var undef;
  return undef;
} 
    $(document).ready(function() {
//    var $jQ = jQuery.noConflict(); 
        // Change this to match domains of referrers you want to ignore.
        // You'll want to ignore referrers from your own domains.
        // Use only the base domain name without subdomains (ex. "company.com")
        // Separate multiple domains with commas (leave the brackets).
        var excludedReferrers = ["idirect.net"];

        // Base domain of company's landing pages.
        // Cookies will be created with this domain.
        // Ex. If your landing page domain is "pages.yourcompany.com" then use "yourcompany.com"
        var cookieDomain = "idirect.net";
        
        // The URL parameter that has your pay-per-click info.
        // Typically "kw" or "keyword" (depends on how you set up your PPC URLs)
        var payPerClickParameter = "_kk";
        
        // Css Classes for the fields to be updated. (Original code worked from IDs, but Sitecore WFFM generates IDs dynamically. This code
        // assumes that the appropriate classes are added as parameters to the respective form field items.
        var searchStringField = ".Search_String__c input.scfSingleLineTextBox";
        var searchEngineField = ".Search_Engine__c input.scfSingleLineTextBox";
        var payPerClickKeywordField = ".Pay_Per_Click_Keyword__c input.scfSingleLineTextBox";

        var refer = document.referrer;
        var searchString;
        var searchEngine;

        // if there's no referrer, do nothing
        if ((refer == undefined) || (refer == "")) {;
        } else {
			jQuery(searchEngineField).attr("value", refer);

            // get the domain of the referring website
            var referrerDomain =
            refer.substr(refer.indexOf("\/\/") + 2, refer.indexOf("\/", 8) - refer.indexOf("\/\/") - 2).toLowerCase();

            var excludedDomainFound = false;
            var i = 0;

            // search the excluded domain list to see if the referrer domain is on it
            while ((i < excludedReferrers.length) && !excludedDomainFound) {
                var thisExcludedDomain = excludedReferrers[i].toLowerCase();

                // weird semantics here -- indexOf returns "-1" if the search string isnt found.
                // thus excludedDomainFound is true only when indexOf matches an excluded domain (!= -1)
                excludedDomainFound = (referrerDomain.indexOf(thisExcludedDomain) != -1);
                i++;
            }

            // only if the referrer isn't in our excluded domain list...
            if (!excludedDomainFound) {

                // extract the URL parameters from common search engines
                // To add your own, each engine needs a:
                //    name: how the search engine will appear on your Marketo leads
                //    url: REGEX for matching the engine's referrer.  ex.  /\.google\./i
                //    query: URL parameter that contains the search query - usually "p" or "q"
                var searchEngines = [
			        { name: "Yahoo", url: /\.yahoo\.co/i, query: "p" },
			        { name: "Google", url: /\.google\./i, query: "q" },
			        { name: "Microsoft Live", url: /\.live\.com/i, query: "q" },
			        { name: "MSN Search", url: /search\.msn\./i, query: "q" },
			        { name: "AOL", url: /\.aol\./i, query: "query" },
			        { name: "Bing", url: /\.bing\.com/i, query: "q" },
			        { name: "Ask", url: /\.ask\.com/i, query: "q" }
                ];

                // find the referring search engine (if any)
                i = 0;
                while ((i < searchEngines.length) && (searchEngine == undefined)) {
                    if (refer.match(searchEngines[i].url)) {
                        searchEngine = searchEngines[i].name;
                        searchString = jQuery.getQueryString({
                            ID: searchEngines[i].query,
                            URL: refer,
                            DefaultValue: ""
                        });
                    }
                    i++;
                }

                // If no search engine is found, this person probably used a less
                // popular one.  Use the referring doman, then guess the query parameter
                if (i == searchEngines.length) {

                    searchEngine = referrerDomain;

                    var queries = ["q", "p", "query"];
                    var j = 0;
                    while ((j < queries.length) && (searchString == undefined)) {
                        searchString = jQuery.getQueryString({
                            ID: queries[j++],
                            URL: refer,
                            DefaultValue: ""
                        });
                    }

                    // no search strings found -- use this text instead.
                    if (searchString == undefined) {
                        searchString = "";
                    }
                }

				// Use the provided URL parameter to get the PPC keyword.
                var payPerClickWord = getQueryVariable(payPerClickParameter);
                if (payPerClickWord == undefined) {
                    payPerClickWord = "";
                }
                //alert("searchEngine: " + searchEngine + "\npayPerClickWord: " + payPerClickWord + "\nsearchString: " + searchString);

                // Put the info into cookies.  These values will be extracted 
                // and put into a Marketo form later.  Expires in 2 years.
                jQuery.cookie('mktoPPCKeyword', payPerClickWord, {expires: 730, path: '\/', domain: cookieDomain});
                jQuery.cookie('mktoSearchEngine', searchEngine, {expires: 730, path: '\/', domain: cookieDomain});
                jQuery.cookie('mktoSearchString', searchString, {expires: 730, path: '\/', domain: cookieDomain});
            }
        }

        //Get the values from the cookies and put them into the hidden fields
        var storedVal;
        if ((storedVal= jQuery.cookie('mktoSearchString')) == null) storedVal= "";
        jQuery(searchStringField).attr("value", storedVal);
        
        if ((storedVal= jQuery.cookie('mktoSearchEngine')) == null) storedVal= "";
        jQuery(searchEngineField).attr("value", storedVal);
        
        if ((storedVal= jQuery.cookie('mktoPPCKeyword')) == null) storedVal= "";
        jQuery(payPerClickKeywordField).attr("value", storedVal);

    });

