var beaconRefreshCounter = 0;
var refreshBeaconURL;
var startBeaconIntervalFlag = false;
var maxCounter;
var refreshId;

function startRefresh(url, counter, interval) {
   refreshBeaconURL = url;
   maxCounter = counter;
   refreshId = setInterval("refreshBeaconDefinition()", interval);
}

function refreshBeaconDefinition() {
   beaconRefreshCounter++;
   if (beaconRefreshCounter > maxCounter) {
      clearAliveInterval();
      return;
   }

   AjaxRequest.get(
      {
         'url' : refreshBeaconURL,
         'onSuccess' : function(req) {}
      });
}

function clearAliveInterval() {
   if (refreshId) {
      clearInterval(refreshId);
   }

   return true;
}

/**
 * Process all beacons linked to a specific page.
 */
function processBeacon(actionPath, forwardName, sessionAdcode, signupAdcode, beaconParentDivId, contextPath, jsessionId, context) {
   if (!startBeaconIntervalFlag) {
      startBeaconIntervalFlag = true;
      var reloadURL = contextPath + "/beacon/refreshBeacon.act" + ";jsessionid=" + jsessionId + "?context=" + context;
      startRefresh(reloadURL, 5, 600 * 1000);
   }

   // check path, forward names
   var beaconArray = checkPath(beacons, actionPath, forwardName);
   if (beaconArray == null) {
      return;
   }

   // check context 
   beaconArray = checkContext(beaconArray, context);

   // check adcode
   beaconArray = checkAdcode(beaconArray, sessionAdcode, signupAdcode, activeBeaconMap);

   // check consumtion
   beaconArray = checkConsumtion(beaconArray, beaconConsumption);
 
   // check affiliates
   beaconArray = checkAffiliates(beaconArray, sessionAdcode, signupAdcode);

   if (beaconArray == null) {
      return;
   }

   for (var j = 0; j < beaconArray.length; j++) {
      removeElement(j, beaconParentDivId);

      var beaconElementId = createIframe(j);
      appendElement(beaconElementId, beaconParentDivId);

      if (beaconElementId != null) {
         var item = beaconArray[j];
         var beaconURL = contextPath + item.beaconPath + ";jsessionid=" + jsessionId + 
                        "?context=" + context + "&pageId=" + item.pageId + 
                        "&adcodeType=" + item.adcodeType;

         beaconElementId.src = beaconURL;
      }
   }
}

/**
 * Parse beacon configuration map to retrieve eligible beacon array for firing. 
 */
function checkPath(checkedBeacons, actionPath, forwardName) {
   if (!checkedBeacons || !actionPath || !forwardName) return null;

   var actionPath = trim(actionPath);
   var forwardName = trim(forwardName);

   var foundBecons = new Array();
   
   for (var i = 0; i < checkedBeacons.length; i++) {
      var aBeacon = checkedBeacons[i];
      if (aBeacon.path instanceof Array) {
         for (var j = 0; j < aBeacon.path.length; j++) {
            var aPath = aBeacon.path[j];
            var ap = trim(aPath.actionPath);
            var fw = trim(aPath.forwardName);

            if (ap == actionPath && (fw == "*" || fw == forwardName)) {
               foundBecons.push(aBeacon);
            }
         }
      }
   }
 
   return (foundBecons.length > 0) ? foundBecons : null;
} 

function checkContext(checkedBeacons, context) {
   if (!checkedBeacons || !context) return checkedBeacons;

   var length = context.length;
   if (length < 3) {
      return checkedBeacons;
   }

   var cProductCode = context.substring(0, 1);
   var cCommunityCode = context.substring(1, 2);
   var cBrand = context.substring(2, 3);
 
   var foundBecons = new Array();

   for (var i = 0; i < checkedBeacons.length; i++) {
      var aBeacon = checkedBeacons[i];
      var productCode = aBeacon.productCode;
      var communityCode = aBeacon.communityCode;
      var brand = aBeacon.brand;

      var validBeacon = true;

      if (productCode != null && productCode != "*" && productCode != cProductCode) {  
         validBeacon = false;
      }

      if (communityCode != null && communityCode != "*" && communityCode != cCommunityCode) {
         validBeacon = false;
      }

      if (brand != null && brand != "*" && brand != cBrand) {
         validBeacon = false;
      }

      if (validBeacon) {
         foundBecons.push(aBeacon);
      }
   }

   return (foundBecons.length > 0) ? foundBecons : null;
}

