// 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_checkRules()
{
  var retRuleID       = 0;
  var arrRules        = II_getRules();
  var arrMatchHistory = II_getMatchHistory();

  if (arrMatchHistory.length == 0)
    return;

  var timesince = parseInt(II_gtSV('TimeSinceLastCheck'));

  for (var idx=0; idx < arrRules.length; idx++)
  {
    var rule              = arrRules[idx];
    var ruleid            = II_gtRC("ri", rule);
    var pagematchtype     = II_gtRC("pmt", rule);
    var pagematch         = II_gtRC("pm", rule);
    var prevpagematchtype = II_gtRC("ppmt", rule);
    var prevpagematch     = II_gtRC("ppm", rule);
    var ruletype          = II_gtRC("rt", rule);
    var rulevalue1        = II_gtRC("rv1", rule);
    var rulevalue2        = II_gtRC("rv2", rule);
    var rulevalue3        = II_gtRC("rv3", rule);
    var andruletype       = II_gtRC("art", rule);
    var andrulevalue1     = II_gtRC("arv1", rule);
    var andrulevalue2     = II_gtRC("arv2", rule);
    var andrulevalue3     = II_gtRC("arv3", rule);
    var wtl               = II_gtRC("wtl", rule);

    if (retRuleID > 0)
      break;

    var bPageMatched = false;
    var bPrevPageMatched = false;
          
    if (pagematchtype == '2') bPageMatched = true;
    if (prevpagematchtype == '0') bPrevPageMatched = true;
    
    if ((pagematchtype == '0' || pagematchtype == 1) && pagematch.length > 0)
    {
      var match1 = II_searchHistoryEntry('r'+ruleid+'pm',1);  
      if ((pagematchtype == '0' && match1 > 0) || (pagematchtype == '1' && match1 == 0))
        bPageMatched = true;
    }

    if ((prevpagematchtype == '1' || prevpagematchtype == 2) && prevpagematch.length > 0)
    {
      if (prevpagematchtype == '1' && II_searchHistoryEntry('r'+ruleid+'ppm',2) > 0)
        bPrevPageMatched = true;
      else if (prevpagematchtype == '2' && document.referrer != null && document.referrer.indexOf(prevpagematch) != -1)
        bPrevPageMatched = true;
    }

    if (bPageMatched == true && bPrevPageMatched == true)
    {
      if (II_checkRuleExceptions(rule) > 0)
      {
        switch(ruletype)
        {
          case '100':  // user has visited the page 'n' times
            if (pagematchtype == '0')
            {
              var match1 = II_searchAllHistory('r'+ruleid+'pm');
              if (match1 >= rulevalue1)
                retRuleID = ruleid;
            }
            else if (pagematchtype == '1')
            {
              var match1 = II_searchAllHistory('r'+ruleid+'pm');
              if (arrMatchHistory.length - match1 >= rulevalue1)
                retRuleID = ruleid;
            }
            else if (pagematchtype == '2')
            {
              var match1 = arrMatchHistory.length;
              if (match1 >= rulevalue1)
                retRuleID = ruleid;
            }
            break;
            
          case '102':  // cookie rule
            var cookieval = II_getCookie(rulevalue1);
            if (cookieval != null && cookieval.indexOf(rulevalue2) != -1)
              retRuleID = ruleid;
            break;
            
          case '103':  // js rule
            eval("if (typeof(window." + rulevalue1 + ") != undefined && window." + rulevalue1 + " == '" + rulevalue2 + "') { retRuleID = ruleid; }");
            break;   
            
          case '104':  // form field rule
            eval("if (typeof(document." + rulevalue1 + ") != undefined && document." + rulevalue1 + ".value == '" + rulevalue2 + "') { retRuleID = ruleid; }");
            break;
            
          case '105': // site abandonment
            retRuleID = ruleid;
            break;
                      
          default:
        }  
        
        if (retRuleID > 0 && andruletype != '0')
        {
          switch(andruletype)
          {
            case '100':  // user has visited the page 'n' times
              if (pagematchtype == '0')
              {
                var match1 = II_searchAllHistory('r'+ruleid+'pm');
                if (match1 < andrulevalue1)
                  retRuleID = 0;
              }
              else if (pagematchtype == '1')
              {
                var match1 = II_searchAllHistory('r'+ruleid+'pm');
                if (arrMatchHistory.length - match1 < andrulevalue1)
                  retRuleID = 0;
              }
              else if (pagematchtype == '2')
              {
                var match1 = arrMatchHistory.length;
                if (match1 < andrulevalue1)
                  retRuleID = 0;
              }
              break;
              
            case '102':  // cookie rule
              var cookieval = II_getCookie(andrulevalue1);
              if (cookieval == null || cookieval.indexOf(andrulevalue2) == -1)
                retRuleID = 0;
              break;
              
            case '103':  // js rule
              eval("if (typeof(window." + andrulevalue1 + ") != undefined && window." + andrulevalue1 + " == '" + andrulevalue2 + "') { retRuleID = ruleid; } else { retRuleID = 0; }");
              break;   
              
            case '104':  // form field rule
              eval("if (typeof(document." + andrulevalue1 + ") != undefined && document." + andrulevalue1 + ".value == '" + andrulevalue2 + "') { retRuleID = ruleid; } else { retRuleID = 0; }");
              break;
              
            case '105': // site abandonment
              retRuleID = ruleid;
              break;
                        
            default:
          }          
        }
        if (timesince < wtl && wtl != '99999')
          retRuleID = 0;
      }
    }
  }

  return(retRuleID);
}


