
/******************** SETTINGS ****************************/

var textAreaHeight = 200; // height of edit box


/**********************************************************/


/*
	Sends request for get post message
*/
function ape_quick_edit(id)
{
	// checking if link 'Quick Edit' exists, if not exists user probably typed on adress bar javascript:ape_quick_edit(id)
	if ($('#edit' + id))
	{
		// if other post is editing, cancel edit
		if (ape_id != id && ape_id != -1)
		{
			if (confirm("Are you sure you want to cancel last edit?"))
				ape_cancel_edit(ape_id);
			else
			{
				ape_hide_menu();
				return;
			}
		}

		if (ape_id != id)
		{
			ape_hide_menu();
			ape_id = id;
			ape_temp_post = $('#post' + ape_id).html();
			
			// Show loading info
			$('#post' + ape_id).html($('#post' + ape_id).html() + '<div style="float:right"><img src="' + base_url + '/extensions/ajax_post_edit/loading.gif"> ' + ape['Loading'] + '</div>');

			var values = {
				action: 'get',
				id: ape_id,
				csrf_token: ape['csrf_token']
			};
			$.post(ape_url, values, function(data) {ape_on_ready_get_post(data)});
		}
	}
}


/*
	Function executed after receiving post data
*/
function ape_on_ready_get_post(data)
{
	var parsed_message = match(data, 'parsed_message');

	// If there aren't any errors
	if (parsed_message != '')
	{
		var entry_content_html = data.substring(0, data.indexOf('<!-- END FORM -->'));
		
		
		$('#post' + ape_id).fadeOut('fast', function() {
			$(this).html(entry_content_html);

			$('#postedit').height(textAreaHeight + 'px');

			$('#post' + ape_id).fadeIn('fast', function() { $('#postedit').focus(); } );
		} );

		return 1;
	}

	if (data.substring(0, 12) == 'csrf_confirm')
	{
		response = data.split(':');
		if (confirm(response[1]))
		{
			ape['csrf_token'] = response[2];

			var values = {
				action: 'get',
				id: ape_id,
				csrf_token: response[2]
			};
			$.post(ape_url, values, function(data) {ape_on_ready_get_post(data)});
		}
	}
	else
		alert(data);
	
	$('#post' + ape_id).html(ape_temp_post);
	id = -1;
}


/*
	Sends ajax request with typed message
*/
function ape_update_post()
{
	$('#post_edit_form input, #post_edit_form textarea').attr('disabled', 'disabled');

	ape_update_values = {
		action: 'update',
		id: ape_id,
		req_message: $('#postedit').val(),
		csrf_token: ape['csrf_token']
	};

	if ($('#fldsilent'))
		ape_update_values['silent'] = $('#fldsilent').attr('checked') ? 1 : 0;

	if ($('#req_subject'))
		ape_update_values['req_subject'] = $('req_subject').val;

	$.post(ape_url, ape_update_values, function(data) {ape_on_ready_update_post(data)});

	// Show saving info
	$('#edit_info').show();
}


