

function phone ( id ) {
	
	this.id = id;
	this.phn = $(id);
	this.phn_country   = $('' + id + '_country');
	this.phn_town      = $('' + id + '_town');
	this.phn_number    = $('' + id + '_number');
	this.phn_extension = $('' + id + '_extension');
	
	this.phn_country.min_l = 1;
	this.phn_country.max_l = 4;
	this.phn_town.min_l = 3;
	this.phn_town.max_l = 6;
	this.phn_number.min_l = 4;
	this.phn_number.max_l = 7;
	this.phn_extension.min_l = 0;
	this.phn_extension.max_l = 5;
	this.phn.min_l = 10;
	this.phn.max_l = 15;
	
	if ( !this.phn || !this.phn_country || !this.phn_town || 
		 !this.phn_number || !this.phn_extension ) 
	{ throw new Error("PHONE id NOT FOUND!"); }
}

phone.prototype = Object;

phone.prototype.run = function () {

	var PHONE = this;
	function on_key_up() {
		var val    = this.value;
		this.value = val.replace( /[^0-9]+/g, '' );
		var len = this.value.length;
		if ( len > this.max_l ) {
			this.value = this.value.substr( 0, this.max_l);
		}
		PHONE.set();
	};
	this.phn_country.onkeyup   = on_key_up;
	this.phn_town.onkeyup      = on_key_up;
	this.phn_number.onkeyup    = on_key_up;
	this.phn_extension.onkeyup = on_key_up;
	
	if ( this.check_is_correct() ) {
		$('wrong_' + this.id).innerHTML = '';
	} else {
		$('wrong_' + this.id).innerHTML = '(!)';
	}
	
}

phone.prototype.set = function () {

	this.phn.value = '+' + this.phn_country.value + '-' + this.phn_town.value + '-' + 
		this.phn_number.value + 
		( this.phn_extension.value.length > 0 ? '#' + this.phn_extension.value : '');
	if ( this.check_is_correct() ) {
		$('wrong_' + this.id).innerHTML = '';
	} else { 
		$('wrong_' + this.id).innerHTML = '(!)';
	}
}

phone.prototype.check_is_correct = function () {
	var val,txtel, sum = 0;
	
	txtel = this.phn_country;
	val = txtel.value;
	if ( val.length < txtel.min_l || val.length > txtel.max_l ) { return false; }
	sum += val.length;
	
	txtel = this.phn_town;
	val = txtel.value;
	if ( val.length < txtel.min_l || val.length > txtel.max_l ) { return false; }
	sum += val.length;
	
	txtel = this.phn_number;
	val = txtel.value;
	if ( val.length < txtel.min_l || val.length > txtel.max_l ) { return false; }
	sum += val.length;
	
	txtel = this.phn_extension;
	val = txtel.value;
	if ( val.length < txtel.min_l || val.length > txtel.max_l ) { return false; }
	sum += val.length;
	
	if ( sum > this.phn.max_l || sum < this.phn.min_l ) { return false; }
	
	return true;
}