function II_checkRuleExceptions(rule)
{
  var ruleid            = II_gtRC("ri", rule);
  var excprevoffercount = II_gtRC("epoc", rule);
  var excprevoffertime  = II_gtRC("epot", rule);
  var excprevvisit      = II_gtRC("epv", rule);
  var exconlyprevvisit  = II_gtRC("eopv", rule);

  if (excprevoffercount.length > 0)
  {
    var pages = II_gtSV("PrevOfferCount");
    if (pages != '' && pages >= excprevoffercount)
      return(0);
  }
      
  if (excprevoffertime.length > 0)
  {
    var ii_time = II_gtSV("PrevOfferTime");
    if (ii_time != '')
    {
      var ii_curTime = new Date().getTime();
      ii_time = parseInt(ii_time) + (parseInt(excprevoffertime) * 1000);

      if (ii_curTime < ii_time)
        return(0);
    }
  }

  if (excprevvisit.length > 0)
  {
    arrPrev = excprevvisit.split('^');
    if (arrPrev != null && arrPrev.length > 0)
    {
      for (var idx=0; idx < arrPrev.length; idx++)
      {
        if (II_searchAllHistory('r'+ruleid+'epv') > 0)
          return(0);
      }
    }
  }

  if (exconlyprevvisit.length > 0)
  {
    arrOnlyPrev = exconlyprevvisit.split('^');
    if (arrOnlyPrev != null && arrOnlyPrev.length > 0)
    {
      for (var idx=0; idx < arrOnlyPrev.length; idx++)
      {
        if (II_searchAllHistory('r'+ruleid+'eopv') == 0)
          return(0);
      }
    }
  }

  return(ruleid);
}

function II_searchAllHistory(rulematch)
{
  var matchCount      = 0;
  var arrMatchHistory = II_getMatchHistory();
  
  if (arrMatchHistory.length > 0)
  {
    for (var idx=arrMatchHistory.length - 1; idx >= 0; idx--)
    {
      var histEntryMatches = arrMatchHistory[idx];
      if (histEntryMatches.indexOf(rulematch) != -1)
        matchCount++;
    }
  }
  return(matchCount);
}

function II_searchHistoryEntry(rulematch, idx)
{
  var matchCount      = 0;
  var arrMatchHistory = II_getMatchHistory();

  if (arrMatchHistory.length > 0 && arrMatchHistory.length - idx >= 0)
  {
    var histEntryMatches = arrMatchHistory[arrMatchHistory.length - idx];
    if (histEntryMatches.indexOf(rulematch) != -1)
      matchCount++;    
  }
  return(matchCount);
}

