// Copyright (C) 2004-2005 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. 
  
function II_checkRules()
{
  var retRuleID       = 0;
  var arrRules        = II_getRules();
  var arrMatchHistory = II_getMatchHistory();

  if (arrMatchHistory.length == 0)
    return;

  for (var idx=0; idx < arrRules.length; idx++)
  {
    var rule            = arrRules[idx];
    var ruleid          = II_getRuleComponent("ruleid", rule);
    var ruletype        = II_getRuleComponent("ruletype", rule);
    var firstpagematch  = II_getRuleComponent("firstpagematch", rule);
    var secondpagematch = II_getRuleComponent("secondpagematch", rule);
    var rulevalue1      = II_getRuleComponent("rulevalue1", rule);
    var rulevalue2      = II_getRuleComponent("rulevalue2", rule);
    var rulevalue3      = II_getRuleComponent("rulevalue3", rule);

    if (retRuleID > 0)
      break;
        
    switch(ruletype)
    {
      case '1': 
        var count = II_getStoredValue("PageCountSinceLastShown");
        if (count != '' && rulevalue1 != '')
        {
          if (parseInt(count) == parseInt(rulevalue1))
            retRuleID = II_checkRuleExceptions(rule);
        }
        break;

      case '2':
        if (document.referrer != null && document.referrer.indexOf(rulevalue1) != -1)
          retRuleID = II_checkRuleExceptions(rule);
        break;

      case '3':
        var match1 = II_searchLastHistoryEntry(firstpagematch);
        if (match1 > 0)
          retRuleID = II_checkRuleExceptions(rule);
        break;

      case '4':
        var match1 = II_searchLastHistoryEntry(firstpagematch);
        if (match1 > 0)
        {
          var match2 = II_searchAllHistory(firstpagematch);
          if (match2 >= rulevalue1)
            retRuleID = II_checkRuleExceptions(rule);
        }
        break;

      case '5':
        var match1 = II_searchLastHistoryEntry(secondpagematch);
        if (match1 > 0)
        {
          var match2 = II_searchPrevHistoryEntry(firstpagematch);
          if (match2 > 0)
            retRuleID = II_checkRuleExceptions(rule);
        }
        break;

      case '6':
        var match1 = II_searchLastHistoryEntry(firstpagematch);
        if (match1 > 0)
        {
          retRuleID = II_checkRuleExceptions(rule);
        }
        break;
      
      case '7':    // cookie rule, user visits page, 'value' found in 'cookie'
        var match1 = II_searchLastHistoryEntry(firstpagematch);
        if (match1 > 0)
        {
          var cookieval = II_getCookie(rulevalue1);
          if (cookieval != null)
          {
            if (cookieval.indexOf(rulevalue2) != -1)
              retRuleID = II_checkRuleExceptions(rule);
          }
        }
        break;
    }
  }

  return(retRuleID);
}


function II_checkRuleExceptions(rule)
{
  var retRuleID         = II_getRuleComponent("ruleid", rule);
  var excprevoffercount = II_getRuleComponent("excprevoffercount", rule);
  var excprevoffertime  = II_getRuleComponent("excprevoffertime", rule);
  var excprevvisit      = II_getRuleComponent("excprevvisit", rule);
  var exconlyprevvisit  = II_getRuleComponent("exconlyprevvisit", rule);

  // break up excprevvisit and exconlyprevvisit into arrays of locations
 
  if (excprevoffercount.length > 0)
  {
    var pages = II_getStoredValue("PrevOfferCount");
    if (pages != '' && pages >= excprevoffercount)
      return(0);
  }
      
  if (excprevoffertime.length > 0)
  {
    var ii_time = II_getStoredValue("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++)
      {
        var match1 = II_searchAllHistory(arrPrev[idx]);
        if (match1 > 0)
          return(0);
      }
    }
  }

  if (exconlyprevvisit.length > 0)
  {
    arrOnlyPrev = exconlyprevvisit.split('^');
    if (arrOnlyPrev != null && arrOnlyPrev.length > 0)
    {
      for (var idx=0; idx < arrOnlyPrev.length; idx++)
      {
        var match1 = II_searchAllHistory(arrOnlyPrev[idx]);
        if (match1 == 0)
          return(0);
      }
    }
  }

  return(retRuleID);
}


