/**
 * @author Ryan
 */
function PhoneNumber(options){
	this._init(options);
}
PhoneNumber.prototype = {
	options:{
		firstInputId: "area_code",
		secondInputId: "first_phone",
		thirdInputId: "second_phone",
		generateInHiddenField: false,
		hiddenFieldId: "generatedPhoneNumber",
		hasExtension: false,
		extensionInputId: "extension"
	},
	_options: new Object,
	setOptions: function(options) {
		Object.extend(this.options, options || {});
	},
	_init: function(options){
		// Setting up original options with default options
		Object.extend(this._options, this.options);
		this.setOptions(options);

		this.firstInput = $(this.options.firstInputId);
		this.secondInput = $(this.options.secondInputId);
		this.thirdInput = $(this.options.thirdInputId);
		this.inputs = [this.firstInput,this.secondInput,this.thirdInput];
				
		this.firstInput.observe("keyup", this.onKeyUpPhoneNumber.bind(this));
		this.secondInput.observe("keyup", this.onKeyUpPhoneNumber.bind(this));
		this.thirdInput.observe("keyup", this.onKeyUpPhoneNumber.bind(this));
		
		if(this.options.hasExtension){
			this.extensionInput = $(this.options.extensionInputId);
			this.inputs.push(this.extensionInput);
			this.extensionInput.observe("keyup", this.onKeyUpPhoneNumber.bind(this));
		}
		
		if(this.options.generateInHiddenField){
			this.generatePhoneNumber();
		}
	},
	onKeyUpPhoneNumber: function(e){
		var input = e.element();
		var position = this.getPosition(input);
		if(input.value.length == input.maxLength && position + 1 < this.inputs.length){
			this.inputs[position + 1].focus();
			this.inputs[position + 1].select();
		}
		else if(input.value.length == 0 && e.keyCode == 8 && position != 0){
			this.inputs[position - 1].focus();
			this.inputs[position - 1].select();
		}
		
		if(this.options.generateInHiddenField){
			this.generatePhoneNumber();
		}
	},
	getPosition: function(input){
		return this.inputs.indexOf(input);
	},
	generatePhoneNumber: function(){
		var phoneNumber = "";
		for(var i = 0; i < this.inputs.length; i++){
			if (this.inputs.length > i + 1) {
				if (!(this.options.hasExtension && this.inputs.length == i + 2)) {
					phoneNumber = [phoneNumber, this.inputs[i].value, "-"].join("");
				}
				else if(!(this.inputs[this.inputs.length -1].value.strip().empty())){
					phoneNumber = [phoneNumber, this.inputs[i].value, "#"].join("");
				}
				else{
					phoneNumber = [phoneNumber, this.inputs[i].value].join("");
				}
			}
			else{
				phoneNumber = [phoneNumber, this.inputs[i].value].join("");
			}
		}
		$(this.options.hiddenFieldId).value = phoneNumber;
	}
}
Object.extend(PhoneNumber, PhoneNumber.prototype);

