﻿$.fn.editorPlugin = function() {
	var html = "<div class=\"toolbar\">\
			<input type=\"button\" class=\"btn\" template=\"&lt;h1&gt;_TEXT_&lt;/h1&gt;\" newline=\"true\"  value=\"H1\" />\
			<input type=\"button\" class=\"btn\" template=\"&lt;h2&gt;_TEXT_&lt;/h2&gt;\" newline=\"true\" value=\"H2\" />\
			<input type=\"button\" class=\"btn icon bold\" template=\"[[_TEXT_]]\" />\
			<input type=\"button\" class=\"btn icon italic\" template=\"//_TEXT_//\" />\
			<input type=\"button\" class=\"btn icon strike\" template=\"--_TEXT_--\" />\
			<input type=\"button\" class=\"btn icon underline\" template=\"___TEXT___\" />\
			<input type=\"button\" class=\"btn icon left\" template=\"&lt;&lt;_TEXT_&lt;&lt;\" />\
			<input type=\"button\" class=\"btn icon justify\" template=\"((_TEXT_))\" />\
			<input type=\"button\" class=\"btn icon center\" template=\"||_TEXT_||\" />\
			<input type=\"button\" class=\"btn icon right\" template=\"&gt;&gt;_TEXT_&gt;&gt;\" />\
			<input type=\"button\" class=\"btn icon quote\" template=\"&quot;&quot;_TEXT_&quot;&quot;\" />\
	  	  	<input type=\"button\" class=\"btn icon line\" template=\"_TEXT_&lt;hr /&gt;\" />\
			<input type=\"button\" class=\"btn icon chain \" template=\"&lt;a href=&quot;_LINK_&quot;&gt;_TEXT_&lt;/a&gt;\" />\
			<input type=\"button\" class=\"btn icon image\" template=\"&lt;img src=&quot;_LINK_&quot; /&gt;\" />\
			<input type=\"button\" class=\"btn icon youtube\" template=\"_LINK_\" />\
			<input type=\"button\" class=\"btn icon list_ord\" template=\"_TEXT_\" />\
			<input type=\"button\" class=\"btn icon list_num\" template=\"_TEXT_\" />\
			<input type=\"button\" class=\"btn icon view\" />\
			<input type=\"button\" class=\"btn image_align_button icon image_left\" align=\"left\" />\
			<input type=\"button\" class=\"btn image_align_button icon image_center\" align=\"center\" />\
			<input type=\"button\" class=\"btn image_align_button icon image_right\" align=\"right\" />\
	  	</div>\
		\
		<div class=\"preview\"></div>\
		\
		<textarea class=\"content\"></textarea>";

	var editor = $(this),
		content = $(this).html();

  	editor.html(html);
	editor.addClass("editor");
	$(".content",editor).val(htmlToMarkup(content));

	$(".preview", editor).hide();
	$(".image_align_button", editor).hide();
	$(".toolbar .view", editor).click(onShowPreviewClick);
	$(".toolbar .btn", editor).not(".view").click(onTemplateButtonClick);
	$(".image_align_button", editor).click(onImageAlignButtonClick);
};

function onImageAlignButtonClick() {
	var editor = $(this).parent().parent(),
		focusedImage = $(".active", editor);
	focusedImage
		.removeClass("right")
		.removeClass("left")
		.removeClass("center");
	var align = $(this).attr("align");
	focusedImage.addClass(align);
}

function onImageClick() {
	var editor = $(this).parent().parent();
	$("img", editor).removeClass("active");
	$(this).addClass("active");
}

