
var aCall = {};
aCall.availableCodes = ['ipPort', '+7 495', '+7 499'];
aCall.availableCodesForSend = ['*', '8495', '8499'];
aCall.currentCodesIndex = 1;
aCall.currentState = 'input_state';


$(function(){

	aCallObjInit();
	
	aCall.btn.clearInputBtn = new Button4StatesEx(aCall.nodes.$clearInputBtn, {onClick : onClearInputClick});
	
	$('#numpadBody .key', aCall.nodes.$aCall).each( numPadKeyInit );
	$('#keyAsterisk').dblclick(onAsteriskKeyDblClick);

	
	$('#phone_code, .a_call_slider', aCall.nodes.$aCall).hover(onPhoneCodeMouseover, onPhoneCodeMouseout).click(onPhoneCodeSliderClick);
	aCall.nodes.$phoneCodeInput.html(aCall.availableCodes[aCall.currentCodesIndex]);

	aCall.nodes.$phoneNumberInput.keyup(onPhoneNumberInputKeyup).blur(onPhoneNumberInputBlur).focus(onPhoneNumberInputFocus);
	
	aCall.btn.SendBtn = new Button4StatesEx($('#a_call .main_btn.a_call_send_btn'), {onClick : onSendBtnClick, activeState : false});
	aCall.btn.CancelBtn = new Button4StatesEx($('#a_call .main_btn.a_call_cancel_btn'), {onClick : onCanselBtnClick});
	new Button4StatesEx($('#a_call .main_btn.a_call_terminate_btn'), {onClick : onTerminateBtnClick});
	new Button4StatesEx($('#a_call .main_btn.a_call_answer_btn'), {onClick : onAnswerBtnClick});
	new Button4StatesEx($('#a_call .main_btn.a_call_reject_btn'), {onClick : onRejectBtnClick});
	
	aCall.nodes.$phoneNumberInput.val('');
	aCall.nodes.$inputFieldTip.click(function(){$(this).hide(); aCall.nodes.$phoneNumberInput.focus();});
						 
	if (!useTmpPassword) 
	{
		aCall.nodes.$aCall.addClass('promo');
		aCall.promo = true;
	}


	setButtonStatusForInput();
	
	aCallSoundControlInit();
	
	new Button4StatesEx($('a.back_btn', aCall.nodes.$aCall), {onClick : onBackBtnClick});
	
	aCall.nodes.$aCall.click(tryInit).keydown(onACallKeydown);
	
	lineDrawInit();
	
	aCall.currentState = aCall.nodes.$aCall.attr('class').match(/\w*_state/)[0];
	
	$(window).unload(onWindowUnload);
	
	
	
	if ( !( typeof noAutoLogon != 'undefined' && noAutoLogon == true ) && $.cookies.get( 'isLogonComplete' ) == '1' ) tryInit();
	
	if (jQuery.browser.opera) forOperaInit(); 
	
});


function aCallObjInit(){
	
	aCall.nodes = {};
	aCall.btn = {};
	var aCallNodes = aCall.nodes;
	aCallNodes.$aCall = $('#a_call');
	aCallNodes.$aCallSlider = $('.a_call_slider', aCallNodes.$aCall);
	aCallNodes.$phoneCodeInput = $('#phone_code', aCallNodes.$aCall);
	aCallNodes.$phoneNumberInput = $('#phone_number', aCallNodes.$aCall);
	aCallNodes.$clearInputBtn = $('.backspace_btn', aCallNodes.$aCall);
	aCallNodes.$inputFieldTip = $('.input_field_tip', aCallNodes.$aCall);
	aCallNodes.$status = $('.a_call_status', aCallNodes.$aCall);
	
	aCall.Call = {};
	
}

function numPadKeyInit(){ 
	
	var $node = $(this);
	new Button4StatesEx($node, {onClick : onNumpadKeyClick});
	
}


function onPhoneCodeMouseover(e){
	
	if ( aCall.currentState == 'trycall_state' ) return;
	
	if (aCall.sliderTimerID) clearTimeout(aCall.sliderTimerID);
	else aCall.nodes.$aCallSlider.animate({left:'-9px'});
	
}


function onPhoneCodeMouseout(e){
	
	if ( aCall.currentState == 'trycall_state' ) return;
	
	aCall.sliderTimerID = setTimeout(function(){aCall.nodes.$aCallSlider.animate({left:'7px'}); aCall.sliderTimerID = null}, 1000);
	
}


