console.log("------================= LOADING TELEGRAM JS ==============------");

var confirmCodePopUpWin;
var confirmCodeInterval;
var confirmCodeIntervalTimeout = 60;
BX.ready(function(){
	var telegramIconCss =
		'.crm-entity-stream-section-icon-telegram {'
		+'position: absolute;'
		+'top: 5px;'
		+'left: -44px;'
		+'z-index: 200;'
		+'width: 31px;'
		+'height: 31px;'
		+'border-radius: 50%;'
		+'background-color: #7f8389;'
		+'background-image: url(\'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAfCAYAAADwbH0HAAAACXBIWXMAAAuJAAALiQE3ycutAAABp0lEQVRIS+2VPSiEcRzHj+FMZDCQS6kbvMSkSDLYxK0MRhtlMJBJUcpgUDcoGQyKScqslMFyRcrAhsnbIOkUD5/f83xd7pw75zlSnk99+j/P7+X7j/MSCggI+NM4jlOOg7iFEyr/HFzSjot4/iJ4TqhdXAiO4Bju6640qMc16h/ywgT24zreeVe4l1zgDF6rZLUhrX0fQlpxDk+Vm4LaEjbiJjqqGU1aLwz2q1gexh0Ly4T6CfZgDR6q7ML7GUdYUflhuERhK3jlpmRA/RnnbZ6zBS/VSkFt2w3MB7P22U3hsbeaHfq72GY7nDFMqpUG9Wk3OB/MVjJ84K19hN4NjmrcLh1RKyv0ezX6NVhoxnHcwUeFrHHUacRmZq3+GfSTWKvxwmE5Sk6XXu27Ukpt2U3PATNHWvEPeXbphhedG+ZWteYfwuxv8L2yc8Jc6mfBN+RVv13M+YQP9pwNeh1a8w9h9nlbqP0O9/HYwJmw2nuo3WKF1vxDWDfaVxpTyWplGNedLrzvqV0cCIxip17ToD6A7j8HzgWVfwcurMdJjKgUEPBvCIVeAXZSIo5UTfS+AAAAAElFTkSuQmCC\');'
		+'background-repeat: no-repeat;'
		+'background-position: center center;'
		//+'background: #7f8389 url(images/icons-sprite.svg?4) no-repeat center 0;'
		+'box-shadow: 0 1px 1px 0 rgba(0,0,0,.04);'
		+'transition: left 300ms ease;'
		+'}';
		
	document.head.appendChild(BX.create('style', {
		html: telegramIconCss
	}));
	
	if(typeof BX.CrmHistoryItemActivity !== 'undefined'){
		BX.CrmHistoryItemActivity.prototype.getTitle = function()
		{
			if( this._data.ASSOCIATED_ENTITY.PROVIDER_ID == 'CRM_Alotelegram' ){
				var bxTitle = BX.prop.getString(this.getAssociatedEntityData(), "SUBJECT", "");
				if ( this._data.ASSOCIATED_ENTITY.DIRECTION == 1 ) {
					return bxTitle + ' Исх.'; // ' +this._data.ASSOCIATED_ENTITY.OWNER_TITLE +'
				} else {
					var arOrigin = this._data.ASSOCIATED_ENTITY.ORIGIN_ID.split("_");
					var sndrNum = (typeof arOrigin[1] !== 'undefined' ) ? ' ('+arOrigin[1]+')' : '';
					return bxTitle + ' от: ' +this._data.ASSOCIATED_ENTITY.OWNER_TITLE +sndrNum;
				}
				
			}
		};
	}
	if(typeof BX.CrmHistoryItem !== 'undefined'){
	BX.CrmHistoryItem.prototype.prepareContentDetails = function(){
		if( this._data.ASSOCIATED_ENTITY.PROVIDER_ID == 'CRM_Alotelegram' ){
			console.log("BX.CrmHistoryItem getMessage: ", this.getMessage());
			console.log("BX.CrmHistoryItem.prototype.prepareContentDetails: ", this);
			//this._data.ASSOCIATED_ENTITY.OWNER_TITLE
			var telMegramMessageBody = BX.create("DIV",
				{
					attrs: { className: "crm-entity-stream-content-detail-tgmessagebody" },
					html: this._data.ASSOCIATED_ENTITY.DESCRIPTION_RAW
				}
			);
			return [telMegramMessageBody];
		}
	}
	BX.CrmHistoryItem.prototype.getIconClassName = function(){
		if( this._data.ASSOCIATED_ENTITY.PROVIDER_ID == 'CRM_Alotelegram' ){
			return "crm-entity-stream-section-icon crm-entity-stream-section-icon-telegram";
		}
	}
	}
});
/*
BX.addCustomEvent("timeline_activity_add", function(module_id,command,params) {
	if( module_id == 'crm' ){
		
	}
	console.log('AloVoice: Catch onPopupShow EVENT: ', module_id,command,params);
	console.log('AloVoice: DATAS: ', BX.PopupWindow.uniquePopupId);
});
*/	
function alovoiceTgConfirmationSending(event){ 
	event.preventDefault();
	event.stopImmediatePropagation();

}

