/*
** Script:			Ajax.JS Form Analyzer
**
** Author:			Shaun Ault
**
** Copyright:		2008
**
** Description:     Iterates over form elements and alleviates server-side cpu
**					usage by performing rudimentary validation on data fields.
**
**					Warnings will be shown in the specified color, while errors
**					can appear in another.  Upon user correction of the highlighted
**					fields they will revert back to the default state.
*/

//////////////////////////// CONFIG SETTINGS ///////////////////////////////////
var error_color = '#ffc4c4';		// color to change to when error in form
var warning_color = '#ffc4c4';		// color to change to when warning in form
////////////////////////////////////////////////////////////////////////////////

function consoleLog(data)
{
	var alerts = false;
	if(typeof(console) == 'object') {
		console.log(data);
	}
	else
	{
		if (alerts == true)
		{
			alert(data);
		}
	}
}

function prepForm(form_id, post_data, form_callback, dropdown_other)
{
	var inputs = $(form_id).getElements('input,select,textarea');

	inputs.each(function(input) {
		if (input.value == input.title)
		{
			input.addClass('default');
		}
		if (input.type != 'button' && input.type != 'submit')
		{
			input.addEvents({
				'focus': function(){
					this.addClass('focus');
					if (this.value == this.title)
					{
						this.value = '';
						this.removeClass('default');
					}
				},
				'blur': function(){
					if (this.value == '')
					{
						this.value = this.title;
						this.addClass('default');
					}
					this.removeClass('focus');
				}
			});
		}
	});

	if ($defined(dropdown_other))
	{
		for (i = 0; i < dropdown_other.length; i++)
		{
			$(dropdown_other[i]).addEvent('change', function() {
				var display = 'none';
				if (this.value == "other" || this.value == "Other")
				{
					display = 'block';
				}

				var descriptor = this.id + '_other_desc';
				$(descriptor).setStyle('display', display);
				$(this.id + '_other').setStyle('display', display);

				$(this.id + '_other').addEvent('change', function() {
					this.morph('.fixed');
					this.removeClass('warning');
					$(descriptor).setStyle('display', 'none');
					this.removeEvent('change');
					this.removeClass('warning');
				});
			});
		}
	}

	if (!$defined(form_callback) || form_callback == '') {form_callback = 'submitForm';}

	$('submit_btn').addEvent('click', function() {
		return eval(form_callback + '(form_id, post_data)');
	});
}

function submitForm(form_id, field_data)
{
	var label_errors = $$('#' + form_id + ' label.error');
	label_errors.each(function(field_error) {
		field_error.dispose();
	});

	var error = false;
	var inputs = $(form_id).getElements('input,select,textarea');
	inputs.each(function(el, i) {
		if ((el.value == el.title || el.value == '') && el.hasClass('optional') === false && el.type != 'checkbox')
		{
			el.tween('background-color',warning_color);
			error = true;

			if (el.type != 'checkbox')
			{
				el.addEvent('change', function() {
					this.morph('.fixed');
					if (this.getNext('label.error') != 'undefined' && this.getNext('label.error') != null)
					{
						this.getNext('label.error').dispose();
					}
					this.removeEvent('change');
				});
				var errorLabel = new Element('label', {
				    'for': el.id,
				    'html': 'Missing Required Information',
				    'class': 'error error_notice'
				}).inject(el, 'after');
			}
		}
		else
		{
			if(el.getStyle('background-color') != '')
			{
				el.setStyle('background-color','');
			}
		}
	});

	if (error === false)
	{
		var dataArray = new Array();    
		var JSONstring  = '{';
			JSONstring += '"url":"' + window.location + '",';
			JSONstring += '"form_id":"' + form_id + '",';
			JSONstring += '"data_array":{';
		for (i = 0; i < field_data.length; i++)
		{
			if ($(field_data[i]).type == 'checkbox')
			{
				dataArray[i] = '"' + field_data[i] + '":"' + $(field_data[i]).checked + '"';
			}
			else
			{
				if ($(field_data[i]).value == $(field_data[i]).title)
				{
					dataArray[i] = '"' + field_data[i] + '":""';
				}
				else
				{
					dataArray[i] = '"' + field_data[i] + '":"' + $(field_data[i]).value + '"';
				}
			}
		}
		JSONstring += dataArray.join(',');
		JSONstring += '}}';
		var post_data = eval('(' + JSONstring + ')');

		inputs.each(function(el) {
			if(el.getStyle('background-color') != '')
			{
				el.setStyle('background-color','');
			}
		});
		// AJAX
		var jsonRequest = new Request({                 
			url: '/forms/ajax_post.php?type=' + form_id,
			method: 'post',
			onComplete: function(response){
				response = eval(response);
				if (response.mail && response.mail.success === true)
				{
					$(form_id).setStyle('display','none');
					document.body.scrollTo(0, 0);

					if($defined($('response_message')))
					{
						$('response_message').addClass('success');
						$('response_message').innerHTML = response.text;
						$('response_message').setStyle('display','block');
					}
				}
				else
				{
					if ($defined(response.field))
					{
						$(response.field).tween('background-color',error_color);
						$(response.field).addEvent('change',function() {
							this.setStyle('background-color','');
							this.getNext('label.error').dispose();
							this.removeEvent('change');
						});
						var errorLabel = new Element('label', {
						    'for': response.field.id,
						    'html': response.text,
						    'class': 'error'
						}).inject($(response.field), 'after');
					}
				}
			}
		}).post(post_data);
	}
	else
	{
		// alert('Oops, we never accounted for this.  Sorry for the inconvienience.');
	}
	return false;
}

if($defined($('country')) && $defined($('state')))
{
	$('country').addEvent('change', function() {
		if (this.value == "United States")
		{
			$('state_label').htmlFor = 'state_us';
			$('state_label').innerHTML = 'State<span class="req">*</span>';
			$('state_section').setStyle('display','block');

			$('state').setStyle('display','none');
			$('state_canada').setStyle('display','none');
			$('state_canada').addClass('optional');
			$('state_us').setStyle('display','inline');
			$('state_us').removeClass('optional');
		}
		else if (this.value == "Canada")
		{
			$('state_label').htmlFor = 'state_canada';
			$('state_label').innerHTML = 'Province<span class="req">*</span>';
			$('state_section').setStyle('display','block');

			$('state').setStyle('display','none');
			$('state_us').setStyle('display','none');
			$('state_us').addClass('optional');
			$('state_canada').setStyle('display','inline');
			$('state_canada').removeClass('optional');
		}
		else
		{
			$('state_section').setStyle('display','none');

			$('state_us').setStyle('display','none');
			$('state_us').addClass('optional');
			$('state_canada').setStyle('display','none');
			$('state_canada').addClass('optional');
			$('state').setStyle('display','none');
		}
		$$('#state_section label.error').each(function(error){
			error.dispose();
		});
	});
}