function II_doAvailCheck(ruleid)
{ 
  var rule = II_gtRS(ruleid);
  var deptid = II_gtRC("idi", rule);
  if (deptid == '-2') deptid = 'Default';
  var timestamp = (new Date()).getTime();
  II_gAvailableImage.src = II_gProtocol + '://admin.instantservice.com/resources/smartbutton/' + II_gAccountID + '/' + deptid + '/available.gif?ts=' + timestamp;
}

var II_gAvailableImage = null;
if (II_gUsingIE || II_gUsingNS)
{  
  if (navigator.appName.indexOf("Microsoft") != -1 && navigator.platform.indexOf("Mac") != -1)
    II_gAvailableImage = document.createElement('IMG');
  else
    II_gAvailableImage = new Image();
}
II_gAvailableImage.onload = function (evt) 
{
  II_gAgentsAvail = true;
  var timestamp = (new Date()).getTime();
  var ii_srcFile = (II_gUsingTestServers) ? "/II_TestRules.js" : "/II_Rules.js";
  callServer(II_gProtocol + '://admin.instantservice.com/resources/smartbutton/' + II_gAccountID + ii_srcFile + '?ts=' + timestamp);
  if (window.ISVT_onInviteOffered) ISVT_onInviteOffered(II_gRuleID, II_gInvitationID);
}
II_gAvailableImage.onerror = function (evt) 
{ 
  II_gAgentsAvail = false;
  if (II_gtRC("av", II_gtRS(II_gRuleID)) == "0")
  {
    var timestamp = (new Date()).getTime();
    var ii_srcFile = (II_gUsingTestServers) ? "/II_TestRules.js" : "/II_Rules.js";
    callServer(II_gProtocol + '://admin.instantservice.com/resources/smartbutton/' + II_gAccountID + ii_srcFile + '?ts=' + timestamp);
    if (window.ISVT_onInviteOffered) ISVT_onInviteOffered(II_gRuleID, II_gInvitationID);    
  }
  else
  {
    if (window.ISVT_onInviteNotOffered) ISVT_onInviteNotOffered(II_gRuleID, II_gInvitationID);  
  }
}

// This script is copyright (c) Henrik Petersen, NetKontoret
// Feel free to use this script on your own pages as long as you do not change it.
// It is illegal to distribute the script as part of a tutorial / script archive.
// Updated version available at: http://www.echoecho.com/toolfloatinglayer.htm
// This comment and the 4 lines above may not be removed from the code.

NS6=false;
IE4=(document.all);
if (!IE4) {NS6=(document.getElementById);}
NS4=(document.layers);

function adjust() {
if ((NS4) || (NS6)) {
if (lastX==-1 || delayspeed==0)
{
lastX=window.pageXOffset + floatX;
lastY=window.pageYOffset + floatY;
}
else
{
var dx=Math.abs(window.pageXOffset+floatX-lastX);
var dy=Math.abs(window.pageYOffset+floatY-lastY);
var d=Math.sqrt(dx*dx+dy*dy);
var c=Math.round(d/10);
if (window.pageXOffset+floatX>lastX) {lastX=lastX+delayspeed+c;}
if (window.pageXOffset+floatX<lastX) {lastX=lastX-delayspeed-c;}
if (window.pageYOffset+floatY>lastY) {lastY=lastY+delayspeed+c;}
if (window.pageYOffset+floatY<lastY) {lastY=lastY-delayspeed-c;}
}
if (NS4){
document.layers['floatlayer'].pageX = lastX;
document.layers['floatlayer'].pageY = lastY;
}
if (NS6){
document.getElementById('floatlayer').style.left=lastX + "px";
document.getElementById('floatlayer').style.top=lastY + "px";
}
}
else if (IE4){
var iiel;
var iimode=document.compatMode;
if(iimode && iimode=='BackCompat') iiel = document.body;
else iiel = (document.documentElement && typeof document.documentElement.scrollTop != 'undefined') ? document.documentElement : document.body;
if (lastX==-1 || delayspeed==0)
{
lastX=iiel.scrollLeft + floatX;
lastY=iiel.scrollTop + floatY;
}
else
{
var dx=Math.abs(iiel.scrollLeft+floatX-lastX);
var dy=Math.abs(iiel.scrollTop+floatY-lastY);
var d=Math.sqrt(dx*dx+dy*dy);
var c=Math.round(d/10);
if (iiel.scrollLeft+floatX>lastX) {lastX=lastX+delayspeed+c;}
if (iiel.scrollLeft+floatX<lastX) {lastX=lastX-delayspeed-c;}
if (iiel.scrollTop+floatY>lastY) {lastY=lastY+delayspeed+c;}
if (iiel.scrollTop+floatY<lastY) {lastY=lastY-delayspeed-c;}
}
document.all['floatlayer'].style.posLeft = lastX;
document.all['floatlayer'].style.posTop = lastY;
} 
setTimeout('adjust()',50);
}

