/**
 * Elizabeth Souther
 * Online Form Section JavaScript
 */

//= require "jquery-1.4.2"
//= require "jquery.form"

/**
 * jQuery Plugin Functions
 */
;(function($) {
	
	$.fn.toggleShow = function() {
		$(this).stop().animate({opacity: "toggle", height: "toggle"}, 200);
	};
	
	$.fn.prependTokenField = function() {
		$(this).prepend($('<input/>', {id: 'token', type: 'hidden', value: $("#form_selection").data('token'), name: 'ts'}));
	};
	
	$.fn.paintRequiredFields = function() {
		$(this).find('input[class*=":"]').each(function(index) {
			if (!$(this).hasClass(":integer")) {
				var $label = $(this).parent().children("label");
				var labelContent = $label.html();
				labelContent += ' <span class="required">*</span>';
				$label.html(labelContent);
			}
		});
	};
	
	$.fn.bindAjaxSubmit = function() {
		$(this).bind('submit', function(evt) {
			var $formArea = $('#form_area');
			
			$.ajax({
				url: $(this).attr('action'),
				type: 'POST',
				dataType: 'json',
				data: $(this).serialize(),
				success: function(json) {

					if (json.status == "OK") {
						$formArea.fadeOut(400, function() {
							$(this).html('').append('<p id="form_response">' + json.message + '</p>').fadeIn(400);
						});
					} else {
						alert("Errors prevented the form from being submitted. Please re-check your form and try again.");
					}
					return true;
				}
			});

			evt.preventDefault();
			return false;
		});
	};
	
})(jQuery);

/**
 * jQuery Document Ready Function (runs once page loads)
 */
$(document).ready(function() {
	var baseURL  = "/forms/";
	var tokenURL = "/form_token.php";
	
	// Download and cache a form authenticity token
	$.get(tokenURL, function(data) {
		$('#form_selection').data("token", data);
	}, 'text');
	
	$("a.submit").live('click', function() {
		$(this).parents('form').trigger('submit');
	});
	
	// Downloadable Forms selection list behavior
	$('#download_selection select').change(function() {
		var selection = $(this).val();
		
		if (selection != "null") {
			window.location.href = (baseURL + selection);
		}
	});
	
	// Online Forms selection list behavior
	$('#form_selection select').change(function() {
		var $formArea = $('#form_area');
		var selected  = $(this).val();
		
		if (selected == 'null') {
			$formArea.stop().animate({opacity: "0"}, 400, function() {
				$formArea.html('<p>Select a form from the lists above and it will appear here.</p>');
				$formArea.stop().animate({opacity: "1"}, 400);
			});
		} else {		
			$formArea.stop().animate({opacity: "0"}, 400, function() {
				var formURL = baseURL + selected;
				var now = new Date();
				var cachedForm = $.jStorage.get(formURL);
				
				if (cachedForm && (now - cachedForm.date) / 1000 < 86400) {
					
					// Load cached form and fill form area
					var cachedHTML = cachedForm.html;
					$formArea.html(cachedHTML);
					
					var $theForm = $formArea.find('form');
					
					// Add token, required field asterisks, and AJAX submit action
					$theForm.prependTokenField();
					$theForm.paintRequiredFields();
					$theForm.bindAjaxSubmit();
					
					$formArea.css({opacity: "1"});
					
				} else {
					
					$.get(formURL, function(data) {

						// load the form, keep it hidden, and cache the data for future requests in localStorage
						$formArea.html(data);
						$.jStorage.set(formURL, { date: now, html: data });


						// The form we just loaded:
						var $theForm = $formArea.find('form');

						// Record the form's origin URL
						$theForm.data('origin_url', formURL);

						// add token field and paint required field labels
						$theForm.prependTokenField();
						$theForm.paintRequiredFields();
						
						// bind ajax submit() function
						$theForm.bindAjaxSubmit();

						// show the form
						$formArea.stop().animate({opacity: "1"}, 400);
					}, 'html');
				}
				
			});
		}
	});
	
	$('#cert_of_insurance #check_fax').live('click', function() {
		$('#client_fax_input').toggleShow();
	});
	
	$('#cert_of_insurance #check_email').live('click', function() {
		$('#client_email_input').toggleShow();
	});
	
	$('#employment_application #union_yes').live('change', function() {
		if ($(this).is(":checked")) {
			$('#union_numbers_input').toggleShow();
		}
	});
	
	$('#employment_application #union_no').live('change', function() {
		if ($(this).is(":checked")) {
			$('#union_numbers_input').toggleShow();
		}
	});
	
	$('#other_check').live('click', function() {
		$('#industry').toggleShow();
	});
	
});
