/**
 * Championship Manager Shop - JavaScript Library
 * jQuery Form Fields plugin
 *
 * @date 2009-07-01
 * @version 1.2
 * @copyright Eidos Interactive Ltd 2009
 */

(function ($) {
  /**
   * Form Fields Plugin
   *
   * adds input fields behaviour to input fields with class 'field-clear'
   *  + clears field on focus (except if custom value was entered)
   *  + fills field with default value if field is empty
   */
  $.fn.form_fields = {
    _params: {
      'class_clear': 'field-clear',
      'class_focus': 'field-focus'
    },
    initialize: function() {
      var plugin_form_fields = this; // Reference to plugin
      // Parse all input fields with 'class_clear' class
      jQuery('.'+this._params.class_clear).each(function(i) {
        var o = jQuery(this);
        // store original value
        o.attr('original_value', o.attr('value'));
        // add behaviours to each input field
        o.bind('focus', function(e) {
          // Only clear if value = original value
          //  => no custom value was entered
          if (jQuery(this).attr('value') == jQuery(this).attr('original_value')) {
            // If item has 'class_focus':
            // do not clear until keypress
            if (jQuery(this).attr('class').indexOf(plugin_form_fields._params.class_focus) > 0) {
              jQuery(this).setCursorPosition(0); // move cursor to beginning of input
              plugin_form_fields.bind_keydown(this);
            } else {
              jQuery(this).attr('value', '');
            }
          }
        });
        o.bind('blur', function(e) {
          // Only restore original if value = empty
          if (jQuery(this).attr('value') == '') {
            jQuery(this).attr('value', jQuery(this).attr('original_value'));
          }
        });
      });
      // Parse all input fields with 'class_clear' class
      jQuery('.'+this._params.class_focus).each(function(i) {
        jQuery(this).focus();
      });
    },
    
    bind_keydown: function(o) {
      jQuery(o).bind('keydown', function(e) {
        // unbind() does not work with IE, use boolean instead
        if (typeof(jQuery(o).attr('bound')) === 'undefined') {
          jQuery(o).attr('value', ''); // Clear content
          jQuery(o).unbind(); // remove keypress bind after first key strike
          jQuery(o).attr('bound', true);
        }
      });
    }
  };
  
  $.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  };

})(jQuery);

jQuery(document).ready(function() {
  jQuery(document).form_fields.initialize();
});