//Ready function
var modals = [];

$(function() {
	$("div.requestbutton table.ajaxbutton a.submit, a.button.submit").live("click", function() {
		// Gather data
		$('div.ui-dialog').wrapAll('<form id="modalform" />');
		var data = [];
		var form = $('#modalform').formToArray();
		$('div.ui-dialog').unwrap();
		
		for(var n in form) {
			if(form[n].value !== null && typeof form[n].value != 'undefined') {
				data[form[n].name] = form[n].value;
			}
		}
		
		// Submit
		if(typeof(_gaq) != "undefined") {
			$("#requestlead").formSubmit({
				before: function_before,  // pre-submit callback 
				error: function_error,  // error callback 
				success: function_succes, // post-submit callback
				data: data,
				allowPost: true,
		        allowScript: false,
				analytics: _gaq
			});
		} else {
			$("#requestlead").formSubmit({
				before:	function_before,		// pre-submit callback 
	    		error: function_error,			// error callback 
	    		success: function_succes,		// post-submit callback
	    		data: data,
	        	allowPost: true,
	        	allowScript: false
			});
		}
		
		return false;
	});
	
	if($("#requestlead").length) {
		function getFormnames() {
			formnames = new Array();
			i = 0;
			$("div#forms form > div").each(function() {
				hidden_q = ($("tbody",this).filter(function() { return $(this).css("display") == "none" })).length;
				total_q = $("tbody",this).length;
				
				if(hidden_q != total_q || (hidden_q == 0 && total_q == 0) ) {
					formnames[i] = $(this).attr("class");
					i++;
				}
			});
			
			formnames.sort();
			return formnames;
		}
		
		function createModal(formname) {
			if(!$('#modal-'+formname).length) {
				$('<div id="modal-'+formname+'"></div>').dialog({
						modal: true,
						/*width: 'auto',*/
						minWidth: 355,
						maxWidth: 500,
						autoOpen: false,
						beforeclose: function (event, ui) {
							//$("div",forms[formname]).remove();
							//$("div",modals[formname]).clone().appendTo(forms[formname]);
						}
				});
				if(jQuery.browser.msie && ((parseInt(jQuery.browser.version) == 6 ) || (parseInt(jQuery.browser.version) == 7))){
					$('#modal-'+formname).dialog("option", "width", '365px');
				} else {
					$('#modal-'+formname).dialog("option", "width", 'auto');
				}
				return true;
			} else {
				return false;
			}
		}
		
		function bindButtons() {
			formnames = getFormnames();
			
			$.each(formnames, function(index, value) {	
				if(value != "form1") {
					createModal(value);
					modals[value] = $('#modal-'+value);
					$('#forms .'+value+' > *').appendTo($('#modal-'+value));
					$("#modal-"+formnames[index]).dialog( "option", "title", index+1+' van '+formnames.length );
				}
				
				$('a.modal-next-'+formnames[index]).unbind("click");
				$('a.modal-prev-'+formnames[index]).unbind("click");
				
				$('a.modal-next-'+formnames[index]).live("click", function(event) {
					event.preventDefault();
					$("#modal-"+formnames[index]).dialog('close');
					$("#modal-"+formnames[(index+1)]).dialog('open');
				});
				
				$('a.modal-prev-'+formnames[index]).live("click", function(event) {
					event.preventDefault();
					$("#modal-"+formnames[index]).dialog('close');
					$("#modal-"+formnames[index-1]).dialog('open');
				});
			});
		}
		
		bindButtons();
	}
});

// Form submit functions

function function_before(form, options)
{	
	$("table.ajaxbutton span.img").css("display","inline");
}

// Modified for multiple-modal-window error handling
function function_error(data)
{
	$("table.ajaxbutton span.img").css("display","none");
	$(".error").removeClass('error');
	
	if(data.error && data.error != 'validation_error') {
		alert(data.error);
	} else if(data.missing_fields) {
		$.each(data.missing_fields, function(i, item) {
			$("label[for='" + item + "']").addClass('error'); // labels
			$("tbody." + item + " tr th").addClass('error');  // table cell header
			$("tbody." + item + " tr th span.hidden").removeClass('hidden')
			$("tbody." + item + " tr th h3").addClass('error');  // table cell header
		});
		
		// Clean up old modal boxes
		for(var n in modals) {
			modals[n].dialog('close');
		}
		escape = false;
		
		// Get all incorrect fields and open corresponding modal
		$.each(data.missing_fields, function(i, item) {
			if ( $("tbody."+ item).parents('.form1').length ) {
			 	escape = true;
			}
		});
		
		// Walk through all modals and open modal with errors in it
		for(var n in modals) {
			if(!escape){
				$.each(data.missing_fields, function(i, item) {
					if ( $("tbody."+ item).parents('#modal-' + n).length ) {
						modals[n].dialog('open');
						escape = true;
					}
				});
			}
		}
			
		alert($("input[type='hidden'][name='errormessage']").attr("value"));
	} else if (data.debug) {
		alert(data.debug);
	} else {
		alert('Error');
	}
}

function function_succes(data)
{
	window.location = $("input[type='hidden'][name='redirect']").attr("value");
}
