// 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;
}


// djd@barclays.com:
// Change to add independent tracking to the JavaScript for MI. This code works
// by redefining the functions that are called when an invite is accepted or
// declined.
// Handles the WebTrends stuff by redefining the InstantInvite handles so that
// they will call the DCS multiTrack routines building the correct Tags
function redefineEventHandlers()
{
	window['ii_executeRuleTriggeredEvent'] = function (param1, param2, param3)
	{ 
	  if(II_gAgentsAvail==true){
    	var ii_rand = Math.floor(Math.random() * 100) + 1;
    	if(ii_rand<=90){
    		var js = "dcsMultiTrack(\'DCSext.CHATaction\',\'triggeredA\',\'WT.ti\',\'triggeredA-\'+II_gRuleID+\'-\'+II_gInvitationID,\'DCS.dcsuri\',\'/WebChat\'+document.location.pathname,\'DCSext.ruleId\',II_gRuleID,\'DCSext.inviteId\',II_gInvitationID);"; setTimeout(js, 500);
   			II_show();
    	}
    	if(ii_rand>=91){
    		var jsprime = "dcsMultiTrack(\'DCSext.CHATaction\',\'triggeredB\',\'WT.ti\',\'triggeredB-\'+II_gRuleID+\'-\'+II_gInvitationID,\'DCS.dcsuri\',\'/WebChat\'+document.location.pathname,\'DCSext.ruleId\',II_gRuleID,\'DCSext.inviteId\',II_gInvitationID);"; setTimeout(jsprime, 500);
   		}
   	}
 	};	
	window['ii_executeInvitationAcceptedEvent'] = function(param1,param2,param3)
	{ var js = "dcsMultiTrack(\'DCSext.CHATaction\',\'accepted\',\'WT.ti\',\'accepted-\'+II_gRuleID+\'-\'+II_gInvitationID,\'DCS.dcsuri\',\'/WebChat\'+document.location.pathname,\'DCSext.ruleId\',II_gRuleID,\'DCSext.inviteId\',II_gInvitationID);"; setTimeout(js, 500); };
	window['ii_executeInvitationDeclinedEvent'] = function(param1,param2,param3) 
	{ var js = "dcsMultiTrack(\'DCSext.CHATaction\',\'declined\',\'WT.ti\',\'declined-\'+II_gRuleID+\'-\'+II_gInvitationID,\'DCS.dcsuri\',\'/WebChat\'+document.location.pathname,\'DCSext.ruleId\',II_gRuleID,\'DCSext.inviteId\',II_gInvitationID);"; setTimeout(js, 500); };
}

// djd@barclays.com
// Modified to detect when an offer is made and redefine the event handlers
function II_upSV(name, value)
{
  var updated = false;
  var arrStoredValues = II_getCookie('IS2_StoredValues');

// An offer has been made so let's redefine the event handlers
  if(name == 'PrevOfferCount' && value > 0){
  	//redefineEventHandlers();
  }
  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)
{
  
  if(componentname == 'cjo'){
  	redefineEventHandlers();
  	}
  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()
{ 
  return(document.domain);
}


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_gDomain='localhost';
var II_gProtocol=II_getProtocol();
var II_gAccountID=6192;
var II_gCookieName='IS2_Rules_6192';
var II_gTSCookieName='IS2_TestServers_6192';
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>');  
