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

var textAreaHeight = 200; // height of edit box


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

// Detect Internet Explorer
var ie = /msie/i.test (navigator.userAgent);

/*
	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).innerHTML;
			ape_show_loading_info();

			sendRequest('action=get&id=' + ape_id + '&csrf_token=' + ape['crsf_token'], function() {ape_on_ready_get_post()});
		}
	}
}


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

	// If there aren't any errors
	if (parsed_message != '')
	{
		var entry_content_html = http.responseText.substring(0, http.responseText.indexOf('<!-- END FORM -->'));
		$('post' + ape_id).innerHTML = entry_content_html;

		$('postedit').style.height = textAreaHeight + 'px';
		$('postedit').focus();
		return 1;
	}

	if (http.responseText.substring(0, 12) == 'csrf_confirm')
	{
		response = http.responseText.split(':');
		if (confirm(response[1]))
		{
			ape['crsf_token'] = response[2];
			sendRequest('action=get&id=' + ape_id + '&csrf_token=' + response[2], function() {ape_on_ready_get_post()});
		}
	}
	else
		alert(http.responseText);
	
	$('post' + ape_id).innerHTML = ape_temp_post;
	id = -1;
}


/*
	Sends ajax request with typed message
*/
function ape_update_post()
{
	ape_enable(false);

	ape_update_url = 'action=update&id=' + ape_id + '&req_message=' + encodeURIComponent($('postedit').value) + '&utf=1';
	if ($('fldsilent'))
		ape_update_url += '&silent=' + ($('fldsilent').checked ? 1 : 0);

	if ($('req_subject'))
		ape_update_url += '&req_subject=' + encodeURIComponent($('req_subject').value);
	
	ape_update_url += '&csrf_token=' + ape['crsf_token'];

	sendRequest(ape_update_url, function() {ape_on_ready_update_post()});
	ape_show_saving_info();
}


/*
	Function executed after receiving update request
*/
function ape_on_ready_update_post()
{
	var message = match(http.responseText, 'message');
	if (message != '')
	{
		// Update post message for pun_quote extension
		try
		{
			pun_quote_posts[ape_id] = $('postedit').value;
		}
		catch (e) {}
	
		var last_edit = match(http.responseText, '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
		$('post' + ape_id).innerHTML = message + last_edit + sig; // display post
		ape_id = -1;
		return 1;
	}


	var error = match(http.responseText, 'error');

	// if message has errors
	if (error != '')
	{
		var cur_message = $('postedit').value;

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

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

			$('postedit').value = cur_message;
			if ($('fldsilent'))
				$('fldsilent').checked = cur_silent;

		}
		ape_enable(true);
		ape_hide_saving_info();
	}
	else
	{
		if (http.responseText.substring(0, 12) == 'csrf_confirm')
		{
			response = http.responseText.split(':');
			if (confirm(response[1]))
			{
				ape['crsf_token'] = response[2];
				sendRequest(ape_update_url.substring(0, ape_update_url.indexOf('&csrf_token=') + 12) + response[2], function() {ape_on_ready_update_post()});
			}
			else
			{
				ape_enable(true);
				ape_hide_saving_info();
			}
		}
		else
			alert(http.responseText);
	}
}


/*
	Hides edit box and show recently used post content
*/
function ape_cancel_edit()
{
	$('post' + ape_id).innerHTML = ape_temp_post;
	ape_id = -1;
}


/*
	Shows loading message (@ Loading...)
*/
function ape_show_loading_info()
{
	$('post' + ape_id).innerHTML += '<div style="float:right"><img src="' + base_url + '/extensions/ajax_post_edit/loading.gif"> ' + ape['Loading'] + '</div>';
}


/*
	Shows saving message (@ Saving...)
*/
function ape_show_saving_info()
{
	$('edit_info').style.display = 'block';
}

/*
	Hides saving information
*/
function ape_hide_saving_info()
{
	$('edit_info').style.display = 'none';
}


/*
	ape_enable (or disable) form box
*/
function ape_enable(t)
{
	var enb = !t;
	$('postedit').disabled = enb;
	$('btn_updatePost').disabled = enb;
	$('btn_cancelUpdate').disabled = enb;
	$('btn_fullEdit').disabled = enb;
	if ($('fldsilent'))
		$('fldsilent').disabled = enb;
}


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

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

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

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

	menu.className = 'popup brd brd-page main-content';
	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').style.left = pos[0] - $('menu').offsetWidth + 'px';

	document.onclick = function() {
			if (ape_menu_hovered == false)
				ape_hide_menu();
		};
}


/*
	Hides popup menu
*/
function ape_hide_menu()
{
	if ($('menu'))
		document.body.removeChild($('menu'));
}


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


/*
	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 '';
}


/*
	Function sending ajax request
	@data = data to send
	@onready = function which will be executed after receiving data
*/
function sendRequest(data, onready)
{
	// Without this IE don't get second reply (i think there's something wrong with onreadystatechange function)
	if (ie)
		http = getHTTPObject();

	http.onreadystatechange = function()
	{
		if (http.readyState == 4)
			onready();
	};

	http.open('POST', base_url + '/extensions/ajax_post_edit/edit.php', true);
	http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');

	http.send(data);
}


/*
	Function creating ajax request object
*/
function getHTTPObject()
{
	var xmlhttp;
	/*@cc_on
	@if (@_jscript_version >= 5)
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				xmlhttp = false;
			}
		}
	@else
		xmlhttp = false;
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp = false;
		}
	}
	return xmlhttp;
}


/*
	Function returning element from elid
*/
function $(el_id)
{
	return document.getElementById(el_id);
}


var http = getHTTPObject(); 	// We create the HTTP Object
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_url = '';
