//
// badge.js
//
// Displays a Trustcash badge that launches a Trustcash popup
//

var POPUP_WIDTH = 800;
var POPUP_HEIGHT = 690;
var POPUP_BASE = "/popup/";

var BADGE_SMALL = "badge-small.png";
var BADGE_SMALL_WIDTH = 175;
var BADGE_SMALL_HEIGHT = 60;
var BADGE_BASE_URL = "/images/badges/";

var DIAGRAM_URL = 'https://www.trustcash.com/site/diagram.php';
var DIAGRAM_WIDTH = 820;
var DIAGRAM_HEIGHT = 620;

var MPA3_REDIRECT_URL = "/signup/trustcash_redirect.php";

//var session_id = "1&&hU&3Uqh^1q71_7&`  h_[q{[w5[q5h  111[h5[q`3[1q{    D-n$;;J23[&^o)-LRJ,$x;i9^DZVP^h[&9^:$tH-Wa^<e^`[q9^Zrqkz{)hQq5qq{15x)5QiQhh5)_HxHJ`)HQ1q";

if (!window.baseURL) {
  window.baseURL = "https://www.trustcash.com";
}
if (!window.baseGraphicsURL) {
  window.baseGraphicsURL = "https://www.trustcash.com";
}

function isEmpty (val)
{
  return !val || val == "";
}

function getQueryVariable(name)
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == name) {
      return pair[1];
    }
  }
  return null;
}

function getCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') {
		  c = c.substring(1,c.length);
		}
		if (c.indexOf(nameEQ) == 0) {
		  return c.substring(nameEQ.length,c.length);
		}
	}
	return null;
}

function getCookieOrQueryString (name) {
  var value = getQueryVariable(name);
  return value ? value : getCookie(name);
}

