// Copyright 2009, J.F. Kelley (except as noted).
// All rights reserved, except: you may use this for your Unicity business with the following conditions:
// You keep this copyright statement in place.
var toolversion = 1.3
var unicityname = 'myslimhealth'
var videoid=''
var trackid = ''
var mysubdom = ''
var pagename=getPageName()
var ctch_str = ''
var mixedformk = "ddb4dcb01c0855664e270a4c95a29cf3635f787616cee800669a51"
var hnew = "d5ff4b9a8e9d0f5e15c521bbd2b98188"

var debug_log="invisible"

var loggedactions = ''

var welcomebiz = ''

var sargs = new Object()
parseSearch('',sargs)

if (sargs["debug"] && sargs["debug"] == "y") {
  debug_log="visible"
  }

if (sargs["url"]) document.location=unescape(sargs["url"])

var starttime=(new Date()).getTime()

addEvent(window,"load",biz_init)

var docookie=true

var still_loaded = true

//addEvent(window,"beforeunload", function(event) {
function doBeforeUnload() {
 if (still_loaded) {
   logMe('Exit.  Time on page: ' + (Math.ceil(((new Date()).getTime() - starttime)/1000)) + ' sec.  Tool Version ' + toolversion + ' - Actions: ' + loggedactions)
   }
 stil_loaded=false
 }

function addUnloadEvent() {
  if (navigator.userAgent.toLowerCase().indexOf("safari")!=-1) {
    var bodyElt;
    bodyElt = document.getElementById("bodyObject");
    if (!bodyElt) {
      bodyElt = document.getElementsByTagName("body")[0];
      }
    if (bodyElt) {
      bodyElt.addEventListener("unload", doBeforeUnload, false);
      }
    }
  else {
    window.onunload=doBeforeUnload;
    }
  }

function biz_init() {
  document.title='MLMDirect.Biz - Your Unicity Career (' + toolversion + ')'

  twisty_debug = true;

  if (sargs["remember"] && sargs["remember"] == "no") docookie=false

  if (document.getElementById("noscript"))  document.getElementById("noscript").style.display="none"

  var domains = location.hostname.split(".")
  if (domains[1] && domains[1] == "mlmdirect" && domains[2] && domains[2] == "biz" && domains[0].toLowerCase() != "www") {
    mysubdom = domains[0].toLowerCase()
    unicityname=mysubdom
    }
  else if (sargs["biz"]) unicityname=sargs["biz"].toLowerCase()
  else {
    var cname = getCookie("unicityname")
    if (cname) unicityname = cname
    }
  setTimeout("window.status='Business name: ' + unicityname",2000)

  if (sargs["tid"]) trackid=sargs["tid"].toLowerCase()
  else {
    var ctid = getCookie("trackid")
    if (ctid) trackid = ctid
    }

  if (sargs["log"]) {
    var hun=hex_md5(sargs["log"])
    if (!idents[hun]) alert("Your url says log=" + sargs["log"] + ".  That is not a recognized business name.  Please try again.")
    else {
       var ldiv = document.getElementById("logsdiv")
       if (ldiv) ldiv.style.display=""
       else document.location="Contact.html?log=" + sargs["log"]
       }
    return
    }

  else if (sargs["admin"]) {
    if (!document.getElementById("admin1")) document.location = "Contact.html?admin=" + sargs["admin"]
    else processNewDistributors()
    return
    }

  if (sargs["uid"]) videoid=sargs["uid"]
//else { // no point in reading a stored video id since it expires in 8 viewings anyway.
//  var vid = getCookie("videoid")
//  if (vid) videoid = vid
//  }

  if (docookie && unicityname) setCookie("unicityname",unicityname,offsetDays(365))
  if (docookie && videoid) setCookie("videoid",videoid,offsetDays(365))


  if (-1 < pagename.indexOf("index.html")) {
    logMe("PageLoad (" + navigator.userAgent + ")")
    insertMe()
    if (sargs["format"]) var myformat = sargs["format"]
    else var myformat = ""
    if ((myformat == "email") || (myformat == "outlook") || (myformat == "print")) prepEmail(myformat)
    else {
      if (videoid) showUnicityVideos()
      if (unicityname) setTimeout('leadProtect()',100)
      }
    }
  else if (pagename == "Contact.html") {
    logMe("PageLoad (" + navigator.userAgent + ")")
    loadContact()
  //if (unicityname == "myslimhealth") doGoogleAnalytics() // TODO - needs new codes
    }
  else if (pagename == "newdist.html") {
    logMe("PageLoad (" + navigator.userAgent + ")","mlmdirect")
    loadNewDist()
    }
  else if (pagename == "welcome.html") {
    logMe("PageLoad (" + navigator.userAgent + ")","mlmdirect")
    if (!mysubdom) {
      document.getElementById("signindiv").style.display=""
      document.getElementById("validbody").style.display="none"
      var bInp = document.getElementById("enterbiz")
      if (unicityname) bInp.value=unicityname
      bInp.focus()
      bInp.select()
      }
    else {
      document.getElementById("enterbiz").value=mysubdom
      document.getElementById("validbody").style.display=""
      document.getElementById("enterbiz").focus()
      welcomeGo()
      }
    if (document.all) document.getElementById("my_uid").onpaste=updateLogEmailUrl
    }
  }

