/**
 * Snepo contact JS
 *
 * Here we provide an AJAX implementation for the contact form, with a normal POST fallback
 */
 
 function resetSendButton(){
 	$('form.snepo_contact_form').find( 'input[type="submit"]' ).val('send');
 }
$(function() {
  
  //attach focus to the inputs
  $('form.snepo_contact_form input[type="text"], form.snepo_contact_form textarea').each(function(index){
  	$(this).bind('focus',function(){
  		if($.trim($(this).val()) == $(this).attr('rel')){
  			$(this).val('');
  		}
  	});
  	$(this).bind('blur',function(){
  		if($.trim($(this).val()) == ''){
  			$(this).val($(this).attr('rel'));
  		}
  	});
  	
  });
  // Capture the Form submission
  $( 'form.snepo_contact_form' ).submit(function() {
    //check if the inputs have been edited
    var send_mail = true;
    $('form.snepo_contact_form input[type="text"], form.snepo_contact_form textarea').removeClass('contact_error');
    $('form.snepo_contact_form input[type="text"], form.snepo_contact_form textarea').each(
        function(index){
        	var inp = $(this);
        	if($.trim(inp.val()) == inp.attr('rel')){
        		send_mail = false;
        		inp.addClass('contact_error');
        	}
        }
    );
    
    if(!send_mail){ 
    	$( this ).find( 'input[type="submit"]' ).val('Oops!');
	    setTimeout('resetSendButton()', 2000);
    	return false;
    }
    // Disable the form and notify the user we're sending
    $( this ).find( 'input[type=submit]' )
             .attr( 'disabled', 'disabled' )
             .val( 'Hold on!' );
    
    // Get form data
    var data = $( this ).serialize();
    
    // Fix scope
    var form_element = this;
    // POST and receive
    $.ajax({
      type: 'POST',
      url: $( this ).attr( 'action' ),
      data: data,
      cache: false,
      dataType: 'json',
      success: function( data ) {
        // Check for success
        if ( data.success )
        {
          // Success message
          $( form_element ).find( 'input[type="submit"]' ).val('Thanks!');
          //reset the form values
          $('form.snepo_contact_form input[type="text"], form.snepo_contact_form textarea').each(
		        function(index){
		            var inp = $(this);
		            inp.val(inp.attr('rel'));
		            inp.removeClass('contact_error');
		        }
		    );
		    setTimeout('resetSendButton()', 2000);
        } else {
          // Error message
          $( form_element ).find( 'input[type="submit"]' ).val('Oops!');
          setTimeout('resetSendButton()', 2000);
        }
      },
      error: function() {
        // Error message
        $( form_element ).find( 'input[type="submit"]' ).val('Oops!');
        setTimeout('resetSendButton()', 2000);
      },
      complete: function() {
        // Enable the form
        $( form_element ).find( 'input[type="submit"]' ).removeAttr('disabled');
      }
    });
    
    // Return false to stop submission
    return false
  });
  
});
