//Ensure that all code is executed after the loading of jQuery (and after page load);
jQuery(function() {

	var cc_t_comments; //Container for comments
	var cc_t_comment; //Clonable div for comment (to be placed in cc_t_comments;
	var cc_t_pagination; //Div with button "More"
	var cc_e_listener; //globalised object for time
	var cc_t_comment_edit; //Edit box
	var cc_t_comment_textarea;
	var cc_t_comment_button;
	var cc_l_timestamp = 0;
	var cc_f_pageno = 1;
	var cc_f_pagemax = 1;
	var cc_f_update = 0;
	var cc_f_comments = 0;
	var cc_template = null;

	var cc_show_comments = jQuery("#ClaCommentsShow");
	cc_t_comments = jQuery('#cc_t_comments');
	cc_t_pagination = jQuery('#cc_t_pagination');
	cc_t_comment_textarea = jQuery('#comment_textarea');
	cc_t_comment_button = jQuery('#comment_button');
	cc_t_comment_edit = cc_t_comments.find('.js-cla-comments-edit');

	//Ajax event bindings for our ajax notifiers
	jQuery(document).ajaxComplete(function(event,request, settings) {
		if (settings.url === '/intranet/common/cla_comments.php') {
			jQuery('.spinner').hide();
		}
	});

	cc_t_comments.on('click', 'a.cc_delete', function () {
		if (confirm(lmsg('common.cla_comments.delete_prompt')))
			cla_comment_delete(jQuery(this).attr('c_id'));
		return false; // prevent propagation of event
	});

	cc_t_comments.on('click', '.js-cla-comment-edit', function () {
		cla_comment_cancel_edit();
		var t_comment = jQuery(this).closest('.cc_t_comment');
		t_comment.find('.js-cla-comments-edit').removeClass('d-none');
		t_comment.find('textarea[name=comment_textedit]').val(t_comment.find('.cc_comment').data('plain'));
		t_comment.find('.cc_comment').hide();
		return false; // prevent propagation of event
	});

	cc_t_comments.on('click', '.cc_edit_save_button', function(e) {
		if (e.button !== 0) {
			return;
		}
		var tag_id = jQuery(this).attr('c_id');
		var cc_t_edit_textarea = jQuery(this).parent().find('textarea');
		if (tag_id > 0 && cc_t_edit_textarea.val().length!==0) {
			cla_comment_edit(tag_id, cc_t_edit_textarea.val());
		}
	});

	cc_t_comments.on('click', '.cc_edit_cancel_button', cla_comment_cancel_edit);

	//We just need to load page 1, the code should do the rest from now on.
	cla_comment_loadpage(1);
	cla_comment_setinterval(cc_refresh_period > 0 ? false : true); //Ensure that the interval is setup

	//We now hook onto the click event of the more button
	cc_t_pagination.click(function() {
		if (cc_f_pageno == cc_f_pagemax)
			return;
		cc_f_pageno += 1;
		cla_comment_loadpage(cc_f_pageno);
		return false;
	});

	// Adding a new comment
	cc_t_comment_button.click(function() {
		if (jQuery.trim(cc_t_comment_textarea.val()).length > 0) {
			cla_comment_submit(jQuery.trim(cc_t_comment_textarea.val()));
			cc_t_comment_textarea.val('').blur();
			return false; //Cancel the event
		}
	});

	// focus/blur event when adding a new comment  (aj)
	cc_t_comment_textarea.focus(function(){
		if(this.value == this.defaultValue) this.value = '';
	}).blur(function(){
		if(this.value === '') {
			this.value = this.defaultValue;
		}
	});

	function cla_comment_ajax(oData, sCallback)
	{
		oData.parameters = cc_parameters;
		oData.csrf_token = document.csrf_token;

		jQuery('.spinner').show();

		jQuery.ajax({
			type: 'POST',
			url: '/intranet/common/cla_comments.php',
			data: oData,
			dataType: 'json',
			success: sCallback
		});
	}

	function cla_comment_loadpage(page_no)
	{
		var pData = {'p': page_no, 'act': 'r'};
		cla_comment_ajax(pData, function(comment_page) {
			if (!comment_page.is_error) {
				if (comment_page.comments.length > 0) {
					jQuery.each(comment_page.comments, function() {
						cla_comment_render(this);
					});
				}
				cc_f_pagemax = comment_page.pc;
				cc_f_comments = comment_page.tc;
				cla_comment_morecomments_visible();
			} else {
				cla_comment_ajax_error(update);
			}
		});
	}

	//Submit new comment
	function cla_comment_submit(scomment)
	{
		if (jQuery.trim(scomment).length)
		{
			var pData = {'act': 'n', 'in': scomment};
			cla_comment_ajax(pData, function(update) {
				if (!update.is_error)
				{
					if (update.comments.length > 0)
					{
						jQuery.each(update.comments, function() {
							cla_comment_render(this, true);
							cc_f_comments++;// += 1;
							//This bit here basicly says if its rendered in 5 updates that its actually theoretically a whole page, so skip one in the numbers.
							cc_f_update += 1;
							if (cc_f_update >= 5) {
								cc_f_update = 0; cc_f_pageno += 1;
							}
						});
						cc_f_pagemax = update.pc;
						cla_comment_morecomments_visible();
					}
				} else
				{
					cla_comment_ajax_error(update);
				}
			});
		}
	}

	//Edit a comment
	function cla_comment_edit(comment_id, scomment)
	{
		//cc_t_comment_
		if (jQuery.trim(scomment).length && comment_id)
		{
			var pData = {'act': 'e', 'in': scomment, 'cid': comment_id};
			cla_comment_ajax(pData, function(update) {

				var tmp_obj = jQuery('#cc_t_comment_' + comment_id).find('.cc_comment');
				if (!update.is_error)
				{
					tmp_obj.html(update.comments[0].body);
					tmp_obj.data('plain', update.comments[0].body_plain);
					tmp_obj.show();
					if (cc_t_comment_edit.attr('tag') == comment_id)
						cc_t_comment_edit.remove();
					cla_comment_cancel_edit();
				} else
				{
					cla_comment_ajax_error(update);
				}
			});
		}
	}

	//Function to delete comment
	function cla_comment_delete(comment_id)
	{
		if (comment_id > 0)
		{
			var pData = {'act': 'd', 'cid': comment_id};
			cla_comment_ajax(pData, function(odelete) {
				if (!odelete.is_error)
				{
					if (odelete.comments.length > 0)
					{
						alert(document.lc['common.cla_comments.delete_failed']);
					}
					else
					{
						cc_f_update -= 1;
						if (cc_f_update === 0) {
							cc_f_update = 4; cc_f_pageno -= 1;
						}
						if (cc_f_pageno < 1) {
							cc_f_pageno = 1;
						}
						cc_f_pagemax = odelete.pc;
						cc_f_comments--;// -= 1;
						cla_comment_morecomments_visible();

						jQuery('#cc_t_comment_' + comment_id).fadeOut(function() {
							jQuery(this).remove();
						});
					}
				}
				else
				{
					alert(odelete.error_msg);
				}
			});
		}
	}

	//Ensure that new posts are frequently grabbed.
	function cla_comment_setinterval(bclear)
	{
		//ensure if not defined, it defaults to false
		bclear = typeof(bclear) != 'undefined' ? bclear : false;

		if (bclear)
		{
			//Clear interval
			if (cc_e_listener)
				clearInterval(cc_e_listener);
			cc_e_listener = null;
		} else
		{
			//Set interval
			if (cc_e_listener)
				return; //Shouldnt be set to anything;

			cc_e_listener = setInterval(function() {
				var pData = {'act': 'u', 'in': cc_l_timestamp};
				cla_comment_ajax(pData, function(update) {
					if (!update.is_error)
					{
						if (update.comments.length > 0)
						{
							jQuery.each(update.comments, function() {
								cla_comment_render(this, true, true);
								cc_f_update += 1;
								if (cc_f_update >= 5) {
									cc_f_update = 0;
									cc_f_pageno += 1;
								}
							});
							cc_f_pagemax = update.pc;
							cla_comment_morecomments_visible();
						}
					}
				});
				cla_comment_update_times(); //Force update on rotation
			}, cc_refresh_period*1000);
		}
	}

	function cla_comment_render(jcomment, r_prepend, bignore)
	{
		if (!cc_new_on_top) {
			r_prepend = !r_prepend;
		}
		if (jcomment.date > cc_l_timestamp && !bignore) {
			cc_l_timestamp = jcomment.date;
		}
		if (!jcomment.body) {
			jcomment.body = '';
		}
		//Where pagination method has changed, this is the only way logically around this
		//Only process rendering if rendered object does not already exist.
		if (jQuery('#cc_t_comment_' + jcomment.id).length)
			return; //Break out of function

		jcomment.date_formatted = cla_comment_format_time(jcomment.date);

		if (!cc_template)
		{
			cc_template = _.template(jQuery('#cc_t_comment_template').html());
		}
		var t_comment = cc_template(jcomment);
		if (!r_prepend)
			cc_t_comments.append(t_comment);
		else
			cc_t_comments.prepend(t_comment);
	}

	function cla_comment_morecomments_visible() {
		if (cc_f_pageno === 0) {
			cc_f_pageno = 1;
		}
		if (cc_f_pageno >= cc_f_pagemax)
			jQuery('#cc_t_pagination').hide();
		else
			jQuery('#cc_t_pagination').show();
		jQuery('#cc_count').text(cc_f_comments);
		jQuery('#cc_label').text(cc_f_comments === 1 ? document.lc['common.cla_comments.comment'] : document.lc['common.cla_comments.comments']);
	}

	function cla_comment_format_time(timestamp14)
	{
		if (timestamp14.length != 14)
			return 'bad date';

		var o_Date = new Date();
		var c_Date = o_Date.valueOf();
		var t_date;
		o_Date.setUTCFullYear(timestamp14.substr(0,4));
		o_Date.setUTCMonth((timestamp14.substr(4,2) - 1));
		o_Date.setUTCDate(timestamp14.substr(6,2));
		o_Date.setUTCHours(timestamp14.substr(8,2));
		o_Date.setUTCMinutes(timestamp14.substr(10,2));
		o_Date.setUTCSeconds(timestamp14.substr(12,2));
		c_Date -= o_Date.valueOf();
		c_Date = c_Date / 1000; //We only want whole seconds
		timestamp14 = null;
		if (c_Date < 60)
			timestamp14 = lmsg('common.cla_comments.common.lt_minute');
		else if (c_Date < 3600) //Less than 1 hour
		{
			t_date = c_Date % 60;
			t_date = (c_Date - t_date) / 60;
			timestamp14 = lmsg('common.cla_comments.common.minutes', t_date);
		}
		else if (c_Date < 86400) //Less than 1 day
		{
			t_date = c_Date % 3600;
			t_date = (c_Date - t_date) / 3600;
			timestamp14 = lmsg('common.cla_comments.common.hours', t_date);
		}
		else if ( c_Date < 604800 )
		{
			t_date = c_Date % 86400;
			t_date = (c_Date - t_date) / 86400;
			timestamp14 = lmsg('common.cla_comments.common.days', t_date);
		}
		else
		{
			timestamp14 = o_Date.toLocaleDateString();
		}

		return timestamp14;
	}

	function cla_comment_update_times()
	{
		setTimeout(function(){
			jQuery('.cc_comment_time').each(function() {
				var t_time = jQuery(this).attr('date');
				jQuery(this).text(cla_comment_format_time(t_time));
			});
		}, 500);
	}

	function cla_comment_ajax_error(response)
	{
		if (response.is_error)
			alert(response.error_msg);
	}

	function cla_comment_cancel_edit()
	{
		jQuery('.js-cla-comments-edit').addClass('d-none');
		jQuery('.cc_comment').show();
	}
});