function insertMe() {
  if (unicityname) {
    var hun = hex_md5(unicityname)
    if (idents[hun]) {
      var insname = unmix(idents[hun][0],unicityname)
      if (insname) {
        var iObjs = findElementsByClassName(document,"insertname")
        for (var i=0;i<iObjs.length;i++) {
          iObjs[i].innerHTML = insname
          }
        }

      var insphone = unmix(idents[hun][2],unicityname)
      if (insphone) {
        var iObjs = findElementsByClassName(document,"insertphone")
        for (var i=0;i<iObjs.length;i++) {
          iObjs[i].innerHTML = " at " + insphone
          }
        }

      var insurl = '<a href="http://' + unicityname + '.mlmdirect.biz">http://' + unicityname + '.mlmdirect.biz</a>'
      var iObjs = findElementsByClassName(document,"inserturl")
      for (var i=0;i<iObjs.length;i++) {
        iObjs[i].innerHTML = insurl
        }

      }
    }
  }

function welcomeGo() {
  var trybiz = document.getElementById("enterbiz").value.toLowerCase()
  if (docookie && trybiz) setCookie("unicityname",trybiz,offsetDays(365))
  welcomebiz=''
  if (trybiz) {
    var hun = hex_md5(trybiz)
    if (idents[hun]) {
      welcomebiz=trybiz
      var wg_biz   = trybiz
      var wg_name  = unmix(idents[hun][0],trybiz)
      var wg_city  = unmix(idents[hun][1],trybiz)
      var wg_phone = unmix(idents[hun][2],trybiz)
      var wg_email = unmix(idents[hun][3],trybiz)
      var wg_pic   = unmix(idents[hun][4],trybiz)
      var wg_pw    = unmix(idents[hun][5],trybiz)
      var wg_sub   = trim(unmix(idents[hun][6],trybiz).toLowerCase())

      document.getElementById("myname").innerHTML  = wg_name
      document.getElementById("mycity").innerHTML  = wg_city
      document.getElementById("myphone").innerHTML = wg_phone
      document.getElementById("myemail").innerHTML = wg_email
      document.getElementById("mybiz").innerHTML   = wg_biz
      if (wg_pic) document.getElementById("myphoto").src=wg_pic

      var eldiv = document.getElementById("myemaillinkdiv")
      eldiv.style.color=""
      eldiv.innerHTML = '<a href="http://' + trybiz + '.mlmdirect.biz?format=email" target="_blank">' + trybiz + '.mlmdirect.biz?format=email</a>'

      var prdiv = document.getElementById("myprintlinkdiv")
      prdiv.style.color=""
      prdiv.innerHTML = '<a href="http://' + trybiz + '.mlmdirect.biz?format=print" target="_blank">' + trybiz + '.mlmdirect.biz?format=print</a>'


      var lldiv = document.getElementById("myloglinkdiv")
      lldiv.style.color=""
      lldiv.innerHTML = '<a href="http://mlmdirect.biz?log=' + trybiz + '" target="_blank">mlmdirect.biz?log=' + trybiz + '</a>'

      var stlink = document.getElementById("sampletoollink")
      if (stlink) {
        var uselink = "http://" + trybiz + '.mlmdirect.biz'
        stlink.href=uselink
        stlink.innerHTML = uselink
        }

      var stlink = document.getElementById("adddistlink")
      if (stlink) {
        var uselink = "http://" + trybiz + '.mlmdirect.biz/newdist.html'
        stlink.href=uselink
        stlink.innerHTML = uselink
        }
      document.getElementById("adddistli").style.display=""

      var hsub = hex_md5(wg_sub)
      if (affiliates[hsub]) {
        var usLinks = findElementsByClassName(document,"uscd_link")
        for (var i=0;i<usLinks.length;i++) {
          usLinks[i].href="http://www.ultimatesuccesscds.com/cmd.asp?af=" + affiliates[hsub]
          }
        }
      }
    }
  if (!welcomebiz) {
    document.getElementById("myname").innerHTML = "(your name)"
    document.getElementById("mycity").innerHTML = "(your city)"
    document.getElementById("myphone").innerHTML = "(your phone)"
    document.getElementById("myemail").innerHTML = "youremail@example.com"
    document.getElementById("mybiz").innerHTML = "(your Unicity business name)"
    document.getElementById("myphoto").src="genericphoto80.jpg"

    var eldiv = document.getElementById("myemaillinkdiv")
    eldiv.style.color="red"
    eldiv.innerHTML = '(You must first sign in above with a MyUnicity.Net business name registered with MLMDirect)'

    var eldiv = document.getElementById("myprintlinkdiv")
    eldiv.style.color="red"
    eldiv.innerHTML = '(You must first sign in above with a MyUnicity.Net business name registered with MLMDirect)'

    var lldiv = document.getElementById("myloglinkdiv")
    lldiv.style.color="red"
    lldiv.innerHTML = '(You must first sign in above with a MyUnicity.Net business name registered with MLMDirect)'

    var stlink = document.getElementById("sampletoollink")
    if (stlink) {
      var uselink = "http://myslimhealth.mlmdirect.biz"
      stlink.href=uselink
      stlink.innerHTML = uselink
      }
    }
// <div id="myemaillinkdiv">(you must first sign in above with a registered MyUnicity.Net business name)</div>

  document.getElementById("validbody").style.display=""

  var tInp = document.getElementById("my_tid")
  var uInp = document.getElementById("my_uid")
  if (tInp) tInp.value=""
  if (uInp) uInp.value=""

//<td valign="top"><img id="myphoto" src="genericphoto80.jpg" width="80px"><br /><span style="font-size:70%">optional photo</span></td>
//<td valign="top">
//<div id="myname">(your name)</div>
//<div id="mycity">(your city/state)</div>
//<div id="myphone">(your phone)</div>
//<div id="myemail">youremail@example.com</div>
//<div id="mybiz">(your MyUnicity.net business name)</div>
  }