function checkConsumtion(checkedBeacons, checkedConsumption) {
   if (!checkedBeacons || !checkedConsumption || 
       !(checkedConsumption instanceof Array)) return checkedBeacons;

   var foundBecons = new Array();
   
   for (var i = 0; i < checkedBeacons.length; i++) {
      var aBeacon = checkedBeacons[i];
      var bmaxhit = parseInt(aBeacon.maxPerUser);

      var validBeacon = true;
      if (bmaxhit > 0) {
         for (var j = 0; j < checkedConsumption.length; j++) {
           if (checkedConsumption[j].pageId == aBeacon.pageId &&
              parseInt(checkedConsumption[j].hits) >= bmaxhit) {

              validBeacon = false;
              break;
          }
        }
      }

      if (validBeacon) {
         foundBecons.push(aBeacon);
      }
   }
 
   return (foundBecons.length > 0) ? foundBecons : null;
} 

/**
 * Parse beacon pageId-adcode map against adcodes.
 */
function checkAdcode(checkedBeacons, sessionAdcode, signupAdcode, activeBeaconMap) {
   if (!checkedBeacons) { 
      return null;
   }

   if (!activeBeaconMap) {
      return checkedBeacons;
   }

   /**
    * adcodes are numeric
    */
   var sesAdcode = parseInt(sessionAdcode);
   var sgnAdcode = parseInt(signupAdcode);

   var foundBecons = new Array();

   for (var i = 0; i < checkedBeacons.length; i++) {
      var aBeacon = checkedBeacons[i];
      var pageId = aBeacon.pageId;
      var adcodeType = aBeacon.adcodeType;
      var checkedAdcode = ("signup" == adcodeType) ? sgnAdcode : sesAdcode;

      var activeAdcodes = activeBeaconMap[pageId];
      if (activeAdcodes) {
         var match = false;

         if (activeAdcodes instanceof Array) {
            for (var k = 0; k < activeAdcodes.length; k++) {
               var oneAdcode = activeAdcodes[k];
               oneAdcode = oneAdcode.toString();

               if (oneAdcode == "*") {
                  match = true;
               } else {
                  if (oneAdcode.indexOf('-') > -1) {
                     var acds = oneAdcode.split("-");

                     if (parseInt(acds[0]) <= checkedAdcode && checkedAdcode <= parseInt(acds[1])) {
                        match = true;
                     }
                  } else if (parseInt(oneAdcode) == checkedAdcode) {
                     match = true;
                  }
               }

               if (match) {
                  foundBecons.push(aBeacon);
                  break;
               }
            }
         }
      }
   }

   return (foundBecons.length > 0) ? foundBecons : null;
}

/**
 * Parse beacon affiliates against adcodes. 
 */