function onPhoneCodeSliderClick(e){
	
	//debugger;
	switch(e.target.id) {
		case 'a_call_slider_up':
			aCall.currentCodesIndex ?  aCall.currentCodesIndex-- : aCall.currentCodesIndex = aCall.availableCodes.length-1;
			break;
		case 'a_call_slider_down':
			aCall.currentCodesIndex == aCall.availableCodes.length-1 ? aCall.currentCodesIndex = 0 :  aCall.currentCodesIndex++;
			break;
		default:
			return;
	}
	
	aCall.nodes.$phoneCodeInput.html(aCall.availableCodes[aCall.currentCodesIndex]);
	aCall.nodes.$phoneNumberInput.focus();
	if (aCall.currentCodesIndex) inputAnalizer();
	else if (!Call) setACallState('input_state');
	
}


function onNumpadKeyClick() {
	
	if (!(Phone && logonComplete)) return;

	var key = this.id.substr(3);
	
	Phone.PlaySound("TONE_" + key, false); //закомментировано т.к. FF может виснуть при частом начатии} 

	if ( (key == 'Sharp') || (aCall.promo) && (key == 'Asterisk') && (key == 'Sharp') ) return;
	
	if (key == 'Asterisk')
	{ 
		aCall.asteriskClickTimerId = setTimeout(function(){ numpadKeyHandler('*');  aCall.asteriskClickTimerId = null;}, 200);
	}
	else
	{
		numpadKeyHandler( (key == 'Sharp') ? '#' : key );
	} 
}


function numpadKeyHandler(key)
{
	var $inputNode = aCall.nodes.$phoneNumberInput;
//	if ( ( $inputNode.val().length < 7 )||(aCall.currentCodesIndex == 0)||!aCall.promo ) $inputNode.val( $inputNode.val() + key );
	if ( ( $inputNode.val().length < 7 )||(aCall.currentCodesIndex == 0)||!aCall.promo ) insertKeyToPhoneNumberInput(key);
//	inputAnalizer();	
}


function insertKeyToPhoneNumberInput(key)
{
	var $inputNode = aCall.nodes.$phoneNumberInput;

	if (jQuery.browser.opera) 
	{
		var r = aCall.phoneNumberSelectionTextRangeObj; //fix for Opera. При клике на кнопку Opera сбрасывает выделение
		$inputNode.setSelection(r.start, r.end);
	}

	var textRangeObj = $inputNode.getSelection();
	var newStart = textRangeObj.start;
	if ( !(((key == '*') || (key == '+')) && newStart != 0) )
	{
		$inputNode.replaceSelection(key);
		newStart++
	}

	inputAnalizer();

	$inputNode.setSelection(newStart, newStart);
	aCall.phoneNumberSelectionTextRangeObj = aCall.nodes.$phoneNumberInput.getSelection();
}


function onAsteriskKeyDblClick()
{
	clearTimeout(aCall.asteriskClickTimerId);
	aCall.asteriskClickTimerId = null;
	numpadKeyHandler('+');
}


function onClearInputClick()
{
	var $inputNode = aCall.nodes.$phoneNumberInput;

	if (jQuery.browser.opera) 
	{
		var r = aCall.phoneNumberSelectionTextRangeObj; //fix for Opera. При клике на кнопку Opera сбрасывает выделение
		$inputNode.setSelection(r.start, r.end);
	}

	var textRangeObj = $inputNode.getSelection();
	
	if ( textRangeObj.start == 0 && textRangeObj.length == 0) return;

	var newStart = textRangeObj.start;

	
	if (!textRangeObj.length)
	{
		$inputNode.setSelection(textRangeObj.start-1, textRangeObj.start);
		newStart--;
	} 

	$inputNode.replaceSelection('');

	inputAnalizer();

	$inputNode.setSelection(newStart, newStart);
	aCall.phoneNumberSelectionTextRangeObj = aCall.nodes.$phoneNumberInput.getSelection();

/*
	var $inputNode = aCall.nodes.$phoneNumberInput;
	var str = $inputNode.val();
	var newStr = str.substring(0,str.length-1);
	$inputNode.val(newStr);
	inputAnalizer();
*/
}


function forOperaInit()
{
	aCall.btn.clearInputBtn.buttonNode.mouseover(function(){  aCall.phoneNumberSelectionTextRangeObj = aCall.nodes.$phoneNumberInput.getSelection();   });
}


function setButtonStatusForInput(){
	
	var str = aCall.nodes.$phoneNumberInput.val();
	
	if (str == '') {
		aCall.btn.clearInputBtn.disable();
		aCall.btn.SendBtn.disable();
	} else {
		aCall.btn.clearInputBtn.enable();
		aCall.btn.SendBtn.enable();
		aCall.nodes.$inputFieldTip.hide();
	} 	
}


