/* * *******************************************************************************
 * The content of this file is subject to the CRMTiger Pro license.
 * ("License"); You may not use this file except in compliance with the License
 * The Initial Developer of the Original Code is vTiger
 * The Modified Code of the Original Code owned by https://crmtiger.com/
 * Portions created by CRMTiger.com are Copyright(C) CRMTiger.com
 * All Rights Reserved.
 * ****************************************************************************** */
 
jQuery.Class("WhatsappCommon_Js",{

	whatsapppopup : false,
	
    registerEventsForWhatappChatPopup : function() {
        jQuery('#whatsapp').live('click', function(e){
			var whatsapppopup = true;
            var recordId = jQuery('#recordId').val();
            var whatsappnumber = jQuery('#whatsappnumber').val();
            if(whatsappnumber == ''){
                app.helper.showErrorNotification({title: 'Error', message: 'WhatsApp number is Blank OR number in record is not a WhatsApp number'});
                return false;
            }
            var moduleName = app.getModuleName();
            var params = {
                'module' : 'CTWhatsApp',
                'view' : "WhatsappChatPopup",
                'mode' : "chatPopup",
                'sourcemodulename' : moduleName,
                'recordid' : recordId
            }
            var progressIndicatorElement = jQuery.progressIndicator({
                'position' : 'html',
                'blockInfo' : {
                    'enabled' : true
                }
            });
            AppConnector.request(params).then(
                function(data) {
                    progressIndicatorElement.progressIndicator({
                        'mode' : 'hide'
                    })
                    app.showModalWindow(data, function(data){
                        jQuery(".conversation-container").animate({ scrollTop: jQuery('.conversation-container').prop("scrollHeight")}, 0);
                    });
                    $('.modal-backdrop').hide();
                }
            );
        });
    },

    registerEventsForSendNewMsg : function() {
		//Add attachment
		jQuery('#filename_detail').live('change', function(e){
            var file = $('#filename_detail').prop('files')[0];
            $('.write_msg').val(file.name);
        });
		//Add attachment
		
        jQuery('.msg_send_btn').live('click', function(e){
            var thisInstance = this;
            var msgbody = jQuery('.write_msg').val();
            var mobileno = jQuery('#mobileno').val();
            var module_recordid = jQuery('#module_recordid').val();
            var moduleName = app.getModuleName();
            
            if(msgbody == ''){
				app.helper.showErrorNotification({title: 'Error', message: 'Please enter your Message.'});
				return false;
			}
			
			//Add attachment
			var file = $('#filename_detail').prop('files')[0];
            if(file === undefined){
                var filename = '';
            }else{
                var reader = new FileReader();
                reader.addEventListener('load', function() {
                    var res = reader.result; 
                    jQuery('[name="selectfile_data"]').val(res);
                });

                reader.readAsDataURL(file);
                var filename = file.name;
                var filetype = file.type;
            }
			
			var currentdatetime = jQuery('#currentdatetime').val();
			var currentusername = jQuery('#currentusername').val();
			
			setTimeout(function(){ 
				var base64imagedata = jQuery('[name="selectfile_data"]').val();
				var whatsappstorageurl = jQuery('#whatsappstorageurl').val();
				
				var msg_history = jQuery('#ap');
				if(msgbody.indexOf('csv') > -1 || msgbody.indexOf('txt') > -1 || msgbody.indexOf('pdf') > -1 || msgbody.indexOf('mp4') > -1) {
					var msgurl = whatsappstorageurl+'/'+msgbody;
					var newtag = '<a href="'+msgurl+'" target="_black">'+msgurl+'</a>';
				}else if (msgbody.indexOf('jpeg') > -1 || msgbody.indexOf('jpg') > -1 || msgbody.indexOf('png') > -1) {
					var newtag = '<image src="'+base64imagedata+'" style="height: 60px;">';
				}else{
					var escapeEl = document.createElement('textarea');
					escapeEl.innerHTML = msgbody;
					var newtag = escapeEl.innerHTML;
				}
				
				message = '<div class="message sent">' +
						'    <p>'+newtag+'</p> ' +
						'    <span class="metadata">' +
						'        <span class="time"><b>'+currentusername+'</b> '+currentdatetime+'</span>' +
						'        <img src="layouts/v7/modules/CTWhatsApp/images/checkblack.png" style="width: 14px;"/>' +
						'    </span>' +
						'</div>';
				msg_history.append(message);
				jQuery('.write_msg').val('');
				jQuery(".conversation-container").animate({ scrollTop: jQuery('.conversation-container').prop("scrollHeight")}, 0);
				
                var params = {
					'module' : 'CTWhatsApp',
					'view' : "WhatsappChatPopup",
					'mode' : "sentWhatsappMsg",
					'mobileno' : mobileno,
					'msgbody' : msgbody,
					'module_recordid' : module_recordid,
					'base64imagedata' : base64imagedata,
                    'filename' : filename,
                    'filetype' : filetype
				}
				
				AppConnector.request(params).then(
					function(data) {
						jQuery('.write_msg').val('');
						jQuery('#filename_detail').val('');
						jQuery('[name="selectfile_data"]').val('');	
					}
				);
			}, 500);
        });
    },

    registerEventsForSendNewMsgOnEnter : function() {
        jQuery('.chat-container').live("keypress", function(e){
            if(e.keyCode == 13){
                var thisInstance = this;
				var msgbody = jQuery('.write_msg').val();
				var mobileno = jQuery('#mobileno').val();
				var module_recordid = jQuery('#module_recordid').val();
				var moduleName = app.getModuleName();
				
				if(msgbody == ''){
					app.helper.showErrorNotification({title: 'Error', message: 'Please enter your Message.'});
					return false;
				}
				
				//Add attachment
				var file = $('#filename_detail').prop('files')[0];
				if(file === undefined){
					var filename = '';
				}else{
					var reader = new FileReader();
					reader.addEventListener('load', function() {
						var res = reader.result; 
						jQuery('[name="selectfile_data"]').val(res);
					});

					reader.readAsDataURL(file);
					var filename = file.name;
					var filetype = file.type;
				}
				
				var currentdatetime = jQuery('#currentdatetime').val();
				var currentusername = jQuery('#currentusername').val();
				
				setTimeout(function(){ 
					var base64imagedata = jQuery('[name="selectfile_data"]').val();
					var whatsappstorageurl = jQuery('#whatsappstorageurl').val();
					
					var msg_history = jQuery('#ap');
					if(msgbody.indexOf('csv') > -1 || msgbody.indexOf('txt') > -1 || msgbody.indexOf('pdf') > -1 || msgbody.indexOf('mp4') > -1) {
						var msgurl = whatsappstorageurl+'/'+msgbody;
						var newtag = '<a href="'+msgurl+'" target="_black">'+msgurl+'</a>';
					}else if (msgbody.indexOf('jpeg') > -1 || msgbody.indexOf('jpg') > -1 || msgbody.indexOf('png') > -1) {
						var newtag = '<image src="'+base64imagedata+'" style="height: 60px;">';
					}else{
						var escapeEl = document.createElement('textarea');
						escapeEl.innerHTML = msgbody;
						var newtag = escapeEl.innerHTML;
					}
					
					message = '<div class="message sent">' +
							'    <p>'+newtag+'</p> ' +
							'    <span class="metadata">' +
							'        <span class="time"><b>'+currentusername+'</b> '+currentdatetime+'</span>' +
							'        <img src="layouts/v7/modules/CTWhatsApp/images/checkblack.png" style="width: 14px;"/>' +
							'    </span>' +
							'</div>';
					msg_history.append(message);
					jQuery('.write_msg').val('');
					jQuery(".conversation-container").animate({ scrollTop: jQuery('.conversation-container').prop("scrollHeight")}, 0);
					
					var params = {
						'module' : 'CTWhatsApp',
						'view' : "WhatsappChatPopup",
						'mode' : "sentWhatsappMsg",
						'mobileno' : mobileno,
						'msgbody' : msgbody,
						'module_recordid' : module_recordid,
						'base64imagedata' : base64imagedata,
						'filename' : filename,
						'filetype' : filetype
					}
					
					AppConnector.request(params).then(
						function(data) {
							jQuery('.write_msg').val('');
							jQuery('#filename_detail').val('');
							jQuery('[name="selectfile_data"]').val('');	
						}
					);
				}, 500);
            }
        });
    },

    registerEventsForAllWhatappChat : function() {
        jQuery('#allwhatsappmsg').live('click', function(e){
            var moduleName = app.getModuleName();
            var currentdate = jQuery('#currentdate').val();
            var licensedate = jQuery('#licensedate').val();
            if(licensedate <= currentdate){
                var message = "Your WhatsApp license has been expired. Please Upgrade you CTWhatsApp from <a href='https://crmtiger.com/whatsapp/'>https://crmtiger.com/whatsapp/</a>";
                app.helper.showErrorNotification({'title': 'Error', 'message': message});
                return false;
            }
            
            var whatsappmodule = 'All Messages';
            var params = {
                'module' : 'CTWhatsApp',
                'view' : "WhatsappChat",
                'mode' : "allWhatsAppMSG",
                'whatsappmodule' : whatsappmodule
            }
            var progressIndicatorElement = jQuery.progressIndicator({
                'position' : 'html',
                'blockInfo' : {
                    'enabled' : true
                }
            });
            AppConnector.request(params).then(
                function(data) {
                    progressIndicatorElement.progressIndicator({
                        'mode' : 'hide'
                    })
                    app.showModalWindow(data, function(data){
                        jQuery('.modal-backdrop').css('z-index','0'); 
                    });
                }
            );
        });
    },

    registerEventsForSelectModuleChat : function() {
        jQuery('.selectedmodulename').live('click', function(e){
        	var select_modulename = jQuery(e.currentTarget).data('modulename');
        	var translatemodulename = jQuery(e.currentTarget).data('translatemodulename');
        	var modulerecordcount = jQuery(e.currentTarget).data('modulerecordcount');
        	var value = jQuery('[name="search"]').val('');
        	
        	jQuery('.fText').text('');
        	jQuery('.fText').text(translatemodulename+' ('+modulerecordcount+')');
			jQuery('#module_name').val(select_modulename);

            if(select_modulename == 'Contacts'){
                jQuery('.Contactsname').removeClass('hide');
                jQuery('.ContactsData').removeClass('hide'); 
                jQuery('.Contactsname').addClass('show');
                jQuery('.ContactsData').addClass('show');                

                jQuery('.Leadsname').removeClass('show');
                jQuery('.Leadsname').addClass('hide');
                jQuery('.Vendorsname').removeClass('show');
                jQuery('.Vendorsname').addClass('hide');
                jQuery('.Accountsname').removeClass('show');
                jQuery('.Accountsname').addClass('hide');
                jQuery('.AllMessagename').removeClass('show');
                jQuery('.AllMessagename').addClass('hide');
				jQuery('.Unknownname').removeClass('show');
                jQuery('.Unknownname').addClass('hide');

                jQuery('.LeadsData').removeClass('show');
                jQuery('.LeadsData').addClass('hide');
                jQuery('.VendorsData').removeClass('show');
                jQuery('.VendorsData').addClass('hide');
                jQuery('.AccountsData').removeClass('show');
                jQuery('.AccountsData').addClass('hide');
                jQuery('.AllMessageData').removeClass('show');
                jQuery('.AllMessageData').addClass('hide');
				jQuery('.UnknownData').removeClass('show');
                jQuery('.UnknownData').addClass('hide');
            }else if(select_modulename == 'Leads'){
                jQuery('.Contactsname').removeClass('show');
                jQuery('.Contactsname').addClass('hide');
                jQuery('.Vendorsname').removeClass('show');
                jQuery('.Vendorsname').addClass('hide');
                jQuery('.Accountsname').removeClass('show');
                jQuery('.Accountsname').addClass('hide');
                jQuery('.AllMessagename').removeClass('show');
                jQuery('.AllMessagename').addClass('hide');
				jQuery('.Unknownname').removeClass('show');
                jQuery('.Unknownname').addClass('hide');

                jQuery('.ContactsData').removeClass('show');
                jQuery('.ContactsData').addClass('hide');
                jQuery('.VendorsData').removeClass('show');
                jQuery('.VendorsData').addClass('hide');
                jQuery('.AccountsData').removeClass('show');
                jQuery('.AccountsData').addClass('hide');
                jQuery('.AllMessageData').removeClass('show');
                jQuery('.AllMessageData').addClass('hide');
				jQuery('.UnknownData').removeClass('show');
                jQuery('.UnknownData').addClass('hide');

                jQuery('.Leadsname').removeClass('hide');
                jQuery('.LeadsData').removeClass('hide'); 
                jQuery('.Leadsname').addClass('show');
                jQuery('.LeadsData').addClass('show');

            }else if(select_modulename == 'Accounts'){
                jQuery('.Leadsname').removeClass('show');
                jQuery('.Leadsname').addClass('hide');
                jQuery('.Vendorsname').removeClass('show');
                jQuery('.Vendorsname').addClass('hide');
                jQuery('.Contactsname').removeClass('show');
                jQuery('.Contactsname').addClass('hide');
                jQuery('.AllMessagename').removeClass('show');
                jQuery('.AllMessagename').addClass('hide');
				jQuery('.Unknownname').removeClass('show');
                jQuery('.Unknownname').addClass('hide');

                jQuery('.LeadsData').removeClass('show');
                jQuery('.LeadsData').addClass('hide');
                jQuery('.VendorsData').removeClass('show');
                jQuery('.VendorsData').addClass('hide');
                jQuery('.ContactsData').removeClass('show');
                jQuery('.ContactsData').addClass('hide');
                jQuery('.AllMessageData').removeClass('show');
                jQuery('.AllMessageData').addClass('hide');
				jQuery('.UnknownData').removeClass('show');
                jQuery('.UnknownData').addClass('hide');

                jQuery('.Accountsname').removeClass('hide');
                jQuery('.AccountsData').removeClass('hide'); 
                jQuery('.Accountsname').addClass('show');
                jQuery('.AccountsData').addClass('show');

            }else if(select_modulename == 'Vendors'){
                jQuery('.Leadsname').removeClass('show');
                jQuery('.Leadsname').addClass('hide');
                jQuery('.Contactsname').removeClass('show');
                jQuery('.Contactsname').addClass('hide');
                jQuery('.Accountsname').removeClass('show');
                jQuery('.Accountsname').addClass('hide');
                jQuery('.AllMessagename').removeClass('show');
                jQuery('.AllMessagename').addClass('hide');
				jQuery('.Unknownname').removeClass('show');
                jQuery('.Unknownname').addClass('hide');

                jQuery('.LeadsData').removeClass('show');
                jQuery('.LeadsData').addClass('hide');
                jQuery('.AccountsData').removeClass('show');
                jQuery('.AccountsData').addClass('hide');
                jQuery('.ContactsData').removeClass('show');
                jQuery('.ContactsData').addClass('hide');
                jQuery('.AllMessageData').removeClass('show');
                jQuery('.AllMessageData').addClass('hide');
				jQuery('.UnknownData').removeClass('show');
                jQuery('.UnknownData').addClass('hide');

                jQuery('.Vendorsname').removeClass('hide');
                jQuery('.VendorsData').removeClass('hide'); 
                jQuery('.Vendorsname').addClass('show');
                jQuery('.VendorsData').addClass('show');
            }else if(select_modulename == 'New Messages'){
                jQuery('.Leadsname').removeClass('show');
                jQuery('.Leadsname').addClass('hide');
                jQuery('.Contactsname').removeClass('show');
                jQuery('.Contactsname').addClass('hide');
                jQuery('.Accountsname').removeClass('show');
                jQuery('.Accountsname').addClass('hide');
                jQuery('.Vendorsname').removeClass('show');
                jQuery('.Vendorsname').addClass('hide');
				jQuery('.Unknownname').removeClass('show');
                jQuery('.Unknownname').addClass('hide');

                jQuery('.LeadsData').removeClass('show');
                jQuery('.LeadsData').addClass('hide');
                jQuery('.AccountsData').removeClass('show');
                jQuery('.AccountsData').addClass('hide');
                jQuery('.ContactsData').removeClass('show');
                jQuery('.ContactsData').addClass('hide');
                jQuery('.VendorsData').removeClass('show');
                jQuery('.VendorsData').addClass('hide');
				jQuery('.UnknownData').removeClass('show');
                jQuery('.UnknownData').addClass('hide');

                jQuery('.AllMessagename').removeClass('hide');
                jQuery('.AllMessageData').removeClass('hide'); 
                jQuery('.AllMessagename').addClass('show');
                jQuery('.AllMessageData').addClass('show');
            }else if(select_modulename == 'Unknown Number'){
                jQuery('.Leadsname').removeClass('show');
                jQuery('.Leadsname').addClass('hide');
                jQuery('.Contactsname').removeClass('show');
                jQuery('.Contactsname').addClass('hide');
                jQuery('.Accountsname').removeClass('show');
                jQuery('.Accountsname').addClass('hide');
                jQuery('.Vendorsname').removeClass('show');
                jQuery('.Vendorsname').addClass('hide');
				jQuery('.AllMessagename').removeClass('show');
                jQuery('.AllMessagename').addClass('hide');

                jQuery('.LeadsData').removeClass('show');
                jQuery('.LeadsData').addClass('hide');
                jQuery('.AccountsData').removeClass('show');
                jQuery('.AccountsData').addClass('hide');
                jQuery('.ContactsData').removeClass('show');
                jQuery('.ContactsData').addClass('hide');
                jQuery('.VendorsData').removeClass('show');
                jQuery('.VendorsData').addClass('hide');
				jQuery('.AllMessageData').removeClass('show');
                jQuery('.AllMessageData').addClass('hide');

                jQuery('.Unknownname').removeClass('hide');
                jQuery('.UnknownData').removeClass('hide'); 
                jQuery('.Unknownname').addClass('show');
                jQuery('.UnknownData').addClass('show');
            }
        });
    },

    registerEventsForSendNewMsgOnSelectRecord : function() {
        jQuery('#filename').live('change', function(e){
            var tabid = jQuery('.tabid').val();
            msgbody = jQuery('#'+tabid+' .writemsg').val();
            var file = $('#'+tabid+' #filename').prop('files')[0];
            $('#'+tabid+' .writemsg').focus();
            $('#'+tabid+' .writemsg').val(file.name);
        });

        jQuery('.sendmsg').live('click', function(e){
            var thisInstance = this;
            var msgbody = '';
            var tabid = jQuery('.tabid').val();
            msgbody = jQuery('#'+tabid+' .writemsg').val();   
            
            if(msgbody == ''){
                app.helper.showErrorNotification({title: 'Error', message: 'Please enter your Message.'});
                return false;
            }
            var mobileno = jQuery('.phone_no').val();
            var module_recordid = jQuery('.module_recordid').val();

            var file = $('#'+tabid+' #filename').prop('files')[0];
            if(file === undefined){
                var filename = '';
            }else{
                var reader = new FileReader();
                reader.addEventListener('load', function() {
                    var res = reader.result; 
                    jQuery('[name="selectfile_data"]').val(res);
                });

                reader.readAsDataURL(file);
                var filename = file.name;
				var filetype = file.type;
            }
			
            setTimeout(function(){ 
                var base64imagedata = jQuery('[name="selectfile_data"]').val();
                var whatsappstorageurl = jQuery('#whatsappstorageurl').val();
                var currentdatetime = jQuery('#currentdatetime').val();
                var currentusername = jQuery('#currentusername').val();
				
				var msg_history = jQuery('#'+tabid+' .contChat');
				if(msgbody.indexOf('csv') > -1 || msgbody.indexOf('txt') > -1 || msgbody.indexOf('pdf') > -1 || msgbody.indexOf('mp4') > -1) {
					var msgurl = whatsappstorageurl+'/'+msgbody;
					var newtag = '<a href="'+msgurl+'" target="_black">'+msgurl+'</a>';
				}else if (msgbody.indexOf('jpeg') > -1 || msgbody.indexOf('jpg') > -1 || msgbody.indexOf('png') > -1) {
					var newtag = '<image src="'+base64imagedata+'" style="height: 60px;">';
				}else{
					var escapeEl = document.createElement('textarea');
					escapeEl.innerHTML = msgbody;
					var newtag = escapeEl.innerHTML;
				}
				
				message =  '<br><div class="myChat">' +
						   '    <p>'+newtag+'</p><br>' +
						   '     <span class="chatTime"><b>'+currentusername+'</b>  '+currentdatetime+' ' +
						   '    	<img src="layouts/v7/modules/CTWhatsApp/images/checkblack.png" style="width: 20px;"/>' +
						   '     </span> ' +
						   '</div><br><br>';
				msg_history.append(message);
				jQuery('#'+tabid+' .writemsg').val('');
                $('#'+tabid+' .contChat').animate({scrollTop: $('#'+tabid+' .contChat')[0].scrollHeight}, 0);
                var sourceModuleName = jQuery('#module_name').val();
                var params = {
                    'module' : 'CTWhatsApp', 
                    'view' : "WhatsappChat",
                    'mode' : "sendMSGOnWhatsapp",
                    'mobileno' : mobileno,
                    'msgbody' : msgbody,
                    'module_recordid' : module_recordid,
                    'base64imagedata' : base64imagedata,
                    'filename' : filename,
					'filetype' : filetype,
                    'sourceModuleName' : sourceModuleName
                }
                
                AppConnector.request(params).then(
                    function(data) {
						jQuery('#'+tabid+' .writemsg').val('');
						jQuery('#'+tabid+' #filename').val('');
						jQuery('[name="selectfile_data"]').val('');
                    }
                );
                return false;
            }, 500);
        });
    },

    registerEventsForSendNewMsgOnSelectRecordOnEnter : function() {
        jQuery('.tabcontent').live("keypress", function(e){
            if(e.keyCode == 13){
				var thisInstance = this;
				var msgbody = '';
				var tabid = jQuery('.tabid').val();
				msgbody = jQuery('#'+tabid+' .writemsg').val();   
				
				if(msgbody == ''){
					app.helper.showErrorNotification({title: 'Error', message: 'Please enter your Message.'});
					return false;
				}
				var mobileno = jQuery('.phone_no').val();
				var module_recordid = jQuery('.module_recordid').val();

				var file = $('#'+tabid+' #filename').prop('files')[0];
				if(file === undefined){
					var filename = '';
				}else{
					var reader = new FileReader();
					reader.addEventListener('load', function() {
						var res = reader.result; 
						jQuery('[name="selectfile_data"]').val(res);
					});

					reader.readAsDataURL(file);
					var filename = file.name;
					var filetype = file.type;
				}
				
				setTimeout(function(){ 
					var base64imagedata = jQuery('[name="selectfile_data"]').val();
					var whatsappstorageurl = jQuery('#whatsappstorageurl').val();
					var currentdatetime = jQuery('#currentdatetime').val();
					var currentusername = jQuery('#currentusername').val();
					
					var msg_history = jQuery('#'+tabid+' .contChat');
					if(msgbody.indexOf('csv') > -1 || msgbody.indexOf('txt') > -1 || msgbody.indexOf('pdf') > -1 || msgbody.indexOf('mp4') > -1) {
						var msgurl = whatsappstorageurl+'/'+msgbody;
						var newtag = '<a href="'+msgurl+'" target="_black">'+msgurl+'</a>';
					}else if (msgbody.indexOf('jpeg') > -1 || msgbody.indexOf('jpg') > -1 || msgbody.indexOf('png') > -1) {
						var newtag = '<image src="'+base64imagedata+'" style="height: 60px;">';
					}else{
						var escapeEl = document.createElement('textarea');
						escapeEl.innerHTML = msgbody;
						var newtag = escapeEl.innerHTML;
					}
					
					message =  '<br><div class="myChat">' +
							   '    <p>'+newtag+'</p><br>' +
							   '     <span class="chatTime"><b>'+currentusername+'</b>  '+currentdatetime+' ' +
							   '    	<img src="layouts/v7/modules/CTWhatsApp/images/checkblack.png" style="width: 20px;"/>' +
							   '     </span> ' +
							   '</div><br><br>';
					msg_history.append(message);
					jQuery('#'+tabid+' .writemsg').val('');
                    $('#'+tabid+' .contChat').animate({scrollTop: $('#'+tabid+' .contChat')[0].scrollHeight}, 0);
					var sourceModuleName = jQuery('#module_name').val();
					var params = {
						'module' : 'CTWhatsApp',
						'view' : "WhatsappChat",
						'mode' : "sendMSGOnWhatsapp",
						'mobileno' : mobileno,
						'msgbody' : msgbody,
						'module_recordid' : module_recordid,
						'base64imagedata' : base64imagedata,
						'filename' : filename,
						'filetype' : filetype,
                        'sourceModuleName' : sourceModuleName
					}
					
					AppConnector.request(params).then(
						function(data) {
							jQuery('#'+tabid+' .writemsg').val('');
							jQuery('#'+tabid+' #filename').val('');
							jQuery('[name="selectfile_data"]').val('');
						}
					);
					return false;
				}, 500);
            }
        });
    },

    registerEventsForSearch : function() {
		jQuery('[name="search"]').live("keyup", function() {
			var value = jQuery('[name="search"]').val();
			var sourcemodule = $('#module_name').val();
			if(sourcemodule != ''){
				if(value.length == 0){
					$('.moredata').show();
                    $('#loadmore').show();
                    $('.moredata').removeClass('hide');
                    $('#loadmore').removeClass('hide');
                    $('.norecorddata').addClass('hide');
                    jQuery('#notfound').val(0);
					if(sourcemodule == 'Unknown Number'){
						jQuery('.Unknownname #defaultOpen').removeClass('hide');
						jQuery('.Unknownname .searchrecords').remove();
						jQuery('.UnknownData .tabcontent').removeClass('hide');
						jQuery('.UnknownData .searchmsgs').remove();
					}else{
						jQuery('.'+sourcemodule+'name #defaultOpen').removeClass('hide');
						jQuery('.'+sourcemodule+'name .searchrecords').remove();
						jQuery('.'+sourcemodule+'Data .tabcontent').removeClass('hide');
						jQuery('.'+sourcemodule+'Data .searchmsgs').remove();
					}
				}
			}
		});
		
		jQuery('[name="search"]').live("keypress", function(e) {
			if(e.keyCode == 13){
				var value = jQuery('[name="search"]').val();
				var sourcemodule = $('#module_name').val();
				if(sourcemodule != ''){
					if(value.length >= 3){
						var lasttab_id = jQuery('#lasttab_id').val();
						if(lasttab_id == ''){
							var lasttab_id = $("."+sourcemodule+"name button").last().find('#recordidtabid').val();
						}
						var params = {
							'module' : 'CTWhatsApp',
							'view' : "WhatsappChat",
							'mode' : "searchRecords",
							'lasttabid' : lasttab_id,
							'sourcemodule' : sourcemodule,
							'serachvalue' : value
						}
						AppConnector.request(params).then(
							function(data) {
							if(data.result['getlasttabid']){
								var getlasttabid = data.result['getlasttabid'];
								jQuery('#lasttab_id').val(getlasttabid);
							}
							
							if(sourcemodule == 'Unknown Number'){
                                jQuery('.moredata').addClass('hide');
								jQuery('.Unknownname .searchrecords').remove();
								jQuery('.UnknownData .searchmsgs').remove();
								jQuery('.Unknownname #defaultOpen').addClass('hide');
								jQuery('.UnknownData .tabcontent').addClass('hide');
								var sidebardata = data.result['sidebar'];
								jQuery('.Unknownname').append(sidebardata);
								var msgdata = data.result['msgdata'];
								jQuery('.UnknownData').append(msgdata);
							}else{
                                jQuery('.loadmore').addClass('hide');
                                jQuery('.moredata').addClass('hide');
                                jQuery('#loadmore').addClass('hide');
								jQuery('.'+sourcemodule+'name .searchrecords').remove();
								jQuery('.'+sourcemodule+'Data .searchmsgs').remove();
								jQuery('.'+sourcemodule+'name #defaultOpen').addClass('hide');
								jQuery('.'+sourcemodule+'Data .tabcontent').addClass('hide');
								var sidebardata = data.result['sidebar'];
                                var notfound = jQuery('#notfound').val();
                                if(notfound != 1){
                                    jQuery('.'+sourcemodule+'name').append(sidebardata);
                                }
								var msgdata = data.result['msgdata'];
								jQuery('.'+sourcemodule+'Data').append(msgdata);
							}
						});
					}
				}
			}
		});

        jQuery('#serachrecord').live("click", function(e) {
            var value = jQuery('[name="search"]').val();
            if(value == ''){
                app.helper.showErrorNotification({title: 'Error', message: 'Please enter charachters in serach box.'});
                return false;
            }
            var sourcemodule = $('#module_name').val();
            if(sourcemodule != ''){
                var lasttab_id = jQuery('#lasttab_id').val();
                if(lasttab_id == ''){
                    var lasttab_id = $("."+sourcemodule+"name button").last().find('#recordidtabid').val();
                }
                var params = {
                    'module' : 'CTWhatsApp',
                    'view' : "WhatsappChat",
                    'mode' : "searchRecords",
                    'lasttabid' : lasttab_id,
                    'sourcemodule' : sourcemodule,
                    'serachvalue' : value
                }
                AppConnector.request(params).then(
                    function(data) {
                    if(data.result['getlasttabid']){
                        var getlasttabid = data.result['getlasttabid'];
                        jQuery('#lasttab_id').val(getlasttabid);
                    }
                 
                    if(sourcemodule == 'Unknown Number'){
                        jQuery('.Unknownname .searchrecords').remove();
                        jQuery('.UnknownData .searchmsgs').remove();
                        jQuery('.Unknownname #defaultOpen').addClass('hide');
                        jQuery('.UnknownData .tabcontent').addClass('hide');
                        var sidebardata = data.result['sidebar'];
                        jQuery('.Unknownname').append(sidebardata);
                        var msgdata = data.result['msgdata'];
                        jQuery('.UnknownData').append(msgdata);
                    }else{
                        jQuery('.loadmore').addClass('hide');
                        jQuery('.moredata').addClass('hide');
                        jQuery('#loadmore').addClass('hide');
                        jQuery('.'+sourcemodule+'name .searchrecords').remove();
                        jQuery('.'+sourcemodule+'Data .searchmsgs').remove();
                        jQuery('.'+sourcemodule+'name #defaultOpen').addClass('hide');
                        jQuery('.'+sourcemodule+'Data .tabcontent').addClass('hide');
                        var sidebardata = data.result['sidebar'];
                        var notfound = jQuery('#notfound').val();
                        if(notfound != 1){
                            jQuery('.'+sourcemodule+'name').append(sidebardata);
                        }
                        var msgdata = data.result['msgdata'];
                        jQuery('.'+sourcemodule+'Data').append(msgdata);
                    }
                });
            }
        });
    },

    registerEventsForReadMessagePerUser : function() {
        jQuery('.tablinks').live("click", function(e) {
            jQuery(this).find('.whatsappunreadcount').remove();
            var module_recordid = jQuery(e.currentTarget).data('module_recordid');
            var params = {
                'module' : 'CTWhatsApp',
                'view' : "WhatsappChat",
                'mode' : "readMessages",
                'module_recordid' : module_recordid
            }
            AppConnector.request(params).then(
                function(data) {
					
            })
      });
    },
	
	registerEventsForSendMessagewithMass : function() {
        jQuery('#sendmasswhatsappmsg').live("click", function(e) {
            var listInstance = window.app.controller();
			var listSelectParams = listInstance.getListSelectAllParams(false);
            listSelectParams['search_params'] = JSON.stringify(listInstance.getListSearchParams());
            if(listSelectParams.selected_ids === undefined){
				app.helper.showErrorNotification({title: 'Error', message: 'Please select atleast one record.'});
				return false;
			}
			var source_module = app.getModuleName();
			var params = {
                'module' : 'CTWhatsApp',
                'view' : "MassSendMessages",
                'mode' : "sendMessagePopup",
                'source_module' : source_module,
                'selected_ids' : listSelectParams.selected_ids
            }
			app.helper.showProgress();
			AppConnector.request(params).then(
                function(data) {
				app.helper.hideProgress();
				app.showModalWindow(data, function(data){
					jQuery('#sendmessage').on("click", function(e) {
						var msgbody = jQuery('#message').val();
                        var cvid = jQuery("input[name='cvid']").val();
						if(msgbody == ''){
							app.helper.showErrorNotification({title: 'Error', message: 'Please enter your Message.'});
							return false;
						}
						var params = {
							'module' : 'CTWhatsApp',
							'view' : "MassSendMessages", 
							'mode' : "sendMessage",
							'selected_ids' : listSelectParams.selected_ids,
							'msgbody' : msgbody,
							'source_module' : source_module,
                            'cvid' : cvid,
                            'searchvalue' : listSelectParams.search_params
						}
						app.helper.showProgress();
						AppConnector.request(params).then(
							function(data) {
								app.helper.hideProgress();
								app.helper.showSuccessNotification({'title': 'Success', 'message': 'Message sent successfully'});
								app.helper.hideModal();
                                setTimeout(function(){
                                    location.reload();
                                }, 1000);
						});
					});
				});
            });
		});
    },
	
	//Add Comment
	registerEventsForComments : function() {
        jQuery('#commentsdate').live("click", function(e) {
            var popupInstance = Vtiger_Popup_Js.getInstance();
			var params = {
                'module' : 'CTWhatsApp',
                'view' : "Comments",
				'mode' : "commentsPopup"
            }
			popupInstance.showPopup(params,Vtiger_Edit_Js.popupSelectionEvent,function() {
				jQuery('#savecomments').on("click", function(e) {
					var recordid = jQuery('#module_recordid').val();
					var datefilter = jQuery('#datefilter').val();
					if(datefilter == ''){
						app.helper.showErrorNotification({title: 'Error', message: 'Please select Date'});
						return false;
					}
					var customdate = jQuery('#customdate').val();
					var commententry = jQuery("input[name='commententry']:checked").val();
					
					var params = {
						'module' : 'CTWhatsApp',
						'view' : "Comments",
						'mode' : "saveComments",
						'recordid' : recordid,
						'datefilter' : datefilter,
						'customdate' : customdate,
						'commententry' : commententry
					}
					app.helper.showProgress();
					AppConnector.request(params).then(
						function(data) {
						app.helper.hideProgress();
						app.helper.hidePopup();
						app.helper.showSuccessNotification({'title': 'Success', 'message': 'Comments added successfully'});
					});
				});
			});
		});
		
		jQuery('#datefilter').live("change", function(e) {
            var datefilter = jQuery('#datefilter').val();
			if(datefilter == "custom"){
				jQuery('.customdateblock').removeClass('hide');
			}else{
				jQuery('.customdateblock').addClass('hide');
			}
		});
		
		jQuery('#modulefields').live("change", function(e) {
            var modulefields = jQuery('#modulefields').val();
			var oldtext = jQuery('#message').val();
			var newtext = oldtext+' '+modulefields;
			jQuery('#message').val(newtext);
		});
    },
	//Add Comment
	
	//Open Image in new window
	registerEventsForOpenImageFile : function() {
        jQuery('.myChat, .repChat, .message').live("click", function(e) {
            var currentTarget = jQuery(e.currentTarget);
            var imageURL = currentTarget.find('img').attr('src');
            if(imageURL.indexOf('images') > -1){
			}else{
				window.open(imageURL);
			}
      });
    },
	//Open Image in new window
	
	registerRelatedQuickCreateEvent : function (){
		var thisInstance = this;
		
		jQuery("#quickcreateWhatsapp").live("change", function(e){
			var popupInstance = Vtiger_Popup_Js.getInstance();
			var activetabid = jQuery(".avtivetabid").val(); 
			
			var quickCreateModuleName = jQuery("#"+activetabid).find('#quickcreateWhatsapp').val();
			if(quickCreateModuleName == ''){
				return false;
			}
			var sendername = jQuery('#'+activetabid).find('.pName').html();
			var senderphone = jQuery('#'+activetabid).find('.pRight').html();
			var params = {
				'module' : 'CTWhatsApp',
				'view' : "QuickCreateRecord", 
				'mode' : "quickCreatePopup",
				'quickCreateModuleName' : quickCreateModuleName,
				'sendername' : sendername,
				'senderphone' : senderphone  
			}
			popupInstance.showPopup(params,Vtiger_Edit_Js.popupSelectionEvent,function() {
				jQuery('.modal-backdrop').css({'z-index':'auto'});
				jQuery('#saverecord').on("click", function(e) {
					var serialize = jQuery('#newrecord').serializeFormData();
					var params = {
						'module' : 'CTWhatsApp',
						'view' : "QuickCreateRecord",
						'mode' : "saveRecord",
						'quickCreateModuleName' : quickCreateModuleName,
						'serializedata' : serialize,
						'sender_phone' : senderphone
					}
					app.helper.showProgress();
					AppConnector.request(params).then(
						function(data) {
						app.helper.hideProgress();
						var recordurl = 'index.php?module='+quickCreateModuleName+'&view=Detail&record='+data.result;
						jQuery('#'+activetabid).find('.pName').html('')
						jQuery('#'+activetabid).find('.pName').html('<a href="'+recordurl+'" target="_blank">'+sendername+'');
						app.helper.hidePopup();
						app.helper.showSuccessNotification({'title': 'Success', 'message': 'Record is save successfully.'});
					});
				});
			});
		});
	},

    //CreateRelatedRecord
    registerCreateRelatedRecord : function() {
        jQuery('.quickcreateRelated').live('change', function(e) {
            var popupInstance = Vtiger_Popup_Js.getInstance();
            var activetabid = jQuery(".avtivetabid").val(); 
            var recordid = jQuery('#'+activetabid+' .module_recordid').val();
            var quickCreateModuleName = jQuery("#"+activetabid).find('#quickcreateRelated').val();
            if(quickCreateModuleName == ''){
                return false;
            }
            var sourceModuleName = $('#module_name').val();
            
            var params = {
                'module' : 'CTWhatsApp',
                'view' : "QuickCreateRecord", 
                'mode' : "relatedQuickCreatePopup",
                'quickCreateModuleName' : quickCreateModuleName
            }
            popupInstance.showPopup(params,Vtiger_Edit_Js.popupSelectionEvent,function() {
                jQuery('.modal-backdrop').css({'z-index':'auto'});
                jQuery('#saverecord').on("click", function(e) {
                    var serialize = jQuery('#newrecord').serializeFormData();
                    
                    var params = {
                        'module' : 'CTWhatsApp',
                        'view' : "QuickCreateRecord",
                        'mode' : "saveRelatedRecord",
                        'quickCreateModuleName' : quickCreateModuleName,
                        'serialize' : serialize,
                        'recordid' : recordid,
                        'sourceModuleName' : sourceModuleName
                    }
                    app.helper.showProgress();
                    AppConnector.request(params).then(
                        function(data) {
                        app.helper.hideProgress();
                        app.helper.hidePopup();
                        app.helper.showSuccessNotification({'title': 'Success', 'message': 'Record is save successfully.'});
                    });
                });
            });
        });
    },
    //CreateRelatedRecord

    //Edit Repord On Whatsapp Popup
    registerEventForEditRecordInPopup : function() {
        jQuery('.editField').live("click", function(e) {
            var popupInstance = Vtiger_Popup_Js.getInstance();
            var currentTarget = jQuery(e.currentTarget);
            var activetabid = jQuery(".avtivetabid").val();
            var SourceModuleName = jQuery("#module_name").val();
            var ModuleRecordId = jQuery("#"+activetabid+" .module_recordid").val();
            var msgBody = currentTarget.prev('.repChat').find('p').text();
            if(ModuleRecordId === undefined){
                var ModuleRecordId = jQuery("#module_recordid").val();
            }

            if(msgBody == ''){
                var msgBody = currentTarget.prev('.received').find('p').text();
            }
            
            var params = {
                'module' : 'CTWhatsApp',
                'view' : "QuickCreateRecord", 
                'mode' : "editRecordWithSelectBody",
                'sourceModuleName' : SourceModuleName,
                'moduleRecordId' : ModuleRecordId,
                'msgBody' : msgBody  
            }
            popupInstance.showPopup(params,Vtiger_Edit_Js.popupSelectionEvent,function() {
                jQuery('.modal-backdrop').css({'z-index':'auto'});
                jQuery('#saveEditRecord').on("click", function(e) {
                    var fieldname = jQuery("#fieldname").val();
                    var params = {
                        'module' : 'CTWhatsApp',
                        'view' : "QuickCreateRecord", 
                        'mode' : "saveEditRecordWithSelectBody",
                        'sourceModuleName' : SourceModuleName,
                        'moduleRecordId' : ModuleRecordId,
                        'msgBody' : msgBody,
                        'fieldname' : fieldname
                    }
                    app.helper.showProgress();
                    AppConnector.request(params).then(
                        function(data) {
                        app.helper.hideProgress();
                        app.helper.hidePopup();
                        app.helper.showSuccessNotification({'title': 'Success', 'message': 'Record is edit successfully.'});
                    });
                });

            });
        });
    },
    //Edit Repord On Whatsapp Popup

    /**
     * Registered the events for this page
     */
    registerEvents : function(form) {
        var thisInstance = this;
        this.registerEventsForWhatappChatPopup();
        this.registerEventsForSendNewMsg();
        this.registerEventsForSendNewMsgOnEnter();
        this.registerEventsForAllWhatappChat();
        this.registerEventsForSelectModuleChat();
        this.registerEventsForSendNewMsgOnSelectRecord();
        this.registerEventsForSendNewMsgOnSelectRecordOnEnter();
        this.registerEventsForSearch();
        this.registerEventsForReadMessagePerUser();
        this.registerEventsForSendMessagewithMass();
        this.registerEventsForComments();
        this.registerEventsForOpenImageFile();
        this.registerRelatedQuickCreateEvent();
        this.registerCreateRelatedRecord();
        this.registerEventForEditRecordInPopup();
    }    
});

