/*
 *
 */

var monitorTimeout;

function updatePhotobank() {
	if (document.getElementById("hiddenframe").contentWindow.document.body.innerText == 'error') {
		alert('Ошибка при загрузке.');
		return false;
	}

	$('#photo').val('');
	$('#caption').val('');
	$.getJSON("/json/getmyartphotos", function (data) {
		$('#photobank').html('');
		$.each(data, function (key, val) {
			$("<img/> ", {
				"class": "my-new-list",
				src: '/photos/articles/small/' + val.name,
				title: 'img #' + val.id + ' :: ' + val.caption,
				photoId: val.id
			}).appendTo('#photobank');
		});

		$("#photobank img").on("click", function () {
			imgText = '\n[img|#' + $(this).attr('photoid') + ']\n';
			insertAtCursor('articleText', imgText);
			markdown();
			togglePhotobank();
		});
	});
}

function markBold()
{
	wrapText('articleText', '**', '**');
	markdown();
}

function markItalic()
{
	wrapText('articleText', '*', '*');
	markdown();
}

function markUnderline()
{
	wrapText('articleText', '_', '_');
	markdown();
}

function insertPoint()
{
	pointId = prompt('Укажите номер точки', '');
	if (pointId) {
		insertAtCursor('articleText', '[#' + pointId + '|ссылка на точку]');
		markdown();
	}
}

function insertAtCursor(myFieldId, myValue) {
	myField = document.getElementById(myFieldId);

	//IE support
	if (document.selection) {
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	}
	//MOZILLA and others
	else if (myField.selectionStart || myField.selectionStart == '0') {
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos)
				+ myValue
				+ myField.value.substring(endPos, myField.value.length);
	} else {
		myField.value += myValue;
	}
}

function wrapText(elementID, openTag, closeTag) {
	var textArea = $('#' + elementID);
	var len = textArea.val().length;
	var start = textArea[0].selectionStart;
	var end = textArea[0].selectionEnd;
	var selectedText = textArea.val().substring(start, end);
	var replacement = openTag + selectedText + closeTag;
	textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}

function markdown()
{
	$.post('/article/markdown', {text: $('#articleText').val()}, function (data) {
		$('#monitor').html(data);
	});
}

$('#articleText').keyup(function () {
	clearTimeout(monitorTimeout);
	monitorTimeout = setTimeout(function () {
		$('#submitButton').removeClass('btn-default').addClass('btn-info');
		if ($('#mainEditorTable').hasClass('doubleEditor')) {
			markdown();
		}
	}, 200);
}).keydown(function () {
	clearTimeout(monitorTimeout)
}).scroll(function () {
	monH = document.getElementById('monitor').scrollHeight - document.getElementById('monitor').clientHeight;
	areH = document.getElementById('articleText').scrollHeight - document.getElementById('articleText').clientHeight;
	areS = $('#articleText').scrollTop();
	monS = Math.round((areS / areH) * monH);
	$('#monitor').scrollTop(monS);
});

$(document).ready(function () {
	markdown();
	$('#articleText').focus();
	$(document).keyup(function (e) {
		if (e.keyCode == 27) { // escape key maps to keycode `27`
			if ($('#photobankContainer').css('display') == 'block') {
				togglePhotobank();
			}
		}
	});
});

function togglePhotobank()
{
	$('#photobankContainer').slideToggle(200);
}

function toggleAutoview()
{
	$('#mainEditorTable').toggleClass('doubleEditor').toggleClass('singleEditor');
	$('#autoviewSwitcher').toggleClass('active');
	markdown();
	$.cookie('disableAutoview', $('#mainEditorTable').hasClass('singleEditor'), { expires: 30, path: '/' });
}