function inputAnalizer(){
	//debugger;
	//var re = /([0-9]|\-|\.|\s)$/;
	//var re = /[^0-9\-\.\s]|^[\s\-\.]|[\s\-\.]$/g;
	//var re = /^[^0-9]*|[^0-9]*$|[\-\.\s][\-\.\s]+|[^0-9\-\.\s]*/g;

	var re = (aCall.promo) ? /^[^0-9]*|[\-\.\s][\-\.\s]+|[^0-9\-\.\s]*/g : /^[^0-9\*\+]*|[\-\.\s][\-\.\s]+|[^0-9\-\.\s]*/g;
	
	var val = aCall.nodes.$phoneNumberInput.val();
	newVal = val.replace(re, "");
	(val == newVal) ||  aCall.nodes.$phoneNumberInput.val( newVal );
	
	setButtonStatusForInput();
	onPhoneNumberInputBlur();
	
	if (( val.replace(/[^0-9]/g, "").length > 6 )&&( aCall.currentCodesIndex )&&( aCall.promo ) ) { 
		setACallState('readytocall_state');
	} else {
		if (!Call) setACallState('input_state');
	}
		
}


function onPhoneNumberInputKeyup(e){
	
	inputAnalizer();
		
}


function onACallKeydown(e){

	if ((e.keyCode == 13)&&( (aCall.currentState == 'input_state')||(aCall.currentState == 'readytocall_state')) ) onSendBtnClick();
	
}


function onPhoneNumberInputBlur(e){
	
	return;//выключили надпись на поле вода номера
	
	if ((aCall.nodes.$phoneNumberInput.val() == '') && (aCall.currentCodesIndex == 0)) {
	
		aCall.inputFieldTipTimerID = setTimeout(function(){
			
			aCall.inputFieldTipTimerID == null;
			if ((aCall.nodes.$phoneNumberInput.val() == '') && (aCall.currentCodesIndex == 0))
			aCall.nodes.$inputFieldTip.show();
			
		}, 1000);
		
	}
		
}


function onPhoneNumberInputFocus(e){
	
	if (aCall.inputFieldTipTimerID) clearTimeout(aCall.inputFieldTipTimerID);
	aCall.nodes.$inputFieldTip.hide();
	
}


function onPhoneNumberInputChange(e){
	//debugger;
	var re = /^[^0-9]*|[^0-9]*$|[\-\.\s][\-\.\s]+|[^0-9\-\.\s]*/g;
	
	var val = aCall.nodes.$phoneNumberInput.val();
	val = val.replace(re, "");
	aCall.nodes.$phoneNumberInput.val( val );
	
	if ( val.replace(/[^0-9]/g, "").length > 6 ) {
		
//		alert('call');
				
	}
	
	setButtonStatusForInput();		

}


function onSendBtnClick(){
	
	var number = $.trim( aCall.nodes.$phoneNumberInput.val() );
	
	if ( Phone && logonComplete && number.length ) {
	
		setACallState('trycall_state');

		if (aCall.promo) 
		{
			number = aCall.availableCodesForSend[aCall.currentCodesIndex] + number.replace(/[^0-9]/g, "")
		}
		else
		{
			var r = number.match(/^(\*|\+)/);
			number = (r ? r[0] : '') + number.replace(/[^\d]+/g, "");
		}
		
		console.log(number);
		MakeCall(number);

	} else {
		//alert('компонент не активирован или не залогинен');
	}
	
	
}


function onCanselBtnClick(){
	
	TerminateCall();
	//setACallState('readytocall_state');
	setACallState('input_state')
	
}


function onTerminateBtnClick(){
	
	TerminateCall();
	//setACallState('readytocall_state');
	setACallState('input_state')
	
}


function onRejectBtnClick(){
	
	
}