function alvTgStopProfileByNumber(number){ 
	if(number.length>8){
		BX.rest.callMethod('alovoice.main.userinit',{
			FUNC: "alv_tg_stop_profile_by_number",
			TGNUMBER: number,
		}).then(function(result){
			console.log("Tg Register Finish...:",result);
			//tgreginputbox
			/*BX.UI.Notification.Center.notify({
				content: "Зарегистрировано!",
				autoHideDelay: 3000,
			});*/
		});
	}
}

function alvTgGetProfileContactsByNumber(number){ 
	if(number.length>8){
		BX.rest.callMethod('alovoice.main.userinit',{
			FUNC: "alv_tg_get_contacts_list",
			TGNUMBER: number,
		}).then(function(result){
			console.log("Tg Conatcts Finish...:",result);
			//tgreginputbox
			/*BX.UI.Notification.Center.notify({
				content: "Зарегистрировано!",
				autoHideDelay: 3000,
			});*/
		});
	}
}

function alvTgDeleteProfileByNumber(number){ 
	if(number.length>8){
		BX.rest.callMethod('alovoice.main.userinit',{
			FUNC: "alv_tg_delete_profile_by_number",
			TGNUMBER: number,
		}).then(function(result){
			console.log("Tg Register Finish...:",result);
			//tgreginputbox
			BX.UI.Notification.Center.notify({
				content: "Удалено!",
				autoHideDelay: 3000,
			});
		});
	}
}

function alvTgRunProfileByNumber(number){ 
	if(number.length>8){
		BX.rest.callMethod('alovoice.main.userinit',{
			FUNC: "alv_tg_run_profile_by_number",
			TGNUMBER: number,
		}).then(function(result){
			console.log("Tg Register Finish...:",result);
			//tgreginputbox
			/*BX.UI.Notification.Center.notify({
				content: "Зарегистрировано!",
				autoHideDelay: 3000,
			});*/
		});
	}
}

