﻿/*
jplaceholder.js

usage:

$("form").jplaceholder(args);

@param args {
	force: boolean, // execute the this plug-in even the browser supports placeholder feature
	showOnFocus: booealn // hide placeholder text when form input is focusing
}
*/


(function($) {
$.fn.jplaceholder = function(args) {
    var el = document.createElement("input"),		
		// default config
		o = {
			force: false,
			showOnFocus: false
		};					
		
		o = $.extend(o, args);   
	/*
    if (!o.force && "placeholder" in el) {
        return this;
    }
	*/
    $(this).find('input[type!="hidden"], textarea').each(function (i) {
		var t = $(this);
		
		if (!t.attr('jplaceholder')) {return this;}
          
		var	p = t.parent(),				
        	val = t.attr('jplaceholder'),
			ph = $('<span class="jplaceholder">' + val + '</span>'),
			isPassword = t.attr('type')=='password',
			css = {
				position: 'absolute',
				top: (t.offset().top - p.offset().top + 2) + 'px',
				left: (t.offset().left - p.offset().left + 2) + 'px',
				font_family: t.css('font-family'),
				font_size: t.css('font-size'),
				font_weight: t.css('font-weight'),
				padding_left: t.css('padding-left'),  
				padding_top: t.css('padding-top'),
				color: t.css('color')
			},		
			timer;
			
		p.css('position','relative').css('zoom',1);
		
		
		t.attr('placeholder',''); // prevent conflict with browser supports placeholder
		t.css('visibility','visible');					
		
		for (var k in css) {
			ph.css(k.replace(/_/,'-'),css[k]);
		}
		 
		ph.insertAfter(this).hide();  
		
		if (t.val()=='') {
			ph.show();	
		} 
		
		ph.click(function(){
			t.focus();
		});
		t.focus(function(e){	
								
			if ((!o.showOnFocus) || (t.val()!='')) {
				ph.fadeTo('fast', 0);
				return;	
			}					
			
			ph.addClass('focus').fadeTo('fast',0.5);
			
			if (isPassword) {			
				timer = setInterval(function(){
					if (t.val()!='') {
						//ph.hide();
						ph.fadeTo('fast', 0);
						timer = clearInterval(timer);
					};
				}, 50);
			} else {			
				t.keypress(function(e){
					//ph.hide();
					ph.fadeTo('fast', 0);
				});
			}
		}); // focus

		t.blur(function(e){
			if (timer) {
				clearInterval(timer);	
			}
			if (t.val()=='') {
				ph.fadeTo('fast', 1).removeClass('focus');
			}
		}); //blur
 			
	}); // find().each
	
	return this;
};// jplaceholder

})(jQuery);
