
// Search Engine Source Code handling - CSS and non-CSS pages
// Allocates an SEO source if there isn't one in the URL and it wasn't a brand term search
//   also allocates an order code only for the SEO landing pages (seoOrderCode)
// No longer has homepage OPC redirect

  var debug = false; // Enables various diagnostic progress alerts. SET TO FALSE FOR PRODUCTION!
  var seoOrderCode = '014';
  var isSeoPage = false;

// Set source code for various natural search engine referrers
// Passed: nothing
// Returns: source code, or empty string if nothing was set
function getSource()
{
  var dr = document.referrer;
  var dl = document.location.href;
  var dp = document.location.pathname;
  var isBrandMatch = false;
  var theSource = '';

  regExp = /source=[a-z0-9]{4}/ ;

  var brand = (dl.indexOf('24studio') > -1) ? '24studio' : '24ace';

  if (debug) alert('Debug: referrer is ' +dr);

  // Don't carry on if we have no referrer, source is in URL, or it's the error page, or a Servlet (Servlet could be an error page)
  if (dr && dl.toLowerCase().search(regExp) == -1 && dl.indexOf('error.jsp') == -1  && dl.indexOf('ervlet') == -1)
  {

      var identifiers = new Array();
      var sourcesStudio = new Array();
      var sourcesAce = new Array();
      var paramId = new Array();

      //SE identifying strings, lower case
      identifiers [0] = '.google.';
      identifiers [1] = '.bing.';
      identifiers [2] = '.yahoo.';
      identifiers [3] = 'search.aol.';
      identifiers [4] = 'search.virginmedia';
      identifiers [5] = '.ask.';
      identifiers [6] = 'search.bt';

      // Search term param names
      paramId [0] = 'q';
      paramId [1] = 'q';
      paramId [2] = 'p';
      paramId [3] = 'q';
      paramId [4] = 'q';
      paramId [5] = 'q';
      paramId [6] = 'q';

      // Respective source codes **Production**
      sourcesStudio [0] = 'TX5O';
      sourcesStudio [1] = 'TX5P';
      sourcesStudio [2] = 'TX5Q';
      sourcesStudio [3] = 'TX5R';
      sourcesStudio [4] = 'TX5S';
      sourcesStudio [5] = 'TX5T';
      sourcesStudio [6] = 'TX5U';

      sourcesAce [0] = 'AX3A';
      sourcesAce [1] = 'AX4A';
      sourcesAce [2] = 'AX5A';
      sourcesAce [3] = 'AX5G';
      sourcesAce [4] = 'AX5H';
      sourcesAce [5] = 'AX5J';
      sourcesAce [6] = 'AX6A';


      // iterate to id the engine
      for (i=0; i<= identifiers.length; i++)
      {
        if (dr.indexOf(identifiers[i]) > -1)
        {
          if (debug) alert('Debug: search engine identified - ' +identifiers[i]);

          isBrandMatch = brandMatch(getValue(paramId[i], dr), brand);

          if (dp == '/online-shopping')
          {
            isSeoPage = true;
            if (!isBrandMatch) theSource = (brand == '24studio') ? 'TM4C' : '';
          }
          else if (dp == '/christmas')
            {
              isSeoPage = true;
              if (!isBrandMatch) theSource = (brand == '24studio') ? 'TM4E' : '';
            }
          else if (dp == '/competitions')
            {
              isSeoPage = true;
              if (!isBrandMatch) theSource = (brand == '24studio') ? 'TM4G' : '';
            }
          else if (dp == '/gifts')
            {
              isSeoPage = true;
              if (!isBrandMatch) theSource = (brand == '24studio') ? 'TM4D' : '';
            }
          else if (dp == '/weddings')
            {
              isSeoPage = true;
              if (!isBrandMatch) theSource = (brand == '24studio') ? 'TM4F' : '';
            }
          else if (!isBrandMatch) // default search engine
            {
              theSource = (brand == '24studio') ? sourcesStudio[i] : sourcesAce[i];
            }

          break;
        }
      }

    if (debug) alert('Debug: source is "' +theSource +'", isSeoPage is ' +isSeoPage);
    return theSource;

  }
  else
  {
    if (debug) alert('Debug: no referrer, referrer source already set, or Servlet / error page');
    return '';
  }
  return theSource;
}

