/*----------------------------------------------------------------------------------|  www.vdm.io  |----/
				fdsh 
/-------------------------------------------------------------------------------------------------------/

	@version		1.0.39
	@build			4th April, 2023
	@created		17th December, 2020
	@package		Reservation
	@subpackage		messages.js
	@author			farhad shahbazi <http://farhad.com>	
	@copyright		Copyright (C) 2015. All Rights Reserved
	@license		GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html
  ____  _____  _____  __  __  __      __       ___  _____  __  __  ____  _____  _  _  ____  _  _  ____ 
 (_  _)(  _  )(  _  )(  \/  )(  )    /__\     / __)(  _  )(  \/  )(  _ \(  _  )( \( )( ___)( \( )(_  _)
.-_)(   )(_)(  )(_)(  )    (  )(__  /(__)\   ( (__  )(_)(  )    (  )___/ )(_)(  )  (  )__)  )  (   )(  
\____) (_____)(_____)(_/\/\_)(____)(__)(__)   \___)(_____)(_/\/\_)(__)  (_____)(_)\_)(____)(_)\_) (__) 

/------------------------------------------------------------------------------------------------------*/

/* JS Document */

/***[JCBGUI.site_view.javascript_file.26.$$$$]***/
var pmlist = []
jQuery(document).ready(function($) {
  // auto height textarea for send
  function auto_grow(element) {
    element.style.height = "5px";
    element.style.height = (element.scrollHeight)+"px";
  }
  function readMessage(chatAjaxRoute, mid, seid) {
    $.ajax({
      url: chatAjaxRoute,
      method: 'post',
      data: {
        [token]: '1',
        task: 'ajax.ajaxReadMessage',
        format: 'json',
        raw: 'true',
        mid: mid,
        seid: seid
      },
      success: function(msg) {
      },
      error: function(err) {
      }
    });
  }
	function dateFormat(inputDate, format) {
		const date = new Date(inputDate);
		const p2e = s => s.replace(/[۰-۹]/g, d => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d))
		perday = p2e(date.toLocaleDateString('fa-IR')).split('/');
		const day = perday[2];
		const month = perday[1];
		const year = perday[0];
		const hour = date.getHours();
		const min = date.getMinutes();
		format = format.replace("MM", month.toString().padStart(2, "0"));
		if (format.indexOf("yyyy") > -1) {
			format = format.replace("yyyy", year.toString());
		} else if (format.indexOf("yy") > -1) {
			format = format.replace("yy", year.toString().substr(2, 2));
		}
		format = format.replace("dd", day.toString().padStart(2, "0"));
		format = format.replace("H", hour.toString().padStart(2, "0"));
		format = format.replace("M", min.toString().padStart(2, "0"));
		return format;
	}
  function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
  
	var token = $("#token").attr("name");
	var chatAjaxRoute = Joomla.getOptions('chatAjaxRoute');
	var from = Joomla.getOptions('userId');
	var to = Joomla.getOptions('to');
	var seid = Joomla.getOptions('seid');
	var pid = Joomla.getOptions('pid');
	var uid = Joomla.getOptions('uid');
	var channel_token = Joomla.getOptions('channel_token');
  
  
  
  
  $(document).on('contextmenu', '.pm', function(e) {
    e.preventDefault();
    
    cm = $('#context-menu');
    cb = $('#chat-body');
    cm.data('refer', this.id);
    focused = $('.focus');
    $.each(focused, function(i, val){
      val.classList.remove('focus');
    });
    
    
    $(this).addClass('focus');
    if (this.classList.contains('me')) {
      $('#editctxbtn').css('display', 'flex');
      $('#delctxbtn').css('display', 'flex');
      cm.data('user-name', 'خودم');
    }
    else {
      $('#editctxbtn').css('display', 'none');
      $('#delctxbtn').css('display', 'none');
      cm.data('user-name', $('#user-name').text());
    }
    cm.css('display', 'block');
    t = Math.min(e.pageY, cb.offset().top + cb.height() - cm.height());
    l = Math.min(e.pageX, cb.offset().left + cb.width() - cm.width());
    cm.css('top', t);
    cm.css('left', l);
  });
  $(document).on('click', 'div[id^=rep-]', function(e) {
    destid = '#pm-' + this.id.substr(4)
    p = $(destid);
    // console.log(destid);
    p.addClass('focus2');
    e = jQuery('#chat-body')[0];
    e.scrollTop = e.scrollTop + p.offset().top - 1.5 * e.clientHeight;
    setTimeout(function(){
        p.removeClass('focus2');
    }, 1500);
  });
  $(document).on('click', '#chat-body', function(e) {
    e.preventDefault();
    cm = $('#context-menu');
    cm.css('display', 'none');
    focused = $('.focus');
    $.each(focused, function(i, val){
      val.classList.remove('focus');
    });
    $('#editctxbtn').css('display', 'none');
    $('#delctxbtn').css('display', 'none');

  });
  li = 0;

  $(document).on('click', '#reply-close', function(e) {
    rh = $('#reply-header');
    rh.css('display', 'none');
    $('#reply-id').val('0');
    focused = $('.focus');
    $.each(focused, function(i, val){
      val.classList.remove('focus');
    });
  });
  $(document).on('click', 'li.Menu_MenuItemWrapper__NyeOc', function(e) {
    e.preventDefault();
    li = e;
    function copyToClipboard(text) {
      var dummy = document.createElement("textarea");
      document.body.appendChild(dummy);
      dummy.value = text;
      dummy.select();
      document.execCommand("copy");
      document.body.removeChild(dummy);
    }
    // copyToClipboard(this.innerText.trim())

    cm = $('#context-menu');
    cm.css('display', 'none');
    text = $('#' + cm.data('refer') + ' > div.text > span').text().trim();
    pmid = cm.data('refer').substr(3);
    switch($(this).data('cmd')) {
      case 'copy':
        copyToClipboard(text);
        Toastify({
          text: 'رونوشت پیام انجام شد.',
          duration: 3000,
          close: true,
          gravity: "top", // `top` or `bottom`
          position: "center", // `left`, `center` or `right`
          stopOnFocus: true, // Prevents dismissing of toast on hover
          style: {
            background: "#091e42a6",
          },
          offset: {
            y: 20
          },
          onClick: function(){} // Callback after click
        }).showToast();
        break;
      case 'reply':
        rh = $('#reply-header');
        rh.css('display', 'flex');
        cm = $('#context-menu');
        $('#reply-user').html(cm.data('user-name'));
        $('#reply-text').html(text);
        $('#reply-id').val(pmid);
        break;
      case 'edit':
        jQuery('#chatMessage').val(text)
        $('#pmid').val(pmid);
        reply = jQuery('#pm-'+pmid+' > div.reply');
        if(reply.length >= 1) {
          replyid = reply[0].id.substr(4);
          $('#reply-id').val(replyid);
        }
        break;
        
    }

  });
  
  
  
  $(document).on('input', '#chatMessage', function(e) {
    target = $(this);
    auto_grow(target[0]);
  });
  // im = jQuery('div.text > span > img')
  var modal = document.getElementById("myModal");
  var modalImg = document.getElementById("img01");
  var captionText = document.getElementById("caption");
  $(document).on('click','div.text > span > img',function (e) {
    modal.style.display = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;
  })
  var span = document.getElementsByClassName("closeimg")[0];
  span.onclick = function() { 
      modal.style.display = "none";
  }
  
  var filename = '';
  var delayInMilliseconds = 1500; //1 second
	$(':file').on('change', function () {
    var file = this.files[0];
    // filename = file.name;
    // if (file.size > 10240) {
    //   alert('max upload size is 10k');
    // }

    // Also see .name, .type
	});
  $('#submit-delete').on('click', function () {
    // alert('deleted ' + $("#confirm-delete").data('id'));
    id = $("#confirm-delete").data('id');
    
    $.ajax({
      url: chatAjaxRoute,
      method: 'post',
      data:{[token] : '1' , task: 'ajax.deleteChat', format: 'json', raw: 'true', mid: id},
      success: function (msg) {
        // console.log($('#pm-' + id));
        $('#pm-' + id).remove();
      },
      error: function (err) {
      }
    });
    
    
    
    
  });
  // $( "#confirm-delete" ).on('shown', function(){
    // alert("I want this to appear after the modal has opened!");
  // });
  
  $( "#delctxbtn" ).on('click', function(){
    // alert($("#context-menu").data('refer'));
    $("#confirm-delete").data('id', $("#context-menu").data('refer').substr(3));
  });
  
  $('#chatSendBtn').on('click', function () { // for sending file
    var _this= $(this);
    var formdata = new FormData($('#sending-form')[0]);
    $.ajax({
      // Your server script to process the upload
      url: '/components/com_reservation/controllers/fileupload.php',
      type: 'POST',
      // Form data
      data: formdata,
      // Tell jQuery not to process data or worry about content-type
      // You *must* include these options!
      cache: false,
      contentType: false,
      processData: false,
      // dataType: "JSON",
      beforeSend: function () {
          //Your functions before send AJAX Request
      },
      success: function (msg) {
        filename = msg;

        if(filename) {
          url = '/components/com_reservation/files/' + filename;
          sleep(delayInMilliseconds).then(() => {
            ext = filename.split('.').pop().toLowerCase();
            image_ext = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'jfif', 'pjpeg', 'webp', 'tif', 'tiff'];
            var msg = '';
            if(image_ext.includes(ext)) {
              msg = '<img src="'+url+'">';
            }
            else {
              msg = '<a href="'+url+'">' + filename + '</a>';
            }
            
            $.ajax({
              url: chatAjaxRoute,
              method: 'post',
              data:{[token] : '1' , task: 'ajax.saveChat', format: 'json', raw: 'true', message:msg,from: from, to: to, seid: seid, pid: pid},
              success: function (msge) {
                var currentdate = new Date(); 
                
                appendmsg = '<div class="pm me" id="pm-' + msge.id + '"><div class="text"><span class="massage">' + msg  + '</span><div class="info-message"><span class="readtick unread" style=""></span><span class="time">' + dateFormat(currentdate, 'yyyy/MM/dd H:M') + '</span></div></div></div>';
                
                $('#chat-body').append(appendmsg);
                _this.next('#chatMessage').val('');
                var chatBoxBody = $('#chat-body')[0];
                scrollToEnd(chatBoxBody);
              },
              error: function (err) {
              }
            });
            $('#atachedfile').val('');
            filename = '';
          });
        }
      },
      error: function (error) {
      },
      // Custom XMLHttpRequest
      xhr: function () {
        var myXhr = $.ajaxSettings.xhr();
        if (myXhr.upload) {
          // For handling the progress of the upload
          myXhr.upload.addEventListener('progress', function (e) {
            if (e.lengthComputable) {
              $('progress').show();
              $('progress').attr({
                value: e.loaded,
                max: e.total,
              });
              $('#chatSendBtn').css('cursor','no-drop');
              $('#chatSendBtn').prop('disabled', true);
              if(e.loaded == e.total) {
                $('#chatSendBtn').css('cursor','pointer');
                $('#chatSendBtn').prop('disabled', false);
                $('progress').hide();
                // $('#atachedfile').clearFields();
              }
            }
          }, false);
        }
        return myXhr;
      }
	  });
	});
  
  
	// Enable pusher logging - don't include this in production
	// Pusher.logToConsole = true;

	var pusher = new Pusher('ded62ba8f60c31da4778', {
		cluster: 'ap2'
	});

	var channel = pusher.subscribe(channel_token);
	channel.bind('my-event', function(data) {
		if (data.to == from) {

			var user = $('.chat .users').find('#user' + data.from);

			currentdate = new Date();
      reply = '';
      if(data.reply != 0) {
        reply_pm = $('#pm-' + data.reply);
        reply_text = $('#pm-' + data.reply + '> div.text > span').text().trim();
        if(reply_pm.hasClass('me')) {
          reply_user = 'خودم';
        }
        else {
          reply_user = $('#user-name').text();
        }
        // if(reply_pm.hasClass('me')
        reply = '<div id="rep-'+data.reply+'" class="text reply"><div class="Preview_preview__7RTlb" data-prevent-context-menu-mobile="true" style="border-right: 3px solid rgb(19, 194, 194);"><div class="Preview_details__kki9K"><span class="Preview_sender__RUCFl" style="color: rgb(19, 194, 194);">'+reply_user+'</span><div class="Text_text__0QjN9 TextPreview_text_preview__7vRSt"><span>'+reply_text+'</span></div></div></div></div>';
      }
      // console.log('data', data);
      if(!data.pmid)
      {
        $('#chat-body').append('<div class="pm" id="pm-' + data.id + '"><div class="text"><span class="massage">' + data.message + '</span><div class="info-message"><span class="time">' + dateFormat(currentdate, 'yyyy/MM/dd H:M') + '</span></div></div>'+reply+'</div>');
      } else {
        
        appendmsg = '<div class="text"><span class="massage">' + data.message + '</span><div class="info-message"><span class="time">' + dateFormat(currentdate, 'yyyy/MM/dd H:M') + '</span></div></div>'
        $( `#pm-${data.pmid}` ).find('div.text:not(.reply)').replaceWith( appendmsg );
      }
      readMessage(chatAjaxRoute, data.id, seid);
			var chatBoxBody = $('#chat-body')[0];
			scrollToEnd(chatBoxBody);
		} else if (data.id && data.read) {
			p = $('#pm-' + data.id);
			tick = p.find('.readtick');
			tick.addClass('read')
			tick.removeClass('unread')
		}
	});

	function elementViewed(elmselector) {
		selector = '#chat-body';

		wH = $(selector).height(),
			wS = $(selector).scrollTop();

		hT = $(elmselector).offset().top;
		hH = $(elmselector).outerHeight();
		// console.log(elmselector);
		// console.log(wS);
		// console.log(wH);
		// console.log(hT+hH-wH);
		// console.log('');

		alpha = (hT + hH - wH);
		// if (wS > alpha && alpha >= 0 && alpha <= wH) return true;
		if (alpha >= 0 && alpha - wH <=  2 * hH) return true;
		return false;
	}

  function readAvailableMessages() {
    pms = $('.pm:not(.me)');
    $.each(pms, function(i, val) {
      if (elementViewed('#' + val.id)) {
        pm = $('#' + val.id);
        tick = pm.find('.readtick');
        if (tick.hasClass('unread') && !pmlist.includes(val.id)) {
          pmlist.push(val.id);
          idnum = parseInt(val.id.split('-')[1])
          readMessage(chatAjaxRoute, idnum, seid);

        }
      }
    });
  }
	cb = $('#chat-body');
  if(cb[0].clientHeight < cb[0].scrollHeight) { // has scroll
    cb.scroll(function(e) {
      readAvailableMessages();
    });
  } else {
    readAvailableMessages();
  }


	var chatBoxBody = $('#chat-body')[0];
	scrollToEnd(chatBoxBody);

	$(document).on('click', 'button#conversation', function(e) {
		e.preventDefault();

		var _this = $(this);
		var token = $("#token").attr("name");

		showLoading(_this);

		$.ajax({
			url: chatAjaxRoute,
			method: 'post',
			data: {
				[token]: '1',
				task: 'ajax.conversation',
				format: 'json',
				raw: 'true',
				user1: from,
				user2: to,
				seid: seid,
				pid: pid
			},
			success: function(msg) {

				if (msg) {
					_this.removeClass('btn-danger');
					_this.addClass('btn-success');
					_this.text('ادامه گفتگو');
					$('#chatSendBtn').css('cursor', 'no-drop');
					$('#chatSendBtn').prop('disabled', true);
					$('#notice').text('گفتگو خاتمه یافت');
				} else {
					_this.removeClass('btn-success');
					_this.addClass('btn-danger');
					_this.text('پایان گفتگو');
					$('#chatSendBtn').css('cursor', 'pointer');
					$('#chatSendBtn').prop('disabled', false);
					$('#notice').text('گفتگو در حال انجام است');
				}

				hideLoading(_this);
			},
			error: function(err) {
			}
		});
	});
  
  $(document).on('click', '#video_session', function(e) {
		e.preventDefault();

		var _this = $(this);
		var token = $("#token").attr("name");

		showLoading(_this);

		$.ajax({
			url: chatAjaxRoute,
			method: 'post',
			data: {
				[token]: '1',
				task: 'ajax.goToClass',
				format: 'json',
				raw: 'true',
				user1: from,
				user2: to,
				seid: seid,
				pid: pid
			},
			success: function(msg) {

				hideLoading(_this);
			},
			error: function(err) {
			}
		});
	});


	$(document).on('click', '#chatSendBtn', function(e) {
		e.preventDefault();
		var _this = $(this);
		var token = $("#token").attr("name");
		var message = $(this).next('#chatMessage').val();
		var replyid = $('#reply-id').val();
		var pmid = $('#pmid').val();

		showLoading(_this);
		$('#chatSendBtn').prop('disabled', true);
		trimmedmsg = message.replaceAll(' ', '');
		if (trimmedmsg) {
			$.ajax({
				url: chatAjaxRoute,
				method: 'post',
				data: {
					[token]: '1',
					task: 'ajax.saveChat',
					format: 'json',
					raw: 'true',
					message: message,
					from: from,
					to: to,
					seid: seid,
					pid: pid,
          replyid: replyid,
          pmid: pmid
				},
				success: function(msg) {
          reply_msg = '';
          // if(replyid)
            // text = jQuery('#' + replyid + ' > div.text > span').text().trim();
          reply = '';
          reply_pm = $('#pm-' + replyid);
          reply_text = $('#pm-' + replyid + '> div.text > span').text().trim();
          if(reply_pm.hasClass('me')) {
            reply_user = 'خودم';
          }
          else {
            reply_user = $('#user-name').text();
          }

          if(replyid != 0) {
            // if(reply_pm.hasClass('me')
            reply = '<div id="rep-'+replyid+'" class="text reply"><div class="Preview_preview__7RTlb" data-prevent-context-menu-mobile="true" style="border-right: 3px solid rgb(19, 194, 194);"><div class="Preview_details__kki9K"><span class="Preview_sender__RUCFl" style="color: rgb(19, 194, 194);">'+reply_user+'</span><div class="Text_text__0QjN9 TextPreview_text_preview__7vRSt"><span>'+reply_text+'</span></div></div></div></div>';

          }

					currentdate = new Date();
          if(pmid != 0)
          {
            msg.id = pmid;
          }
          // if(pmid == 0)
            // $('#chat-body').append(appendmsg);
          // else {
            // $( `#pm-${pmid}` ).replaceWith( appendmsg );
          // }

          appendmsg = '<div class="pm me" id="pm-' + msg.id + '">'+reply+'<div class="text"><span class="massage">' + message + '</span><div class="info-message"><span class="readtick unread"></span><span class="time">' + dateFormat(currentdate, 'yyyy/MM/dd H:M') + '</span></div></div></div>';
					// $('.chat').find('.card-body').append(appendmsg);
          if(pmid == 0){
            $('#chat-body').append(appendmsg);
          }
          else {
            // console.log(`#pm-${pmid}`);
            // console.log($( `#pm-${pmid}` ).find('div.text:not(.reply)'));
            
            $( `#pm-${pmid}` ).find('div.text:not(.reply)').replaceWith( appendmsg );
          }

					_this.next('#chatMessage').val('');
					var chatBoxBody = $('#chat-body')[0];
					scrollToEnd(chatBoxBody);
					hideLoading(_this);
					$('#chatSendBtn').prop('disabled', false);
          rh = jQuery('#reply-header');
          rh.css('display', 'none');
          $('#reply-id').val('0');
          $('#pmid').val('0');
          focused = $('.focus');
          $.each(focused, function(i, val){
              val.classList.remove('focus');
          });
				},
				error: function(err) {
				}
			});
		}
	});

	function showLoading(_this) {
		_this.children('#loading').css('display', 'block');
	}

	function hideLoading(_this) {
		_this.children('#loading').css('display', 'none');
	}

	function scrollToEnd(element) {
		element.scrollTop = element.scrollHeight;
	}

});/***[/JCBGUI$$$$]***/