function prepEmail(myformat) {
//var bdiv = document.getElementById("allbody")
//if (bdiv) bdiv.setAttribute("align","")
  if (myformat == "print") {
    var hiders = findElementsByClassName(document,"webonly")
    var showmes = findElementsByClassName(document,"printonly")
    }
  else {
    var hiders = findElementsByClassName(document,"webonly")
    var showmes = findElementsByClassName(document,"emailonly")
    }

  for (var i=0;i<hiders.length;i++) {
    hiders[i].parentNode.removeChild(hiders[i])
    }
  for (var i=0;i<showmes.length;i++) {
    showmes[i].style.display=""
    }
  var ulinks = findElementsByClassName(document,"userlink")
  var idst = ""
  if (videoid) idst = '?uid=' + videoid
  if (trackid) {
    if (idst) idst+= '&'
    else idst += '?'
    idst+="tid=" + trackid
    }
  for (var i=0;i<ulinks.length;i++) {
    if (ulinks[i].nodeName == "A") ulinks[i].href="http://" + unicityname + ".mlmdirect.biz" + idst
    }

  doclip = function() {
    dofallback=true
  //isclip = checkClipboard()
    isclip=false; // clipboard pasting doesn't work so nice with Outlook.  Sigh.  TEST PRINT FORMAT IF YOU FIX THIS!
    if (isclip) {
      var stx = document.getElementsByTagName("body")[0].innerHTML
      setClipboard(stx,true)
      var chk = getClipboard()
      if (stx == chk) {
        alert("Your email is on the clipboard.\nGo to your empty email, make sure it is in HTML format, and click Ctrl+V to paste it in.")
        dofallback=false
        }
      }
    if (dofallback) {
      if (myformat == "print") {
        alert("After you click OK...\n1. Click on body of this page.\n2. Click Ctrl+A to select all.\n3. Click Ctrl+C to copy page to clipboard.\n4. Go to an empty Word document and click Ctrl+V to paste.\nNote: You may have to adjust the page breaks before printing!")
        }
      else {
        alert("After you click OK...\n1. Click on body of this page.\n2. Click Ctrl+A to select all.\n3. Click Ctrl+C to copy page to clipboard.\n4. Go to your empty email and click Ctrl+V to paste.\nNote: Make sure your email is set to HTML first!")
        }
      }
    }

  if (myformat == "outlook") {
    try {
      var outlookApp = new ActiveXObject("Outlook.Application");
      var nameSpace = outlookApp.getNameSpace("MAPI");
      mailFolder = nameSpace.getDefaultFolder(6);
      mailItem = mailFolder.Items.add('IPM.Note.FormA');
      mailItem.Subject="a subject test";
      mailItem.To = "putprospect@email.here";
      mailItem.HTMLBody = document.body.innerHTML
      mailItem.display (0);
      }
    catch(e) {
      doclip()
      }
    }
  else doclip()
  }

function loadNewDist() {
  if (unicityname) {
    document.getElementById("nd_biz").value=unicityname
    var hun = hex_md5(unicityname)
    if (idents[hun]) {
      document.getElementById("nd_pw").value=unmix(idents[hun][5],unicityname)
      }
    else {
      }
    }
  document.getElementById("nd_biz").focus()
  }