//Oбработчик нажатия кнопки вставки ссылки
function onTemplateButtonClick() {
	var editor = $(this).parent().parent(),
		template = $(this).attr("template"),
	 	needUrlRequest = template.indexOf("_LINK_") != -1,
		needNewLine = $(this).attr("newline") == "true",
		template = $(this).attr("template"),
		selection = $(".content", editor).getSelection(),
		selectedText = selection.text,
		rightSpace = selectedText[selectedText.length - 1] == ' '? " " : "",
		leftSapce = selectedText[0] == ' '? " " : "";

	selectedText = $.trim(selectedText);
	var newText = leftSapce + template.replace("_TEXT_", selectedText) + rightSpace;

	if (needUrlRequest) {
		var userUrl = window.prompt("Введите адрес ссылки", ""); //.toLowerCase();

		if (userUrl.indexOf("mailto:") == -1 && userUrl.indexOf("@") != -1) userUrl = "mailto:" + userUrl;

		//Video
		if (template == "_LINK_") {
			if (userUrl.indexOf("youtube.com") != -1) {
				var videoId = userUrl
					.replace("http://www.youtube.com/watch?v=", "")
					.replace("&feature=player_embedded")
					.replace("&feature=related", "")
					.replace("http://www.youtube.com/embed/", "");
				userUrl = "^^http://www.youtube.com/embed/" + videoId +  "^^";
			}

			if (userUrl.indexOf("vimeo.com") != -1) {
				var videoId = userUrl.replace("http://vimeo.com/", ""),
					cutIndex = videoId.indexOf("&");
				if (cutIndex != -1) videoId = videoId.substr(0, cutIndex);
				userUrl = "^^http://player.vimeo.com/video/" + videoId + "^^";
			}

			if (userUrl.indexOf("dailymotion.com") != -1) {				
				var videoId = userUrl
					.replace("http://www.dailymotion.com/video/", "")
				  	.replace("http://www.dailymotion.com/embed/video/", "");
				var cutIndex = videoId.indexOf("#");
				if (cutIndex != -1) videoId = videoId.substr(0, cutIndex);
				userUrl = "^^http://www.dailymotion.com/embed/video/" + videoId + "^^";
			}
			newText = template;
		}

		newText = newText.replace("_LINK_", userUrl);
		//alert(template);
	}

	if (needNewLine) {
		//перенос строки для случаев с заголовками - как было описанно в письме
		var fullText = $(".content", editor).val();

		if (selection.start > 0 && fullText[selection.start - 1] != '\n') newText = "\n" + newText;

		if (selection.end < fullText.length && fullText[selection.end ] != '\n') newText = newText + "\n";
	}

	if ($(this).hasClass('list_ord')) newText = formatList(newText, "* ");

	if ($(this).hasClass('list_num')) newText = formatList(newText, "+ ");

	var selection = $(".content", editor).getSelection();
	
	if(selection.start == selection.end) $(".content", editor).insertAtCaretPos(newText);
	else $(".content", editor).replaceSelection(newText);
	
	$(".content", editor).focus();
}

function formatList(text, listSeparator) {
	var lines = text.split('\n'),
		text = "";
	
	for (i = 0; i < lines.length; i++) text += listSeparator + lines[i] + "\n";

	return text;
}

//обработчик нажатия кнокпи предпросмотра
function onShowPreviewClick() {
	var editor = $(this).parent().parent();

	if ($(".preview", editor).is(":visible") == true) {
		$(".img", editor).removeClass('acvtive');
		$(".preview", editor).hide();
		$(".content", editor).show();
		$(".btn", editor).show();
		$(".image_align_button", editor).hide();
		$(".btn.view", editor).show();
		
		var html = $(".preview", editor).html();
		var markup = htmlToMarkup(html);
		$(".content", editor).val(markup);
	} else {
		$(".preview", editor).show();
		$(".content", editor).hide();
		$(".btn", editor).hide();
		$(".image_align_button", editor).show();
		$(".btn.view", editor).show();
						
		var markup = $(".content", editor).val();
		var html = markupToHtml(markup, true);

		html = "<div style=\"clear: both\"></div>" + html + "<div style=\"clear: both\"></div>";
		$(".preview", editor).html(html);
		$(".preview img", editor).click(onImageClick);
	}
}

