// This "on load" event function is used to get the translation for the base 
// validation message.  It creates a hidden div, and then uses the AJAX
// getTranslation function to asynchonously pre-load the translation into the 
// hidden div for later.  At the time the translation is needed by a function,
// it can then synchronously read it out of the hidden div.
//Start js/flexi_forms.jsp
Event.observe(window, 'load', function() 
{
	var primaryContentDiv = $("findProduct");
	if (!primaryContentDiv)
	{
		primaryContentDiv = $("primary")
	}
	var validationMsgBase = primaryContentDiv.down("div#validation_msg_base");
	if (!validationMsgBase)
	{
		primaryContentDiv.insert('<div id="validation_msg_base" style="display:none"></div>');
		getTranslation("validation_msg_base","validation_message");
	}
	
	// create an iFrame off screen to handle google analytics
	var googleAnalytics = primaryContentDiv.down("div#google_analytics");
	if (!googleAnalytics)
	{
		primaryContentDiv.insert('<div id="google_analytics" style="position:absolute;top:-1000px;left:-1000px;width:1px;height:1px"></div>');
	}
});

function FlexiForm(id)
{
	this.formId = id;
	this.form = null;
	this.thanksMsg = "<h2>Thank you. Your form data is being processed</h2>";
	this.thanksImg = null;
	this.thanksContent = null;
	this.googleAnalytics = null;
	this.onSubmitComplete =  function()
		{
			if (this.googleAnalytics != null)
			{
				var ga = $('google_analytics');//id:1047010261 label:oahJCL_D3AEQ1beg8wM
				ga.insert('<iframe frameborder="0" src="/pages/templates/shared/googleanalytics_adwords.jsp?id=' + this.googleAnalytics.id +'&label=' + this.googleAnalytics.label +'"></iframe');
			}
			if (this.thanksContent)
			{
				showThankYou(this.thanksContent, '');
			}
			else
			{
				showThankYou(this.thanksMsg, this.thanksImg);
			}
		}
}

FlexiForm.map = new Object();

FlexiForm.getInstance = function(id)
{
	var result = null;
	if (id)
	{
		var form = $(id);
		var formId = form.id;
		result = FlexiForm.map[formId];
		if (!result)
		{
			result = new FlexiForm(formId);
			result.form = form;
			FlexiForm.map[formId] = result;
		}
	}	
	return result;
}

//alias for FlexiForm.getInstance()
var flexiform = function(id)
{
	return FlexiForm.getInstance(id);
}

FlexiForm.prototype.getForm = function()
{
	if (this.form)
	{
		return this.form;
	}
	var form = $(this.formId);
	this.form = form;
	return form;
}

// set the message to display in the "thank you modal"
FlexiForm.prototype.setThankYouMessage = function(msg)
{
	this.thanksContent = null;
	if (!msg || msg.length == 0)
	{
		this.thanksMsg = "<h2>Thank you. Your form data is being processed</h2>";
	}
	else
	{
		this.thanksMsg = msg;
	}
}

// set the image to display in the "thank you modal".  If null a default image
// will be displayed; if a empty string than no image will be displayed.
FlexiForm.prototype.setThankYouImage = function(img)
{
	this.thanksImg = img;
}

// set the content of the thank you modal to the contents of a div ID
FlexiForm.prototype.setThankYouContent = function(id)
{
	var tydiv = $(id);
	if (tydiv)
	{
		this.thanksContent = tydiv.innerHTML;
		this.thanksMsg = null;
	}
}

FlexiForm.prototype.setOnSubmitComplete = function(func)
{
	if (!func)
	{
		var func = function() {/*no-op*/};
	}
	this.onSubmitComplete = func;
}

FlexiForm.prototype.setGoogleAnalytics = function(ga)
{
	this.googleAnalytics = ga;
}

// This function takes an array of field IDs for the form specified and will 
// mark the fields identified as required if not currently required, or not 
// required if currently required.  The function relies on required form fields
// being designated by putting <span class="req_field_asterix">*</span> in 
// front of the labels associated with a form field
FlexiForm.prototype.toggleRequiredFields = function (fieldIds)
//function toggleRequiredFields(formId, fieldIds)
{
	var labels = $$("form#" + this.formId + " label");
    
    // handle case where label is implicitly associated with a control through
    // nesting. E.g. 
    // <LABEL ID="userlabel">
    //     User Name:<INPUT TYPE="TEXT" ID="user"/>
    // </LABEL>
    labels.each(function(label) {
    	label.style.color = "#333333";
    	var nested = label.down('input, textarea, select');
    	if (nested)
    	{
	    	if (fieldIds.indexOf(nested.id) >= 0)
	    	{
	    		var req = label.down('span.req_field_asterix');
	    		if (req)
	    		{
	    			req.remove();
	    		}
	    		else
	    		{
	    			label.insert({top: '<span class="req_field_asterix">*</span>'});
	    		}
	    	}
    	}
    });
    
    // handle case where label can't be implicitly associated with a control by 
    // nesting and uses the "for" attribute instead. E.g.
    // <TABLE>
    //     <TR>
    //         <TD><LABEL ID="userlabel" FOR="user">User Name:</LABEL></TD>
    //         <TD><INPUT TYPE="TEXT" ID="user"/></TD>
    //     </TR>
    // </TABLE>
    var labelsFor = labels.collect(function(e)
    	{
	    	if(e.readAttribute('for'))
	    	{
	    		return e.readAttribute('for');
	    	}
    	});
    fieldIds.each(function(id) 
    	{
	    	var index = labelsFor.indexOf(id)
	    	if (index >= 0)
	    	{
	    		var req = labels[index].down('span.req_field_asterix');
	    		if (req)
	    		{
	    			req.remove();
	    		}
	    		else
	    		{
	    			labels[index].insert({top: '<span class="req_field_asterix">*</span>'});
	    		}
	    	}
    	});
} 

