/*
forms.js
*/

// form response
function form_response(msg, msg_class) {
	// error
	if (msg_class == 'error') {
		msg = '<strong>Please note the following issues</strong><br /><br />' + msg;
	}
	
	var html      = '<div id="notice" class="' + msg_class + '" style="display:none;">' + msg + '</div>\n';
	
	// remove message area div if it already exists
	if ($("#notice")) {
		$("#notice").remove();
	} else {
		
	}
	
	// insert message after page title
	$("#page-title").after(html);
	$("#notice").slideDown();
}

// submit form
function SubmitForm(obj) {
	// set values
	var id					= $(obj).parents("form").attr("id");
	var action_bar = $(".action-bar");
	
	// disable actions
	DisableActions(action_bar);
	
	// post form
	$("#" + id).submit();
}

// submit form via Ajax call to controller method
function AjaxSubmit(obj) {
	// set values
	var id         = $(obj).parents("form").attr("id");
	var action_bar = $(".action-bar");
	var form       = $(obj).parents("form");
	var form_data  = form.serialize();
	
	// disable actions
	DisableActions(action_bar);
	
	// send data
	$.ajax({
		type:			"POST",
		url:			form.attr("action"),
		data:			form_data,
		dataType: 'json',
		success:	function(response){
			ClearErrors(id);
			EnableActions(action_bar);
			ParseResponse(response, id);
		},
		error: function(response){
			console.error(response);
		}
	});
}

// parse a json encoded response
function ParseResponse(response, form_id) {
	// console.log(response);
	// errors?
	if (response.errors) {
		// build error message and highlight fields
		var msg		 = '';
		$.each(response.errors, function(key, value) {
			msg = msg + '<li>' + value + '</li>';
			if (e = $('#f-' + key)) {
				e.addClass('error');
			}
		});
		
		// display notice
		var notice = '<strong>Please note the following issues:</strong><ul>' + msg + '</ul>';
		SetNotice(escape(notice), 'error');
		
		// scroll to the top of the page so we can see the notice
		scrollTo($('#top'));
	} else if (response.notice) {
		// reset form
		if (form_id) {
			document.forms[form_id].reset();
		}
		
		// display notice
		SetNotice(escape(response.notice), 'info');
		
		// scroll to the top of the page so we can see the notice
		scrollTo($('#top'));
	} else if (response.redirect) {
		// redirect
		location.href = response.redirect;
	}
}

// disable/enable form actions
function DisableActions(container) {
	// disable/hide
	if (container) {
		// disable buttons
		container.find('button').each(function() {
			$(this).blur();
			$(this).disabled = "disabled";
		});
		// disable links
		container.find('a').each(function() {
			$(this).blur();
			$(this).disabled = "disabled";
		});
		// hide child divs
		container.find('div').each(function() {
			$(this).hide();
		});
		
		// add "processing"
		container.append('<div class="processing">processing...</div>');
	}
}

// enable actions
function EnableActions(container) {
	// remove "processing"
	container.find('div.processing').each(function() {
		$(this).remove();
	});
	
	// enable/show
	container.find('button').each(function() {
		$(this).removeAttr("disabled");
		$(this).blur();
	});
	container.find('div').each(function() {
		$(this).show();
	});
}

// resets all forms
function ResetForms() {
	$("form").each(function() {
		$(this).reset();
	});
}

// clear error styled fields for a given form
function ClearErrors(id) {
	// var list = $$('#' + id + ' fieldset > div[id]');
	$("#" + id + " fieldset > div.error").each(function() {
		$(this).removeClass('error');
	});
}


// focus field
function focusField(id) {
	document.getElementById(id).focus();
}

// autoformat phone numbers
var areacodeLength	= 3;
var firstThree			= 3;
var previousLength	= null;
var thisInput				= null;
var originalLength	= null;
var thisAreacode		= null;
var thisFirstThree	= null;
var thisLastFour		= null;
var phone_test			= false;
var international		= false;
function autoFormat(input,type) {
	// lock out NS4
	if (!document.layers) {
		if (type == 'phone') {
			// var temp_selection = input.selectionStart;
			// alert("selectionStart=" + input.selectionStart);
			var addFirstParen		= false;
			var addSecondParen	= false;
			var addDash					= false;
			thisInput						= input.value.replace(/[. ()-\/]/gi,'');
			
			// if first input is a "+" assume its an international number and do not format
			if (input.value.length == 1 && input.value == '+') { international = true; return true; }
			else if (input.value.length == 1 && input.value == '(') { previousLength = 1; return true; }
			
			// don't do anything on backspace
			else if (input.value.length >= previousLength && international == false) {
				thisAreacode		= thisInput.substr(0,3);
				thisFirstThree	= thisInput.substr(3,3);
				thisLastFour		= thisInput.substr(6,4);
				
				// add '('
				if (thisInput.length > 0) { addFirstParen = true; }
				// add ') '
				if (thisAreacode.length == areacodeLength) { addSecondParen = true; }
				// add '-'
				if (thisFirstThree.length == firstThree) { addDash = true; }
				
				// add everything, assign to field
				if (addFirstParen) { thisAreacode = '(' + thisAreacode; }
				if (addSecondParen) { thisAreacode += ') '; }
				if (addDash) { thisFirstThree += '-'; }
				if (phone_test) { alert('writing'); }
				input.value = thisAreacode + thisFirstThree + thisLastFour;
			}
			
			previousLength = input.value.length
			// if (temp_selection && temp_selection != 'undefined') { input.selectionStart = temp_selection; input.selectionEnd = temp_selection; }
		}
	}
}

// onload
$(document).ready(function(){
	// catch Ajax errors and throw them to Firebug console
	$(document).ajaxError(function(){
		if (window.console && window.console.error) {
			console.error(arguments);
		}
	});
	
	// insert required/error field icons
	jQuery.each($("div[class*='field'][class*='required']"), function(e){
		var class_string = $(this).attr('class');
		if (class_string.indexOf("error") > 0) {
			$(this).find("label").append(' <img src="/icon/exclamation.png" alt="error" width="16" height="16" style="margin-bottom:4px;" />');
		} else {
			$(this).find("label").append(' <img src="/icon/bullet_star.png" alt="required" width="16" height="16" style="margin-bottom:4px;" />');
		}
	});
	
	// insert tooltip icons
	jQuery.each($("label[class*='tooltip-trigger']"), function(e){
		$(this).append(' <img src="/icon/help.png" alt="help" class="help" width="16" height="16" style="margin-bottom:4px;" />').hover(
      function () {
        $(this).find("span").show();
      }, 
      function () {
        $(this).find("span").hide();
      }
    );
	});
		
	// first field focus for IE
	// IE switches off the field highlighting of the first field
	// if this comes after the "add highlight" binding below
	jQuery.each(jQuery.browser, function(i) {
		if ($.browser.msie == true) {
			$(":text:first").focus();
		}
	});
	
	// add highlight on field focus
	$(":input").bind("focus blur", function(){
		$(this).toggleClass('field-focus');
	});
	
	// first field focus for non-IE browsers
	jQuery.each(jQuery.browser, function(i, val){
		if ($.browser.msie == false) {
			$(":text:first").focus();
		}
	});
});




