/*
 * Lightweight RTE - jQuery Plugin
 * Basic Toolbars
 * Copyright (c) 2009 Andrey Gayvoronsky - http://www.gayvoronsky.com
 */
var rte_tag		= '-rte-tmp-tag-';

var	rte_toolbar = {
	s1				: {separator: true},
	bold			: {command: 'bold', tags:['b', 'strong'], hint: 'Выделить жирным'},
	italic			: {command: 'italic', tags:['i', 'em'], hint: 'Курсив'},
	strikeThrough	: {command: 'strikethrough', tags: ['s', 'strike'], hint: 'Перечеркивание' },
	underline		: {command: 'underline', tags: ['u'], hint: 'Подчеркивание'},
	s2				: {separator: true },
	orderedList		: {command: 'insertorderedlist', tags: ['ol'], hint: 'Нумерованный список' },
	unorderedList	: {command: 'insertunorderedlist', tags: ['ul'], hint: 'Ненумерованный список' },
	s6				: {separator : true },
	color			: {exec:
		function() {
			var self = this;
			var panel_ = self.create_panel('Set color for text', 385);
			var mouse_down = false;
			var mouse_over = false;
			panel_.append('\
<div class="colorpicker1"><div class="rgb" id="rgb"></div></div>\
<div class="colorpicker1"><div class="gray" id="gray"></div></div>\
<div class="colorpicker2">\
	<div class="palette" id="palette"></div>\
	<div class="preview" id="preview"></div>\
	<div class="color" id="color"></div>\
</div>\
<div class="clear"></div>\
<p class="submit"><button id="ok">Ok</button><button id="cancel">Cancel</button></p>'
).show();

			var preview = $('#preview', panel_);
			var color = $("#color", panel_);
			var palette = $("#palette", panel_);
			var colors = [
				'#660000', '#990000', '#cc0000', '#ff0000', '#333333',
				'#006600', '#009900', '#00cc00', '#00ff00', '#666666',
				'#000066', '#000099', '#0000cc', '#0000ff', '#999999',
				'#909000', '#900090', '#009090', '#ffffff', '#cccccc',
				'#ffff00', '#ff00ff', '#00ffff', '#000000', '#eeeeee'
			];

			for(var i = 0; i < 25; i++)
				$("<div></div>").addClass("item").css('background', colors[i]).appendTo(palette);

			var height = $('#rgb').height();
			var part_width = $('#rgb').width() / 6;

			$('#rgb,#gray,#palette', panel_)
				.mousedown( function(e) {mouse_down = true; return false; } )
				.mouseup( function(e) {mouse_down = false; return false; } )
				.mouseout( function(e) {mouse_over = false; return false; } )
				.mouseover( function(e) {mouse_over = true; return false; } );

			$('#rgb').mousemove( function(e) { if(mouse_down && mouse_over) compute_color(this, true, false, false, e); return false;} );
			$('#gray').mousemove( function(e) { if(mouse_down && mouse_over) compute_color(this, false, true, false, e); return false;} );
			$('#palette').mousemove( function(e) { if(mouse_down && mouse_over) compute_color(this, false, false, true, e); return false;} );
			$('#rgb').click( function(e) { compute_color(this, true, false, false, e); return false;} );
			$('#gray').click( function(e) { compute_color(this, false, true, false, e); return false;} );
			$('#palette').click( function(e) { compute_color(this, false, false, true, e); return false;} );

			$('#cancel', panel_).click( function() { panel_.remove(); return false; } );
			$('#ok', panel_).click(
				function() {
					var value = color.html();

					if(value.length > 0 && value.charAt(0) =='#') {
						if(self.iframe_doc.selection) //IE fix for lost focus
							self.range.select();

						self.editor_cmd('foreColor', value);
					}

					panel_.remove();
					return false;
				}
			);

			function to_hex(n) {
				var s = "0123456789abcdef";
				return s.charAt(Math.floor(n / 16)) + s.charAt(n % 16);
			}

			function get_abs_pos(element) {
				var r = { x: element.offsetLeft, y: element.offsetTop };

				if (element.offsetParent) {
					var tmp = get_abs_pos(element.offsetParent);
					r.x += tmp.x;
					r.y += tmp.y;
				}

				return r;
			};

			function get_xy(obj, event) {
				var x, y;
				event = event || window.event;
				var el = event.target || event.srcElement;

				// use absolute coordinates
				var pos = get_abs_pos(obj);

				// subtract distance to middle
				x = event.pageX  - pos.x;
				y = event.pageY - pos.y;

				return { x: x, y: y };
			}

			function compute_color(obj, is_rgb, is_gray, is_palette, e) {
				var r, g, b, c;

				var mouse = get_xy(obj, e);
				var x = mouse.x;
				var y = mouse.y;

				if(is_rgb) {
					r = (x >= 0)*(x < part_width)*255 + (x >= part_width)*(x < 2*part_width)*(2*255 - x * 255 / part_width) + (x >= 4*part_width)*(x < 5*part_width)*(-4*255 + x * 255 / part_width) + (x >= 5*part_width)*(x < 6*part_width)*255;
					g = (x >= 0)*(x < part_width)*(x * 255 / part_width) + (x >= part_width)*(x < 3*part_width)*255	+ (x >= 3*part_width)*(x < 4*part_width)*(4*255 - x * 255 / part_width);
					b = (x >= 2*part_width)*(x < 3*part_width)*(-2*255 + x * 255 / part_width) + (x >= 3*part_width)*(x < 5*part_width)*255 + (x >= 5*part_width)*(x < 6*part_width)*(6*255 - x * 255 / part_width);

					var k = (height - y) / height;

					r = 128 + (r - 128) * k;
					g = 128 + (g - 128) * k;
					b = 128 + (b - 128) * k;
				} else if (is_gray) {
					r = g = b = (height - y) * 1.7;
				} else if(is_palette) {
					x = Math.floor(x / 10);
					y = Math.floor(y / 10);
					c = colors[x + y * 5];
				}

				if(!is_palette)
					c = '#' + to_hex(r) + to_hex(g) + to_hex(b);

				preview.css('background', c);
				color.html(c);
			}
		}, hint: 'Выделить цветом'
	},

	image			: {exec:
		function() {
			var self = this;
			var panel_ = self.create_panel('Вставить картинку', 385);
			panel_.append('\
<p><label>№ картинки</label><input type="text" id="url" size="30" value=""></p>\
<div class="clear"></div>\
<p class="submit"><button id="ok">Ok</button><button id="cancel">Отмена</button></p>'
).show();
			$('#url', panel_).focus();


			var url = $('#url', panel_);

			$('#cancel', panel_).click( function() { panel_.remove(); return false;} );
			$('#ok', panel_).click(
				function() {
					var file = '[p align=left]'+url.val()+'[/p]';
					self.editor_cmd('inserthtml', file);
					panel_.remove();
					return false;
				}
			)
		}, tags: ['image'], hint: 'Добавить картинку' },

	YouTube			: {exec:
		function() {
			var self = this;
			var panel_ = self.create_panel('Вставить ролик с YouTube', 385);
			panel_.append('\
<p><label>№ ролика</label><input type="text" id="url" size="30" value=""></p>\
<div class="clear"></div>\
<p class="submit"><button id="ok">Ok</button><button id="cancel">Отмена</button></p>'
).show();
			$('#url', panel_).focus();

			var url = $('#url', panel_);

			$('#cancel', panel_).click( function() { panel_.remove(); return false;} );
			$('#ok', panel_).click(
				function() {
					var file = '[youtube='+url.val()+'][/youtube]';
					self.editor_cmd('inserthtml', file);
					panel_.remove();
					return false;
				}
			)
		}, tags: ['youtube'], hint: 'Добавить ссылку на ролик с YouTube' },
	link			: {exec:
		function() {
			var self = this;
			var panel_ = self.create_panel("Вставить ссылку", 385);
			panel_.append('\
<p><label>URL</label><input type="text" id="url" size="30" value=""><button id="view">Просмотр</button></p>\
<div class="clear"></div>\
<p><label>Комментарий</label><input type="text" id="title" size="30" value=""><label>Окно</label><select id="target"><option value="">Это</option><option value="_blank">Новое</option></select></p>\
<div class="clear"></div>\
<p class="submit"><button id="ok">Ok</button><button id="cancel">Отмена</button></p>'
).show();
			$('#url', panel_).focus();

			$('#cancel', panel_).click( function() { panel_.remove(); return false; } );

			var url = $('#url', panel_);

			$('#view', panel_).click( function() {
					(url.val().length >0 ) ? window.open(url.val()) : alert("Введите URL для просмотра");
					return false;
				}
			);
			$('#ok', panel_).click(
				function() {
					var url = $('#url', panel_).val();
					var target = $('#target', panel_).val();
					var title = $('#title', panel_).val();

					if(self.get_selected_text().length <= 0) {
						alert('Выберите текст для создания ссылки!');
						return false;
					}

					panel_.remove();

					if(url.length <= 0)
						return false;

					self.editor_cmd('unlink');

					// we wanna well-formed linkage (<p>,<h1> and other block types can't be inside of link due to WC3)
					self.editor_cmd('createLink', rte_tag);
					var tmp = $('<span></span>').append(self.get_selected_html());

					if(target.length > 0)
						$('a[href*="' + rte_tag + '"]', tmp).attr('target', target);

					if(title.length > 0)
						$('a[href*="' + rte_tag + '"]', tmp).attr('title', title);

					$('a[href*="' + rte_tag + '"]', tmp).attr('href', url);

					self.selection_replace_with(tmp.html());
					return false;
				}
			)
		}, tags: ['a'], hint: 'Добавить ссылку на выделенный текст' },
	unlink			: {command: 'unlink', hint: 'Убрать ссылку с выделения'},
	s8				: {separator : true },
	removeFormat	: {exec:
		function() {
			this.editor_cmd('removeFormat');
			this.editor_cmd('unlink');
		},
		hint: 'Очистить форматирование'
		},
	word			: {exec: function() { this.set_content(cleanup_word(this.get_content(), true, true, true)); },
	hint: 'Убрать ненужное форматирование Word'
	},
	clear			: {exec: function() { if(confirm('Clear Document?')) this.set_content(''); },
	hint: 'Очистить документ'
	}
};