FlexiForm.prototype.resetForm = function ()
{
	this.getForm().reset();
}

// alias for backward compatability
function resetForm(formId)
{
	FlexiForm.getInstance(formId).resetForm();
}

FlexiForm.prototype.validateSubmit = function ()
{
	var valErr = this.validateForm();
	if (valErr)
	{
		alert(valErr);
	}
	else
	{
		this.getForm().submit();
	}
}

// alias for backward compatability
function validateSubmit(formId)
{
	FlexiForm.getInstance(formId).validateSubmit();
}

FlexiForm.prototype.validatePostSalesForce = function()
{
	var valErr = this.validateForm();

	if (valErr)
	{
        alert(valErr);
    } 
	else 
	{
		// ship off to SalesForce
		postToSalesForce(this.formId);
    }
}

// alias for backward compatibility
function validatePostSalesForce(formId, thanks, img)
{
	var ff = FlexiForm.getInstance(formId);
	
	// If no spaces, assume div ID -- could do more complicated regex, but
	// this ought to be quick, easy, and correct 99.99% of time
	if (thanks && thanks.length > 0 && thanks.indexOf(' ')  == -1)
	{
		ff.setThankYouContent(thanks);
	}
	ff.validatePostSalesForce();
}

// Performs basic form validation.  Verifies all required fields are completed
// and that email address is in correct format
FlexiForm.prototype.validateForm = function()
{
	var form = this.getForm();
	var msg='';
	var labels = $$("form#" + this.formId + " label");

	labels.each(function(label) 
		{
			label.style.color = "#333333";
			
			if (label.down('span.req_field_asterix'))
			{
				var fieldID = getLabelsFieldIdentifier(form, label);
				var fieldValue = fieldValue = getFieldValue(form, fieldID);
		    		
		    	if (fieldID && !fieldValue)
		    	{
		    		msg+='- ' + getTextContent(label).replace(/[\*:]/g,'') + ' \n\n';
		    		label.style.color = 'red';
		    	}
		    	// test email field for proper format
		    	else if (fieldID && fieldValue && fieldID == 'email')
		    	{
		    		if (!fieldValue.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/))
		    		{
		    			msg+='- ' + getTextContent(label).replace(/[\*:]/g,'') + ' \n\n';
		    			label.style.color = 'red';
		    		}
		    	}
			}
		});
	
	var baseMsg = getTextContent($("findProduct").down("div#validation_msg_base"));
	if (msg) 
	{
		return baseMsg + '\n\n' + msg;
	}
	return null;
}

FlexiForm.prototype.postToSalesForce = function()
{    
	var form = this.getForm();
	
	// handle the fact that BioP and BioS use different IDs for postal code
	if ($('zip') && $('postalcode'))
	{
		$('postalcode').value = $('zip').value;
	}
	
	// secondary questions are questions that do not have a salesforce analog 
	// field -- therefore, we need to bundle up all the questions and answers
	// and put them into the description field before posting to salesforce.
	var secondary_questions = $$("form#" + this.formId + " label.secondary_question");
	if (secondary_questions && secondary_questions.length > 0)
	{
		// verify the 'description' field exists -- if not, then add it.
		var descriptionField = form.down('input[name="description"]');
		if (!descriptionField)
		{
			descriptionField = form.insert('<input type="hidden" id="description" name="description"/>');
			descriptionField.value = "";
		}
		
		// collect the questions and answers to append to the description field value
		var descriptionText = descriptionField.value ? descriptionField.value : "";
		secondary_questions.each(function(secondary_question) 
		    {
				var fieldID = getLabelsFieldIdentifier(form, secondary_question);
				var answerText = getFieldValue(form, fieldID);
				if (!answerText)
				{
					answerText = "";
				}
			    descriptionText += "Question: " + getTextContent(secondary_question).replace(/^\*/,'') + " \n";
			    descriptionText += "Answer: " + answerText;
			    descriptionText += " \n \n";
		    });
		form.description.value = descriptionText;
	}

    $(this.formId).action = "/ajax-posttosalesforce.do";

    new $(this.formId).request( {
        encoding: 'UTF-8',
        onFailure: function() {showError()},
        onSuccess: function(transport) {
            var notice = $('result');
            var json  = transport.responseJSON;
            notice.update(json.status);
          },
        onComplete: this.onSubmitComplete
    });
}

