// Copyright (C) InstantService, Inc. All rights reserved. 
// All content is protected under U.S. copyright laws. Any unauthorized duplication, modification, 
// or reverse-engineering of this code without express written permission of InstantService, Inc. 
// is a violation of copyright law and is subject to penalty and prosecution.  
// This comment and the 4 lines above may not be removed from the code.

function II_getRules()
{
  var arrRules = II_getCookie(II_gCookieName);
  return((arrRules == null) ? new Array() : arrRules.split('^^^'));
}

function II_getUsingTestServers()
{
  var ii_arr = II_gtSV("TestServers");
  if (ii_arr != null)
  {
    ii_arr = ii_arr.split('+');
    for (var ii_idx = 0; ii_idx < ii_arr.length; ii_idx++)
    {
      if (ii_arr[ii_idx] == document.location.host) return(true);
    }
  }
  return(false);
}

function II_getMatchHistory()
{
  var arrMatchHistory = II_getCookie('IS2_MatchHistory');
  return((arrMatchHistory == null) ? new Array() : arrMatchHistory.split('^'));
}

function II_getStoredValues()
{
  var arrStoredValues = II_getCookie('IS2_StoredValues');
  return((arrStoredValues == null) ? new Array() : arrStoredValues.split(','));
}

function II_getCookie(name) 
{  
  var arg = name + "=";  
  var alen = arg.length;  
  var clen = document.cookie.length;  
  var i = 0;  

  while (i < clen) 
  {    
    var j = i + alen;    
    if (document.cookie.substring(i, j) == arg)   
    {   
      var endstr = document.cookie.indexOf (";", j);  
    
      if (endstr == -1)    
        endstr = document.cookie.length;  
 
      return unescape(document.cookie.substring(j, endstr));
    }

    i = document.cookie.indexOf(" ", i) + 1;    
    if (i == 0) break;   
  }  

  return null;
}

function II_setCookie(name, value) 
{  
  var argv = II_setCookie.arguments;  
  var argc = II_setCookie.arguments.length;  
  var expires = (argc > 2) ? argv[2] : null;  

  document.cookie = name + "=" + escape(value) + 
    ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + 
    "; path=/"  +  
    ((II_gDomain == null || II_gDomain == "") ? "" : ("; domain=" + II_gDomain));
}

function II_testCookieCapability()
{
  var result = false;

  II_setCookie('IS2_TestCookie', 'test', null);
  var val = II_getCookie('IS2_TestCookie');
  II_setCookie('IS2_TestCookie', 'test', new Date(0));
  if (val != null && val == 'test')
    result = true;

  return(result);
}
        
function II_updateMatchHistoryCookie() 
{
  var i = j;
  var j = 0; 
  var HistoryEntry = document.location.href;

  if (document.referrer == document.location.href)
    return false;

  var arrRules        = II_getRules(); 
  var arrMatchHistory = II_getMatchHistory();
  
  if (arrMatchHistory.length > II_MAX_RULEMATCHLIST_SIZE - 1)
    arrMatchHistory = II_shiftMatchHistoryCookie(arrMatchHistory, II_MAX_RULEMATCHLIST_SIZE);

  if ((HistoryEntry != null) && (HistoryEntry != "undefined")) 
  {
    arrMatchHistory[arrMatchHistory.length] = ' ';

    var nMatch = -1;
    var sSearchMatch = '';

    for (i=0; i < arrRules.length; i++)
    {
      var matchrule = II_findMatch(HistoryEntry.toLowerCase(), II_gtRC("ri", arrRules[i]), arrRules[i]);
      if (matchrule.length > 0)
      {
        if (arrMatchHistory[arrMatchHistory.length - 1] == ' ')
          arrMatchHistory[arrMatchHistory.length - 1] = matchrule;
        else
          arrMatchHistory[arrMatchHistory.length - 1] += matchrule;
      }
    }

    var fullList = "";
    for (j=0; j <= arrMatchHistory.length - 1; j++)
    { 
      fullList += arrMatchHistory[j];
      if (j < arrMatchHistory.length - 1)
        fullList += "^";
    }

    II_setCookie('IS2_MatchHistory', fullList, II_COOKIE_EXPIRATION);
  }

  II_upSV("RuleTriggered", "0");    
  II_upSV("TimeSinceLastCheck", 0);

  return true;
}