var html_toolbar = {
	s1				: {separator: true},
	word			: {exec: function() { this.set_content(cleanup_word(this.get_content(), true, true, true)); }},
	clear			: {exec: function() { if(confirm('Clear Document?')) this.set_content(''); }}
};

function cleanup_word(s, bIgnoreFont, bRemoveStyles, bCleanWordKeepsStructure) {
	s = s.replace(/<o:p>\s*<\/o:p>/g, '') ;
	s = s.replace(/<o:p>[\s\S]*?<\/o:p>/g, '&nbsp;') ;

	// Remove mso-xxx styles.
	s = s.replace( /\s*mso-[^:]+:[^;"]+;?/gi, '' ) ;

	// Remove margin styles.
	s = s.replace( /\s*MARGIN: 0cm 0cm 0pt\s*;/gi, '' ) ;
	s = s.replace( /\s*MARGIN: 0cm 0cm 0pt\s*"/gi, "\"" ) ;

	s = s.replace( /\s*TEXT-INDENT: 0cm\s*;/gi, '' ) ;
	s = s.replace( /\s*TEXT-INDENT: 0cm\s*"/gi, "\"" ) ;

	s = s.replace( /\s*TEXT-ALIGN: [^\s;]+;?"/gi, "\"" ) ;

	s = s.replace( /\s*PAGE-BREAK-BEFORE: [^\s;]+;?"/gi, "\"" ) ;

	s = s.replace( /\s*FONT-VARIANT: [^\s;]+;?"/gi, "\"" ) ;

	s = s.replace( /\s*tab-stops:[^;"]*;?/gi, '' ) ;
	s = s.replace( /\s*tab-stops:[^"]*/gi, '' ) ;

	// Remove FONT face attributes.
	if (bIgnoreFont) {
		s = s.replace( /\s*face="[^"]*"/gi, '' ) ;
		s = s.replace( /\s*face=[^ >]*/gi, '' ) ;

		s = s.replace( /\s*FONT-FAMILY:[^;"]*;?/gi, '' ) ;
	}

	// Remove Class attributes
	s = s.replace(/<(\w[^>]*) class=([^ |>]*)([^>]*)/gi, "<$1$3") ;

	// Remove styles.
	if (bRemoveStyles)
		s = s.replace( /<(\w[^>]*) style="([^\"]*)"([^>]*)/gi, "<$1$3" ) ;

	// Remove style, meta and link tags
	s = s.replace( /<STYLE[^>]*>[\s\S]*?<\/STYLE[^>]*>/gi, '' ) ;
	s = s.replace( /<(?:META|LINK)[^>]*>\s*/gi, '' ) ;

	// Remove empty styles.
	s =  s.replace( /\s*style="\s*"/gi, '' ) ;

	s = s.replace( /<SPAN\s*[^>]*>\s*&nbsp;\s*<\/SPAN>/gi, '&nbsp;' ) ;

	s = s.replace( /<SPAN\s*[^>]*><\/SPAN>/gi, '' ) ;

	// Remove Lang attributes
	s = s.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3") ;

	s = s.replace( /<SPAN\s*>([\s\S]*?)<\/SPAN>/gi, '$1' ) ;

	s = s.replace( /<FONT\s*>([\s\S]*?)<\/FONT>/gi, '$1' ) ;

	// Remove XML elements and declarations
	s = s.replace(/<\\?\?xml[^>]*>/gi, '' ) ;

	// Remove w: tags with contents.
	s = s.replace( /<w:[^>]*>[\s\S]*?<\/w:[^>]*>/gi, '' ) ;

	// Remove Tags with XML namespace declarations: <o:p><\/o:p>
	s = s.replace(/<\/?\w+:[^>]*>/gi, '' ) ;

	// Remove comments [SF BUG-1481861].
	s = s.replace(/<\!--[\s\S]*?-->/g, '' ) ;

	s = s.replace( /<(U|I|STRIKE)>&nbsp;<\/\1>/g, '&nbsp;' ) ;

	s = s.replace( /<H\d>\s*<\/H\d>/gi, '' ) ;

	// Remove "display:none" tags.
	s = s.replace( /<(\w+)[^>]*\sstyle="[^"]*DISPLAY\s?:\s?none[\s\S]*?<\/\1>/ig, '' ) ;

	// Remove language tags
	s = s.replace( /<(\w[^>]*) language=([^ |>]*)([^>]*)/gi, "<$1$3") ;

	// Remove onmouseover and onmouseout events (from MS Word comments effect)
	s = s.replace( /<(\w[^>]*) onmouseover="([^\"]*)"([^>]*)/gi, "<$1$3") ;
	s = s.replace( /<(\w[^>]*) onmouseout="([^\"]*)"([^>]*)/gi, "<$1$3") ;

	if (bCleanWordKeepsStructure) {
		// The original <Hn> tag send from Word is something like this: <Hn style="margin-top:0px;margin-bottom:0px">
		s = s.replace( /<H(\d)([^>]*)>/gi, '<h$1>' ) ;

		// Word likes to insert extra <font> tags, when using MSIE. (Wierd).
		s = s.replace( /<(H\d)><FONT[^>]*>([\s\S]*?)<\/FONT><\/\1>/gi, '<$1>$2<\/$1>' );
		s = s.replace( /<(H\d)><EM>([\s\S]*?)<\/EM><\/\1>/gi, '<$1>$2<\/$1>' );
	} else {
		s = s.replace( /<H1([^>]*)>/gi, '<div$1><b><font size="6">' ) ;
		s = s.replace( /<H2([^>]*)>/gi, '<div$1><b><font size="5">' ) ;
		s = s.replace( /<H3([^>]*)>/gi, '<div$1><b><font size="4">' ) ;
		s = s.replace( /<H4([^>]*)>/gi, '<div$1><b><font size="3">' ) ;
		s = s.replace( /<H5([^>]*)>/gi, '<div$1><b><font size="2">' ) ;
		s = s.replace( /<H6([^>]*)>/gi, '<div$1><b><font size="1">' ) ;

		s = s.replace( /<\/H\d>/gi, '<\/font><\/b><\/div>' ) ;

		// Transform <P> to <DIV>
		var re = new RegExp( '(<P)([^>]*>[\\s\\S]*?)(<\/P>)', 'gi' ) ;	// Different because of a IE 5.0 error
		s = s.replace( re, '<div$2<\/div>' ) ;

		// Remove empty tags (three times, just to be sure).
		// This also removes any empty anchor
		s = s.replace( /<([^\s>]+)(\s[^>]*)?>\s*<\/\1>/g, '' ) ;
		s = s.replace( /<([^\s>]+)(\s[^>]*)?>\s*<\/\1>/g, '' ) ;
		s = s.replace( /<([^\s>]+)(\s[^>]*)?>\s*<\/\1>/g, '' ) ;
	}

	return s;
}
