var form_itl = ['<p>You will be redirect to the next page in ', ' seconds. <a href="', '">Click here</a> to go there now.</p>'];

function form_update(data, config)
{
	var have_errors = data.errors && data.errors.length > 0;
	
	//if we have a plain old instant URL redirect
	if(data.url && !data.message && !have_errors && data.url_delay <= 0)
	{
		window.location.assign(data.url);
	}
	
	//get our form object
	var form = $(config.form).parents('.form:eq(0)'); //'#form_'+data.form_name);
	
	//enable the submit button again	
	//original search had "[original_value]" in it
	form.find('input[type=submit][disabled]').each(function() {
		$(this).removeAttr('disabled');//.val($(this).attr('original_value')).removeAttr('original_value');
	});
	
	//need to scrape the form clean of any previous messages
	form.find('.form-notice').remove();
	form.find('.field-single,.field-multi').removeClass('field-error');
	
	
	
	//if we have no errors and are told to remove the form, do it
	if(!have_errors && data.remove_form)
	{
		form.find('form').remove();
	}
	
	//if we have errors or a message or a redirect URL with a delay
	if(data.message || have_errors || (data.url && data.url_delay > 0))
	{
		var notice = $('<div class="form-notice"></div>');
		
		//if we have a message
		if(data.message)
			notice.append('<p>'+data.message+'</p>');
			
		if(have_errors)
		{
			var errors = $('<ul></ul>');
			var error, key;
			for(key in data.errors)
			{
				error = data.errors[key];
				//if the error has a field, flag the field as having an error
				if(error.field)
				{
					form.find(error.field).addClass('field-error');
				}
					
				//add error to the list
				errors.append('<li>'+error.error+'</li>');
			}
			
			//add errors to notice
			notice.append(errors);
		}
		
		//if we have a url timed redirect and no errors
		if(!have_errors && data.url && data.url_delay > 0)
		{
			notice.append(form_itl[0]+data.url_delay+form_itl[1]+data.url+form_itl[2]);
			setTimeout("window.location='"+data.url+"';", data.url_delay*1000);
		}
		
		//add notice to the form
		form.prepend(notice);

		//reload the recaptcha if we have one and we didn't remove the form
		if ((have_errors || !data.remove_form) && typeof Recaptcha != 'undefined') 
		{ 
			if($('#recaptcha_div').length > 0)
			{
				Recaptcha.destroy();
				Recaptcha.create("6LdOjAUAAAAAAFP8vWWxgODxcXu__EShfbqRoAba", "recaptcha_div", { theme: "clean" });
			}
			else if($('#recaptcha_image').length > 0)
			{
				Recaptcha.reload(); 
			}
		}
		
		//scroll to the notice
		//get the offset of the parent
		var offset = form.offset();
		window.scrollTo(0, $(window).height() <= offset.top ? offset.top : 0);
	}
}

function form_submit(form, type, callback)
{
	//html type, we do a normal submit
	if(type == 'html')
	{
		if(callback)
			return callback(form);
		else
			//return true so the form submits
			return true;
	}
	//ajax/iframe submit
	else
	{
		//if we have fck instances, tell them to update their hidden input fields
		$(form).find('input:hidden.fckeditor').each( 
			function()
			{
				FCKeditorAPI.GetInstance(this.id).UpdateLinkedField();
			}
		);
		
		//figure out the callback
		callback = typeof callback == 'function' ? callback : form_update;
		
		//submit the request
		$(form).ajaxSubmit(
			{
				iframe: (type == 'iframe'),
				cache: false,
				success: function(data) { callback(data, {type: 'form', form: form}); },
				error: form_error,
				dataType: 'json'
			}
		);
		
		//disable the submit button
		$(form).find('input[type=submit]').each(function() {
			$(this).attr('disabled', 'disabled');//.attr('original_value', $(this).val()).val('Submitting...');
		});
		
		//return false so form doesn't submit
		return false;
	}
}

function form_unsubmit(obj)
{
	var submit = obj.find('input[type=submit][original_value][disabled]');
	submit.removeAttr('disabled').val(submit.attr('original_value')).removeAttr('original_value');
}

function form_error(XMLHttpRequest, textStatus, errorThrown)
{
	//rollback the submit button
	var submit = $('input[type=submit][original_value][disabled]');
	if(submit.length > 0)
		submit.removeAttr('disabled').val(submit.attr('original_value')).removeAttr('original_value');
	//alert user about the error
	alert('A fatal error was encountered while trying to process the form. Debug info: '+textStatus+
		' Response Text('+XMLHttpRequest.readyState+')('+XMLHttpRequest.status+')('+XMLHttpRequest.statusText+'): '+XMLHttpRequest.responseText);
}

function hide_field(obj)
{
	//alert($('#fd_test_multi_check').find('[name="test[multi_check][]"]').fieldValue().join(', '));
	
	//alert(eval("$.inArray('test2', ['test', 'pie']) >= 0"));
	
	//alert($(obj).parents('div.form').attr('id').substr(5));
	
	//$(obj.form).find('label.field-name:not(* em)').css('font-weight', 'bold');
	//$(obj.form).find('label.field-name:not(:has(em))').append('<em>*</em>');
	
	//bind
	$('#fd_test_select_test').bind('change', [{ value: 'two', require: ['date_test', 'single_check'], optional: ['text_test'], disable: ['radio_test'] }], update_field_status);
}

