/**
 * Basic javascript library to support phone codes detection
 *	@author cCube, 2009 
 */


if(typeof(namespace)=='undefined')
{
	namespace = function()
	{
		var a=arguments, o=null, i, j, d, rt;
		for (i=0; i<a.length; ++i) 
		{
			d=a[i].split(".");
			rt = d[0];
			eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
			for (j=1; j<d.length; ++j) 
			{
				o[d[j]]=o[d[j]] || {};
				o=o[d[j]];
			}
		}
	}
}

namespace('ccube.lab');
ccube.lab.phone=Class.create();
ccube.lab.phone.prototype={
	last_value: '',
	tipel: null,
	button_el: null,
	button_cel: null,
	input: null,
	response_handler: null,
	got_call_succeed: null,
	got_call_failed: null,
	enable_call_ev: null,
	request: null,
	default_number: '(928) 131-50-50',
	safe_codes: $A([32,13,9,27,8,16,17,18,20,144,37,38,39,40,33,34,35,36,46,45,96,97,98,99,100,101,102,103,104,105,112,133,113,115,116,
									117,118,119,120,121,122,123]),
	responses: {
    'SUCCESS'                   : 0,
    'IP_ADDRESS_FORBIDDEN'      : 1,
    'NOT_FOUND'                 : 2,
    'PIN_IS_NOT_ACTIVE'         : 3,
    'LOCKED_NUMBER_BW_LIST'     : 4,
    'WRONG_NUMBER'              : 5,
    'SERVICE_IS_NOT_ACTIVE'     : 6,
    'NOWAYOUT'                  : 7,
    'NO_RETAIL_PRICE'           : 8,
    'NO_WHOLESALE_PRICE'        : 9,
    'NOT_ENOUGH_DATA'           : 10,
    'NOT_ENOUGH_MONEY'          : 11,
    'BAD_ACCOUNT'               : 12,
    'LOCKED_NUMBER_STOP_PHONE'  : 13		
	},
	initialize: function(input,tipel,buttonel,buttoncel)
	{
		this.input=$(input)||null;
		this.tipel=$(tipel)||null;
		this.button_el=$(buttonel)||null;
		this.button_cel=$(buttoncel)||null;
		this.watch_events();
		this.response_handler=this.got_server_response.bindAsEventListener(this);
		this.got_call_succeed=this.call_succeed.bindAsEventListener(this);
		this.got_call_failed=this.call_failed.bindAsEventListener(this);
		this.enable_call_ev=this.enable_call.bindAsEventListener(this);
		this.input.value='';
		this.input_blured();
		this.set_button_state('inactive');
	},
	is_valid: function (phone)
	{
		/*
		 *	check if number correct 
		 */
		return(this.normalize_phone(phone).length==10);
	},
	normalize_phone: function(phone)
	{
		/* leave only digits */
		return (''+phone).replace(/[^0-9]/ig,'');
	},
	watch_events: function()
	{
		/* assigning event listeners */
		Event.observe(this.input,'keydown',this.filter_keys.bindAsEventListener(this));
		Event.observe(this.input,'keyup',this.key_actions.bindAsEventListener(this));
		Event.observe(this.input,'blur',this.input_blured.bindAsEventListener(this));
		Event.observe(this.input,'focus',this.input_focused.bindAsEventListener(this));
		Event.observe(this.button_el,'click',this.do_call.bindAsEventListener(this));
	},
	set_tip_element: function(el)
	{
		this.tipel=$(el);
	},
	input_blured: function()
	{
		if(this.input.value=='' || this.input.value==this.default_number)
		{
			this.input.value=this.default_number;
			this.input.addClassName('blur');
		}
	},
	input_focused: function()
	{
		if(this.input.value=='' || this.input.value==this.default_number)
		{
			this.input.value='';
			this.input.removeClassName('blur');
		}
	},
	filter_keys: function(event)
	{
		var input=this.input;
		var val=input.value;
		/* special key(s) in action, allow this */
		if(event.ctrlKey || event.altKey || event.metaKey)
			return;
		/* digits, main keyboard */
		if(event.keyCode>47 && event.keyCode<58 && !event.shiftKey)
			return;
		if( (event.keyCode==57 || event.keyCode==40)&& event.shiftKey)
		{
			/* () + some evristics */
			if(val.indexOf('(')==-1)
				return;
		}
		if( (event.keyCode==41 || event.keyCode==48)&& event.shiftKey)
		{
			/* () + some evristics */
			if(val.indexOf(')')==-1 && val.indexOf('(')!=-1)
				return;
		}
		if(event.keyCode==Event.KEY_RETURN)
			this.do_call();

		/* special keys*/
		if(this.safe_codes.indexOf(event.keyCode)!=-1)
			return;
		/* minus */
		if( (event.keyCode==45 || event.keyCode==189 || event.keyCode==109 )&& !event.shiftKey)
			return;

		Event.stop(event);			
	},
	keyhandler: function(event)
	{
		var input=this.input;
		var code=event.charCode || event.keyCode;
		var ch=String.fromCharCode(code);
		if(code==Event.KEY_RETURN || code==Event.KEY_BACKSPACE || code==Event.KEY_LEFT || 
				code==Event.KEY_RIGHT || code==Event.KEY_DELETE || code==Event.KEY_HOME || 
				code==Event.KEY_END || code==Event.KEY_TAB)
			return;
		
		var ch=String.fromCharCode(code);
		
		if(ch=='-' || (ch>='0' && ch<='9'))
			return;
		var val=input.value;
		if(ch=='(' && val.indexOf('(')==-1)
			return;
		if(ch==')' && val.indexOf(')')==-1 && val.indexOf('(')!=-1)
			return;
		Event.stop(event);
	},
	key_actions: function(event)
	{
		var input=this.input;
		if(input.value.substr(0,2)=='88')
			input.value=input.value.substr(1);
		if(this.normalize_phone(input.value)==this.last_value)
			return;
		if(!this.is_valid(input.value))
		{
			this.tipel.update('');
			/* Если нажали backspace или delete, значит редактируют, значит не посылаем запрос на сервер */
			if(event.keyCode==8 || event.keyCode==46)
				return;
		}
		this.last_value=this.normalize_phone(input.value);
		this.set_button_state(this.is_valid(this.last_value)?'active':'inactive');
		new Ajax.Request('/admin/phones.php', 
			{
				method: 'get',
				parameters: {phone: this.last_value},
				onSuccess: this.response_handler
			}
		);	
	},
	got_server_response: function(tr)
	{
		var r=eval('(' + tr.responseText + ')');
		var cphone=this.normalize_phone(this.input.value);

		if(r.phone!=this.last_value)
			return;
		if(r.error)
		{
			if(cphone.length>2)
			{
				this.input.value=this.format_phone(cphone.substr(0,3),cphone);
				this.tipel.update('');
			}
			return;
		}
		if(this.tipel)
			this.tipel.update('');
		if(r.phone!=cphone)
		{
			/*
			 * if something were typed while we were waiting for server response
			 */
			if(cphone.indexOf(r.phone)!=0)
				return;
			r.phone=cphone;
		}
		if(this.tipel && this.is_valid(r.phone))
			this.tipel.update(r.ident||'');
		this.input.value=this.format_phone(r.code,r.phone);
	},
	format_phone: function(code,phone)
	{
		if(phone.indexOf(code)!=0)
			return phone;
		var format='('+this.dash_format_phone(code)+') '+this.dash_format_phone(phone.substr(code.length));
		return format;
	},
	dash_format_phone: function(phone)
	{
		var len=phone.length;
		var format='';
		var i=len-2;
		for(;i>=2;i-=2)
		{
			format='-'+phone.substring(i,i+2)+format;
		}
		format=phone.substring(0,i+2)+format;
		return format;
	},
	set_button_state: function(state)
	{
		if(!this.button_el)
			return;
		this.button_el.removeClassName('inactive');
		this.button_el.removeClassName('active');
		this.button_el.removeClassName('incall');
		this.button_el.addClassName(state);

		this.button_cel.removeClassName('inactive');
		this.button_cel.removeClassName('active');
		this.button_cel.removeClassName('incall');
		this.button_cel.addClassName(state);

		this.button_el.disabled=(state!='active');
	},
	do_call: function()
	{
		if(this.button_el.disabled)
			return;
		this.set_button_state('incall');
		var date=new Date();
		this.tipel.update('Устанавливаю соединение с call-центром...');
		this.request=new Ajax.Request('/admin/callphone.php', 
					{
						method: 'get',
						onSuccess: this.got_call_succeed,
						onFailure: this.got_call_failed,
						parameters: {phone: this.last_value, JsHttpRequest: date.getTime()+'-script'}
					}
			);		
	},
	call_succeed: function(tr)
	{
		var r=eval('(' + tr.responseText + ')');
		var code=parseInt(r.js);
		switch(code)
		{
			case this.responses.SUCCESS:
				this.tipel.update('<span class="call-succeed">Устанавливаю соединение с Вашим оператором...<br>Ожидайте вызова...</span>');
				new PeriodicalExecuter(this.enable_call_ev, 30);
				break;
			case this.responses.WRONG_NUMBER:
				this.tipel.update('<span class="call-failed">Похоже, что номер набран не верно. Попробуйте проверить правильность номера.</span>');
				this.set_button_state('active');
				break;
			case this.responses.NO_RETAIL_PRICE:
			case this.responses.NO_WHOLESALE_PRICE:
				this.tipel.update('<span class="call-failed">Извините, но в данный момент это направление не доступно.</span>');
				this.set_button_state('active');
				break;
			case this.responses.NOWAYOUT:
				this.tipel.update('<span class="call-failed">Извините, в данное время мы не работаем.</span>');
				this.set_button_state('active');
				break;
			case this.responses.LOCKED_NUMBER_BW_LIST:
			case this.responses.LOCKED_NUMBER_STOP_PHONE:
				this.tipel.update('<span class="call-failed">Извините, вызовы на набранный номер недоступны.</span>');
				this.set_button_state('active');
				break;
			case this.responses.PIN_IS_NOT_ACTIVE:
				this.tipel.update('<span class="call-failed">Извините, прием звонков временно отключен.</span>');
				this.set_button_state('active');
				break;
			case this.responses.NOT_ENOUGH_MONEY:
				this.tipel.update('<span class="call-failed">Извините, в настоящее время, услуга временно не доступна.</span>');
				this.set_button_state('active');
				break;
			default: 
				this.tipel.update('<span class="call-failed">Извините, сервис временно недоступен.</span>');
				this.set_button_state('active');
		}
	},
	call_failed: function(tr)
	{
		this.tipel.update('<span class="call-failed">Извините, сервис временно недоступен.</span>');
		this.set_button_state('active');
	},
	enable_call: function(pe)
	{
		pe.stop();
		this.set_button_state('active');
		this.tipel.update('');
	}
}

