if (!Atira) var Atira = {};

Atira.Input = function() {}

/**
 * @constructor
 */
Atira.Input.Datefield = function(element,options,delegate) {
	this.element = $id(element);
	this.options = options || {};
	this.fixOptions();
	this.delegate = delegate || {};
	this.date = null;
	this.value = this.element.value;
	this.parseDate();
	this.addBehavior();
}

/**
 * @private
 * Sets default options
 */
Atira.Input.Datefield.prototype.fixOptions = function(options) {
	if (typeof(this.options.allowNull)!='boolean') {
		this.options.allowNull=true;
	}
	this.separator = '.';
}

/**
 * @private
 */
Atira.Input.Datefield.prototype.addBehavior = function() {
	this.element.atiraDatefield = this;
	this.element.onkeydown = this.element.onkeypress = this.element.onkeyup = function(event) {
		return this.atiraDatefield.somethingHappened(event);
	}
	this.element.onblur = function(event) {
		return this.atiraDatefield.onBlur();
	}
}

Atira.Input.Datefield.prototype.somethingHappened = function() {
	if (this.value!=this.element.value) {
		this.value = this.element.value;
		this.parseDate();
		if (this.delegate.valueIsChanged) {
			this.delegate.valueIsChanged(this.value);
		}
	}
}

Atira.Input.Datefield.prototype.onBlur = function() {
	this.renderDate();
}

Atira.Input.Datefield.prototype.parseDate = function() {
	if (this.value.length==0 && this.options.allowNull) {
		this.date = null;
		return;
	}
	var reg = /((\d*)([ \/\-](\d*)([ \/\-](\d*))?)?)?/;
	var result = this.value.match(reg);
	var day = (parseInt(result[2]) || new Date().getDate());
	var month = (parseInt(result[4]) || new Date().getMonth()+1);
	var year = (parseInt(result[6]) || new Date().getFullYear());
	if (new String(year).length<4) year += 2000;
	
	var date = new Date();
	date.setFullYear(year,month-1,day);
	date.setHours(0,0,0,0);
	this.date = date;
}

Atira.Input.Datefield.prototype.renderDate = function() {
	if (this.date==null) {
		this.element.value='';
	} else {
		this.element.value = this.date.getDate()+this.separator+(this.date.getMonth()+1)+this.separator+this.date.getFullYear();
	}
}





//////////////////////////////////////// Textfield ////////////////////////////////

Atira.Input.Textfield = function(element,options,delegate) {
	this.element = $id(element);
	this.delegate = delegate || {};
	this.options = options || {};
	this.value = this.element.value;
	this.request = null;
	this.completion = null;
	this.addBehavior();
	if (this.options.complete) {
		this.element.setAttribute("autocomplete","off");
	}
	if (this.element.atiraInputTextfield) {
		this.element.atiraInputTextfield.destroy();
	}
	if (!this.options.completeMinChars) this.options.completeMinChars=2
	this.element.atiraInputTextfield = this;
	this.completionItems = [];
	this.autoExpand();
}

Atira.Input.Textfield.prototype.setDelegate = function(delegate) {
	this.delegate = delegate || {};
}

Atira.Input.Textfield.prototype.destroy = function() {
	this.destoyed = true;
}

Atira.Input.Textfield.prototype.setValue = function(value) {
	this.value = value;
	this.element.value = value;
}

Atira.Input.Textfield.prototype.getValue = function() {
	return this.value;
}

/** @return {Element} the HTML element that the object wraps */
Atira.Input.Textfield.prototype.getElement = function() {
	return this.element;
}

Atira.Input.Textfield.prototype.setName = function(name) {
	this.element.setAttribute('name',name);
}

Atira.Input.Textfield.prototype.setTitle = function(title) {
	this.element.setAttribute('title',title);
}

