﻿/**
 * Substitues default value in field when it's empty
 * @param {Element} input Form element
 * @param {String} value Default value (placeholder)
 * @param {String} cssFilled CSS class name when field is filled
 * @param {String} cssEmpty CSS class name when field is empty
 */
function InputPlaceholder(input, value, cssFilled, cssEmpty){
	if(input)
		this.init(input, value, cssFilled, cssEmpty);
}

//Check if we have native placeholder support (like in Safari)
InputPlaceholder.nativePlaceholder=(navigator.userAgent.match(/Safari/));

InputPlaceholder.prototype.init=function(input, value, cssFilled, cssEmpty){
	var thisCopy = this;
	this.Input = input;
	this.Value = value;
	this.CssFilled = cssFilled;
	this.CssEmpty = cssEmpty;
	
	if(InputPlaceholder.nativePlaceholder){
		input.setAttribute('placeholder', value);
	}
	else{
		this.SaveOriginal = (input.value == value);
		this.setupEvent(this.Input, 'focus', function() {return thisCopy.onFocus()});
		this.setupEvent(this.Input, 'blur',  function() {return thisCopy.onBlur()});
	
		if(input.value == '') this.onBlur();
	}
	
	this.setupEvent(this.Input, 'keyup', function() {return thisCopy.onKeyDown()});		
}

InputPlaceholder.prototype.setupEvent = function (elem, eventType, handler){
	Common.Event.add(elem, eventType, handler);
}

InputPlaceholder.prototype.onFocus = function(){
	if (!this.SaveOriginal &&  this.Input.value == this.Value)
		this.Input.value = '';
	else
		this.clearClass();
}

InputPlaceholder.prototype.isFilled=function(){
	return (this.Input.value != '' && this.Input.value != this.Value);
}

/**
 * Removes all placeholder-specific classes from input
 */
InputPlaceholder.prototype.clearClass=function(){
	this.removeClass(this.CssEmpty);
	this.removeClass(this.CssFilled);
}

/**
 * Removes class from input element
 * @param {String} c Class name
 */
InputPlaceholder.prototype.removeClass=function(c){
	if(c)
		Common.Class.remove(this.Input, c);
}

/**
 * Adds class to input element
 * @param {String} c Class name
 */
InputPlaceholder.prototype.addClass=function(c){
	if(c)
		Common.Class.add(this.Input, c);
}

/**
 * Sets only one placeholder-specific class to input element
 * @param {String} c Class name
 */
InputPlaceholder.prototype.setClass=function(c){
	if(c){
		this.clearClass();
		Common.Class.add(this.Input, c);
	}
}

InputPlaceholder.prototype.onKeyDown = function(){
	this.clearClass();
}

InputPlaceholder.prototype.onBlur = function(){
	if (this.Input.value == '' || this.Input.value == this.Value){
		this.Input.value = this.Value;
		this.setClass(this.CssEmpty);
	}
	else{
		this.setClass(this.CssFilled);
	}
}