﻿function bqqcookie() {
  this.dbid = null
  this.yearborn = null
  this.email = null
  this.sections = {}
  this.cookiename = 'bqquiz'
  this.cookiepath = '/'

  function getSectionNr(inx) {
    return inx == 0 ? 'I' : inx == 1 ? 'II' : 'III'
  }
  this.getCookieData = function() {
    var c = BQ.readCookie(this.cookiename)
    if (c) {
      var data = c.split('%')
      if (data[0].length) this.dbid = data[0]
      if (data[1].length) this.yearborn = data[1]
      for (var d = 2; d < 5; d++) {
        if (data[d].length) this.sections[getSectionNr(d - 2)] = data[d].toString().split(',')
      }
      if (data[d] && data[d].length) this.email = data[d]
    }
  }
  this.setCookieData = function() {
    var cd = (this.dbid != null ? this.dbid : '') + '%'
      + (this.yearborn ? this.yearborn : '') + '%'
      + (this.sections['I'] ? this.sections['I'].toString() : '') + '%'
      + (this.sections['II'] ? this.sections['II'].toString() : '') + '%'
      + (this.sections['III'] ? this.sections['III'].toString() : '') + '%'
      + (this.email ? this.email : '') + '%'
    //save latest result in cookie
    BQ.createCookie(this.cookiename, cd, 365)
  }
  this.setSectionData = function(nr, data, yb) {
    this.sections[nr] = data
    if (yb) this.yearborn = yb
    this.setCookieData()
  }
  this.setYearborn = function(yb) {
    this.yearborn = yb
    this.setCookieData()
  }
  this.setQuizId = function(id) {
    this.dbid = id
    this.setCookieData()
  }
  this.setEmail = function(email) {
    this.email = email
    this.setCookieData()
  }
  this.getCookieData()
}
var bqc = new bqqcookie()
var amzLink = null
var xlatLang = null
var langList = null
function setLangText(text, elem, attr) {
  elem.setAttribute('entext', elem.innerHTML)
  if (xlatLang.blang != 'en') xlatLang.xlatElement(elem.innerHTML, elem, attr, xlatLang.blang, 'en')
}
function _section() {
  this.id = null
  this.blankBackground = 'RGB(255,120,147)'
  this.errNode = null
  this.questions = null
  this.node = null
  this.yrElem = null
  this.area1 = null
  this.area2 = null
  this.score = 0
  this.scoreNode = null
  var _this = this

  this.calcBQ = function() {
    var score = 0
    var unanswered = 0
    var q = this.yrElem ? _this.questions.firstChild.nextSibling : _this.questions.firstChild
    while (q) {
      var o = q.getElementsByTagName('input')
      for (var i = 0; i < o.length; i++) {
        if (o[i].checked) {
          score += parseInt(o[i].value)
          break
        }
      }
      if (i === o.length) {
        q.style.background = this.blankBackground
        unanswered++
      }
      q = q.nextSibling
    }
    if (this.yrElem) {
      if (this.yrElem.value.length === 0) {
        this.yrElem.parentNode.style.background = this.blankBackground
        unanswered++
      }
    }
    return { unanswered: unanswered, score: score }
  }
  this.actionButtons = function() {
    var ab = document.getElementById('actions').cloneNode(true)
    ab.style.display = 'inline'
    ab.setAttribute('section', this.id)
    return ab
  }
  this.createHdr = function(sid, selem) {
    function qclicked(e) {
      var q = _this.yrElem ? _this.questions.firstChild.nextSibling : _this.questions.firstChild
      var opts = []
      while (q) {
        var o = q.getElementsByTagName('input')
        for (var i = 0; i < o.length; i++) {
          if (o[i].checked) {
            opts.push(i)
            break
          }
        }
        if (i === o.length) opts.push(-1)
        q = q.nextSibling
      }
      bqc.setSectionData(_this.id, opts, _this.yrElem ? _this.yrElem.value : null)
      _this.area2.style.display = 'none'
      _this.area1.style.display = ''
    }
    this.id = sid
    this.questions = document.getElementById("Questions" + this.id)
    this.questions.onclick = qclicked
    this.node = selem
    return selem
  }
  this.createFtr = function(xnode) {
    this.dbSaveSection = function() {
      var cols = [], vals = []
      this.getCols = function() {
        var ans = bqc.sections[this.id]
        var ansNr = 0
        var qn = this.questions.firstChild
        while (qn) {
          var sn = qn.getAttribute('sqlname')
          if (sn != 'YearBorn') {
            cols.push(sn)
            vals.push(ans[ansNr])
            ansNr++
          }
          qn = qn.nextSibling
        }
        if (this.yrElem) {
          cols.push('YearBorn')
          vals.push(this.yrElem.value)
        }
        cols.push('score' + this.id)
        vals.push(this.score)
        cols.push('LangOS')
        vals.push("'" + (window.navigator.userLanguage ? window.navigator.userLanguage : window.navigator.language) + "'")
        if (langList) {
          cols.push('LangQuiz')
          vals.push("'" + langList.value + "'")
        }
      }
      this.insSQL = function() {
        return 'insert BQQuiz(' + cols.toString() + ') values(' + vals.toString() + ')'
      }
      this.updSQL = function() {
        var sets = []
        for (var i = 0; i < cols.length; i++) sets.push(cols[i] + '=' + vals[i])
        return 'update BQQuiz SET ' + sets.toString() + ' where id=' + bqc.dbid
      }
      function afterIns(newid) {
        bqc.setQuizId(newid)
        var contact = BQ.readCookie('bqcontactus')
        if (contact) {
          var sql = 'update ContactInfo set fkQuiz = ' + ' where pkCI = ' + contact
          var qdcu = DA.createQuery()
          qdcu.operationType = enums.dbOperation.exec
          qdcu.commandType = enums.commandType.text
          qdcu.commandText = 'update ContactInfo set fkQuiz = ' + newid + ' where pkCI = ' + contact
          qdcu.onSuccess = function(res) { return }
          qdcu.onFailure = function(err) { return }
          qdcu.exec()
        }
      }
      function afterUpd(res) { } // nothing left to do
      function whenErr(err) { } // ignore errors?
      this.getCols()
      var sql = null
      var qd = null
      function setupInsQry() {
        sql = _this.insSQL()
        qd = DA.createQuery(enums.dbOperation.insert, 'Text', sql, afterIns)
        qd.xmlElements = '<AutoNumber DBName="SQL Server"></AutoNumber>'
      }
      function afterLookup(res) {
        if (res == 0) setupInsQry()
        else {
          sql = _this.updSQL()
          qd = DA.createQuery(enums.dbOperation.exec, 'Text', sql, afterUpd)
        }
        qd.exec()
      }
      if (bqc.dbid !== null) {
        var lkupqd = DA.createQuery(enums.dbOperation.lookup, 'Text', 'select count(*) from BQQuiz where id = ' + bqc.dbid, afterLookup)
        lkupqd.exec()
      } else {
        setupInsQry()
        qd.exec()
      }
    }

    this.applyFormula = function(noupd) {
      var res = _this.calcBQ()
      if (res.unanswered) _this.errNode.style.display = 'block'
      else {
        _this.score = res.score
        if (noupd !== true) _this.dbSaveSection()
        _this.scoreNode.lastChild.innerHTML = res.score
        _this.area1.style.display = 'none'
        _this.area2.style.display = 'block'
        var st = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop
        var os = BC.getOffsets(_this.area2)
        var delta = BQ.getY(_this.area2) - st + _this.area2.offsetHeight - BC.getAvailScreenHW().h
        if (delta > 0) window.scrollBy(0, delta)
      }
    }
    this.setInitialOptions = function() {
      var sopts = bqc.sections[this.id]
      if (sopts == null) return
      var q = this.yrElem ? _this.questions.firstChild.nextSibling : _this.questions.firstChild
      var qn = 0, qa = 0
      while (q) {
        if (sopts[qn] && sopts[qn] != -1) {
          var o = q.getElementsByTagName('input')
          if (o && sopts[qn] < o.length) o[sopts[qn]].checked = 'checked'
          qa++
        }
        qn++
        q = q.nextSibling
      }
      if (this.yrElem) this.yrElem.value = bqc.yearborn
      if (qa === qn) this.applyFormula(true)
    }
    this.area1Box = function() {
      this.area1 = document.getElementById("SecFtr" + this.id) //score area
      this.errNode = document.getElementById("QuizErr" + this.id) //error text area
      var but = document.getElementById("ApplyFormula" + this.id)
      but.onclick = this.applyFormula
    }
    this.area2Box = function() {
      this.area2 = document.getElementById("SecFtrScore" + this.id) //score area
      this.scoreNode = document.getElementById("SecFtrScoreNode" + this.id)
    }
    this.area1Box()
    this.area2Box()
    this.yrElem = (yb = this.questions.getElementsByTagName('select')).length ? yb[0] : null
    this.setInitialOptions()
  }
}
function _bq() { //beauty-quotient class
  this.highlightColor = 'RGB(255,210,193)'
  this.questionBorder = 'RGB(255,20,147)'
  this.parentNode = null
  this.score = 0
  this.sectionsNode = null
  this.note = null
  this.qnodes = []
  this.partNodes = {}
  this.sections = {}
  var _this = this

  this.createQuizHTML = function() {
    try {
      this.buildQuiz = function() {
        this.curNode = null
        var qnbr = 0
        var sopts = null
        var so = null //section object
        var _this = this

        // begin
        var qzdiv = this.parentNode // parent node of quiz questions node
        xlatLang.gbParentNode = qzdiv
        var secID = ["I", "II", "III"]
        this.note = document.getElementById("CookiesNote")
        if (!BQ.cookiesEnabled()) {
          this.note.innerHTML = "Your browser does not have Cookies enabled, so your answers will not be saved."
          this.note.style.color = 'red'
          this.note.setAttribute('entext',this.note.innerHTML)
        }
        this.sectionsNode = document.getElementById('Sections')
        for (var s = 0; s < secID.length; s++) {
          so = new _section()
          so.createHdr(secID[s], document.getElementById(secID[s]))
          this.sections[so.id] = so
          so.createFtr(this.curNode)
        }
      }
      function setupLangList(status) {
        if (!status) return
        xlatLang.blang = (window.navigator.userLanguage ? window.navigator.userLanguage : window.navigator.language).substring(0, 2)
        langList = xlatLang.languagesList(xlatLang.blang)
        function xlat(e) {
          var xlnodes = null
          var xi = 0
          function xlatnodes() {
            for (var i = xi + 1; i < xlnodes.length; i++) {
              var entext = xlnodes[i].getAttribute('entext')
              if (entext)
                xlatLang.xlatElement(entext, xlnodes[i], 'innerHTML' in xlnodes[i] ? 'innerHTML' : 'value', langList.value, 'en')
            }
            if (xlat.gbElement) xlatLang.xlatElement('Translation', xlatLang.gbElement.firstChild, null, langList.value, 'en')
          }
          var xnode1 = null
          function xp1(xt) {
            xnode1.innerHTML = xt.translation
            setTimeout(xlatnodes, 5)
          }
          xlnodes = _this.parentNode.getElementsByTagName('*')
          for (xi = 0; xi < xlnodes.length; xi++) {
            if (xlnodes[xi].getAttribute('entext')) {
              xnode1 = xlnodes[xi]
              xlatLang.xlatText(xnode1.getAttribute('entext'), xp1, langList.value, 'en')
              break
            }
          }
        }
        if (langList) {
          langList.id = 'langlist'
          langList.style.cssText = 'position:absolute;right:3px;top:35px;width:120px'
          langList.onchange = xlat
          _this.parentNode.parentNode.appendChild(langList)
        }
        _this.buildQuiz()
      }
      this.parentNode = (qz = document.getElementById('quiz')) ? qz : document.body
      amzLink = document.getElementById("BuyAreaI") 
      xlatLang = new _languageTranslation()
      xlatLang.initialize(setupLangList, true)
    } catch (e) { alert(e.message) }
  }
  this.serviceEmailReq = function(butelem) {
    var email = butelem.previousSibling.value
    function reset() {
      butelem.style.visibility = 'visible'
      app.sc.msgbox.style.display = 'none'
    }
    function sendMail() {
      function getSectionHtml(id) {
        var psc = document.createElement('div')
        psc.style.cssText = 'display:block;clear:left;'
        var st = document.createElement('span')
        st.style.cssText = 'display:block;font-weight:bold;margin:4px 2px;font-size:large;color:RGB(214,81,172)'
        st.innerHTML = 'Section-' + id + ' Results'
        psc.appendChild(st)
        var sc = bqo.sections[id].area2.firstChild.cloneNode(true)
        sc.style.maxWidth = bqo.sections[id].area2.firstChild.offsetWidth + 'px'
        sc.style.cssText = 'font-size:smaller; font-family:verdana; position:relative; top:0; left:0;';  //bqo.sections[section].area2.style.cssText
        psc.appendChild(sc)
        return psc
      }
      function links() {
        var salelnks = document.createElement('div')
        salelnks.style.cssText = 'position: relative; float:left; display:block; width:100%;margin:10px 0;'
        var amzbut = amzLink.cloneNode(true) 
        amzbut.style.margin='8px 0 2px 0';
        salelnks.appendChild(amzbut)
        salelnks.getElementsByTagName('img')[0].alt = "amazon.com"
        return salelnks
      }
      function signature() {
        var sig = document.createElement('div')
        sig.style.cssText = 'position:relative;margin:10px 5px;'
        var sal = document.createElement('span')
        sal.style.cssText = 'display:block;margin:5px 0;font-size:smaller;'
        sal.innerHTML = 'Compliments of The Beauty Quotient Formula,'
        sig.appendChild(sal)
        var bql = document.createElement('a')
        bql.href = 'http://thebeautyquotient.com'
        bql.innerHTML = 'thebeautyquotient.com'
        sig.appendChild(bql)

        var em = document.createElement('a')
        em.style.cssText = 'margin-top:6px;display:block;font-size:smaller;'
        em.href = 'mailto:info@thebeautyquotient.com'
        em.innerHTML = 'info@thebeautyquotient.com'
        sig.appendChild(em)
        return sig
      }
      function clearMessage() {
        app.sc.msgbox.style.display = 'none'
        butelem.style.visibility = ''
      }
      function okay(result) {
        function afterUpd() { return }
        setTimeout(clearMessage, 8000)
        butelem.parentNode.style.display = 'none'
        if (app.isIE) butelem.parentNode.parentNode.style.width = ''
        app.msgbox('E-mail sent.', butelem.parentNode.previousSibling, { img: { src: enums.images.info} })
        if (bqc.email != email) {
          bqc.setEmail(email)
          var sql = "update BQQuiz SET email ='" + email + "' where id=" + bqc.dbid
          qd = DA.createQuery(enums.dbOperation.exec, 'Text', sql, afterUpd, afterUpd)
          qd.exec()
        }
        return
      }
      function failed(err) {
        setTimeout(clearMessage, 12000)
        return app.msgbox(err._message, butelem)
      }
      butelem.style.visibility = 'hidden'
      var secs = document.createElement('div')
      secs.style.cssText = 'margin:4px;';
      var bqt = document.createElement('span')
      bqt.style.cssText = 'font-size:x-large;font-weight:bold;color:RGB(173,195,24);font-family:arial;'
      bqt.innerHTML = 'The Beauty Quotient Formula Quiz'
      secs.appendChild(bqt)
      for (var s in _this.sections) {
        if (_this.sections[s].area2.offsetHeight) {
          secs.appendChild(getSectionHtml(_this.sections[s].id))
        }
      }
      secs.appendChild(signature())
      secs.appendChild(links())
      var oh = document.createElement('div')
      oh.appendChild(secs)
      var webService = eval(webServiceCall).DBI
      var xml = '<Root><To>' + email + '</To><Subject>Beauty Quotient Formula Results</Subject><Body><![CDATA[' + oh.innerHTML + ']]></Body><BodyHTML>Yes</BodyHTML></Root>'
      webService(enums.dbOperation.email, xml, okay, failed)
    }
    if (email.length) {
      if (/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)$/i.test(email)) sendMail()
      else {
        app.msgbox('Please enter a valid email address.', butelem)
        setTimeout(reset, 20000)
      }
    }
  }
  this.emailkeydown = function(e) {
    app.sc.msgbox.style.display = 'none'
    var evt = BC.getEventObject(e)
    evt.stopPropagation()
    if (evt.keyCode === enums.keycode.enter) {
      this.serviceEmailReq(evt.srcElement.nextSibling)
      evt.preventDefault()
    }
  }
}
function _showEmail(elem) {
  var ae = elem.parentNode
  elem.nextSibling.style.display = 'inline';
  if (app.isIE) {
    var emnodes = elem.nextSibling.getElementsByTagName('*')
    for (var i = 0, tw = 0; i < 3; i++) tw += emnodes[i].offsetWidth
    ae.style.width = ae.offsetWidth + tw + 'px'
  }
  var inp = elem.nextSibling.lastChild.previousSibling
  if (bqc.email) inp.value = bqc.email
  inp.focus()
}
