var passwordFields = {};

// test for native support by creating a new input element and seeing if the prototype includes a placeholder
function supportsNativePlaceholders() {
	var i = document.createElement('input');
	return 'placeholder' in i;
}

// initialize script-based support (called if native support is not found)
// 1. prefill any fields that have placeholders
// 2. attach focus/blur event handlers to fill or clear fields as necessary
// 3. attach event handler to forms to make sure to clear placeholder text before submission
function fakePlaceholderSupport() {
	if (!supportsNativePlaceholders()) {
		inputs = Ext.select('input, textarea');
		inputs.each(function(el) {
			input = Ext.get(el.dom);
			fillField(input);
			input.on('blur', fillField);
			input.on('focus', clearField);
		});
		forms = Ext.select('form');
		forms.each(function(el){
			form = Ext.get(el.dom);
			form.on('submit', function(e,t) {
				inputs = Ext.fly(t).select('input, textarea');
				inputs.each(function(el) {
					clearField(el);
				});
			});
		});
	}
}

// fillField is called on DOM ready and whenever an input loses focus
// it handles checking the contents, filling in the text, and changing color to gray
// as well, password fields will have their type changed to text so the placeholder can be read
function fillField(el) {
	// most often called as an event handler, in which case "el" will be an event object -- grab the dom node from that
	if (el.target) {
		el = el.target; 
	}
	el = Ext.get(el);
	ph = el.getAttribute('placeholder');
	val = el.getValue();
	if (Ext.isEmpty(val) && ph) {
		el.dom.value = ph;
		el.setStyle({ color: '#aaa' }).addClass('placeholder');
		if (el.getAttribute('type') == 'password') {
			if(!Ext.isIE)
				el.set({ 'type': 'text' });
			passwordFields[Ext.id(el)] = true; // store a reference to this node so it can be switched back on focus
		}
	}
}

// called on focus and before forms are submitted
// checks for any field that contains placeholder text, and clears/readies it for input
// also changes any password fields back to 'password' type to mask input
function clearField(el) {
	if (el.target) {
		el = el.target;
	}
	el = Ext.get(el);
	ph = el.getAttribute('placeholder');
	val = el.getValue();
	if (val == ph) {
		el.dom.value = '';
		el.setStyle({ color: '' }).removeClass('placeholder');
		if (passwordFields[Ext.id(el)]) {
			if(Ext.isIE)
				el.dom.select();
			else
				el.set({ 'type': 'password' });
		}
	}
}

if (Ext) {

Ext.onReady(function() {
	fakePlaceholderSupport();
});

}