function addLoadEvent(func)
{
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function isAbsoluteURL(URL) {
  return URL.indexOf("http://") == 0 || URL.indexOf("https://") == 0;
}

function appendQueryString(baseURL, queryString, appendToQS){
  // choose a query string separator depending on whether ? is present in the URL
  var hasQ = (baseURL.indexOf("?") != -1);
  var hasA = (baseURL.indexOf("&") != -1);
  var separator;

  if (isEmpty(baseURL)) {
    return queryString;
  }
  if (appendToQS) {
    separator = "&";
  } else {
    separator = (baseURL.indexOf("?") == -1) ? "?" : "&";
  }
  return baseURL + separator + queryString;
}

function showErr (err, title)
{
    var txt = title + ": there was an error on this page.\n\n";
    txt += "Error description: " + err.description + "\n\n";
    txt += "Error message: " + err.message + "\n\n";
    txt += "Error line: " + err.lineNumber + "\n\n";
    txt += "File name: " + err.fileName + "\n\n";
    txt += "Click OK to continue.\n\n";
    alert(txt);
}

function setWindowFeatures (width, height, toolbar, location, directories, resizeable, status, scrollbars, menubar)
{
  if (isEmpty(width)) width = POPUP_WIDTH;
  if (isEmpty(height)) height = POPUP_HEIGHT;
  if (isEmpty(toolbar)) toolbar = "no";
  if (isEmpty(location)) location = "no";
  if (isEmpty(directories)) directories = "no";
  if (isEmpty(resizeable)) resizeable = "no";
  if (isEmpty(status)) status = "no";
  if (isEmpty(scrollbars)) scrollbars = "no";
  if (isEmpty(menubar)) menubar = "no";

  var window_features = "width=" + width;
  window_features += ",height=" + height;
  window_features += ",toolbar=" + toolbar;
  window_features += ",location=" + location;
  window_features += ",directories=" + directories;
  window_features += ",resizeable=" + resizeable;
  window_features += ",status=" + status;
  window_features += ",scrollbars=" + scrollbars;
  window_features += ",menubar=" + menubar;

  return window_features;
}

function perform(windowName, codeForm, URL, queryString)
{
  try {
    codeForm.target = windowName;
  <!--  code = codeForm.code.value;-->
  <!--  code = replaceChars(code);-->
  <!--  codeForm.code.value = code;-->
  <!--  codeForm.id.value = session_id;-->

    var fullURL = URL;
    if (isEmpty(fullURL)) fullURL = window.baseURL + "/popup/popup.php";
    if (!isAbsoluteURL(fullURL)) {
      fullURL = window.baseURL + fullURL;
    }

    // Append queryString to base url if necessary
    if (!isEmpty(queryString)) {
      fullURL = appendQueryString(fullURL, queryString);
    }
    codeForm.action = fullURL;

    // Make new window
    var window_features = setWindowFeatures();
    var win = window.open('', windowName, window_features);
    win.focus();   // Bring new window to front
    return true;

  } catch(err) {
    showErr(err, "trustcash.js - perform()");
    return false;
  }
}

function openTrustcashPopup(windowName, siteid, URL, queryString, launchInline, popupVersion)
{
  // Prepare fullURL
  var fullURL = URL;
  if (isEmpty(fullURL)) {
    fullURL = window.baseURL + getPopupURL(popupVersion) + "home/";  // default popup home
    if (!isEmpty(siteid)) {
      fullURL += (siteid);
    }
  }
  if (!isAbsoluteURL(fullURL)) {  // prepend default base URL
    fullURL = window.baseURL + fullURL;
  }
  // Append queryString if necessary
  if (!isEmpty(queryString)) {
    fullURL = appendQueryString(fullURL, queryString);
  }
  // Append siteid
  if (!isEmpty(siteid) && !isEmpty(URL)) {
    // Only need to do this if we haven't used the default popup url
    fullURL = appendQueryString(fullURL, "siteid=" + siteid);
  }

  try {
    win = null;
    if (launchInline) {
      // Inline directive
      throw "Launching inline!";
    }

    // Make new window
    var window_features = setWindowFeatures();
    var win = window.open(fullURL, windowName, window_features);
    win.focus();   // Bring new window to front

  } catch(err) {
    if (!win) {
      // Launch popup inline either because of launchInline directive or because popup failed to launch
      fullURL = appendQueryString(fullURL, 'inline=t', true);
      window.location = fullURL;
    } else {
      // Some other exception not involving popup window
      showErr(err, "trustcash.js - openTrustcashPopup()");
    }
  }
}

// Diagram popup

function openDiagramWindow() {
  var newURL = DIAGRAM_URL;
  var remote = open(newURL, "x", "width=" + DIAGRAM_WIDTH + ",height=" + DIAGRAM_HEIGHT);
  if (remote.opener == null) {
    remote.opener = window;
  }
}


// For backward compatibility:
function openPPPWindow(windowName, siteid, URL, queryString)
{
  openTrustcashPopup(windowName, siteid, URL, queryString, false);
}

function openPPPCardWindow(windowName, siteid, URL, queryString)
{
  openTrustcashPopup(windowName, siteid, URL, queryString, false);
}

function URLEncode(plaintext )
{
 // The Javascript escape and unescape functions do not correspond
 // with what browsers actually do...
 var SAFECHARS = "0123456789" +     // Numeric
     "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // Alphabetic
     "abcdefghijklmnopqrstuvwxyz" +
     "-_.!~*'()";     // RFC2396 Mark characters
 var HEX = "0123456789ABCDEF";

 var encoded = "";
 alert(plaintext);
 for (var i = 0; i < plaintext.length; i++ ) {
  var ch = plaintext.charAt(i);
     if (ch == " ") {
      encoded += "+";    // x-www-urlencoded, rather than %20
  } else if (SAFECHARS.indexOf(ch) != -1) {
      encoded += ch;
  } else {
      var charCode = ch.charCodeAt(0);
   if (charCode > 255) {
       alert( "Unicode Character '"
                        + ch
                        + "' cannot be encoded using standard URL encoding.\n" +
              "(URL encoding only supports 8-bit characters.)\n" +
        "A space (+) will be substituted." );
    encoded += "+";
   } else {
    encoded += "%";
    encoded += HEX.charAt((charCode >> 4) & 0xF);
    encoded += HEX.charAt(charCode & 0xF);
   }
  }
 } // for
 return encoded;
};


// This function can be tweaked to experiment with badge effectiveness

function getBadge()
{
  if(imgVersion != "") {
    var i = Math.random();
    var imgdata = imgVersion.split(",");
    return imgdata[0] +"."+ Math.floor(i * parseInt(imgdata[1],10)) +".png";
  } else {
    return "badge-9.0.png";
  }
}


// This function can be tweaked to experiment with popup effectiveness

function getPopupURL(popupVersion)
{
  var i = Math.random();
  if (!isEmpty(popupVersion)) {
    return "/popup" + popupVersion + "/";
  } else if (i < 0.5) {
    return "/popup2.0/";
  } else {
    return "/popup2.1/";
  }
}

function loadTrustcashBadge(siteID, badge, targetID, buttonWidth, buttonHeight, isForm)
{
  try {
    // If necessary, populate image attributes using defaults
    if (isEmpty(badge)) {
      badge = getBadge();
      buttonWidth = BADGE_SMALL_WIDTH;
      buttonHeight = BADGE_SMALL_HEIGHT;
    }
    if (isEmpty(targetID)) targetID = "trustcash";
    if (isEmpty(isForm)) isForm = false;
    var alt = "Trustcash";
    var src = isAbsoluteURL(badge) ? badge : window.baseGraphicsURL + BADGE_BASE_URL + badge;
/*
    if (!isEmpty(siteID)) {
      src += "?siteID=" + siteID;
    }
*/
    if (!isForm) {
      // Append image to span id="targetID"
      var img = document.createElement("img");
      img.alt = alt;
      img.src = src;
      if (!isEmpty(buttonHeight)) img.height = buttonHeight;
      if (!isEmpty(buttonWidth)) img.width = buttonWidth;
      img.border = 0;
      var container = document.getElementById(targetID);
      container.appendChild(img);
    } else {
      // Set submit button's attributes
      var submitButton = document.getElementById (targetID);
      submitButton.src = src;
      submitButton.alt = alt;
      submitButton.height = buttonHeight;
      submitButton.width = buttonWidth;
    }
    return badge;

  } catch(err) {
    showErr(err, "trustcash.js - loadTrustcashBadge()");
    return false;
  }
};

// If preload_badge variable is set then load badge
if (!isEmpty(window.preload_badge)) {
  addLoadEvent(function() {
    loadTrustcashBadge();
  });
}

// If trustcash badge has been defined then set it up
var badgeId = "trustcash";
var badge = document.getElementById(badgeId);
if (!badge) {
  badgeId = "pppimage";
  badge = document.getElementById(badgeId);
}

if (badge) { // Populate badge link attributes

  // Get attributes from <a> tag
  var siteId = "", siteType = "", badgeImage = "", mpa3SiteId = "", mpa3Domain = "", defaultNats = "", popupURL = "", queryString = "", session = "";
  // var imgVersion = "badge-9,4";
  var imgVersion = "";
  var productCode = "", productId = "", popupVersion = "";
  var chargeAmount = "", orderDescription = "";
  var launchInline = false;
  var badgeAttributes = badge.attributes;
  var attrLength = badgeAttributes.length;
  for (i = 0; i < attrLength; i++){
    if (badgeAttributes[i].name == "sitetype") siteType = badgeAttributes[i].value.toLowerCase();
    if (badgeAttributes[i].name == "siteid") siteId = badgeAttributes[i].value;
    if (badgeAttributes[i].name == "badge") badgeImage = badgeAttributes[i].value;
    if (badgeAttributes[i].name == "nats") defaultNats = badgeAttributes[i].value;
    if (badgeAttributes[i].name == "mpa3") mpa3SiteId = badgeAttributes[i].value;
    if (badgeAttributes[i].name == "mpa3_domain") mpa3Domain = badgeAttributes[i].value;
    if (badgeAttributes[i].name == "url") popupURL = badgeAttributes[i].value;
    if (badgeAttributes[i].name == "session") session = badgeAttributes[i].value;
    if (badgeAttributes[i].name == "product_code") queryString = appendQueryString(queryString, 'product_code=' + badgeAttributes[i].value, true);
    if (badgeAttributes[i].name == "product_id") queryString = appendQueryString(queryString, 'product_id=' + badgeAttributes[i].value, true);
    if (badgeAttributes[i].name == "debug") queryString = appendQueryString(queryString, 'debug=t', true);
    if (badgeAttributes[i].name == "staging") queryString = appendQueryString(queryString, 'staging=t', true);
    if (badgeAttributes[i].name == "inline") launchInline = true;
    if (badgeAttributes[i].name == "version") popupVersion = badgeAttributes[i].value;
    if (badgeAttributes[i].name == "charge_amount") chargeAmount = badgeAttributes[i].value;
    if (badgeAttributes[i].name == "order_description") orderDescription = badgeAttributes[i].value;
    if (badgeAttributes[i].name == "badge_set") imgVersion = badgeAttributes[i].value;
  }

  // Construct popup URL based on site type
  if (siteType == "nats") {

    // Get NATS code from cookie or query string
    var natsCode = getCookieOrQueryString("nats");
    queryString = appendQueryString(queryString, "nats=" + (isEmpty(natsCode) ? defaultNats : natsCode), true);

    var natsSess = getCookieOrQueryString("nats_sess");
    if (!isEmpty(natsSess)) {
      queryString = appendQueryString(queryString, "natssess=" + natsSess, true);
    }

  } else if (siteType == "mpa3") {
    // Construct MPA3 redirect URL
    if (mpa3Domain) {
      popupURL = mpa3Domain + MPA3_REDIRECT_URL;
      var mpa3RedirectURL = "relative=" + getPopupURL(popupVersion) + "home/" + siteId;
      if (launchInline) {
        // This is usually done in openTrustcashPopup but for mpa3 must be placed in the relative parameter too
        queryString = appendQueryString(queryString, 'inline=t', true);
      }
      // Have to pass query string variables via mpa3 redirect parameter
      if (!isEmpty(queryString)) {
        mpa3RedirectURL += ("?" + escape(queryString));
      }
      queryString = mpa3RedirectURL;
    }
    queryString = appendQueryString(queryString, "mpa3=" + mpa3SiteId, true);

  } else if (!isEmpty(session)) {

    // Append session value if present - only available for non-MPA3/NATS sites
    queryString = appendQueryString(queryString, "session=" + session, true);
  }

  // Set badge element attributes
  // badge.setAttribute ("onclick", "openTrustcashPopup('trustcash', '" + siteId + "', " + popupURL + ")");  // sigh, doesn't work on IE
  if (badge != "none") {
    // Append badge name to query string for analysis purposes
    var badgeName = loadTrustcashBadge (siteId, badgeImage, badgeId);
    queryString = appendQueryString(queryString, 'badgeName=' + badgeName, true);
  }
  if (!isEmpty(chargeAmount)) {
    if (isEmpty(orderDescription)) {
      alert('Need an order description badge attribute');
    } else {
      queryString = appendQueryString(queryString, 'charge_amount=' + chargeAmount + '&order_description=' + orderDescription, true);
    }
  }
  badge.onclick = function() {
                    openTrustcashPopup('trustcash', siteId, popupURL, queryString, launchInline, popupVersion);
                  };
  badge.href = "javascript:void(null);";
}
