coss.PlaceholderElementBinding = {
	implementation : {
		onBindingAttached : function () {
			var el;
			var instances = coss.PlaceholderElementBinding._instances;
			
			//skip element if...
			if (
				$(this).hasClass('w-placeholder-bound') //already bound
				|| ('placeholder' in this && !('attachEvent' in window)) //browser supports placeholders natively
				|| !('activeElement' in document) //browser doesn't support document.activeElement
			)
			return;
			
			instances.push(this);
			
			this._coss_PlaceholderElementBinding = {};
			
			el = this.ownerDocument.createElement('div');
			el.style.position = 'absolute';
			el.style.color = 'GrayText';
			el._coss_PlaceholderElementBinding = {textbox : this};
			$(el).bind('mousedown', coss.PlaceholderElementBinding._handlePlaceholderMousedown);
			this._coss_PlaceholderElementBinding.placeholder = el;
			this.ownerDocument.body.appendChild(el);
			
			$(this).bind('focus', coss.PlaceholderElementBinding._handleTextboxFocus);
			$(this).bind('blur', coss.PlaceholderElementBinding._handleTextboxBlur);
			
			coss.PlaceholderElementBinding._syncPlaceholder(this);
			
			$(this).addClass('w-placeholder-bound');
			
			if (instances.length == 1) {
				$(window).bind('resize', coss.PlaceholderElementBinding._handleAndSyncAll);
				setInterval(coss.PlaceholderElementBinding._handleAndSyncAll, 100);
			}
		}
	},
	
	_instances : [],
	
	_syncPlaceholder : function (aEl, aFocused) {
		var offset;
		var focused = aFocused == true;
		var placeholder = aEl._coss_PlaceholderElementBinding.placeholder;
		
		offset = $(aEl).offset();
		
		$(placeholder).text(aEl.getAttribute('placeholder'));
		placeholder.style.top = (offset.top + parseInt($(aEl).css('border-top-width')) + parseInt($(aEl).css('padding-top'))) + 'px';
		placeholder.style.left = (offset.left + parseInt($(aEl).css('border-left-width')) + parseInt($(aEl).css('padding-left'))) + 'px';
		
		if (focused) {
			placeholder.style.display = 'none';
		}
		else {
			placeholder.style.display = aEl.value == '' ? '' : 'none';
		}
	},
	
	_handlePlaceholderMousedown : function () {
		this._coss_PlaceholderElementBinding.textbox.focus();
	},
	
	_handleTextboxFocus : function () {
		coss.PlaceholderElementBinding._syncPlaceholder(this, true);
	},
	
	_handleTextboxBlur : function () {
		coss.PlaceholderElementBinding._syncPlaceholder(this, false);
	},
	
	_handleAndSyncAll : function () {
		var i;
		var instances = coss.PlaceholderElementBinding._instances;
		
		for (i = 0; i < instances.length; i++) {
			coss.PlaceholderElementBinding._syncPlaceholder(instances[i], document.activeElement === instances[i]);
		}
	}
};

$(document).bind('ready', function () {
	var i;
	var els = $('input[placeholder]');

	for (i = 0; i < els.length; i++) {
		coss.attachElementBinding(els[i], coss.PlaceholderElementBinding);
	}	
});