function define()
{
if ((NS4) || (NS6)) 
{ 
if (halign=="left") {floatX=ifloatX};
if (halign=="right") {floatX=window.innerWidth-ifloatX-layerwidth-20};
if (halign=="center") {floatX=Math.round((window.innerWidth-20)/2)-Math.round(layerwidth/2)};
if (valign=="top") {floatY=ifloatY};
if (valign=="bottom") {floatY=window.innerHeight-ifloatY-layerheight};
if (valign=="center") {floatY=Math.round((window.innerHeight-20)/2)-Math.round(layerheight/2)};
}
if (IE4) 
{
var iiel;
var iimode=document.compatMode;
if(iimode && iimode=='BackCompat') iiel = document.body;
else iiel = (document.documentElement && typeof document.documentElement.scrollTop != 'undefined') ? document.documentElement : document.body;
if (halign=="left") {floatX=ifloatX};
if (halign=="right") {floatX=iiel.offsetWidth-ifloatX-layerwidth-20}
if (halign=="center") {floatX=Math.round((iiel.offsetWidth-20)/2)-Math.round(layerwidth/2)}
if (valign=="top") {floatY=ifloatY};
if (valign=="bottom") {floatY=iiel.offsetHeight-ifloatY-layerheight}
if (valign=="center") {floatY=Math.round((iiel.offsetHeight-20)/2)-Math.round(layerheight/2)}
}
}

var II_ENABLED = true;
var II_MAX_RULEMATCHLIST_SIZE = 30;
var II_COOKIE_EXPIRATION = new Date();
var II_gRuleID = 0;
var II_gInvitationID = 0;
var II_gUsingTestServers = false;
var II_gAgentsAvail = false;
var halign = "";
var valign = "";

function ruleCheck()
{
  if (II_gtSV("RuleTriggered") != "1")
  {
    II_gRuleID = II_checkRules();
    if (II_gRuleID > 0)
    { 
      II_upSV('RuleTriggered', '1');  
      II_gInvitationID = II_gtRC("ii", II_gtRS(II_gRuleID));
      II_doAvailCheck(II_gRuleID);
    }

    setTimeout("II_upSV('TimeSinceLastCheck', parseInt(II_gtSV('TimeSinceLastCheck')) + 5);ruleCheck()", 5000);
  }
}

if (II_gUsingIE || II_gUsingNS)
{  
  II_COOKIE_EXPIRATION.setTime(II_COOKIE_EXPIRATION.getTime() + (182*30*24*60*60*1000));

  if (II_gtSV("TestServers") == '')
    II_initTestServers();
    
  if (II_getUsingTestServers())
    II_gUsingTestServers = true;
    
  if (II_getRules().length == 0)
  {
    if (II_gUsingTestServers) II_createRulesCookie("test");
    else II_createRulesCookie("live");
  }
    
  if (II_updateMatchHistoryCookie())
  {
    ruleCheck();
  }
}
  