function checkAffiliates(checkedBeacons, sessionAdcode, signupAdcode) {
   if (!checkedBeacons) return null;

   /**
    * adcodes are numeric
    */
   var sesAdcode = parseInt(sessionAdcode);
   var sgnAdcode = parseInt(signupAdcode);

   var foundBecons = new Array();
    
   for (var i = 0; i < checkedBeacons.length; i++) {
      var aBeacon = checkedBeacons[i];
      var adcodeType = aBeacon.adcodeType;
      var checkedAdcode = ("signup" == adcodeType) ? sgnAdcode : sesAdcode;

      if (aBeacon.affiliates instanceof Array) {
         for (var j = 0; j < aBeacon.affiliates.length ; j++) {
            var oneAffiliate = aBeacon.affiliates[j];
            var match = false;
            if (oneAffiliate.adcodes instanceof Array) {
               for (var k = 0; k < oneAffiliate.adcodes.length; k++) {
                  var oneAdcode = oneAffiliate.adcodes[k];

                  if (oneAdcode == "*") match =  true;
                  else if (oneAdcode.indexOf("-") > -1) {
                     acds = oneAdcode.split("-");
                     if (parseInt(acds[0]) <= checkedAdcode &&
                          checkedAdcode <= parseInt(acds[1])) match = true;
                  } 
                  else if (parseInt(oneAdcode) == checkedAdcode) match = true;

                  if (match) {
                     var b = new Object();
                     b["pageId"] = aBeacon.pageId;
                     b["maxPerUser"] = aBeacon.maxPerUser;
                     b["adcodeType"] = adcodeType;
                     b["adcode"] = checkedAdcode;
                     b["beaconPath"] = oneAffiliate.beaconPath;

                     foundBecons.push(b);
                     break;
                  }
               }
            }

            if (match) {
               break;
            }
         }
      }
   }
 
   return (foundBecons.length > 0) ? foundBecons : null;
} 

/**
 * Dynamically create a new <iframe> tag.
 * it will be used to store and beacon html/javascript in this iframe.
 */
function createIframe(iframeNum) {
   if (!document.createElement) {
      return null;
   }

   var newIframe = document.createElement('iframe');
   var iframeName = "beaconIframe_" + iframeNum;

   newIframe.setAttribute("id", iframeName);
   newIframe.setAttribute("name", iframeName);
   newIframe.style.visibility = "hidden";
   newIframe.style.width = 0;
   newIframe.style.height = 0;
   newIframe.style.border = 0;

   return newIframe;
}

/**
 * Append beacon <iframe> to its parent <DIV>.
 */
function appendElement(e, parentElementId) {
   var parentElement = element(parentElementId);

   if (parentElement == null) {
      alert("unable to display beacon since parent element is null, parentElementId: " + parentElementId);
   }
   
   parentElement.appendChild(e); 
} 

/**
 * Remove dynamically created beacon <DIV> tag.
 */
function removeElement(divNum, parentElementId) {
   var parentElement = element(parentElementId);

   if (parentElement == null) {
      return;
   }

   var oldDiv = element("beaconIframe_" + divNum);

   if (oldDiv != null) {
      parentElement.removeChild(oldDiv);
   }
}

/** 
 * Trim a string
 */
function trim(val) {
  return String(val).replace(/^\s+|\s+$/g, "");
}

/** 
 * definitions 
 */
/***
var cjadcodes = ["4444","4446","4450-4470","4489", "17001"];
***/

