// Documentation is at: http://www.mypoints.com/emp/u/d/pixelTrackingSelfService.vm

var MyPoints = new function() {

  // MyPoints Partner Cookie settings
  var VID_LENGTH = 20;
  var vidParamName = null;
  var mpcName = "MP_TRACK";
  var mpcDomain = null;
  var mpcExpHours = 2*24; // Two days
  var mpcPath = "/";
  var mpHost = "www.mypoints.com";
  var mpTag = "A";
  var secureHttp = null;

  // Set the given cookie
  var mpSetCookie = function(name,value,expHours,path,domain) {
    var expDate=new Date();
    expDate.setTime(expDate.getTime()+(expHours*60*60*1000));
    document.cookie = name + "=" + escape(value)
      + ((expHours==null) ? "" : ";expires=" + expDate.toGMTString())
      + ((path==null) ? "" : ";path=" + path)
      + ((domain==null) ? "" : ";domain=" + domain);
  };

  // Retrieve cookie value for the given name
  var mpGetCookie = function(name) {
    if (document.cookie.length>0) {
      var cookies = document.cookie.split(';');
      for ( var i = 0; i < cookies.length; i++ ) {
        var cookie = cookies[i].split('=');
        var cName = cookie[0].replace(/^\s+|\s+$/g, '');
        if ( cName == name ) {
          if (cookie.length > 1) {
            return unescape( cookie[1].replace(/^\s+|\s+$/g, '') );
          }
        }
      }
    }
    return "";
  };

  // Check if cookie for the given name is available
  var mpCheckCookie = function(name) {
    var vid=mpGetCookie(name);
    if (vid == null || vid == "")
      return false;
    else
      return true;
  };

  // construct MyPoints Pixel tracking url
  var constructMPUrl = function(mpHost, vid, tag, forceSecureHttp) {
    return ((forceSecureHttp == true) ? "https" : "http") + "://" + mpHost + "/emp/u/" + vid + "/" + tag + "/ctr.gif";
  };

  // Exposed methods to partners
  return {
    // Setting config values
    setCookieDomain : function(val) {
      mpcDomain = val;
    },
    setMPCookieName : function(name) {
      // The cookie name is used only if it is valid.
      // Note: Since we can't report this error to end user,
      // we will continue to use the default name if the given name is not valid.
      if (name.match(/^[a-zA-Z0-9_]+$/) != null) {
          mpcName = name;
      }
    },
    setVIDParamName : function(param) {
      vidParamName= param;
    },
    setMPCookieExpHours : function(hours) {
      mpcExpHours = hours;
    },
    setMyPointsDomain : function(domain) {
      mpHost = domain;
    },
    setMPTag : function(tag) {
      mpTag = tag;
    },
    useSecureHttp : function(val) {
      secureHttp = val;
    },
    // Function to be called from the landing page
    landing : function() {
      var url = location.href;
      var vid = null;
      var vidError = false;
      if (vidParamName != null && vidParamName != "") {
        var param = url.match(new RegExp("([?]|&)" + vidParamName+ "=" + "[a-zA-Z0-9_-]{" + VID_LENGTH + "}(&|$)"));
        if (param != null && param[0] != null) {
          vid = param[0].substring(vidParamName.length+2,param[0].length-((param[0].charAt(param[0].length-1) == '&') ? 1 : 0));
        }
        if (vid == null) {
          vid = "";
          vidError = true;
        }
      } else {
        var param = url.match(new RegExp("[^a-zA-Z0-9_-][a-zA-Z0-9_-]{" + VID_LENGTH + "}(&|$)", "g"));
        if (param != null && param.length == 1 && param[0] != null) {
          vid = param[0].substring(1,param[0].length - ((param[0].charAt(param[0].length-1) == '&') ? 1 : 0));
        }
        if (vid == null) {
          vid = "";
          vidError = true;
        }
      }
      if (vid == "") {
        // nothing to set; skip
      } else if (vidError && mpCheckCookie(mpcName)) {
        // cookie is already set, probably the page with MyPoints html snippet is viewed again. Ignore.
      } else {
        if (mpcDomain == null || mpcDomain == "") {
          mpcDomain = location.hostname.replace(/^www\./,"");
        }
        mpSetCookie(mpcName,vid,mpcExpHours,mpcPath,mpcDomain);
      }
    },
    // function to be called from the confirmation page where the MP tracking pixel is desired
    track : function() {
      var vid = mpGetCookie(mpcName);
      if (vid == null || vid == "") {
        // Ignore if vid is not available. Probably the current page is not linked with mypoints.com
        return "";
      }
      if (secureHttp == null) {
        secureHttp = (location.protocol == "https:") ? true : false;
      }
      var mpUrl = constructMPUrl(mpHost, vid, mpTag, secureHttp);
      document.write("<img src=\"" + mpUrl + "\" height=\"1\" width=\"1\"/>");
      return mpUrl; // Returns pixel value for ease of testing
    }
  };
}