﻿// NOTE: form fieldnames MUST match loopfuse fieldnames EXACTLY until feature OV-1153 has been released

if (window.console) window.console.log("start");

// determine if a given DOM element has a given CSS class applied to it
// (remember, a DOM element may have multiple classes applied)
function isElementMarkedByClass(DomElement, ClassName) {
    var found = false;
    var arrayTokens = DomElement.className.split(',', 3);

    for (var i in arrayTokens)
        if (arrayTokens[i] == ClassName) found = true;

    return found;
}

// read the value of a given cookie in the browser
// return null if no cookie of that name found
function readCookie(key) {
  var cookie = document.cookie;
  var first = cookie.indexOf(key+"=");

  // cookie exists
  if (first >= 0) {
    var str = cookie.substring(first,cookie.length);
    var last = str.indexOf(";");

    // if last cookie
    if (last < 0) last = str.length;

    // get cookie value
    str = str.substring(0,last).split("=");
    return unescape(str[1]);
  } else {
    return null;
  }
}


// Automatically populate form fields that match the attributes of myData.
// Forms to be populated should be marked by a CSS class called "lf_prefill" like <form class="lf-prefill" action="...">
// Elements of forms which should NOT be prefilled should be marked by a CSS class called "lf-nofill" like <input class="lf-nofill" ....>
function prefill(myData) {
    if (window.console) window.console.log(myData);
    myForms = document.getElementsByTagName("form");
    // cycle through forms
    for (var i = 0; i < myForms.length; i++) {
        var curForm = myForms[i];
        // only pre-populate forms who are marked with CSS class lf-prefill
        if (isElementMarkedByClass(curForm, "lf-prefill"))
        // cycle through form elements
            for (var j = 0; j < curForm.elements.length; j++) {
            var curElement = curForm.elements[j];
            var fieldname = curElement.getAttribute('name');
            var fieldtype = curElement.type;
            //Check the name isn't a null value
            if ((fieldname != null) && (fieldname != "") && (fieldtype != "textarea")) {
                //.Net 2 control names are prefixed with Page$Control$ etc, find the control name after the last $
                if (fieldname.lastIndexOf('$') > -1) {
                    fieldname = fieldname.substring((fieldname.lastIndexOf('$') + 1), fieldname.length);
                }
                // avoid populating specific form fields marked with CSS class lf-nofill (e.g. password field)
                // also avoid populating LoopFuse hidden fields
                if ((isElementMarkedByClass(curElement, "lf-nofill") == false) && (fieldname != "vid") && (fieldname != "cid") && (fieldname != "formid") && (fieldname != "repost") && (fieldname != "password") && (fieldname != "thankyou")) {
                    var myDataFieldValue = eval('myData.' + fieldname);
                    if (window.console) window.console.log(fieldname, ":", myDataFieldValue);
                    // set field value to JavaScript object value returned from JSONP call to LoopFuse webservice
                    if (myDataFieldValue) curElement.value = myDataFieldValue;
                }
            }
        }
    }
    if (window.console) window.console.log("prefill done");
}

function getVisitorData() {
    // NOTE: once LoopFuse webservices can return form fields instead of loopfuse fields as the keys then this will work even when the two keynames are not identical (http://loopfuse.org:8080/jira/browse/OV-1153)

    var jsonp_url = "http://webservices.loopfuse.net/webservice/leadinfo?cid="
    + window._lf_cid
    + "&vid="
    + readCookie("LOOPFUSE")
    + "&json_method=?";

    if (window.console) window.console.log("JSON webservice call: " + jsonp_url);

    // asynchronously get visitor registration data as JSON and wrap into JSONP then call prefill() method if any data exists
    $.getJSON(jsonp_url,
      function(data) {
          if (window.console) window.console.log(data);
          if (data != null)
              prefill(data);
      });
}

// add getVisitorData to the event queue for OnLoad event
if (window.addEventListener) {

    if (checkBrowserVersion() == true) {
        window.addEventListener('load', getVisitorData, false);
    }
}
else if (window.attachEvent) {
if (checkBrowserVersion() == true) {
        window.attachEvent('onload', getVisitorData);
    }
}

if (window.console) window.console.log("done");

//Check the browser version for pre-fill requirements
function checkBrowserVersion() {
    var bShow = false;
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
        var ieversion = new Number(RegExp.$1) // capture x.x portion and store as a number
        if (ieversion >= 7)
            bShow = true;
        else
            bShow = false;
    }
    else {
        if (/Safari/.test(navigator.userAgent)) {
            bShow = false;
        }
        else {
            bShow = true;
        }
    }
    return bShow;
}