$.fn.clearForm = function() {
	return this.each(function() {
	  var type = this.type, tag = this.tagName.toLowerCase();
	  if (tag == 'form')
	    return $(':input',this).clearForm();
	  if (type == 'text' || type == 'password' || tag == 'textarea')
	    this.value = '';
	  else if (type == 'checkbox' || type == 'radio')
	    this.checked = false;
	  else if (tag == 'select')
	    this.selectedIndex = 0;
	});
};

// let's start the jQuery while I wait.
// step 1: onload - capture the submit event on the form.
$(function() { // onload...do
	$('#feedback-block #sending_img')
    .hide()  // hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    });

	$("#feedback-button").click(function() {
		$('#feedback-button').hide();
		$("#feedback-block").show("slow");
		$("#feedback-email").hide();
	});
	
   	$("#feedback-block .close").click(function() {
		$("#feedback-block").hide("slow");
		$('#feedback-button').show();
		$('#feedback_form').clearForm();
		$('#feedback-block #feedback_message').html("");
   	});
	
	$("#feedback-reason").change(function(){
		var reason = $("#feedback-reason").val();
		if ( reason == "help" && !logged_in_user )
			$("#feedback-email").show();
		else
			$("#feedback-email").hide();
	});
	
	$('#feedback_form').submit(function() {
	  // now we're going to capture *all* the fields in the
	  // form and submit it via ajax.
	  
	  // :input is a macro that grabs all input types, select boxes
	  // textarea, etc.  Then I'm using the context of the form from 
	  // the initial '#contactForm' to narrow down our selector
	  var inputs = [];
	  $(':input', this).each(function() {
	    inputs.push(this.name + '=' + escape(this.value));
	  })
	  
	  // now if I join our inputs using '&' we'll have a query string
	  jQuery.ajax({
	    data: inputs.join('&'),
	    url: url_send_feedback,
		dataType: "json",
	    error: function() {
	      console.log("Failed to submit");
		  alert("Oops, an error occurred! Please contact us at contact@indee.tv and let us know.");
	    },
	    success: function(data) { 
		  	$('#feedback-block #feedback_message').html(data.message);
	    }
	  }) // checkout http://jquery.com/api for more syntax and options on this method.
	  
	  // by default - we'll always return false so it doesn't redirect the user.
	  return false;
	})
})