function II_upSV(name, value)
{
  var updated = false;
  var arrStoredValues = II_getCookie('IS2_StoredValues');

  if (arrStoredValues == null)
    arrStoredValues = new Array();
  else
    arrStoredValues = arrStoredValues.split(',');

  for (var idx=0; idx < arrStoredValues.length; idx++)
  {
    var arrNameValue = arrStoredValues[idx].split('`');
    if (arrNameValue[0] == name)
    {
      updated = true;
      arrStoredValues[idx] = name + '`' + value;
    }
  }

  if (!updated)
    arrStoredValues[arrStoredValues.length] = name + '`' + value;

  II_setCookie('IS2_StoredValues', arrStoredValues, II_COOKIE_EXPIRATION);
}

function II_gtSV(name)
{
  var arrStoredValues = II_getCookie('IS2_StoredValues');

  if (arrStoredValues == null)
    arrStoredValues = new Array();
  else
    arrStoredValues = arrStoredValues.split(',');

  for (var idx=0; idx < arrStoredValues.length; idx++)
  {
    var arrNameValue = arrStoredValues[idx].split('`');
    if (arrNameValue[0] == name)
      return(arrNameValue[1]);
  }

  return('');
}

function II_shiftMatchHistoryCookie(arrHistory, maxsize) 
{ 
  var i = 0;
  var newArray = new Array();

  for (i = 0; i < maxsize - 1; i++) 
    newArray[i] = arrHistory[i + 1];

  return(newArray);
}

function II_initTestServers()
{
  var i = 0;

  var fullList = "";
  if (window.arrTestServers)
  {
    for (i=0; i <= arrTestServers.length - 1; i++)
    { 
      fullList += arrTestServers[i];
      if (i < arrTestServers.length - 1)
        fullList += "+";
    }
  }
  
  if (fullList != "")
    II_upSV("TestServers", fullList);
}

function II_createRulesCookie(rulesType)
{
  var i = 0;
  var ii_arr = null;
  
  if (rulesType == "test")
    ii_arr = window.arrTestRules;
  else
    ii_arr = window.arrRules;

  // create live version rules
  var fullList = "";
  if (ii_arr)
  {
    for (i=0; i <= ii_arr.length - 1; i++)
    { 
      fullList += ii_arr[i];
      if (i < ii_arr.length - 1)
        fullList += "^^^";
    }
  }
  if (fullList == "")
    fullList = "(no rules defined)";
 
  II_setCookie(II_gCookieName, fullList, null);

  II_upSV("PrevOfferCount", 0);
  II_upSV("PrevOfferTime", 0);
  II_upSV("LastRuleIDTriggered", 0);
  II_upSV("RuleTriggered", "0");
  II_upSV("TimeSinceLastCheck", 0);
}

function II_loadRules()
{
  var arrRules = II_getRules(); 

  if (arrRules.length == 0)
  {
    if (II_testCookieCapability())
    {
      var timestamp = (new Date()).getTime();
      document.write('<script src="' + II_gProtocol + '://admin.instantservice.com/resources/smartbutton/' + II_gAccountID + '/II_Servers.js?ts=' + timestamp + '" type="text/javascript"></script>');
    }
  }
}

function II_findMatch(searchstr, ruleid, rule)
{
  var arrMatches = new Array();
  var match = '';

  if (II_findComponentMatch(ruleid, "pm", searchstr, rule).length > 0)
    match = 'r'+ruleid+'pm';
  if (II_findComponentMatch(ruleid, "ppm", searchstr, rule).length > 0)
    match += 'r'+ruleid+'ppm';
  if (II_findComponentMatch(ruleid, "epv", searchstr, rule).length > 0)
    match += 'r'+ruleid+'epv';
  if (II_findComponentMatch(ruleid, "eopv", searchstr, rule).length > 0)
    match += 'r'+ruleid+'eopv';

  return(match);
}