jQuery(document).ready(function(){

    var thisInstance = new WhatsappCommon_Js();
    thisInstance.registerEvents(); 
    var params = {
        'module' : 'CTWhatsApp',
        'view' : "WhatsappChat",
        'mode' : "getWhatsappIcon"
    }
    AppConnector.request(params).then(
        function(data) {
            if(data.result['whatsappicon'] == 1 ){
                if(data.result['unread_count'] != 0){
                    var unreadcount = "<span style='border-radius: 18px; font: bold 10px Arial; padding: 1px 5px; margin: 2px 8px 4px -3px;background: red;color: white;top:-5px;position:relative;right:3px' >"+data.result['unread_count']+"</span>";
                }else{
                    var unreadcount = '';
                }

                var whatsappbutton = "<li id='allwhatsappmsg' style='margin: 12px 10px 0px 0px;'><input type='hidden' name='whatsappicon' id='whatsappicon' value='"+data.result['whatsappicon']+"'><input type='hidden' name='currentdate' id='currentdate' value='"+data.result['currentdate']+"'><input type='hidden' name='licensedate' id='licensedate' value='"+data.result['licensedate']+"'><input type='hidden' name='whatsapptatus' id='whatsapptatus' value='"+data.result['whatsappStatus']+"'><div class='dropdown'><img src='layouts/v7/modules/CTWhatsApp/image/whatsapp.png' style='cursor: pointer;height: 20px;' />"+unreadcount+"</div></li>";
                jQuery('#navbar li:eq(0)').before(whatsappbutton);
				if(app.getModuleName() == "Contacts" || app.getModuleName() == "Leads" || app.getModuleName() == "Accounts"){
				    var masssendmsg = "<input type='hidden' id='massButton' value='1'><li class='selectFreeRecords'><a id='sendmasswhatsappmsg' href='javascript:void(0);'>Send Whatsapp Message</a></li>";
				    jQuery('.listViewMassActions ul').append(masssendmsg);
                }
            }
        }
    );

    if(app.getModuleName() == "Contacts" || app.getModuleName() == "Leads" || app.getModuleName() == "Accounts"){
        setInterval(function(){
            var massButton = $('#massButton').val();
            if(massButton != 1){
                var masssendmsg = "<input type='hidden' id='massButton' value='1'><li class='selectFreeRecords'><a id='sendmasswhatsappmsg' href='javascript:void(0);'>Send Whatsapp Message</a></li>";
                jQuery('.listViewMassActions ul').append(masssendmsg);
            }
        }, 1500);
    }


	setTimeout(function(){
		var modulerecordid = jQuery('#recordId').val();
		var params = {
			'module' : 'CTWhatsApp',
			'view' : "WhatsappChatPopup",
			'mode' : "allowAccessWhatsapp",
			'source_module' : app.getModuleName(),
			'recordid' : modulerecordid
		 }
		AppConnector.request(params).then(
			function(data) {
				var whatsappicon = jQuery('[name="whatsappicon"]').val();
				if(whatsappicon == 1){
					if(data.result['active'] == 1){
						jQuery('#whatsapp').html('');
						if(data.result['unreadmsg'] != 0){
							var notificationcount = "<span style='border-radius: 18px; font: bold 10px Arial; padding: 1px 5px; background: red; margin: 2px 8px 4px -3px;color: white;' id='smscounts'>"+data.result['unreadmsg']+"</span>";
						}else{
							var notificationcount = "<span style='border-radius: 18px; font: bold 10px Arial; padding: 1px 5px; margin: 2px 8px 4px -3px;color: white;' id='smscounts'>"+data.result['unreadmsg']+"</span>";
						}

						var whatsappimage = "<div id='whatsapp' style='margin: 1px 1px 1px 90px;'><input type='hidden' id='whatsappnumber' value='"+data.result['fieldvalue']+"'><img src='layouts/v7/modules/CTWhatsApp/image/whatsapp.png' style='height: 20px;cursor: pointer;margin: 1px -5px -23px 2px;'>"+notificationcount+"</div>";
						jQuery('.recordBasicInfo').after(whatsappimage);
					}
				}
			}
		);
	}, 1500);
    if(app.view() == 'Detail'){
        setInterval(function(){ 
			var whatsapppoupopen = jQuery('#whatsapppoupopen').val();
			if(whatsapppoupopen == 'true'){				
				var whatsappicon = jQuery('[name="whatsappicon"]').val();
				if(whatsappicon == 1){
					var recordId = jQuery('#recordId').val();
					var moduleName = app.getModuleName();
					var params = {
						'module' : 'CTWhatsApp',
						'view' : "WhatsappChatPopup",
						'mode' : "getAllMsgs",
						'mobileno' : '',
						'module_recordid' : recordId,
						'sourcemodulename' : moduleName
					}
					AppConnector.request(params).then(
						function(data) {
						if(data.result['unreadmsg'] != 0){
							jQuery('#smscounts').show();
							jQuery('#smscounts').css({background: 'red'});
							jQuery('#smscounts').text(data.result['unreadmsg']);
						}else{
							jQuery('#smscounts').hide();
						}
						jQuery('#currentdatetime').val(data.result['currentdatetime']);
						//jQuery('#ap').html('');
						var msg_history = jQuery('#ap');
						for (var i = 0; i < data.result['msgreceived'].length; i++) {
							var image = data.result['msgreceived'][i]['message'];
							if(image.indexOf('csv') > -1 || image.indexOf('txt') > -1 || image.indexOf('pdf') > -1 || image.indexOf('docx') > -1 || image.indexOf('mp4') > -1 || image.indexOf('mp3') > -1) {
								var newtag = '<a href="'+data.result['msgreceived'][i]['message']+'" target="_black">'+data.result['msgreceived'][i]['message']+'</a>';
							}else if (image.indexOf('storage') > -1 || image.indexOf('jpeg') > -1) {
								var newtag = '<image src="'+data.result['msgreceived'][i]['message']+'" style="height: 60px;">';
							}else{
								var newtag = '<p>'+data.result['msgreceived'][i]['message']+'</p>';
							}
							if(data.result['msgreceived'][i]['type'] == "Recieved"){
								
								message =  '<div class="message received">' +
								'    '+newtag+'' +
								'    <span class="metadata"><span class="time"><b>'+data.result['msgreceived'][i]['sendername']+'</b> '+data.result['msgreceived'][i]['createdtime']+'</span></span>' +
								'</div><span class="editField" style="float: left;"><img src="layouts/v7/modules/CTWhatsApp/images/editcontent.png" style="width: 15px;" title="Copy text to any fields"></span>';
							}else{  
								
								message = '<div class="message sent">' +
								'    '+newtag+' ' +
								'    <span class="metadata">' +
								'        <span class="time"><b>'+data.result['msgreceived'][i]['sendername']+'</b> '+data.result['msgreceived'][i]['createdtime']+'</span>' +
								'    </span>' +
								'</div>';
							}
							msg_history.append(message);
						}
						if(data.result['unreadmsg'] != 0){
							var propdata = jQuery('.conversation-container').prop("scrollHeight");
							jQuery(".conversation-container").animate({ scrollTop: propdata + 100}, 0);
						}
						
					});
				}
			}
        }, 5000);
    }
	
	setInterval(function(){ 
		var whatsappmainpoupopen = jQuery('#whatsappmainpoupopen').val();
		if(whatsappmainpoupopen == 'true'){
			var module_recordid = jQuery('.module_recordid').val();
			if(module_recordid !== undefined && module_recordid != ''){
				var tabid = jQuery('.tabid').val();
				if(module_recordid != ''){
					var params = {
						'module' : 'CTWhatsApp',
						'view' : "WhatsappChat",
						'mode' : "getAllMsgs",
						'module_recordid' : module_recordid
					}
					AppConnector.request(params).then(
						function(data) {
							var msg_history = jQuery('#'+tabid+' .contChat');
							for (var i = 0; i < data.result['msgreceived'].length; i++) {
								var image = data.result['msgreceived'][i]['message_body'];
								if(image.indexOf('csv') > -1 || image.indexOf('txt') > -1 || image.indexOf('pdf') > -1 || image.indexOf('docx') > -1 || image.indexOf('mp4') > -1 || image.indexOf('mp3') > -1) {
									var newtag = '<a href="'+data.result['msgreceived'][i]['message_body']+'" target="_black">'+data.result['msgreceived'][i]['message_body']+'</a>';
								}else if (image.indexOf('storage') > -1 || image.indexOf('jpeg') > -1) {
									var newtag = '<image src="'+data.result['msgreceived'][i]['message_body']+'" style="height: 60px;">';
								}else{
									var newtag = '<p>'+data.result['msgreceived'][i]['message_body']+'</p>';
								}
								if(data.result['msgreceived'][i]['message_type'] == "Send"){
									
									message =  '<br><div class="myChat">' +
											   '    '+newtag+'' +
											   '     <span class="chatTime">'+data.result['msgreceived'][i]['sendername']+'  '+data.result['msgreceived'][i]['createdtime']+'</span>' +
											   '</div><br><br><br>';
								}else{
									
									message = '<br><div class="repChat">' +
											  '    	'+newtag+'' +
											  '     <span class="chatTime"><b>'+data.result['msgreceived'][i]['sendername']+'  '+data.result['msgreceived'][i]['createdtime']+'</b></span>' +
											  ' </div><span class="editField" style="float: left;"><img src="layouts/v7/modules/CTWhatsApp/images/editcontent.png" style="width: 15px;" title="Copy text to any fields"></span>';
								}
								msg_history.append(message);
							}
                            if(data.result['msgreceived'].length != 0){
				                $('#'+tabid+' .contChat').animate({scrollTop: $('#'+tabid+' .contChat')[0].scrollHeight}, 0);
                            }
						}
					);
				}
			}
		}
	}, 5000);
});