function update_form_status(event)
{
	//alert(event.target.name);
	//get the value of the field that triggered this and create an array to store processed fields
	var values = $(event.target.form).find('[name="'+event.target.name+'"]').fieldValue(), form = $(event.target.form);
	
	//run an each on the event.data, which should store the
	$.each(event.data, function(index, rule) 
	{
		//if we match the rule condition or the rule value
		if((rule.condition && eval(rule.condition)) || (rule.value && $.inArray(rule.value, values) >= 0))
		{			
			//take care of each action we can do: disable, require, optional
			if(rule.require && rule.require.length > 0)
				form.find(rule.require.join(',')).show()
					.find(':input').trigger('show').end()
					.find('label.field-name:not(:has(em))').append('<em>*</em>');
					
			if(rule.optional && rule.optional.length > 0)
				form.find(rule.optional.join(',')).show()
					.find(':input').trigger('show').end()
					.find('label.field-name em').remove();
				
			//this should probably be done first so that the others work better, 
			//but I'm not changing it yet because of how it might break stuff
			if(rule.disable && rule.disable.length > 0)
				form.find(rule.disable.join(',')).hide();
				
			if(rule.show && rule.show.length > 0)
				form.find(rule.show.join(',')).show()
					.find(':input').trigger('show');
		}
	});
}

function registration_update(data, config, win)
{
	//if our data.type is registration, that means we finished
	if(data.type == 'registration')
	{
		//remove any window unload bindings we might have
		if(win)
			win.onbeforeunload = null;
		else
			window.onbeforeunload = null;

		//need to add the message and remove the form
		var form = $(config.form).parents('.form:eq(0)');
		//removing the form
		form.find('form').remove();
		//remove existing notice
		form.find('.form-notice').remove();

		//if we have a plain old instant URL redirect
		if(data.url && !data.message && data.url_delay <= 0)
		{
			window.location.assign(data.url);
		}
		else
		{
			//add the message
			form.append('<div class="form-notice"><p>'+data.message+'</p></div>');
		}

		return null;
	}
	
	//if we have errors, do the normal form_update
	if(data.errors && data.errors.length > 0 || data.type != 'form')
	{
		form_update(data, config);
		return null;
	}
	
	var form = $(config.form).parents('.form:eq(0)');
	form.find('input[type=submit][disabled]').removeAttr('disabled');

	//need to scrape the form clean of any previous messages
	//form.find('.form-notice').remove();
	//form.find('.field-single,.field-multi').removeClass('field-error');
	
	//replace <form> with our new one
	var new_form = $(data.form_data);
	form.replaceWith(new_form);
	//form.remove();
	
	//some recaptcha stuff here
	var recaptcha = $('#recaptcha_div');
	if(recaptcha.length > 0)
	{
		$.getScript('http://www.google.com/recaptcha/api/js/recaptcha_ajax.js', function() {
			Recaptcha.create("6LdOjAUAAAAAAFP8vWWxgODxcXu__EShfbqRoAba", "recaptcha_div", { theme: "clean" });
		});
	}

	var offset = new_form.offset();
	if(offset)
		window.scrollTo(0, $(window).height() <= offset.top ? offset.top : 0);
	
	return new_form;
}

function stem_registration(data, config)
{
	registration_update(data, config);
}

function support_update_tournaments(event)
{
	//get the value of our field
	var value = $(event.target).fieldValue()[0];
	var tournament = $(event.target.form).find('select[name$="[tournament]"]');
	
	
	//if our value is empty, set the select options to be "Please select an event first."
	if(value == '')
	{
		tournament.empty().append('<option value="">Please select an event first.</option>').trigger('change');
	}
	//send an ajax request for the data
	else
	{
		//update function for our tournament select
		function update_tournament(data)
		{
			//if our response type isn't the one we expect, have the form parse the response
			if(data.type != 'support_tournaments')
				return form_update(data, {type: 'support_tournaments', form: event.target.form});
			//if we have stuff to set, set it
			if(data.tournaments)
			{
				tournament.empty();
				$.each(data.tournaments, function (tournamentid, name)
				{
					tournament.append('<option value="'+tournamentid+'">'+name+'</option>');
				});
			}
			//otherwise put in a blank entry
			else
			{
				tournament.empty().append('<option value="">Not Applicable</option>');
			}
			tournament.trigger('change');
		}
		//make our data request
		$.getJSON('/?action=support_tournaments&event_id='+value, update_tournament);
	}
}

function support_game_open(id)
{
	//get the form
	var form = $('#'+id).parents('form:eq(0)');
	var event_id = form.find('select[name$="[event]"]').fieldValue()[0];
	var tournamentid = form.find('select[name$="[tournament]"]').fieldValue()[0];
	window.open('/?action=support_game&event_id='+event_id+'&tournamentid='+tournamentid+'&id='+id, '_blank', '');
	return false;
}

function support_game_reset(id)
{
	$('#'+id)
		.find('input:hidden').val('').end()
  	.find('.game-label').html('').hide().end()
  	.find('a.select-match').text('Select Match').end()
  	.find('a.clear-match').hide();
}

function clear_default(obj, str)
{
	if($(obj).val() == str)
		$(obj).val('');
}