function II_searchAllHistory(matchValue)
{
  var matchCount      = 0;
  var arrMatchHistory = II_getMatchHistory();
  
  if (arrMatchHistory.length > 0)
  {
    for (var idx=arrMatchHistory.length - 1; idx >= 0; idx--)
    {
      var histEntryMatches = arrMatchHistory[idx].split('```');

      for (var idx2=0; idx2 < histEntryMatches.length; idx2++)
      {
        var singleRuleDetails = histEntryMatches[idx2].split('`');
        var search = singleRuleDetails[1];

        if (search == matchValue)
          matchCount++;
      }
    }
  }
  return(matchCount);
}

function II_searchLastHistoryEntry(matchValue)
{
  var matchCount      = 0;
  var arrMatchHistory = II_getMatchHistory();

  if (arrMatchHistory.length > 0)
  {
    var histEntryMatches = arrMatchHistory[arrMatchHistory.length - 1].split('```');

    for (var idx=0; idx < histEntryMatches.length; idx++)
    {
      var singleRuleDetails = histEntryMatches[idx].split('`');
      var search = singleRuleDetails[1];

      if (search == matchValue)
      {
        matchCount++;
        break;
      }
    }
  }    
  return(matchCount);
}

function II_searchPrevHistoryEntry(matchValue)
{
  var matchCount      = 0;
  var arrMatchHistory = II_getMatchHistory();

  if (arrMatchHistory.length > 1)
  {
    var histEntryMatches = arrMatchHistory[arrMatchHistory.length - 2].split('```');

    // now for each rule that this entry applies to, test for a match
    for (var idx=0; idx < histEntryMatches.length; idx++)
    {
      var singleRuleDetails = histEntryMatches[idx].split('`');
      var search = singleRuleDetails[1];

      if (search == matchValue)
      {
        matchCount++;
        break;
      }
    }
  }    
  return(matchCount);
}


function II_doAvailCheck(ruleid)
{ 
  var rule = II_getRuleString(ruleid);
  var deptid = II_getRuleComponent("invitedept", rule);

  if (deptid == '-2')
    deptid = 'Default';

  document.write('<script src="' + II_gProtocol + '://admin.instantservice.com/resources/smartbutton/' + II_gAccountID + '/' + deptid + '/SmartButton.js" type="text/javascript"></script>');
  
  var ii_srcFile = "/Rules.js";

  if (II_gUsingTestServers)
    ii_srcFile = "/TestRules.js";
    
  document.write('<script src="' + II_gProtocol + '://admin.instantservice.com/resources/smartbutton/' + II_gAccountID + ii_srcFile + '" type="text/javascript"></script>');
}

///// Main
var II_ENABLED                 = true;
var II_MAX_RULEMATCHLIST_SIZE  = 30;
var II_COOKIE_EXPIRATION       = new Date();
var II_gRuleID                 = 0;
var II_gUsingTestServers       = false;

if (II_gUsingIE || II_gUsingNS)
{  
  if (1 == 1)
    II_COOKIE_EXPIRATION.setTime(II_COOKIE_EXPIRATION.getTime() + (182*30*24*60*60*1000));
  else
    II_COOKIE_EXPIRATION.setTime(II_COOKIE_EXPIRATION.getTime() + (60*60*1000));

  if (II_getCookie(II_gTSCookieName) == null)
    II_createTestServersCookie();
    
  if (II_getUsingTestServers())
    II_gUsingTestServers = true;
    
  if (II_getRules().length == 0)
  {
    if (II_gUsingTestServers)
      II_createRulesCookie("test");
    else
      II_createRulesCookie("live");
  }
    
  if (II_updateMatchHistoryCookie())
  {
    II_gRuleID = II_checkRules();
    if (II_gRuleID > 0)
      II_doAvailCheck(II_gRuleID);
  }
}