function II_findComponentMatch(ruleid, componentname, searchstr, rule)
{
  var match = '';
  
  if (componentname == "epv" || componentname == "eopv")
  {
    // these two component have to be subdivided and searched
    var list = II_gtRC(componentname, rule);
    if (list != null && list.length > 0)
    {
      var arrList = list.split('^');
      if (arrList != null && arrList.length > 0)
      {
        for (var idx=0; idx < arrList.length; idx++)
        {
          var sub = arrList[idx];
          if (sub != null && sub.length > 0)
          {
            sub = sub.toLowerCase();
            if (searchstr != null && searchstr.indexOf(sub) != -1)
            {
              if (match.length > 0) 
                match += '```';
              match += sub;
            }              
          }            
        }
      }
    }      
  }
  else
  {
    var sub = II_gtRC(componentname, rule);
    if (sub != null && sub.length > 0)
    {
      sub = sub.toLowerCase();
      if (searchstr != null && searchstr.indexOf(sub) != -1)
      {
        if (match.length > 0) 
          match += '```';
        match += sub;
      }
    }
  }
       
  return(match);
}  

function II_gtRS(ruleid)
{
  var arrRules = II_getRules();

  for (i=0; i < arrRules.length; i++)
  {
    if (II_gtRC("ri", arrRules[i]) == ruleid)
      return(arrRules[i]);
  }

  return('');
}
          
  
function II_gtRC(componentname, rule)
{
  var ruleArray = rule.split('`');
 
  var arrNames = new Array("ri","pmt","pm","ppmt","ppm","rt","rv1","rv2","rv3","art","arv1",
                           "arv2","arv3","epoc","epot","epv","eopv","av","ii","idi","wtl",
                           "cjo","cjp1","cjp2","cjp3");

  if (ruleArray != null && ruleArray.length > 0)
  {
    for (idx=0; idx < arrNames.length; idx++)
    {    
      if (arrNames[idx] == componentname)
        return(ruleArray[idx]);
    }
  }      
  
  return('');
}

function II_getProtocol()
{
  var prot = "http";
  var url = document.location.href;
  if (url != null && url.length > 0)
  {
    url = url.toLowerCase();
    if (url.indexOf("https") == 0) 
      prot = "https";
  }
  return(prot);
}

function II_getDomain()
{ 
  var dom = document.domain;
  var domX = dom;
  var idx = dom.lastIndexOf(".");
  if (idx != -1)
  {
    domX = dom.substring(0, idx) + "X" + dom.substring(idx+1);
    var idx2 = domX.lastIndexOf(".");
    if (idx2 != -1)
    {
      var x = dom.substring(idx2, idx+1);
      if (dom.substring(idx2, idx+1) == ".co.")
      {
        domX = domX.substring(0, idx2) + "X" + domX.substring(idx2+1);
        var idx3 = domX.lastIndexOf(".");
        (idx3 != -1) ? domX = dom.substring(idx3) : domX = dom;          
      }
      else 
        domX = dom.substring(idx2);
    }      
    else
      domX = dom;
  }
  return(domX);
}

function callServer(serverScript) 
{
  if (serverScript.length > 0)
  {
    if (II_gUsingIE || II_gUsingNS)
    {
      var head = document.getElementsByTagName('head').item(0);
      var old  = document.getElementById('lastLoadedCmds');
      if (old) head.removeChild(old);
      script = document.createElement('script');
      script.src = serverScript;
      script.type = 'text/javascript';
      script.defer = true;
      script.id = 'lastLoadedCmds';
      void(head.appendChild(script));
    }
  }
}

var II_gDomain=II_getDomain();
var II_gProtocol=II_getProtocol();
var II_gAccountID=6088;
var II_gCookieName='IS2_Rules_6088';
var II_gTSCookieName='IS2_TestServers_6088';
var II_gUsingIE=false;
var II_gUsingNS=false;

if (document.all && document.getElementById)
  II_gUsingIE = true;
else if (document.getElementById)
  II_gUsingNS = true;  

if (II_gUsingIE || II_gUsingNS)
{
  II_loadRules();
}

if (false && !window.ISVT_onInviteOffered) 
  callServer(II_gProtocol + ':///InstantTracking.js');

document.write('<div id="floatlayer" style="position:absolute;left:10px;top:10px;visibility: hidden;z-index:1000">');
document.write('<div id="floatlayercontent" style="position:relative;left:10px;top:10px;z-index:100"></div>');
document.write('<iframe id="divshim" src="javascript:false;" scrolling="no" frameborder="0" style="position:absolute;top:0px;left:0px;display:none;"></iframe>');
document.write('</div>');  