/////////////////////////////////////////////////////////////////
//
// Author : Matthew Quinlan (matt at quinlan dot net)
// Version : 0.9
// Date: 2010-03-15 (Y-M-D)
// File: prefill.js
// Purpose : Pre-populate LoopFuse-enabled HTML form fields with the values from previous 
//           form submissions as a convenience to the web surfer.
// Requires: Jquery : <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>		
// References : https://loopfuse.helpstream.biz/View.jsp?procId=675ac48d6bb0b1d92d7cc84269df9f88
// Notes : form fieldnames MUST match loopfuse fieldnames EXACTLY until feature OV-1153 has been released
// 
// Instructions : 
//   1. Add the JQuery script to the <head> tag of your HTML page containing the loopfuse lead-capture form (see "Requires" section above)
//   2. Ensure that the HTML page containing the loopfuse lead-capture form is instrumented with the LoopFuse "beacon" correctly. (https://loopfuse.helpstream.biz/View.jsp?procId=64d93e2febb6cd01c24a6bda5a4f1867)
//   3. Add class="lf-prefill" to any <form> tag you wish to pre-populate
//   4. Add class="lf-nofill" to any form element you do NOT wish to pre-populate (e.g. a password or a comments field)
//
/////////////////////////////////////////////////////////////////

if (window.console) window.console.log("start v0.9");

// 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');

				// avoid populating specific form fields marked with CSS class lf-nofill (e.g. password field)
				// also avoid populating LoopFuse hidden fields (vid, cid, form_id, repost, thankyou, submit)
			if ((isElementMarkedByClass(curElement,"lf-nofill")==false) && (fieldname!="vid") && (fieldname!="cid") && (fieldname!="submit") && (fieldname!="formid") && (fieldname!="repost") && (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) {
		window.addEventListener('load', getVisitorData, false);
	}
else if (window.attachEvent) {
		window.attachEvent('onload',getVisitorData);
	}

if (window.console) window.console.log("done");
