
/*
 * @fileoverview JQuery plugin to add HTML5 placeholder
 * attribute to all browsers
 *
 * @author humjay jason@humjay.com
 * @version 0.1
 */

(function($){
	
	// This create an observer pattern with forms that allow our new fields to listen to submits.
	function Broadcaster(el, evts) {
		var subscribers = [];
		var self = this;
		
		$(el).bind(evts, function(e){
			self.notify(e.type)
		});
		
		this.notify = function(evt) {
			$.each(subscribers, function(i, el){
				el.notifiedOf(evt);
			});
			return this;
		};
		
		this.addSubscriber = function(sub) {
			var exists = false;
			$.each(subscribers, function(i, el){
				if(sub === el) exists = true;
			});
			
			if(!exists) subscribers.push(sub);
		}
	}
	
	$.humjay = $.humjay || {};
	$.humjay.placeholder = {
		conf: {
			placeholderAttribute: 'placeholder'
		}
	}
	function Placeholder(el, conf) {
		el = $(el);

		// check if this is a correct element
		if($.inArray(el.attr('tagName').toUpperCase(), "INPUT TEXTAREA".split(' ')) === -1) { return false; }

		// grab what we need and store in private properties
		var self	= this;
		var placeholder = el.attr($.humjay.placeholder.conf.placeholderAttribute);

		// populate the placeholder text
		el.val(placeholder);
		
		// assign handlers
		el
		.focus(function(){
			if(el.val() === placeholder) el.val("");
		})
		.blur(function(e){
			if(el.val() === "") el.val(placeholder);
		});


		this.clearIfDefault = function() {
			if(el.val() === placeholder) el.val("");
		};
		
		this.notifiedOf = function(evt) {
			if(evt === "submit") this.clearIfDefault();
		}
	
	};
	
	$.fn.broadcaster = function(evts) {
		this.each(function(i) {
			var el = new Broadcaster($(this), evts);
			$(this).data("broadcaster", el);
		});
	}

	// jQuery plugin implementation
	$.fn.placeholder = function(conf) { 
		
		if(!('placeholder' in document.createElement('input'))) {

			conf = $.extend({}, $.humjay.placeholder.conf, conf); 

			this.each(function() {		
				if($(this).attr('placeholder')) {

					var el = new Placeholder($(this), conf);
					$(this).data("placeholder", el);
				
					var owner = $(this).parents("form").last()
				
					if(!owner.data("broadcaster")) owner.broadcaster("submit");
		
					owner.data("broadcaster").addSubscriber(el);
				}
				
			});
		}

		return this;

	};
	

})(jQuery);