Atira.Input.Textfield.prototype.addBehavior = function() {
	if (this.element.value.length==0 && this.options.placeholder){
		this.element.value = this.options.placeholder;
	}
	if (this.element.value==this.options.placeholder) {
		Atira.Element.addClassName(this.element,'placeholder');
	}
	
	this.element.atiraTextField = this;
	this.element.onkeydown = function(event) {
		return this.atiraTextField.onKeyDown(event);
	}
	this.element.onkeyup = function(event) {
		return this.atiraTextField.onKeyUp(event);
	}
	this.element.onkeypress = function(event) {
		return this.atiraTextField.onKeyPress(event);
	}
	this.element.onblur = function(event) {
		return this.atiraTextField.onBlur();
	}
	this.element.onfocus = function(event) {
		return this.atiraTextField.onFocus();
	}
}

Atira.Input.Textfield.prototype.onKeyDown = function(event) {
	if (!event) event = window.event;
	switch (event.keyCode) {
		case 38 : this.onArrowUp(event); break;
		case 40 : this.onArrowDown(event); break;
		case 13 : this.onReturnKey(event); break;
		case 27 : this.onEscapeKey(event); break;
	}
	this.valueMightHaveChanged();
}

Atira.Input.Textfield.prototype.onArrowDown = function(event) {
	this.changeCompletion(1);
}

Atira.Input.Textfield.prototype.onArrowUp = function(event) {
	this.changeCompletion(-1);
}

Atira.Input.Textfield.prototype.onReturnKey = function(event) {
	this.finishCompletion();
	if (this.delegate.onReturnKey) {
		this.delegate.onReturnKey(this);
	}
}

Atira.Input.Textfield.prototype.onKeyUp = function(event) {
	this.valueMightHaveChanged();
}

Atira.Input.Textfield.prototype.onKeyPress = function(event) {
	if (!event) event = window.event;
	this.valueMightHaveChanged();
	if (this.options.suppressReturn && event.keyCode==13) {
		return false;
	}
}

Atira.Input.Textfield.prototype.onFocus = function(event) {
	if (this.options.placeholder==this.element.value) {
		this.element.value='';
		Atira.Element.removeClassName(this.element,'placeholder');
	}
	if (this.delegate.onFocus) {
		this.delegate.onFocus(this);
	}
}

Atira.Input.Textfield.prototype.onBlur = function(event) {
	this.clearCompleteTimer();
	this.hideCompletion();
	if (this.delegate.onBlur) {
		this.delegate.onBlur(this);
	}
	if (this.element.value.length==0 && this.options.placeholder) {
		Atira.Element.addClassName(this.element,'placeholder');
		this.element.value=this.options.placeholder;
	}
}

Atira.Input.Textfield.prototype.onEscapeKey = function(event) {
	this.clearCompleteTimer();
	this.hideCompletion();
}

Atira.Input.Textfield.prototype.valueMightHaveChanged = function() {
	if (this.value!=this.element.value) {
		this.value = this.element.value;
		if (this.delegate.valueChanged) {
			this.delegate.valueChanged(this);
		}
		this.complete();
		this.autoExpand();
	}
}

Atira.Input.Textfield.prototype.autoExpand = function() {
	if (this.options.autoExpand) {
		if (Math.abs(this.element.offsetHeight-this.element.scrollHeight)>5) {
			this.element.style.height=(this.element.scrollHeight+10)+'px';
		} 
	}
}

/** Invokes valueChanged(..) on the delegate and initiates completion. Can be used when an element has been wrapped and the valueChanged(..) event is to be invoked without any change actually occured */
Atira.Input.Textfield.prototype.forceValueChanged = function() {
	this.value = this.element.value;
	if (this.delegate.valueChanged) {
		this.delegate.valueChanged(this);
	}
	this.complete();
}

Atira.Input.Textfield.prototype.clearCompleteTimer = function() {
	if (this.completeTimer) window.clearTimeout(this.completeTimer);
}

Atira.Input.Textfield.prototype.complete = function() {
	this.clearCompleteTimer();
	if (this.value.length<this.options.completeMinChars) {
		this.hideCompletion();
		return;
	};
	var self = this;
	this.completeTimer = window.setTimeout(
		function () {
			if (self.options.complete) {
				Atira.Element.addClassName(self.element,'completing');
				var delegate = {
					onSuccess : function(trans) {
						if (trans.responseXML) {
							self.updateCompletion(trans.responseXML);
						}
					},
					onFailure : function(trans) {
					}
				}
				var query = self.value;
				// Allow the delegate to modify the query before the request
				if (self.delegate.modifyCompletionQuery) {
					query = self.delegate.modifyCompletionQuery(query);
				}
				if (self.options.completePostParameter) {
					var parms = {};
					parms[self.options.completePostParameter]=query;
					self.getRequest().request(self.options.complete,delegate,{'method':'POST','parameters' : parms});
				} else {
					self.getRequest().request(self.options.complete+query,delegate);
				}
			}
			self.completeTimer=null;
		}
		,200
	);
}