function prepNew(errmsg) {
  if (!errmsg) errmsg='&nbsp;'
  document.getElementById("newerr").innerHTML = errmsg;
  var trybiz = document.getElementById("nd_biz").value.toLowerCase()
  var trypw = document.getElementById("nd_pw").value.toLowerCase()
  if (!trybiz || !trypw) {
    document.getElementById("newerr").innerHTML = "OOPS!  You must enter your Unicity Business Name <b>and</b> your MLMDirect Password!"
    return
    }
  var hun = hex_md5(trybiz)
  if (idents[hun]) {
    var wg_pw    = unmix(idents[hun][5],trybiz)
    if (trypw) {
      if (trypw != wg_pw) document.getElementById("newerr").innerHTML = "OOPS!  Wrong password.  Try again or contact Jeff."
      else {
        var hn = location.hostname.split(".")
        if (hn.length < 2) var hd = hn[-1 + hn.length]
        else var hd=hn[-2 + hn.length]
        if (hex_md5(hd) == "421aa90e079fa326b6494f812ad13e79") var inppw = unmix("7d3dbc0036eef2",hd)
        else var inppw = unmix("40040d057180e9",hd)
        document.getElementById("newiframe").src="http://spreadsheets.google.com/embeddedform?key=" + unmix(mixedformk,inppw)
        }
      }
    else document.getElementById("newerr").innerHTML = "OOPS!  Wrong password.  Try again or contact Jeff."
    }
  }

function prepLogs() {
  inppw = document.getElementById("logpw").value
  if (inppw) {
    inppw=inppw.toLowerCase()
    var hun = hex_md5(sargs["log"])
    if (inppw == unmix(idents[hun][5],sargs["log"]).toLowerCase()) {
      logMe("GetLogs (" + navigator.userAgent + ")","mlmdirect")
      var mytitle="Get Log File"
      var ts = (new Date()).getTime()
      var fn = hex_md5(sargs["log"].toLowerCase()) + ".csv"
      document.getElementById("logiframe").src="download.php?f=wlogs/" + fn
   // secondWindow("download.php?f=wlogs/" + hex_md5(sargs["log"].toLowerCase()) + ".txt",mytitle,300,300)
      }
    else {
      logMe("GetLogs Failed, wrong pw (" + navigator.userAgent + ")","mlmdirect")
      setTimeout('alert("You provided the wrong MLMDirect password.  Try again or contact your upline)")',1000)
      }
    }
  }

function logAct(stx,ignorearg) {
  if (loggedactions) loggedactions += '; '
  loggedactions += stx
  }

function logMe(stx,fn) {
  var user
  if (!sargs["uid"]) {
    var tryv = getCookie("videoid")
    if (tryv) user="uidcookie=" + tryv
    }
  else user="uid=" + sargs["uid"]

  if (trackid) {
    if (user) user += " "
    user += "tid=" + escape(trackid)
    }

  if (!user) user='uid=unknown'
  if (!fn) fn=hex_md5(unicityname.toLowerCase())
  stx=stx.replace(/,/g,";");
  c_log(stx,user,fn,pagename,debug_log) // TODO: change to invisible!!
  }

function showUnicityVideos() {
  if (videoid) {
    var vDivs = findElementsByClassName(document,"unicityvideo")
    for (var i=0;i<vDivs.length;i++) {
      vDivs[i].style.display=""
      }
    }
  }

function leadProtect() {
  if (unicityname) {
    var last = getCookie("protected")
    if (unicityname != last) {
      setCookie("protected",unicityname,offsetDays(30))
      var ifr = document.createElement("iframe")
    //ifr.width="900px"
    //ifr.height="600px"
      ifr.style.display="none"
      ifr.src="http://www.myunicity.net/" + unicityname
      document.getElementsByTagName("body")[0].appendChild(ifr)
      }
    }
  }

function updateUvUrl() {
  setTimeout("updateUvUrlResume()",100)
  }

function updateUvUrlResume() {
  var oldurl = document.getElementById("uvurl").value.toLowerCase()
  if (oldurl && (-1 < oldurl.indexOf("uid="))) {
    var uid = oldurl.split("uid=")[1]
    var newurl="http://" + sargs["log"] + ".mlmdirect.biz?uid=" + uid
    document.getElementById("newuv").innerHTML = newurl
    }
  }

function updateLogEmailUrl() {
  if (welcomebiz) {
    var tInp = document.getElementById("my_tid")
    var uInp = document.getElementById("my_uid")
    var lObj = document.getElementById("my_emaillink")
    uInp.value=trim(uInp.value)

    isok = jvalidate(tInp)
    isok = jvalidate(uInp) && isok // note, put anded part last if you want function to execute again.

    if (isok) {
      var tid=trim(tInp.value)
      var uidst = uInp.value
      if (-1 < uidst.indexOf("uid=")) {
        var uid=uidst.split("uid=")[1]
        }
      else var uid=''
      if (tid || uid) {
        var urlst = '<a href="http://' + welcomebiz + '.mlmdirect.biz?format=email&tid=' + tid + '&uid=' + uid + '" target="_blank">'
        urlst += welcomebiz + '.mlmdirect.biz?format=email&tid=' + tid + '&uid=' + uid + '</a>'
        lObj.innerHTML = urlst
        jvalidate(tInp,"all")
        }
      else {
        isok=false
        jvalidate(tInp,"all")
        }
      }
    if (!isok) {
      lObj.innerHTML = "(will appear here when you enter one or both items above)"
      }
    }
  }