function setACallState(state){

	if (aCall.nodes.$aCall.hasClass(state))  return;
	
	switch(state) {

	case 'trycall_state':
		aCall.btn.clearInputBtn.disable();
		aCall.nodes.$phoneNumberInput.attr('readonly', 'readonly');
		break;

	case 'readytocall_state':
		aCall.btn.clearInputBtn.enable();
		aCall.nodes.$phoneNumberInput.removeAttr('readonly');
		aCall.btn.SendBtn.buttonNode.focus();
		break;

	case 'input_state':
//		aCall.soundControl.$soundControl.hide();
		aCall.nodes.$phoneNumberInput.removeAttr('readonly').focus();
		if (aCall.nodes.$phoneNumberInput.val()!='') aCall.btn.clearInputBtn.enable();
		
		if ( (aCall.currentState != 'input_state')&&(aCall.currentState != 'waiting_state')&&(aCall.currentState != 'needinstall_state') && !useSocialAuth)
			setTimeout(setUsetInfo, 2000);
		break;

	case 'call_state':
		aCall.btn.clearInputBtn.disable();
		aCall.nodes.$phoneNumberInput.attr('readonly', 'readonly');		
		break;

	case 'needinstall_state':
//		debugger;
		if (!(getOSInfo().isSupported)) {
			aCall.nodes.$aCall.find('.addition_wrap').addClass('notsupported');
		}
		
		break;
		
	case 'waiting_state':
//		aCall.nodes.$aCall.removeClass(aCall.currentState).addClass(state);
//		aCall.currentState = state;
//		$('.waiting', aCall.nodes.$aCall).height( aCall.nodes.$aCall.outerHeight() );
		setACallStatusText("пожалуйста ждите...");
//		return;
		break;
	}
	
	aCall.nodes.$aCall.removeClass(aCall.currentState).addClass(state);
	aCall.currentState = state;
	
}


function setACallStatusText(msg){

	aCall.nodes.$status.html(msg);

}


function getBalance()
{
	$.ajax({
		type: 'GET',
		url: IPPORT_SERVISE_URL,
		data: { cmd: 'xmlhttp', query: 'info', sub: 'balance' },
		dataType: "jsonp",
		success: function(data){
			if (data.error_code) {
				setACallState('input_state');
				setACallStatusText(data.error_message);
			}
			else
			{
				setACallStatusText("На вашем счете: " + data.balance + ' ' + ((data.curr_shortname == "RUR") ?  'р.' : 'USD'));
			};
			
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			setACallStatusText("Ошибка соединения");
			setACallState('input_state');
		}
	});
}


function onBackBtnClick(e){
	
	setACallState('input_state');
	e.stopPropagation();
	
}


function lineDrawInit(){
	
	var $ld = $('.linedraw', aCall.nodes.$aCall);
	
	aCall.linedraw = new Linedraw($ld, {
	
		canvasWidth: $ld.outerWidth(true),
		canvasHeight: $ld.outerHeight(true),
		
		volLineAttr: {
			stroke: '#ff2020',
			"stroke-width": 2
		},
		micLineAttr: {
			stroke: '#3abcff',
			"stroke-width": 1
		},
		
		dx: 14, 		//шаг между точками по x
		h: 7, 			//коэффициент сглаживания кривой, от 0 до ...
		shift: -8,   	//величина сдвига кривых по фазе
		pointCount: 19, //должно быть нечетным.
		middle: 50,		//координата нулевой горизонтальной линии в px 
		staticPoints: 0
	
	});
	
	aCall.linedraw.resetAll();
	
}


function onWindowUnload() { 

	if (Phone) {
		TerminateCall();
		LogOff();
		//alert('LogOff end');
	}
	//callTimerInit();
		
}

	//$('.a_call_soundcontrol_btn_wrap .key', aCall.nodes.$aCall).each( numPadKeyInit );

/* ----------- aCallSoundControl -------------------- */

function aCallSoundControlInit(){
	
	aCall.soundControl = {};
	aCall.soundControl.$soundControl = $('.call', aCall.nodes.$aCall);
	aCall.soundControl.state = 'vol';
	aCall.soundControl.volMute = false;
	aCall.soundControl.micMute = false;
	aCall.soundControl.sliding = false;
	aCall.soundControl.intensVolTimerId = null;
	aCall.soundControl.intensMicTimerId = null;
	
	aCall.soundControl.$volBtn = $('#key_vol', aCall.soundControl.$soundControl).click(aCallVolBtnClick).hover(aCallBtnMouseOver, aCallBtnMouseOut);
	aCall.soundControl.$micBtn = $('#key_mic', aCall.soundControl.$soundControl).click(aCallMicBtnClick).hover(aCallBtnMouseOver, aCallBtnMouseOut);

	aCall.soundControl.$intensityVolWrap = $('.intensity_val', aCall.soundControl.$soundControl).mouseenter(intensityWrapMouseEnter).mouseleave(intensityWrapMouseLeave);
	aCall.soundControl.$intensityMicWrap = $('.intensity_mic', aCall.soundControl.$soundControl).mouseenter(intensityWrapMouseEnter).mouseleave(intensityWrapMouseLeave);
	
//	aCall.soundControl.$muteBtn = $('.mute_btn', aCall.soundControl.$soundControl);
//	aCall.soundControl.muteBtnObj = new Button4StatesEx(aCall.soundControl.$muteBtn, {onClick : onMuteBtnClick});
//debugger;
	aCall.soundControl.$intensityVol = $('.a_call_intensity_vol', aCall.soundControl.$soundControl);
	aCall.soundControl.intensityVolObj = aCall.soundControl.$intensityVol.slider({
			orientation: "vertical",
			range: "min",
			value: 50,
			min: 0,
			max: 100,
			start: function(event, ui) { aCall.soundControl.sliding = true },
			stop: function(event, ui) { aCall.soundControl.sliding = false },
			slide: onIntensityVolSlide

		});
		
	aCall.soundControl.$intensityMic = $('.a_call_intensity_mic', aCall.soundControl.$soundControl);
	aCall.soundControl.intensityMicObj = aCall.soundControl.$intensityMic.slider({
			orientation: "vertical",
			range: "min",
			value: 50,
			min: 0,
			max: 100,
			start: function(event, ui) { aCall.soundControl.sliding = true },
			stop: function(event, ui) { aCall.soundControl.sliding = false },
			slide: onIntensityMicSlide

		});
		
	$('.ui-slider-handle', aCall.soundControl.$soundControl).attr('hideFocus', 'hideFocus');
		
	
	
}