Atira.Input.Textfield.prototype.updateCompletion = function(doc) {
	if (this.destoyed) return;
	var comp = this.getCompletion();
	var html = '';
	var items = doc.getElementsByTagName('item');
	this.completionSelection = -1;
	this.completionItems = [];
	if (items.length>0) {
		for (var i=0;i<items.length;i++) {
			var value = items[i].getAttribute('value');
			var title = items[i].getAttribute('title');
			var hint = items[i].getAttribute('hint');
			html+='<div onmousedown="this.parentNode.atiraTextfield.completionClicked('+i+');"><strong>'+title+'</strong><span>'+(hint || '')+'</span></div>';
			this.completionItems[i]={title:title,value:value,hint:hint};
		}
		comp.innerHTML=html;
		this.positionCompletion();
		comp.style.display='block';
		Atira.Element.addClassName(document.body,'completion_visible');
	} else {
		this.completionSelection = -1;
		this.completionItems = [];
		if (this.options.noCompletionMessage) {
			this.positionCompletion();
			comp.innerHTML='<div class="no_completion">'+this.options.noCompletionMessage+'</div>';
			comp.style.display='block';
		} else {
			this.hideCompletion();
		}
	}
	Atira.Element.removeClassName(this.element,'completing');
}

Atira.Input.Textfield.prototype.completionClicked = function(num) {
	this.completionSelection = num;
	this.finishCompletion();
}

Atira.Input.Textfield.prototype.changeCompletion = function(dir) {
	if (!this.completion) return;
	var count = this.completionItems.length;
	if (count==0) {
		return;
	}
	
	var num = this.completionSelection;
	var old = this.completionSelection;
	var comp = this.getCompletion();
	var items = comp.getElementsByTagName('div');
	num+=dir;
	if (num>count-1) num=0;
	else if (num<0) num=count-1;
	items[num].className='selected';
	if (old>=0 && old!=num) {
		items[old].className='';
	}
	this.completionSelection=num;
}


Atira.Input.Textfield.prototype.finishCompletion = function() {
	var count = this.completionItems.length;
	if (this.completionSelection == undefined) return;
	if (this.completionSelection<0 && count==0) return;
	if (this.completionSelection<0 && count>0) {
		var item = this.completionItems[0];
	} else {
		var item = this.completionItems[this.completionSelection];
	}
	if (item.value != undefined ) {
		this.element.value = this.value = item.value;
		this.hideCompletion();
		if (this.delegate.completionFinished) {
			this.delegate.completionFinished(item);
		}
	}
}

Atira.Input.Textfield.prototype.hideCompletion = function() {
	if (this.completion) {
		this.completion.style.display='none';
		Atira.Element.removeClassName(document.body,'completion_visible');
	}
}

Atira.Input.Textfield.prototype.positionCompletion = function() {
	this.completion.style.left=Atira.Element.getLeft(this.element)+'px';
}

Atira.Input.Textfield.prototype.getCompletion = function() {
	if (!this.completion) {
		this.completion = document.createElement('div');
		this.completion.atiraTextfield = this;
		with (this.completion) {
			className='completion';
			style.width=Atira.Element.getWidth(this.element)+'px';
			style.position='absolute';
			style.zIndex='100';
			style.left=Atira.Element.getLeft(this.element)+'px';
			style.display='none';
		}
		if (Atira.Browser.isIE()) {
			this.completion.style.marginTop=Atira.Element.getHeight(this.element)+'px';
			this.completion.style.marginLeft='2px';
		}
		this.element.parentNode.appendChild(this.completion);
	}
	return this.completion;
}

Atira.Input.Textfield.prototype.getRequest = function() {
	if (!this.request) {
		this.request = new Atira.Request();
	}
	return this.request;
}