//преобразование вики-разметки в html
function markupToHtml(markup) {
	if (!markup) return markup;
	var html = markup
		.split("<<").join("&lt;&lt;")
		.split(">>").join("&gt;&gt;")
		.split("http://").join("http##")
		.split("\n").join("<br />")
		.split("</li><br />").join("</li>")
		.replace(/\[\[([\s\S]*?)\]\]/gm, "<strong>$1</strong>")
	  	.replace(/\|\|([\s\S]*?)\|\|/gm, "<center>$1</center>")
		.replace(/--([\s\S]*?)--/gm, "<s>$1</s>")
		.replace(/\/\/([\s\S]*?)\/\//gm, "<i>$1</i>")
		.replace(/__([\s\S]*?)__/gm, "<u>$1</u>")
	  	.replace(/""([\s\S]*?)""/gm, "<blockquote>$1</blockquote>")
		.replace(/\(\(([\s\S]*?)\)\)/gm, '<div class="justify">$1</div>')
		.replace(/&lt;&lt;([\s\S]*?)&lt;&lt;/gim, '<div class="left">$1</div>')
		.replace(/&gt;&gt;([\s\S]*?)&gt;&gt;/gim, '<div class="right">$1</div>')
		.replace(/\^\^([\s\S]*?)\^\^/gm, '<iframe width="500" height="350" src="$1" frameborder="0"></iframe><br />')
		.split("\n").join("<br />")
		.split("http##").join("http://");
   
	//замена тэгов списка
	html = replaceListTags(html, "+ ", "ol");
	html = replaceListTags(html, "* ", "ul");

	html = html
		.replace(/<\/h1><br \/>/g, "</h1>")
		.replace(/<\/h2><br \/>/g, "</h2>");
	
	return html;
}

// обработка списков
// markup - вики-разметка
// listTag  - тэг списка в вики-разметке
// htmlListTag - тэг списка - ol или ul

function replaceListTags(markup, listTag, htmlListTag) {
	var lines = markup.split("<br />"),
		listTagOpened = false,
		html = "";
	listTag = $.trim(listTag);

	for(i = 0; i < lines.length; i++) {
		var line = lines[i];

		if (line[0] == listTag) {
			if (!listTagOpened) {
				html += "<" + htmlListTag +">\n";
				listTagOpened = true;
			}

			html += "<li>" + $.trim(line.replace(listTag, "").replace("\n", "").replace("\r", "")) + "</li>" + "\n";

			if ((lines.length > i + 1 && lines[i + 1][0] != listTag) ||  (i  == lines.length - 1)) {
				html += "</" + htmlListTag + ">\n";
				listTagOpened = false;
			}
		} else html += line + "<br />";
	}

	html = clearLastCharacter(html, '<br>');
	html = clearLastCharacter(html, '<br />');

	return html;
}

//преобразование вики-разметки в html
function htmlToMarkup(html) {
	if (!html) return html;
	var markup = html
		.split("%3E").join(">")
   		.split("%5E").join("^")
	  	.split("&lt;&lt;").join(">>")
	   	.split("&gt;&gt;").join("<<")
		.replace(/<iframe width="500" height="350" src="(.*?)" frameborder="0"><\/iframe>(<br \/>|<br>|<br\/>)/gi, "^^$1^^")
		.replace(/<iframe src="(.*?)" frameborder="0" height="350" width="500"><\/iframe>(<br \/>|<br>|<br\/>)/gi, "^^$1^^")
	   	.replace(/<div style="clear: both"><\/div>/gi, "")
		.replace(/<br \/>|<br\/>/gi, "\n")
	   	.replace(/<strong>([\s\S]*?)<\/strong>/gim, "[[$1]]")
	   	.replace(/<center>([\s\S]*?)<\/center>/gim, "||$1||")
		.replace(/<s>([\s\S]*?)<\/s>/gim, "--$1--")
		.replace(/<i>([\s\S]*?)<\/i>/gim, "//$1//")
		.replace(/<u>([\s\S]*?)<\/u>/gim, "__$1__")
	   	.replace(/<blockquote>([\s\S]*?)<\/blockquote>/gim, '""$1""')
	   	.replace(/<div class="left">([\s\S]*?)<\/div>/gim, "<<$1<<")
	   	.replace(/<div class="right">([\s\S]*?)<\/div>/gim, ">>$1>>")
		.replace(/<div class="justify">([\s\S]*?)<\/div>/gim, "(($1))");

	markup = replaceHtmlListTags(markup, "ol", "+ ");
	markup = replaceHtmlListTags(markup, "ul", "* ");

	markup = markup
		.replace(/<\/h1>/gi, "</h1>\n")
		.replace(/<\/h2>/gi, "</h2>\n")
		.replace(/<br>|<br\/>|<br \/>/gi, "\n");

	return markup;
}

function replaceHtmlListTags(html, htmlListContainerTag, markupTag) {
	var listOpenTag = "<" + htmlListContainerTag + ">",
		listCloseTag = "</" + htmlListContainerTag  + ">";

	while (html.indexOf(listOpenTag) != -1) {
		var startIndex = html.indexOf(listOpenTag),
			endIndex = html.indexOf(listCloseTag),
			preBlock = $.trim(html.substring(0, startIndex)),
			block = $.trim(html.substring(startIndex + listOpenTag.length, endIndex)),
			postBlock = $.trim(html.substring(endIndex + listCloseTag.length, html.length));
		block = block
			.split('</li>').join('')
			.split('<li>').join(markupTag);
		html = preBlock + block + '<br />' + postBlock;
	}
	return html;
}

function clearLastCharacter(text, character) {
	if (text.substr(text.length - character.length, character.length) == character) {
		text = text.substr(0, text.length - character.length);
	}
	return text;
}

