/**
 * nmcFormHelper plugin - v1.0.5
 * Author: Eli Van Zoeren
 * Copyright (c) 2009 New Media Campaigns
 * http://www.newmediacampaigns.com 
 **/
var nmcFormHelper = {
  
  init : function() {
    nmcFormHelper.input_classes.init();
    
    // Create a new element to test for html5 attributes
    var i = document.createElement('input');
    
    // Check if "placeholder" attribute is available
    if ( !('placeholder' in i) ) nmcFormHelper.placeholder.init();
    
    // Check if "autofocus" attribute is available
    if ( !('autofocus' in i) ) nmcFormHelper.autofocus.init();
    
    // Check if "required" or "pattern" attributes are available
    if ( !('required' in i && 'pattern' in i) ) nmcFormHelper.validation.init();
  },
  
  input_classes : {
    init : function() {
      $(':input').each(function() {
        var inputType = $(this).attr('type');
        if (inputType == 'undefined') { inputType = 'text' }      
        $(this).addClass('input-' + inputType);
      });
    }
  },
  
  placeholder : {
    styling : {'color':'#aaa'},
    
    init : function() {
      // Set up the event handlers to show and hide placeholder
      $('[placeholder]')
        .focus( nmcFormHelper.placeholder.hide )
        .blur( nmcFormHelper.placeholder.show )
        .each( nmcFormHelper.placeholder.show );
        
      // Don't submit placeholder values
      $('form').submit(function() {
        $('[placeholder]', this).each(function() {
          $input = $(this);
          // Clear the value if it is still the placeholder
          if ( $input.val() == $input.attr('placeholder') ) $input.val('');
          return true;
        });
      });
      
      // Hide the placeholders on unload to prevent them
      // from re-appearing if the user clicks the "back" button
      $(window).unload( function() {
        $('[placeholder]').each( nmcFormHelper.placeholder.hide );
      });
    },
    
    show : function() {
      $input = $(this);
      
      if ( $input.val() == '' )
      {
        // If it's a password field, replace with text
        if ($input.attr('type') == 'password') {
          $input = nmcFormHelper.placeholder.replacePassword($input,true);
        }

        // Set the placeholder styling
        $input.css(nmcFormHelper.placeholder.styling);
        
        // Set the value to the placeholder
        $input.val($input.attr('placeholder'));
      }   
    },
    
    hide : function() {
      $input = $(this);
      
      if ( $input.val() == $input.attr('placeholder') )
      {
        // If it's a password field, replace with text
        if ($input.data('type') == 'password') {
          $input = nmcFormHelper.placeholder.replacePassword($input,false);
        }
        
        // Remove the placeholder
        $input.val('');
        
        // Remove the placeholder styling
        $input.attr('style',null);
        
        // The input sometimes loses focus unless
        // I reset it at the end of this function
        $input.focus();
      }
    },
    
    replacePassword : function($field, direction, focus) {
      newHtml = $('<div>').append($field.clone()).remove().html();
      
      newHtml = newHtml.replace(/type=["']?(.+?)["']?/i, '');
      if (direction == true) {
        newHtml = newHtml.replace('input', 'input type="text"');
      } else {
        newHtml = newHtml.replace('input', 'input type="password"');
      }
      
      return $(newHtml)
        .replaceAll($field)
        .data('type','password')
        .focus( nmcFormHelper.placeholder.hide )
        .blur( nmcFormHelper.placeholder.show );
    }
  },

  autofocus : {
    init : function() {      
      // Set the focus to the first one
      $('[autofocus]').slice(0, 1).focus();
    }
  },
  
  validation : {
    init : function() {
      $('form').submit( nmcFormHelper.validation.check );
    },
    
    check : function() {
      $form = $(this);
      $invalidElements = $([]);
      
      // Hide any currently displayed error before we re-check
      var allElements = $('input, textarea', $form);
      allElements.removeClass('requiredError patternError');
      nmcFormHelper.validation.hideErrors( allElements );
      
      // Check for required inputs
      $('input[required], textarea[required]', $form).each(function() {
        var $element = $(this);
        
        if ( $element.val() == '' || $element.val() == $element.attr('placeholder') )
        {
          $element.addClass('requiredError');
          $invalidElements = $invalidElements.add($element);
        }
      });
      
      // Check for pattern mismatches
      $('input[pattern], textarea[pattern]', $form).each(function() {
        var $element = $(this);
        var pattern = new RegExp( '^(?:'+$element.attr('pattern')+')$' );
        
        if ( !( pattern.test($element.val()) ) )
        {
          $element.addClass('patternError');
          $invalidElements = $invalidElements.add($element);
        }
      });
      
      // If there were errors
      if ($invalidElements.length > 0)
      {
        // Pass off all the invalid elements to the error-showing function
        nmcFormHelper.validation.displayErrors($invalidElements);
                    
        // Cancel the form submission
        return false;
      }
    },
    
    hideErrors : function($elements) {
      $elements.removeClass('hasError');
      $elements.siblings('label.errorMsg').remove();
    },
    
    displayErrors : function($elements) {
      $elements.each(function() {
        $this = $(this);
        var errorMsg = $this.attr('title') ? $this.attr('title') : 'There was an error with this field';
        $this.after('<label for="' + $this.attr('id') + '" class="errorMsg">' + errorMsg + '</label>');
      }).addClass('hasError');
    }
  }
    
}