function loadVid() {
  // http://www.unicityvideo.com/video.php?uid=844emgcs2sqq0cou
  // http://slimwinwin.com/bizmeme/index.html?uid=ag4ge8ss4gcsuakc
//var vDiv = document.getElementById("aaronvideo_embed")
//var ifr = document.createElement("iframe")
  var ifr=document.getElementById("uvid_iframe")
  if (videoid) {
    ifr.width="770px"
    ifr.height="600px"
    ifr.src="http://www.unicityvideo.com/video.php?uid=" + videoid
    logAct("Video Loaded - check UnicityVideo tracking")
    }
  else {
//  ifr.width="700px"
//  ifr.height="410px"
  //if (ifr.frameBorder) ifr.frameBorder = 0;
  //if (ifr.style) ifr.style.border="0px solid #FFFFFF";
//  ifr.src="5ps.html"
  //logMe("Default Video Loaded")
    }
  //vDiv.appendChild(ifr)
  }

function loadContact(errmsg) {
  if (!errmsg) errmsg='&nbsp;'
  document.getElementById("ctcherr").innerHTML = errmsg
  var hun = hex_md5(unicityname)
  if (idents[hun]) {
    var alph = shuffle(['a','b','c','d','e','f','g','h','j','k','m','n','p','q','r','s','t','u','v','w','x','y','z'])
    var nums = shuffle(['2','3','4','5','6','7','8','9'])
    var stx = '&nbsp;' + alph[0] + '&nbsp;' + nums[0] + '&nbsp;' + alph[1] + '&nbsp;'
    ctch_str = alph[0] + nums[0] + alph[1]
    document.getElementById("ctchtxt").innerHTML = stx
    document.getElementById("ctch").style.display=""
    document.getElementById("ctchinp").value=""
    document.getElementById("ctchinp").focus()
    }
  else {
    document.getElementById("errbiz").innerHTML = "(" + unicityname + ")"
    document.getElementById("err1").style.display=""
    }
  }

function contactResume() {
  var cans = document.getElementById("ctchinp").value.toLowerCase()
  if (cans != ctch_str) {
    loadContact('OOPS!  The letters/numbers you entered did not match.  Please try again.<br />(Do not enter any spaces)')
    }
  else {
    logMe("Contact Info Loaded")
    var hun = hex_md5(unicityname)
    if (idents[hun]) {
      document.getElementById("distname").innerHTML = unmix(idents[hun][0],unicityname)
      document.getElementById("distcity").innerHTML = unmix(idents[hun][1],unicityname)
      document.getElementById("distphone").innerHTML = unmix(idents[hun][2],unicityname)
      var pic = trim(unmix(idents[hun][4],unicityname))
      if (pic) {
        document.getElementById("distphoto").src=pic
        document.getElementById("distphoto").style.display=""
        }
      else document.getElementById("distphoto").style.display="none"
      document.getElementById("ctch").style.display="none"
      document.getElementById("content").style.display=""
      }
    else {
      document.getElementById("errbiz").innerHTML = "(" + unicityname + ")"
      document.getElementById("err1").style.display=""
      }
    }
  }

function doem() {
  var hun = hex_md5(unicityname)
  if (idents[hun]) {
    location="mailto:" + unmix(idents[hun][3],unicityname) + "?subject=MLMDirect_Contact"
    logMe("Email created")
    }
  else alert("Sorry, the web page is unable to calculate the email address, please call us!")
  }


function processNewDistributors() {
  var admin=sargs["admin"].toLowerCase()
  if (hex_md5(admin) == "c38b72c4adccbf4177fb00f5970672e2") {
    document.getElementById("admin1").style.display=""
    document.getElementById("ctch").style.display="none"
    }
  else {
    alert("Sorry, your ?admin=abc url argument didn't have the right admin code.  Contact Jeff Kelley.")
    }
  }


