/*
	Original jQuery ghostInput Plugin by Michel Gotta / michel@michelgotta.de https://github.com/michelgotta/jquery-ghostinput-plugin
	Handy modifications by Johnny Benson / johnny@punkave.com http://www.punkave.com
	Added slugify input option
	Added limit chars input option
	Added sending options back through the onChange callback
*/

$.fn.ghostInput = function(options, change)
{
  options = $.extend({
    ghostText: ".foo.bar",
    ghostLabel: undefined,
		ghostSlugify: false,
		ghostLength: false,
		ghostLimit: false
  },options);

  ghost = {
    init : function(element) {
      wrapper = $('<div/>').addClass('ghostInput_wrapper').attr('id', 'ghostInput_wrapper_'+element.attr('id'));
			element.addClass('ghostinput');
			element.data('lastVal','');
      element.wrap(wrapper);
      element.after($('<span/>').addClass('ghostInput_input').html($('<span/>').addClass('ghostInput_copy')));
      element.focus(function(event){
			  $('#'+wrapper.attr('id')).addClass('focused');
			}).blur(function(event){
			  $('#'+wrapper.attr('id')).removeClass('focused');				
			});
      if (options.ghostLabel!==undefined ) {
        element.before( $('<label/>').attr({'for': element.attr('name'), 'class': 'ghostInput_label'}).html(options.ghostLabel) );
      }
    },
		slugify : function(val)
		{
			return val.replace(/\s/g,'-').replace(/[^a-zA-Z0-9\-]/g,'');			
		},
		limit : function(val)
		{
			return val.substring(0, options.ghostLength);
		},
    textchange : function() 
		{
			if (options.ghostSlugify) 
			{
				if ($(this).val() !== $(this).data('lastVal')) 
				{
					$(this).val(ghost.slugify($(this).val()));				
				}				
			}
			if (options.ghostLength && (options.ghostLength <= $(this).val().length))
			{
				$(this).val(ghost.limit($(this).val()));
				options.ghostLimit = true; // We have reached the ghostLength				
			}
			else
			{
				options.ghostLimit = false; // We have not reached the ghostLength				
			}
      if ($(this).val() !== wrapper.find('.ghostInput_copy').html()) {
        wrapper = $('#ghostInput_wrapper_'+$(this).attr('id'));
        if ($(this).val() !== '') {
          wrapper.find('.ghostInput_label').hide();
          wrapper.find('.ghostInput_input').show().html($('<span/>').addClass('ghostInput_copy').html($(this).val() ));
          wrapper.find('.ghostInput_copy').after(options.ghostText);
        } else {
          wrapper.find('.ghostInput_label').show();
          wrapper.find('.ghostInput_input').fadeOut(100, function() {
            $(this).html('');
          });
        };
        if (options.change!==undefined) {
          options.change(options);
        }
      }
			$(this).data('lastVal', $(this).val());
    }
  };
  ghost.init($(this));
  $(this).bind('keyup', ghost.textchange);
}