/*
	Function executed after receiving update request
*/
function ape_on_ready_update_post(data)
{
	var message = match(data, 'message');
	if (message != '')
	{
		// Update post message for pun_quote extension
		try
		{
			pun_quote_posts[ape_id] = $('#postedit').val;
		}
		catch (e) {}
	
		var last_edit = match(data, 'last_edit');

		var sig = '';
		
		if (ape_temp_post.toLowerCase().indexOf('<div class="sig-content">') != -1) // if post has signature
			sig = ape_temp_post.substring(ape_temp_post.toLowerCase().indexOf('<div class="sig-content">')); // get it
		
		// display post
		$('#post' + ape_id).fadeOut('fast', function() {
			$('#post' + ape_id).html(message + last_edit + sig);
			$('#post' + ape_id).fadeIn('fast');
			ape_id = -1;
		} ); 
		return 1;
	}


	var error = match(data, 'error');
	// if message has errors
	if (error != '')
	{
		var cur_message = $('#postedit').val();

		// if recently displayed errors
		if (document.getElementById('edit-error'))
		{
			error = error.substring(error.indexOf('>')+1);
			error = error.substring(0, error.lastIndexOf('</'));
			$('#edit-error').html(error);
		}
		else
		{
			if ($('#fldsilent'))
				var cur_silent = $('#fldsilent').checked;

			var html = $('#post' + ape_id).html();
			var replace = html.substring(0, html.indexOf('<', 2));
			html = html.replace(replace, replace + error);
			$('#post' + ape_id).html(html);

			$('#postedit').val(cur_message);
			if ($('#fldsilent'))
				$('#fldsilent').attr('checked', cur_silent);

		}
		$('#post_edit_form input, #post_edit_form textarea').removeAttr('disabled');
		
		// Hide saving info
		$('#edit_info').hide();
	}
	else
	{
		if (data.substring(0, 12) == 'csrf_confirm')
		{
			response = data.split(':');
			if (confirm(response[1]))
			{
				ape['csrf_token'] = response[2];
				ape_update_values['csrf_token'] = response[2];
				$.post(ape_url, ape_update_values, function(data) {ape_on_ready_update_post(data)});
			}
			else
			{
				$('#post_edit_form input, #post_edit_form textarea').removeAttr('disabled');
				
				// Hide saving info
				$('#edit_info').hide();
			}
		}
		else
			alert(data);
	}
}


/*
	Hides edit box and show recently used post content
*/
function ape_cancel_edit()
{
	$('#post' + ape_id).fadeOut('fast', function() {
		$('#post' + ape_id).html(ape_temp_post);
		$('#post' + ape_id).fadeIn('fast');
		ape_id = -1;
	} );
}


/*
	Shows popup menu
*/
function ape_show_menu(id)
{
	if (ape_id == id)
		return;

	var pos = findPos(document.getElementById('menu' + id));
	pos[0] += document.getElementById('menu' + id).offsetWidth;
	pos[1] += document.getElementById('menu' + id).offsetHeight + 3;

	var menu = document.createElement('div');
	menu.setAttribute('id', 'menu');

	menu.style.left =  pos[0] + 'px';
	menu.style.top =  pos[1] + 'px';

	menu.className = 'popup';
	menu.onmouseover = function () {ape_menu_hovered = true}
	menu.onmouseout = function () {ape_menu_hovered = false}

	menu.innerHTML =
		'<ul>' +
			'<li><a id="edit' + id + '" href="javascript:ape_quick_edit(' + id + ')">' + ape['Quick edit'] + '</a></li>' +
			'<li><a href="' + base_url + '/' + ape['url_edit'].replace('$1', id) + '">' + ape['Normal edit'] + '</a></li>' +
		'</ul>';

	document.body.appendChild(menu);
	
	$('#menu').fadeIn('fast');

	document.getElementById('menu').style.left = pos[0] + 4 - document.getElementById('menu').clientWidth + 'px';
	
	document.onclick = function() {
			if (ape_menu_hovered == false)
				ape_hide_menu();
		};
}


/*
	Hides popup menu
*/
function ape_hide_menu()
{
	$('#menu').fadeOut('fast', function() { $(this).remove() } );
}


/**********************************************************/


/*
	Returns obj absolute position [x,y]
*/
function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop];
}


/*
	This function matches text from str beetwen <substr> and </substr>
*/
function match(str, substr)
{
	// if str contains <substr>
	if (str.indexOf('<' + substr + '>') != -1)
	{
		newstr = str.substring(str.indexOf('<' + substr + '>') + substr.length+2);
		newstr = newstr.substring(0, newstr.indexOf('</' + substr + '>'));
		return newstr;
	}
	else
		return '';
}


var ape_temp_post;		// post message with html
var ape_id = -1;		// currently edited post id
var ape_menu_hovered = false;	// if menu is hovered
var ape;
var ape_update_values;
var ape_url = base_url + '/extensions/ajax_post_edit/edit.php';
