jQuery(document).ready(function($) {

	"use strict";

	// Detect height of chat container
	$(document).on('click', '.datebook-chat-button-emoji-icon', function() {

		// Detect height of chat window
		var height_one = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

		var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
		var window_height = (iOS) ? (screen.height > 0 ? screen.height : height_one) : height_one;

		// Detect height of header
		var chatheaderHeight = document.getElementById('datebook-chat-header').clientHeight;

		// Detect height of footer
		var chatfooterHeight = document.getElementById('datebook-chat-footer').clientHeight;

		var chatcontainerHeight = window_height - chatheaderHeight - chatfooterHeight;
		
		if (chatcontainerHeight) {
			// Detect height of header
			var listcontainer = document.getElementById("datebook-list-messages");
			//listcontainer.style.height = chatcontainerHeight + "px";
		}
		
		document.getElementById("datebook-list-messages").scrollTop = document.getElementById("datebook-list-messages").scrollHeight;

	});

	// Move messages to top in message popup window
	function datebook_move_messages_to_top(){

		// Detect height of chat window
		var height_one = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

		var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
		var window_height = (iOS) ? (screen.height > 0 ? screen.height : height_one) : height_one;

		// Detect height of header
		var chatheaderHeight = document.getElementById('datebook-chat-header').clientHeight;

		// Detect height of header
		var chatfooterHeight = document.getElementById('datebook-chat-footer').clientHeight;

		var listcontainer = document.getElementById("datebook-list-messages");
		if (listcontainer ) {
			//var height_two = window_height - chatheaderHeight - chatfooterHeight;
			//listcontainer.style.height = height_two + "px";
			document.getElementById("datebook-list-messages").scrollTop = document.getElementById("datebook-list-messages").scrollHeight;
		}

	}


	// Update messages in message popup window every X seconds
	function datebook_load_new_stuff(){
		var url = window.location.href;
		var captured = /sid=([^&]+)/.exec(url)[1];
		var senderid = captured ? captured : 'sid';

		$.ajax({
			type: 'GET',
			url: datebookajaxlocal.ajax_my_messages_url,
			dataType: 'json',
			data : {
				action : 'datebook_message_actions',
				senderid : senderid,
				whatisit : 'chatupdate'
			},
			success: function(data) {

				if (data) {
					if (data.status === 200) {

						$('.datebook-online-caption').html(data.online_status_sender);

						if (data.newmessage) {

    		    	        var newmessage = data.newmessage;
							$('#datebook-list-messages').append(newmessage);

							$('#datebook-lastmessagenotread').insertAfter($('#datebook-list-messages div:last'));
							if (data.lastmessagenotread) {
								$('#datebook-lastmessagenotread').show();
							}
							datebook_move_messages_to_top();
						}
						
						$.each(data.profile_data, function(index, value) {

							if (value.countnewmsgsender > 0) {
								
								$('#datebook-messages-profile-box-' + value.profile_id + ' .datebook-new-messages-count-sidebar').html(value.countnewmsgsender);
								$('#datebook-messages-profile-box-' + value.profile_id + ' .datebook-new-messages-count-sidebar').removeClass('d-none');
								$('#datebook-messages-profile-box-' + value.profile_id + ' .datebook-new-messages-count-sidebar').addClass('d-inline');
								if (value.notify > 0 && datebookajaxlocal.path_to_sound) {
									var getaudio = new Audio(datebookajaxlocal.path_to_sound);
									getaudio.play();
								}
							}

						});
						
					}
				}
			}
		});
	}


	function datebook_all_chat_fuctions(){

		// Move messages to top in message popup window
		datebook_move_messages_to_top();

		// Update messages in message popup window every X seconds
		setInterval(function(){

			datebook_load_new_stuff();

		}, datebook_chat_window.datebook_chat_update_period); // Check for new messages every 5 seconds (5000 = 5 seconds)

		$('html, body').animate({ scrollTop: 2000 }, 500);

    }

	// Load chat window functions and height
    window.onload = datebook_all_chat_fuctions();
	//window.onresize = datebook_all_chat_fuctions();
	//window.addEventListener('load', datebook_all_chat_fuctions(), false);

	// Submit message in chat window
	$(document).on('click', '.datebook-chat-submit', function() {

		var senderid = $('#datebook-chat-sid').val();
		var message = $('#datebook-messagebox').val();

		$.ajax({
			type: 'POST',
			url: datebookajaxlocal.ajax_my_messages_url,
			dataType: 'json',
			data : {
				action : 'datebook_message_actions',
				senderid : senderid,
				message : message,
				whatisit : 'chatsubmit'
			},
			success: function(data) {

				if (data) {
					if (data.status === 200) {

						if (data.newmessage) {

							$('#datebook-messagebox').val('');
							$('#datebook-messagebox').attr('style', '');
							$('.datebook-message-form .collapse').removeClass('show');

    		    	        var newmessage = data.newmessage;
							$('#datebook-list-messages').append(newmessage);

							$('#datebook-lastmessagenotread').insertAfter($('#datebook-list-messages div:last'));
							if (data.lastmessagenotread) {
								$('#datebook-lastmessagenotread').hide();
							}

							datebook_move_messages_to_top();

							var chatpointsdeducted = data.chatpointsdeducted;
							$('.datebook-chat-points-number').html(chatpointsdeducted);

							var sendmessagenotallowed = data.sendmessagenotallowed;
							if(sendmessagenotallowed === 1){
								var chatnotallowedmessage = data.chatnotallowedmessage;
								$('.datebook-modal-footer').append(chatnotallowedmessage);
								$('.datebook-message-form').remove();								
							}
						}
					}
				}
			}
		});
	});


	// Upload fie in chat form
	$(document).on('change', '#datebook-select-file', function() {   // If you want to upload without a submit button 

		$('#datebook-loader').insertAfter($('#datebook-list-messages div:last'));
		$('#datebook-loader').show();

		datebook_move_messages_to_top();

		var form_data = new FormData();

		var file_data = $('#datebook-select-file').prop('files')[0];
		form_data.append('imagefile', file_data);

		var action = 'datebook_message_actions';
		form_data.append('action', action);

		var senderid = $('#datebook-chat-sid').val();
		form_data.append('senderid', senderid);

		var whatisit = 'chatfileupload';
		form_data.append('whatisit', whatisit);
		
		var html = '';

		$.ajax({
			url: datebookajaxlocal.ajax_my_messages_url,
			type: 'POST',
			dataType: 'json',
			data: form_data,
			contentType: false,
			processData: false,
			cache: false,
			success: function(data){

				if (data) {
					if (data.status === 200) {

						if (data.newmessage) {

							$('#datebook-loader').hide();

							var newmessage = data.newmessage;
							$('#datebook-list-messages').append(newmessage);
							
							$('#datebook-lastmessagenotread').insertAfter($('#datebook-list-messages div:last'));
							if (data.lastmessagenotread) {
								$('#datebook-lastmessagenotread').show();
							}

							datebook_move_messages_to_top();

						}
					}

				} else {

					$('#datebook-loader').hide();

				}
			},
		});
	});


	// Show all messages when clicking on Show more button in chat popup window
	$(document).on('click', '.datebook-show-button', function() {

		var realheight = document.getElementById('datebook-list-messages').scrollHeight;
		var el = $('#datebook-list-messages'),
		curHeight = el.height(),
		autoHeight = el.css('height', curHeight+'px').height()+realheight-1000;
		el.height(curHeight).animate({scrollTop: autoHeight}, 2000);
		el.css('overflow-y', 'scroll');

	});
	
	// If enter is pressed, send the message
	 $('#datebook-messagebox').on('keydown', function(e) {
		if(e.which === 13 && !e.shiftKey){
			$('.datebook-chat-submit').trigger('click');
			e.preventDefault();
        }
    });


	// Show a message that the user is blocked / placed in the ignore list
	$(document).on('click', '.datebook-user-blocked', function(e) {
		
		e.preventDefault();

		var profile_id = $(this).attr('profile-id');

		$.ajax({
			type: 'GET',
			url: datebookajaxlocal.ajax_my_messages_url,
			dataType: 'json',
			data: {
				action : 'datebook_message_actions',
				id : profile_id,
				whatisit : 'addblacklist'
			},
			success: function(data) {

				if (data.success === 1) {

					var newmessage = data.newmessage;
					$('.datebook-list-messages').html(newmessage);
					return false;

				} else if (data.success === 2) {

					var newmessage = data.newmessage;
					$('.datebook-list-messages').html(newmessage);
					return false;

				}
			}
		});
	});


	// Focus in textarea in chat window
	$(function() {
		var data = $('#datebook-messagebox').val();
		$('#datebook-messagebox').focus().val('').val(data);
	}); 

	// Expand textarea in chat window when long text goes to second line
	$('#datebook-messagebox').each(function () {
		this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
	}).on('input', function () {
		this.style.height = (this.scrollHeight) + 'px';
	});

	// Display Emoji panel in chat window
	$('#datebookemojicollapse').on('shown.bs.collapse', function() {
		$('html,body').animate({scrollTop: $('#datebookemojicollapse').offset().top}, 500);
	});

	// Place Emoji in text field in chat window
	function typeInTextarea(el, newText) {
		var start = el.prop('selectionStart');
		var end = el.prop('selectionEnd');
		var text = el.val();
		var before = text.substring(0, start);
		var after  = text.substring(end, text.length);
		el.val(before + newText + after);
		el[0].selectionStart = el[0].selectionEnd = start + newText.length;
		el.focus();
		return false;
	}

	$(document).on('click', '.datebook-chat-emoji-icons .datebook-single-emoji', function() {
		var emoji_alt = $(this).attr('data-emoji');
		var messagebox = document.getElementById('datebook-messagebox');
		// Focus element, in case that it's not
		messagebox.focus();
		typeInTextarea($('#datebook-messagebox'), emoji_alt);
		return false;
	});

});

(function (window, document) {
	
	"use strict";

	var layout = document.getElementById('datebook-messages-layout'),
		menu = document.getElementById('datebook-messages-menu'),
		menuLink = document.getElementById('datebook-menuLink');

	function toggleClass(element, className) {

		var classes = element.className.split(/\s+/),
			length = classes.length,

		i = 0;

		for(; i < length; i++) {
			if (classes[i] === className) {
				classes.splice(i, 1);
				break;
			}
		}

		// The className is not found
   	    if (length === classes.length) {
			classes.push(className);
		}

		element.className = classes.join(' ');
	}

	// Pre check functionn
	function datebook_menuLink(){
		menuLink.onclick = function(e) {

			var active = 'active';

			e.preventDefault();
			toggleClass(layout, active);
			toggleClass(menu, active);
			toggleClass(menuLink, active);
		};
	}

	window.onload = datebook_menuLink();

}(this, this.document));