function aCallBtnMouseOver(e){

	var sc = aCall.soundControl;
	
	if (e.target.id == 'key_vol') {
		if (sc.intensVolTimerId) {
			clearTimeout(sc.intensVolTimerId);
			sc.intensVolTimerId = null;
		}
		else {
			sc.$intensityVolWrap.slideDown('fast');
		}
	}
	else 
		if (sc.intensMicTimerId) {
			clearTimeout(sc.intensMicTimerId);
			sc.intensMicTimerId = null;
		}
		else {
			sc.$intensityMicWrap.slideDown('fast');
		}
	
}


function aCallBtnMouseOut(e){

	var sc = aCall.soundControl;
	
	if (e.target.id == 'key_vol') sc.intensVolTimerId = setTimeout(function(){sc.intensVolTimerId = null; sc.$intensityVolWrap.slideUp('fast');}, 300);
	else sc.intensMicTimerId = setTimeout(function(){sc.intensMicTimerId = null; sc.$intensityMicWrap.slideUp('fast');}, 300);
	
}


function intensityWrapMouseEnter(e) {
	
	var sc = aCall.soundControl;
	
	if ( $(e.target).hasClass('intensity_val') ) (sc.intensVolTimerId) && ( clearTimeout(sc.intensVolTimerId), sc.intensVolTimerId = null )
	else (sc.intensMicTimerId) && ( clearTimeout(sc.intensMicTimerId), sc.intensMicTimerId = null  )
	
}


function intensityWrapMouseLeave(e) {
	
	var sc = aCall.soundControl;
	
	if ( $(e.target).hasClass('intensity_val') ) {
		sc.intensVolTimerId = setTimeout(function(){sc.intensVolTimerId = null; sc.$intensityVolWrap.slideUp('fast');}, 300);
	}
	else {
		sc.intensMicTimerId = setTimeout(function(){sc.intensMicTimerId = null; sc.$intensityMicWrap.slideUp('fast');}, 300);
	}
	
}


function aCallVolBtnClick(){

	var sc = aCall.soundControl;
	sc.$volBtn.toggleClass('mute');
	$('.ui-slider-handle', sc.intensityVolObj).toggleClass('mute');
	Call&&(Call.VolMute = !Call.VolMute);

}


function aCallMicBtnClick(){

	var sc = aCall.soundControl;
	sc.$micBtn.toggleClass('mute');
	$('.ui-slider-handle', sc.intensityMicObj).toggleClass('mute');
	Call&&(Call.MicMute = !Call.MicMute);			

}


function aCallSoundControlStatusInit(){

	var sc = aCall.soundControl;
	var v = Phone.Volume;
	v = Math.round( (v*100)/0xffff );
	sc.intensityVolObj.slider( 'value' , v );	

	v = Phone.MicLevel;
	v = Math.round( (v*100)/0xffff );
	sc.intensityMicObj.slider( 'value' , v );	
	
}


function onIntensityVolSlide(event, ui){

	setTimeout(function(){Call&&(Call.Volume = (ui.value * 0xffff) / 100) ;}, 100);

}


function onIntensityMicSlide(event, ui){

	setTimeout(function(){Call&&(Call.MicLevel = (ui.value * 0xffff) / 100) ;}, 100);

}