//alias for backward compatibility
postToSalesForce = function(formId, onComplete)
{
	var ff = FlexiForm.getInstance(formId);
	if (onComplete)
	{
		ff.setOnSubmitComplete(onComplete);
	}
	ff.postToSalesForce();
}

// Function to get the value of a field from the associated label.  The field
// is associated with the label either by nesting it within the label tag or
// by the "for" attribute identifier on
function getLabelsFieldIdentifier(form, label)
{
	var field = label.down('input, textarea, select');
	var fieldID = null;
	if (field)
	{
		fieldID = field.id;
		if (!fieldID)
		{
			fieldID = field.name;
		}
	}
	else
	{
		if (label.readAttribute('for'))
		{
			fieldID = label.readAttribute('for');
		}
	}
	return fieldID;
}

// An extended version of prototype's $F function that works with radio button 
// groups and check box groups as well as inputs identified by name instead of
// ID
function getFieldValue(formId, identifier)
{
	var value = null;
	var field = $(identifier);
	if (field)
	{
		// simplest case: just use prototype's $F function
		value = $F(field);
	}
	if (!value)
	{
		// wasn't able to find the form input by ID -- trying to find by name
		var form = $(formId);
		
		// check for radio button group
		var radioBtns = form.getInputs('radio',identifier);
		if (radioBtns.length > 0)
		{
			var checked = radioBtns.find(function(radio) { return radio.checked; });
			if (checked)
			{
				value = checked.value;
				var other = getOtherInfo(checked);
				if (other)
				{
					value += " - " + other;
				}
			}
		}
		else
		{
			// check for check box group
			var checkboxes = form.getInputs('checkbox',identifier);
			if (checkboxes.length > 0)
			{
				var checked = checkboxes.collect(function(checkbox) 
				    { 
						if (checkbox.checked)
						{
							var val = checkbox.value;
							var other = getOtherInfo(checkbox);
							if (other)
							{
								val += " - " + other;
							}
							return val;
						}
				    });
				if (checked)
				{
					checked = checked.compact();
					if (checked.length > 0)
					{
						value = checked;
					}
				}
			}
			else
			{
				// not a radio button group or check box group so just get
				// inputs by name
				var inputs = form.getInputs(null, identifier);
				if (inputs && inputs.length > 0)
				{
					if (inputs.length == 1)
					{
						// return single value if only one
						value = $F(inputs[0]);
					}
					else
					{
						// return array of values if more than one
						value = inputs.collect(function (input)
								{
									return $F(input);
								});
					}
				}
			}
		}
	}
	return value;
}

function getOtherInfo(checked)
{
	var value = "";
	// if radio button indicates it is an "other" field that has an
	// additional input field for user specification, grab the 
	// value of that field as well and append it 
	if(checked.hasClassName('other'))
	{
		var otherField = $('other_' + checked.name);
		if (otherField)
		{
			value = otherField.value;
		}
	}
	return value;
}

//------------------------------------------------------
// functions from reply database for form validation
//------------------------------------------------------
function valRadioButton(btn) 
{
	var cnt = -1;
	for (var i = btn.length - 1; i > -1; i--) 
	{
	   if (btn[i].checked) 
	   {
		   cnt = i; i = -1;
	   }   
	}
	if (cnt > -1) 
	{
		return btn[cnt].value;
	}
	else 
	{
		return null;
	}
}

function valRadioButtonCount(btn) 
{
	var cnt = -1;
	for (var i=btn.length-1; i > -1; i--) 
	{
   	   if (btn[i].checked) 
   	   {
   		   cnt++
   	   }
	}
	return cnt
}

function EitherOr() { /*defined here just to prevent js error*/ }

function getCountries(selector) {
	// Send AJAX message to get the list of countries and codes.
	var ajax = new Ajax.Request('/ajax-getcountries.do',{
		method: 'get',
		onSuccess: function(transport) {
		try {
			var array = eval("(" + transport.responseJSON.message + ")");
			for (i = 0; i < array.length; i++) {
				var option = document.createElement("option");
				option.text = array[i].label;
				option.value = array[i].code;
				selector.options[i] = option;
			}
		} catch(ex) {
			alert(ex.description);
		}
		},
		onFailure: function() { alert("Error: can't connect to server.") }
	});
}
//End js/flexi_forms.jsp