function openTgAddProfileWin(){ 
	var diTitle = 'Добавить Телеграм аккоунт';
	var popId = "alovoice_tg_add_account";
	
	
	var tgRegisterNumberWin = new BX.PopupWindow(popId, null, {
		content: '<div class="row alv_form_input_wrap" id="tgreginputbox"><span id="flag" class="alv_phone_flag"></span><input type="text" placeholder="Укажите ваш телефон" id="tg_account_number" class="main-ui-control main-ui-control-string alv_form_input"></div>',
		closeIcon: {right: "20px", top: "10px"},
		titleBar: diTitle, 
		zIndex: 0, 
		offsetLeft: 0,
		offsetTop: 0,
		draggable: {restrict: false},
		events: {
			onAfterPopupShow: function () {
				console.log("onAfterPopupShow: Tg add Setting win show...................",BX('tg_account_number'));
				new BX.PhoneNumber.Input({
					node: BX('tg_account_number'),
					forceLeadingPlus: false, // принудительно установить +
					flagNode: BX('flag'), //
					flagSize: 24, // Размер флага [16, 24, 32]
					defaultCountry: 'uz', // Страна по-умолчанию
					onChange: function(e) {
						console.log("Change phone input:",e);
						// вызывается при изменении значения
					}
				});
			},
		},
		buttons: [
			new BX.PopupWindowButton({
				id: "alv_tg_reg_confirm_code_wait_btn",
				text: "Подключить",
				className: "popup-window-button-accept",
				events: {
					click: function(e){
						var tgNumber = BX("tg_account_number").value;
						var tgNumberCode = (BX("tg_add_input_confirm_code")) ? BX("tg_add_input_confirm_code").value : 0;
						if(tgNumber.length > 8 && tgNumberCode.length>4){
							
							console.log("This proxy test values:",tgNumber,tgNumberCode); 
							BX.cleanNode(BX("tgreginputbox"));
							
							if(tgNumber.length>8,tgNumberCode.length>4){
								
								BX.rest.callMethod('alovoice.main.userinit',{
									FUNC: "alv_tg_register_account_confcode",
									TGNUMBER: tgNumber,
									TGCONFCODE: tgNumberCode,
								}).then(function(result){
									console.log("Tg Register Finish...:",result);
									//tgreginputbox
									BX.UI.Notification.Center.notify({
										content: "Зарегистрировано!",
										autoHideDelay: 3000,
									});
								});
								
							}
							
							confirmCodePopUpWin.close();
						} else if(tgNumber.length > 8){
							console.log("Перед регистрацией номера: ",tgNumber);
							
							BX.append(BX.create('input', {events:{keyup:function(){ console.log("KeyUp event:",this); clearInterval(confirmCodeInterval);}},attrs: {id:'tg_add_input_confirm_code',style:'max-width:96%;margin-top:10px;',class:'main-ui-control main-ui-control-string alv_form_input',type: 'text',placeholder:"Введите код..."}}),BX('popup-window-content-'+popId));
							BX.focus(BX('tg_add_input_confirm_code'));
							confirmCodePopUpWin = this.popupWindow;
							confirmCodeInterval = setInterval(function(){ 
							
								BX.adjust(BX('alv_tg_reg_confirm_code_wait_btn'),{attrs: {text: "Отправить"}});
								
								BX.adjust(BX('tg_add_input_confirm_code'),{attrs: {placeholder:"Введите код...("+confirmCodeIntervalTimeout+")"}});
								confirmCodeIntervalTimeout = confirmCodeIntervalTimeout-1;
								if(confirmCodeIntervalTimeout<2){clearInterval(confirmCodeInterval);} 
							}, 1000);
							
							BX.rest.callMethod('alovoice.main.userinit',{
								FUNC: "alv_tg_register_account",
								TGNUMBER: tgNumber,
							}).then(function(result){
								console.log("Tg Register Finish...:",result);
								//tgreginputbox
								/*BX.UI.Notification.Center.notify({
									content: "Отправлено!",
									autoHideDelay: 3000,
								});*/
							});
							
							//this.popupWindow.close();
						} 
						else {
							BX.remove(BX('tg_add_input_error_span'));
							BX.prepend(BX.create('span', {attrs: {id:'tg_add_input_error_span',style: 'color:red;'},text:'Неправильный номер'}),BX('popup-window-content-'+popId));
						}
						
					}
				}
			
			}),
			new BX.PopupWindowButton({
				text: "Закрыть",
				className: "webform-button-link-cancel",
				events: {click: function(){
					this.popupWindow.close();
				}}
			})
		]
	}); 
	tgRegisterNumberWin.show();
}