// Get query string value
// Passed: parameter id, URL / referrer
// Returns: param value or null if none found
function getValue(paramName, urlString)
{
  var paramValue = '';
  var debugStr = '';

  if (paramName != '' && urlString != '')
  {
    // get 'name=value' pairs from query string

    var qs = urlString.split('?');

    if (qs.length > 1)
    {
      var pairs = qs[1].split('&');
      var thisPair = new Array();

      if (pairs.length > 0)
      {
        for (j=0; j<pairs.length; j++)
        {
          thisPair = pairs[j].split('=');
          if (thisPair.length != 2)
          {
            debugStr += "\n bad 'name=value' format";
          }

          else  if (thisPair[0] == paramName)
               {
                  paramValue = unescape(thisPair[1].replace(/\+/g, ' '));
                  debugStr += "\n found '" +paramValue +"'";
               }
        }
      }
      else debugStr += "\n no name=value pairs.";
    }
    else debugStr += "\n no query string.";
  }
  else debugStr += "\n missing paramName or urlString.";

  if (debug) alert('Debug: getValue(): ' +debugStr);

  return paramValue;

}

// Check for a brand-only search
// Passed: search string, brand
// Returns: boolean. True if search string gives a brand term match
function brandMatch(searchTerms, brand)
{
  var isMatch = false;
  if (searchTerms != '')
  {
    if (brand == '24studio')
    {
      //brandRegExp = /^(http:\/\/)?(www\.)?\W*(24)?\W*st?udi?o(24)?(\.co\.uk)?\W*(catalog)?(ue)?(catalouge)?(cards)?$|^st?udi?o?\W*(24)?\W*(catalog)?(ue)?(catalouge)?(cards)?$/;
      brandRegExp = /st?udi?o/;
    }
    else
    {
      brandRegExp = /\bace\b|ace24|24ace/;
    }

    if (searchTerms.toLowerCase().match(brandRegExp)) isMatch = true;
  }
  if (debug) alert( 'Brand term match: ' +isMatch);
  return isMatch;
}


// Insert hidden iframe CSS call
// Passed: source code
// Returns: nothing
function setFrame(theSource)
{
  if (theSource != '' || isSeoPage )
  {
    var dl = document.location.href;
    var brand = (dl.indexOf('24studio') > -1) ? '24studio' : '24ace';
  	var iProtocol = (document.location.protocol == "https:" ? "https:" : "http:");
    var iLocation = iProtocol + '//www.' +brand +'.co.uk/ss/num_of_items.jsp?stylesheet=/ss/css/common/num_of_items2.css' ;

    if ( theSource != '') iLocation = iLocation +'&amp;source=' +theSource;
    if ( isSeoPage ) iLocation = iLocation +'&amp;cssoc=' +seoOrderCode;

    document.write("<if"+"rame src='" + iLocation + "' width='1' height='1' frameborder='0' marginheight='0'"
		+ " marginwidth='0' scrolling='no' style='position:absolute;display:none;'></if"+"rame>");

    if (debug) alert('Debug: iframe set by referrer - ' +iLocation);
  }
}


// Firstly - CSS cssurn OPC cookie path workaround.
var brand = (document.location.href.indexOf('24studio') > -1) ? '24studio' : '24ace';

if (document.cookie.indexOf('cssurn=') > -1)
{
				var cName = 'cssurn';
				var value = document.cookie.match('cssurn=[^;]*')[0].substr(7);
				var days = 365;
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();

				document.cookie = cName+"="+value+expires+"; path=/; domain=." +brand +".co.uk";
}

//Set studio.tv landing cookie so we can serve a suitable banner
if (brand == '24studio' && document.location.href.indexOf('www.24') > -1
                        && ( getValue('source', document.location.href).toUpperCase() == 'SJ3A' || getValue('source', document.location.href).toUpperCase() == 'TM88' )
                        && getValue('cssoc', document.location.href) == '006' )
{
  if (document.cookie.indexOf('csstv=') == -1) // if cookie not already set
  {
				var cName = 'csstv';
				var value = '1';
				var days = 30;
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();

				document.cookie = cName+"="+value+expires+"; path=/; domain=." +brand +".co.uk";
	}
}


// Call SEO allocation code immediately for all non-CSS pages
// NB CSS pages load this script in the header so functions are only called from the footer, not immediately here

if (document.location.href.indexOf('www.24') == -1 ) // Non-CSS page
{
 //setFrame(getSource());  //// Isolated again due to false-triggering of Kaspersky. Visitors failing to update virus database?
}


///////////////