function processClipboard() {
  var users=getClipboard()
  var errst=''
  if (users) {
    sti=getClipboard()
    if (sti) {
      var stx=''
      var stl=sti.split("\n")
      var stc,ts,dname,city,ph,em,bizname,pic,sub
      for (var i=0;i<stl.length;i++) {
        if (stl[i]) {
          stc=stl[i].split("\t")
          if (9 == stc.length) {
            ts=stc[0]
            dname=stc[1]
            city=stc[2].replace(/'/g,'&#39;')
            ph=stc[3]
            em=stc[4]
            bizname=stc[5].toLowerCase()
            pic=stc[6]
            sub=stc[7]
            dpw=stc[8]
            if (stx) stx += '\n'
            stx += 'idents["' + hex_md5(bizname) + '"] = ['
            stx += '"' + mix(dname,bizname) + '",'  // 0 Distributor Name
            stx += '"' + mix(city,bizname) + '",'   // 1 City, State
            stx += '"' + mix(ph,bizname) + '",'     // 2 Contact Phone
            stx += '"' + mix(em,bizname) + '",'     // 3 Contact Email
            stx += '"' + mix(pic,bizname) + '",'    // 4 Distributor picture web link
            stx += '"' + mix(dpw,bizname) + '",'    // 5 Password
            stx += '"' + mix(sub,bizname) + '"'     // 6 Submitter Email
            stx += '];'
            }
          else {
            errst="There are not exactly 9 columns of data (A-I) in every row on the clipboard."
            stx=''
            i=stl.length+1
            }
          }
        }
      if (stx) {
        setClipboard(stx)
        document.getElementById("admin1").style.display="none"
        document.getElementById("admin2").style.display=""
        }
      }
    else errst='Nothing on clipboard'
    if (errst) alert(errst)
    }
  }

function processAffiliate() {
  afem = document.getElementById("aff_email").value.toLowerCase()
  afid = document.getElementById("aff_id").value
  aflb = document.getElementById("aff_lab").value
  if (!afem || !afid) {
    alert("Provide email and id!")
    return
    }

  stx='affiliates["' + hex_md5(afem) + '"] = "' + afid + '" // ' + aflb
  setClipboard(stx)
  document.getElementById("admin1").style.display="none"
  document.getElementById("admin3").style.display=""

  }

function doGoogleAnalytics() {
  var scr1 = document.createElement("script")
  if (scr1) {
    scr1.language='javascript'
    scr1.type='text/javascript'
    if ("https:" == document.location.protocol) scr1.src="https://ssl.google-analytics.com/ga.js";
    else scr1.src="http://www.google-analytics.com/ga.js";
    document.getElementsByTagName("head")[0].appendChild(scr1)
    try {
      var pageTracker = _gat._getTracker("UA-3977045-6");
      pageTracker._trackPageview();
      }
    catch(err) {}
    }

  //  Google Code for BizMeme Contact Conversion Page
  var google_conversion_id = 1036762161;
  var google_conversion_language = "en_US";
  var google_conversion_format = "1";
  var google_conversion_color = "cd6601";
  var google_conversion_label = "-GhZCP35kAEQsfiu7gM";
  if (5.0) {
    var google_conversion_value = 5.0;
    }
  var scr2 = document.createElement("script")
  if (scr2) {
    scr2.language='javascript'
    scr2.type='text/javascript'
    scr2.src = "http://www.googleadservices.com/pagead/conversion.js"
    document.getElementsByTagName("head")[0].appendChild(scr2)
    }
  // <script language="JavaScript" src="http://www.googleadservices.com/pagead/conversion.js">

  // <noscript>
  // <img height="1" width="1" border="0" src="http://www.googleadservices.com/pagead/conversion/1036762161/?value=5.0&amp;label=-GhZCP35kAEQsfiu7gM&amp;guid=ON&amp;script=0"/>
  // </noscript>
  }



// v v v Top of Common2 v v v


var global_popper = ""
var global_helpwindow = ""
var global_popContent = ""
function secondWindow(myurl,mytitle,myWidth,myHeight,isStripped,mytop,myleft) {
  if (!isStripped) isStripped = false;
  if (myWidth) var wd=myWidth
  else var wd = -50 + document.documentElement.clientWidth;
  if (myHeight) ht=myHeight
  else var ht=-50 + document.documentElement.clientHeight

  // HERE'S SOMETHING WIERD: if you have your windows spread over two screens of varying heights, mytop=25 can be off top of screen!!!
  if (!mytop) {
    if (document.all) var mytop = 125 // IE simply will NOT give up the absolute top of the window.
    else var mytop = 25 + window.screenY
    }
  if (!myleft) {
    if (document.all) var myleft = 125 + window.screenLeft
    else var myleft = 25 + window.screenX
    }

  if ((global_popper) && (!global_popper.closed)) {
////global_popper.close()
//  global_popper.location=myurl
//  global_popper.focus()
    }

  if (mytop != '*') var mytopst = ',top=' + mytop
  else var mytopst = ''

  if (myleft != '*') var myleftst = ',left=' + myleft
  else var myleftst = ''

  if (isStripped == "partial") var myargs = "toolbar=no,location=no,status=yes,menubar=yes,scrollbars=yes,width="+wd+",height="+ht+",resizable=yes" + mytopst + myleftst
  else if (isStripped) var myargs = "toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,width="+wd+",height="+ht+",resizable=yes" + mytopst + myleftst
  //else if (isStripped) var myargs = "scrollbars=yes,width="+wd+",height="+ht+",resizable=yes,top="+mytop+",left="+myleft
  else            var myargs = "toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,width="+wd+",height="+ht+",resizable=yes" + mytopst + myleftst
  mytitle=mytitle.replace(/ /g,"_")
  global_popper=window.open(myurl,mytitle,myargs)
  global_popper.focus()
  return global_popper
  }



function lTrim (myString) {
  if (!myString) return ""
  else return myString.replace( /^\s*/, "" );
  }

function rTrim (myString) {
  if (!myString) return ""
  else return myString.replace( /\s*$/, "" );
  }

function trim (myString) {
  return rTrim(lTrim(myString));
  }


function enterSubmit(e,callback) {
  // e.g., <input ... onkeydown="enterSubmit(event,'domything()')" ... />
  if (!e) e = window.event;
  var key = (typeof e.which == 'number')?e.which:e.keyCode;
  //window.status=key
  if (key == 13)  eval(unescape(callback))
  }

// c_log version 1.1 - convert to CSV version
function c_log(stx,user,mysubdom,mypage,isvis) {
  if (!user) user=""
  if (!mypage) mypage=getPageName()
  if (!mysubdom) mysubdom = getPathName() // mysubdom is required.  it is the file name for the log file.
  stsrc = 'lg.php'
  stsrc += '?stp=' + mypage + '&lfn=' + encodeURIComponent(mysubdom) + '&stx=' + encodeURIComponent(stx) + '&usr=' + encodeURIComponent(user)
  var lframe = document.getElementById("RSiframe");
  if (!lframe) lframe=c_createLogFrame(isvis,stsrc)
  else if (lframe) {
    lframe.src=stsrc
    fstyle = (lframe.style) ? lframe.style : (lframe.frameElement.style) ? lframe.frameElement.style : ""
    if (fstyle) {
      if (isvis=='visible') {
        fstyle.border='1px'
        fstyle.width='500px'
        fstyle.height='200px'
        fstyle.backgroundColor='#FFDDDD'
        }
      else {
        fstyle.border='0px'
        fstyle.width='0px'
        fstyle.height='0px'
        }
      }
    }
//else alert("Internal web page error: unable to create L-frame.\nPlease advise webmaster using Contact link (you can still use this webpage)")
  }

function c_createLogFrame(isvis,stsrc) {
  var iframeObj='';
  if (document.createElement) {
    // create the iframe and assign a reference to the
    // object to our global variable iframeObj.
    // this will only happen the first time
    // callToServer() is called
    try {
      var lframe=document.createElement('iframe');
      lframe.setAttribute('id','RSiframe');
      if (stsrc) lframe.src=stsrc
      fstyle = (lframe.style) ? lframe.style : (lframe.frameElement.style) ? lframe.frameElement.style : ""
      if (fstyle) {
        if (isvis=='visible') {
          fstyle.border='1px'
          fstyle.width='500px'
          fstyle.height='200px'
          fstyle.backgroundColor='#FFDDDD'
          }
        else {
          fstyle.border='0px'
          fstyle.width='0px'
          fstyle.height='0px'
          }
        }

      iframeObj = document.body.appendChild(lframe);

      if (document.frames) {
        // this is for IE5 Mac, because it will only
        // allow access to the document object
        // of the iframe if we access it through
        // the document.frames array
        iframeObj = document.frames['RSiframe'];
        }
      }
    catch(exception) {
      // This is for IE5 PC, which does not allow dynamic creation
      // and manipulation of an iframe object. Instead, we'll fake
      // it up by creating our own objects.
      iframeHTML='\<iframe id="RSiframe" style="';
      if (!isvis) {
        iframeHTML+='border:0px;';
        iframeHTML+='width:0px;';
        iframeHTML+='height:0px;';
        }
      iframeHTML+='"><\/iframe>';
      document.body.innerHTML+=iframeHTML;
      iframeObj = new Object();
      iframeObj.document = new Object();
      iframeObj.document.location = new Object();
      iframeObj.document.location.iframe = document.getElementById('RSiframe');
      iframeObj.document.location.replace = function(location) {
        this.iframe.src = location;
        }
      }
    }
  return iframeObj
  }

//- Fcn: getPageName 1.2
// Globals: (none, returns what will become page_name at top)
function getPageName () {
  var page_n=location.href
  var i=page_n.indexOf("?",0)
  if (-1 < i) {
    page_n=page_n.substring(0,i)
    }
  var ip=page_n.indexOf("#",0)
  if (-1 < ip) {
     page_n=page_n.substring(0,ip)
     }
  var i=page_n.indexOf("/",0)
  while (i > -1) {
    page_n=page_n.substring(1+i,page_n.length)
    i=page_n.indexOf("/",0)
    }
  if (page_n == "") { page_n = "index.html" };
  return page_n;
  }

function getPathName() {
  var jparts = location.href.split("/")
  var last=''
  var stx
  if (jparts.length > 2) {
    for (var i=2;i< -1 + jparts.length;i++) {
      stx = jparts[i].replace(/\./g,"-")
      if (last) last+='_'
      last+=stx
      }
    }
  else var last='unknown'
  return last
  }



//- Function: "setCookie()"
//-   Set a cookie attribute/value
//-   Optional 3rd arg: when expire, a Date() object.  cf: offsetDays().  Null means this browser session only.
//-   E.g. setCookie("email",myemail,offsetDays(365))
//-   Other optional arguments not used here.
function setCookie(name, value,path) {
  var args = setCookie.arguments;
  var len = setCookie.arguments.length;
  var expires = (len > 2) ? args[2] : null;
  var path = (len > 3) ? args[3] : null;
  var domain = (len > 4) ? args[4] : null;
  var secure = (len > 5) ? args[5] : false;
  document.cookie = name + "=" + escape (value) +
  ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
  ((path == null) ? "" : ("; path=" + path)) +
  ((domain == null) ? "" : ("; domain=" + domain)) +
  ((secure == true) ? "; secure" : "");
  }

//- Function: "offsetDays()"
//-   Converts number of days to an offset Date object (e.g., for setCookie())
//-   Optional second arg: a Date object to offset from.
function offsetDays (days) {
  var args = offsetDays.arguments;
  var len = offsetDays.arguments.length;
  var retDate = (len>1) ? args[1] : new Date();
  retDate.setTime(retDate.getTime() + days * 24 * 60 * 60 * 1000);
  return retDate;
  }

//- Fcn: getCookieVal 1.1
//-   Return value at startpoint, assume delimited by ';'
function getCookieVal (startpoint) {
  var cook=document.cookie.replace(/\n|\r|\r\n|\n\r/g,"")
//alert(cook);
  var endindex = cook.indexOf (";", startpoint);
  if (endindex == -1) endindex = cook.length;
  return unescape(document.cookie.substring(startpoint, endindex));
  }

//- Fcn: getCookie 1.1
//-   External: (content\foocart.htm?), newuser.html, std\uncookie.js
//-   Return value for a attribute in cookie
function getCookie (name) {
  var prefix = name + "=";
  var prefixlen = prefix.length;
  var strlen = document.cookie.length;
  var i = 0;
  while (i < strlen) {
    var j = i + prefixlen;
    if (document.cookie.substring(i, j) == prefix) return getCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
    }
  return null;
  }

//- Fcn: deleteCookie 1.2
//-   External: (content\foocart.htm?), newuser.html, std\uncookie.js
//-   Delete an attribute/value pair from cookie
function deleteCookie (name) {
  var expires = new Date();
  expires.setTime (expires.getTime() - 10*24*60*60*1000);
//  setCookie(name,"",expires)
  var cookieval = getCookie (name);
  cookieval = ""
  document.cookie = name + "=" + cookieval + "; expires=" + expires.toGMTString();
  }


function addEvent(myObj,myEv,fn) {
  // e.g., addEvent(window,"load",function(event) { init() })
  if (myObj.addEventListener) {
    myObj.addEventListener(myEv,fn,true);
    return true
    }
  else if (myObj.attachEvent) {
    var ret = myObj.attachEvent("on"+myEv,fn);
    return ret;
    }
  else return false;
  }

function findElementsByClassName(pobj,cl) {
  var retnode = [];
  var myclass = new RegExp('\\b'+cl+'\\b');
  var elem = pobj.all || pobj.getElementsByTagName('*');
  for (var i = 0; i < elem.length; i++) {
    var classes = elem[i].className;
    if (myclass.test(classes)) retnode.push(elem[i]);
    }
  return retnode;
  }


//- Fcn: parseSearch 1.3
//  Optional Global:
//    var sargs = new Object()
//  Sample usage:
//    parseSearch('',sargs)
//    alert(sargs["email"])
function parseSearch(tryurl,gvar) {
  if (!gvar) gvar=''
  if (!tryurl) tryurl = location.toString()
  var uargs = tryurl.split("?")[1]
//uargs=location.search.substring(1,location.search.length);
  if(uargs) {
    if (-1 < uargs.indexOf("#")) uargs = uargs.split("#")[0] // 20070415 added
    if (-1 < uargs.indexOf('&',0)) {           // DevNote: 20070103 - swap which one is tested and which is default.
      var argArray=uargs.split("&")            // DevNote: 20070103
      }
    else var argArray=uargs.split("\%26");     // DevNote: 20070103
    var thisst,thisArgset,thiseval
    for (var i=0;i<argArray.length;i++) {
      thisst=argArray[i];
      thisArgset = thisst.split('=');
      if ((gvar!='') || (thisArgset[1])) {
        if ("object" == typeof gvar) gvar[thisArgset[0]] = thisArgset[1]
        else if (gvar) thiseval = gvar + '["' + thisArgset[0] + '"] = "' + thisArgset[1] + '"'
        else thiseval = thisArgset[0]+'="'+thisArgset[1]+'"'
        eval(thiseval)
        }
      }
    }
  }


//  v v v Top of common.js v v v

function souffle(n,start) {
  if (!start) start=0
  var Q = new Array()
  for (var i=start;i<n;i++) {
    Q.push(i)
    }
  return(shuffle(Q))
  }

function shuffle(Q) {
  var R, T, J;
  for (J = Q.length - 1; J > 0; J--) {
    R = Random(J + 1);
    T = Q[J];
    Q[J] = Q[R];
    Q[R] = T;
    }
  return Q;
  }

function Random(X) {
  return Math.floor(X * (Math.random() % 1));
  }