var beacons = [

   {name : "entrance session adcode",
    pageId : "14",
    maxPerUser : "*",
    productCode : "*",
    communityCode : "*",
    brand : "*",
    adcodeType : "session",
    path : [{actionPath : "/regnow/userinfo/add", forwardName : "*"},
            {actionPath : "/welcome", forwardName : "*"}],
    affiliates : [
       {name : "lavalife",
        adcodes : ["*"],
        beaconPath : "/beacon/getGuestBeacon.act"}
       ]
   },


   {name : "registration(convert to free) - session adcode",
    pageId : "15",
    maxPerUser : "1",
    productCode : "*",
    communityCode : "*",
    brand : "*",
    adcodeType : "session",
    path : [
            {actionPath : "/regnow/profile/add", forwardName : "success"}, 
            {actionPath : "/register/question/add", forwardName : "*"}
           ],

    affiliates : [
       {name : "lavalife",
        adcodes : ["*"],
        beaconPath : "/beacon/getFreeBeacon.act"}
       ]
   },


   {name : "registration(create profile) - session adcode",
    pageId : "27",
    maxPerUser : "1",
    productCode : "*",
    communityCode : "*",
    brand : "*",
    adcodeType : "session",
    path : [ {actionPath : "/regnow/newCard", forwardName : "success"} ],

    affiliates : [
       {name : "lavalife",
        adcodes : ["*"],
        beaconPath : "/beacon/getFreeBeacon.act"}
       ]
   },



   {name : "purchaseSummary(convert to paid) - signup adcode",
    pageId : "18",
    maxPerUser : "1",
    productCode : "*",
    communityCode : "*",
    brand : "*",
    adcodeType : "signup",
    path : [{actionPath : "/regnow/summary", forwardName : "success"},
            {actionPath : "/subscription/purchaseSummary", forwardName : "success"}],
    affiliates : [
       {name : "lavalife",
        adcodes : ["*"],
        beaconPath : "/beacon/getPaidBeacon.act"}
       ]
   },

   {name : "regflow tracking userinfo",
    pageId : "19",
    path : [{actionPath : "/regnow/userinfo/add", forwardName : "*"}],
    maxPerUser : "*", productCode : "*", communityCode : "*", brand : "*", adcodeType : "session",
    affiliates : [ {name : "lavalife", adcodes : ["*"], beaconPath : "/beacon/getGuestBeacon.act"} ]
   },

   {
    name : "regflow tracking profile",
    pageId : "20", 
    path : [ {actionPath : "/regnow/profile/add", forwardName : "success"}],
    maxPerUser : "1", productCode : "*", communityCode : "*", brand : "*", adcodeType : "session",
    affiliates : [ {name : "lavalife", adcodes : ["*"], beaconPath : "/beacon/getFreeBeacon.act"} ]
   },

   {
    name : "regflow tracking new card",
    pageId : "21", 
    path : [ {actionPath : "/regnow/newCard", forwardName : "success"}],
    maxPerUser : "1", productCode : "*", communityCode : "*", brand : "*", adcodeType : "session",
    affiliates : [ {name : "lavalife", adcodes : ["*"], beaconPath : "/beacon/getFreeBeacon.act"} ]
   },

   {
    name : "regflow tracking purchase summary",
    pageId : "22", 
    path : [ {actionPath : "/regnow/summary", forwardName : "success"}],
    maxPerUser : "1", productCode : "*", communityCode : "*", brand : "*", adcodeType : "session",
    affiliates : [ {name : "lavalife", adcodes : ["*"], beaconPath : "/beacon/getFreeBeacon.act"} ]
   },

   {
    name : "regflow tracking purchase decline",
    pageId : "23", 
    path : [ {actionPath : "/regnow/decline", forwardName : "success"}],
    maxPerUser : "1", productCode : "*", communityCode : "*", brand : "*", adcodeType : "session",
    affiliates : [ {name : "lavalife", adcodes : ["*"], beaconPath : "/beacon/getFreeBeacon.act"} ]
   },

   {
    name : "regflow tracking entry",
    pageId : "24", 
    path : [ {actionPath : "/regnow/profileEntryAdd", forwardName : "success"}],
    maxPerUser : "1", productCode : "*", communityCode : "*", brand : "*", adcodeType : "session",
    affiliates : [ {name : "lavalife", adcodes : ["*"], beaconPath : "/beacon/getFreeBeacon.act"} ]
   },

   {
    name : "regflow tracking entry preview",
    pageId : "25", 
    path : [ {actionPath : "/regnow/preview", forwardName : "success"}],
    maxPerUser : "1", productCode : "*", communityCode : "*", brand : "*", adcodeType : "session",
    affiliates : [ {name : "lavalife", adcodes : ["*"], beaconPath : "/beacon/getFreeBeacon.act"} ]
   },

   {
    name : "regflow tracking thanks",
    pageId : "26", 
    path : [ {actionPath : "/regnow/welcome", forwardName : "success"}],
    maxPerUser : "1", productCode : "*", communityCode : "*", brand : "*", adcodeType : "session",
    affiliates : [ {name : "lavalife", adcodes : ["*"], beaconPath : "/beacon/getFreeBeacon.act"} ]
   }

];

/**
 * Global Variables.
 */
beaconScriptLoaded = true;
beaconConsumption = null; 
activeBeaconMap = null;
