/////////////////////////////////////////////////////////////////
//
// Title : Prefill
// Author : Matthew Quinlan (matt at quinlan dot net)
// Version : 1.0
// Date: 2010-08-26 (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 (dynamically loaded if not already in use on webpage)
//
// References : https://loopfuse.helpstream.biz/View.jsp?procId=675ac48d6bb0b1d92d7cc84269df9f88
//
// License : This code is licensed under Creative Commons Attribution 3.0 Unported License.  
//           http://creativecommons.org/licenses/by/3.0/
//           This means that you can use it and modify it as long as you do not remove my name from these comments.
//
// Instructions : 
//   1. 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)
//   2. Add class="lf-prefill" to the <form> tag you wish to pre-populate
//   3. Add class="lf-nofill" to any form element tag you do NOT wish to pre-populate (e.g. a password or a comments field)
//
// Disclaimer : This code is offered as-is and without warranty expressed or implied.
//              This code is a community contribution that is maintained by the author, not by the author's employer (LoopFuse).
//
////////////////////////////////////////////////////////////////////

// set debug=1 here if you wish to see console debugging output
debug=0;
if (typeof(window.console) == "undefined") debug=0;

if (debug) console.log("start v1.0");

// Load jQuery if not present 
if (typeof jQuery === "undefined" ) 
		{
		if (debug) console.log("loading jQuery");
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type","text/javascript");
    script_tag.setAttribute("src",
      "http://code.jquery.com/jquery-latest.min.js")
    script_tag.onload = jQueryReadyCallback; // Run jQueryReadyCallback() once jQuery has loaded
    script_tag.onreadystatechange = function () { // Same thing but for IE
      if (this.readyState == 'complete' || this.readyState == 'loaded') jQueryReadyCallback();
    }
    document.getElementsByTagName("head")[0].appendChild(script_tag);
		if (debug) console.log("jQuery loaded");
} else 
		{
		if (debug) console.log("jQuery already present");		
    jQueryReadyCallback();
		}


// Place any logic here that cannot be executed until JQuery is loaded
function jQueryReadyCallback()
	{
	if (debug) console.log("page ready: mark required fields and set form onsubmit handler");
	// After document is loaded mark the required fields with an asterisk and alter form's onsubmit (if undefined)
	$(document).ready(function() {
		getVisitorData();
	});
	}


// 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 (debug) 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 (debug) console.log(fieldname,":",myDataFieldValue);
						// set field value to JavaScript object value returned from JSONP call to LoopFuse webservice
						if (myDataFieldValue) curElement.value = myDataFieldValue;
					}
				}
		}
	
	if (debug) 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)
	
	// exit early if no cookie exists
	if (readCookie("LOOPFUSE")==null) return;
	
	var jsonp_url = "http://webservices.loopfuse.net/webservice/leadinfo?cid="
	+ window._lf_cid
	+ "&vid="
	+ readCookie("LOOPFUSE")
	+ "&json_method=?";
	
	if (debug) 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 (debug) console.log(data);
	      		if (data!=null)
	          prefill(data);
	      });
	}

if (debug) console.log("done");