/******************************************************************************************* EDITOR */
function AsynchUploader() {}
AsynchUploader.instances = [];
AsynchUploader.prototype = {
	action: '/upload_image',
	init: function(form,callback,context) {
		this.instanceId = AsynchUploader.instances.length;
		AsynchUploader.instances.push(this);
		this.iframe = as.append("<iframe class='upload-frame' frameborder='0' scrolling='no' name='instanceId"+this.instanceId+"'></iframe>",document.body);
		this.form = form;
		this.callback = context ? as.bind(callback,context) : callback;
		this.form.action = this.action;
		as.append("<input type='hidden' name='as_editor' value='true' />",this.form);
		as.append("<input type='hidden' name='instance_id' value='"+this.instanceId+"' />",this.form);
		this.form.target = this.iframe.name;
	}
}
/*******************************************************************************************\\ EDITOR \\*/
/******************************************************************************************* EDITOR */
function ASEditor() {}
ASEditor.instances = [];
ASEditor.prototype = {
	iframeSRC: '/js/aseditor/canvas.html',
	editorCSS: '/js/aseditor/aseditor.css',
	ASPopupJSSRC: '/js/aspopup.js',
	ASPopupCSSSRC: '/style/aspopup.css',
	selectionListeners: {},
	init: function(textarea) {
		ASEditor.instances.push(this);
		this.instanceId = ASEditor.instances.length-1;
		this.textarea = textarea;
		this.textarea.aseditor = this;
		this.form = this.textarea.form;
		this.getEditorCSS();
		this.getASPopup();
		this.hideTextarea();
		this.editorData = this.textarea.onclick();
		if (this.editorData.toolbar) {
			this.toolbarData = this.textarea.onclick().toolbar;
			this.showEditor();
		}
		else if (this.editorData.config) {
			var script = as.create("script");
			as.append(script,as.$$("head"));
			script.type = 'text/javascript';
			script.id = "aseditor-config" + this.instanceId;
			script.src = this.editorData.config;
		}
		return this;
	},
	setToolbarFromConfig: function(toolbarData) {
		this.toolbarData = toolbarData;
		as.remove(as.$$("script#aseditor-config"+this.instanceId));
		this.showEditor();
	},
	getEditorCSS: function() {
		var cssLoaded = false;
		as.w('link').each(function() {if (this.href.match(/aseditor.css/)) {cssLoaded = true}});
		if (!cssLoaded) {
			var css = as.$$("head").appendChild(document.createElement('link'));
			css.rel = "stylesheet";
			css.href = this.editorCSS;
		}
	},
	getASPopup: function() {
		var aspopupJSLoaded = aspopupCSSLoaded = false;
		as.w('script').each(function() {if (this.src.match(/aspopup.js/)) {aspopupJSLoaded = true}});
		if (!aspopupJSLoaded) {
			var aspopupJS = as.$$("head").appendChild(document.createElement('script'));
			aspopupJS.type = "text/javascript";
			aspopupJS.src = this.ASPopupJSSRC;
		}
		if (!aspopupCSSLoaded) {
			var aspopupCSS = as.$$("head").appendChild(document.createElement('link'));
			aspopupCSS.rel = "stylesheet";
			aspopupCSS.href = this.ASPopupCSSSRC;
		}
	},
	hideTextarea: function() {
		this.defaultSize = as.getElementPosition(this.textarea);
		this.textarea.style.display = "none";
	},
	showEditor: function() {
		this.editorContainer = as.after(
			"<div class='aseditor-container'>"+
				"<div class='toolbar'></div>"+
				"<div class='editor'><div class='editor-wrapper'><iframe frameborder='0' scrolling='no' src='"+this.iframeSRC+"?instanceId="+this.instanceId+"'></iframe></div></div>"+
			"</div>",
			this.textarea
		);
		this.editor = as.$$("iframe",this.editorContainer);
		this.toolbar = as.$$("div.toolbar",this.editorContainer);
		//as.style(this.editorContainer,{width: this.defaultSize.width + 'px'});
		as.style(this.editor,{height: (this.defaultSize.height || '250') + "px"/*, width: this.defaultSize.width - 14 + "px"*/});
		
		as.w("input.clear",this.editorContainer).click(this.clearEditor,this);
	},
	clearEditor: function(e) {
		e && e.preventDefault();
		this.docBody.innerHTML = ""; this.saveSelection();
	},
	initEditor: function(doc,body) {
		this.win = this.editor.contentWindow;
		as.e.unload(this.win,this.saveData,this);
		this.doc = doc;
		this.docBody = body;
		this.editorArea = body;
		
		this.editorArea.innerHTML = this.textarea.value;
		this.clearBeforeLoad();
		this.editorArea.contentEditable = "false";
		this.doc.designMode = 'on';
		this.doc.designMode = 'off';
		this.doc.designMode = 'on';
		this.editorArea.contentEditable = "true";
		this.editorArea.style.height = this.defaultSize.height ? (this.defaultSize.height - 20) : "250"  + "px";
		
		as.e.click(this.doc,function() {this.editorArea.focus();},this);
		as.e.unload(window,this.CLS,this);
		as.e.mouseup(this.docBody,this.saveSelection,this);
		as.e.focus(this.docBody,this.saveSelection,this);
		as.e.keyup(this.doc,this.saveSelection,this);
		as.e.submit(this.form,this.onFormSubmit,this);
		if (this.initialized) {
			this.restoreData();
			return;
		}
		this.initToolbar();
		this.initialized = true;
	},
	turnOff: function() {
		this.textarea.style.display = "block";
		this.editorContainer.style.display = "none";
	},
	turnOn: function() {
		this.textarea.style.display = "none";
		this.editorContainer.style.display = "block";
	},
	focus: function() {		
		this.win.focus();
		this.editorArea.focus();
		
		var editorCS = as.getElementPosition(this.editorContainer);
		if (editorCS.top + editorCS.height > document.documentElement.scrollTop + document.documentElement.offsetHeight) {
			document.documentElement.scrollTop = editorCS.top + editorCS.height - document.documentElement.offsetHeight;
		}
	},
	onFormSubmit: function() {
		this.saveSelection();
		this.CLS();
	},
	CLS: function() {
		ASEditor.instances = null;
		this.textarea.aseditor = null;
	},
	initToolbar: function() {
		for (var i=0,l=this.toolbarData.length;i<l;i++) {
			try {
				this.toolbarFunctions[this.toolbarData[i]] && as.bind(this.toolbarFunctions[this.toolbarData[i]],this)();
			}
			catch(e) {}
		}
	},
	toolbarFunctions: {
		smiles: function() {
			new EditorToolbarSmiles().init(this);
		},
		image: function() {
			new EditorToolbarImageUpload().init(this);
		},
		video: function() {
			new EditorToolbarVideo().init(this);
		},
		bold: function() {
			new EditorToolbarBold().init(this);
		},
		italic: function() {
			new EditorToolbarItalic().init(this);
		},
		strike: function() {
			new EditorToolbarStrike().init(this);
		},
		ol: function() {
			new EditorToolbarOrderedList().init(this);
		},
		ul: function() {
			new EditorToolbarUnorderedList().init(this);
		},
		alignLeft: function() {
			new EditorToolbarAlignLeft().init(this);
		},
		alignRight: function() {
			new EditorToolbarAlignRight().init(this);
		},
		alignCenter: function() {
			new EditorToolbarAlignCenter().init(this);
		},
		cut: function() {
			new EditorToolbarCut().init(this);
		},
		quote: function() {
			new EditorToolbarQuote().init(this);
		},
		link: function() {
			new EditorToolbarLink().init(this);
		},
		font: function() {
			new EditorToolbarFont().init(this);
		},
		yap: function() {
			new EditorToolbarYap().init(this);
		},
		html: function() {
			new EditorToolbarHTML().init(this);
		}/*,
		word: function() {
			new EditorToolbarWord().init(this);
		}*/
	},
	addToolbarElement: function(opts) {
		var element = as.append("<a href='#'><span class='element-pic'></span><b><i></i></b></a>",this.toolbar);
		element.className = opts.className || '';
		if (opts.dropDown) {
			as.append("<span class='drop-down'></span>",element);
		}
		return element;
	},
	addSelectionListener: function(style,fn,context) {
		this.selectionListeners[style] = {fn: fn, context: context};
	},
	fireSelectionListeners: function() {
		var node = this.savedRange.startContainer || this.savedRange.parentElement();
		while (node.nodeType != 1) {
			node = node.parentNode;
		}
		for (var style in this.selectionListeners) {
			this.selectionListeners[style].fn.call(this.selectionListeners[style].context,as.style(node,style),node);
		}
	},
	setSelection: function(after,collapse) {
		var newRange, newSelection;
		//after = as.after("<br />",after);
		if (this.doc.createRange) {
			newRange = this.doc.createRange();
			newSelection = this.win.getSelection();				
			newRange.selectNode(after);
			newRange.collapse(!!collapse);
			newSelection.removeAllRanges();
			newSelection.addRange(newRange);
			this.win.focus();
			this.editorArea.focus();
		}
		else if (this.editorArea.createTextRange) {
			this.editorArea.focus();
			newRange = this.editorArea.createTextRange();
			newRange.moveToElementText(after);
			newRange.collapse(!!collapse);
			newRange.select();
		}
		this.saveSelection();
	},
	setEnd: function() {
		if (this.doc.createRange) {
			if (!this.editorArea.lastChild) {this.appendContent("<br />")}
			this.setSelection(this.editorArea.lastChild,false);
		}
		else if (this.editorArea.createTextRange) {
			this.setSelection(this.editorArea,false);
		}
	},
	setStart: function() {
		if (this.doc.createRange) {
			if (!this.editorArea.firstChild) {this.appendContent("<br />")}
			this.setSelection(this.editorArea.firstChild,true);
		}
		else if (this.editorArea.createTextRange) {
			this.setSelection(this.editorArea,true);
		}
	},
	appendContent: function(content) {
		this.focus();
		if (this.win.getSelection) {
			this.restoreSelection();
			var range = this.win.getSelection().getRangeAt(0);
			var container = range.endContainer;
			var offset = range.endOffset;
			switch(container.nodeType) {
				case 3:
				var value = container.nodeValue;
				as.after(document.createTextNode(value.substring(offset)),container);
				var lastAppend = as.after(content,container);
				as.after(document.createTextNode(value.substring(0,offset)),container);
				as.remove(container);
				this.setSelection(lastAppend)
				break;
				
				case 1:
				var appended = (offset == 0 ? as.prepend(as.create(content),container) : as.after(as.create(content),container.childNodes[offset-1]));
				this.setSelection(appended);
				break;
			}
		}
		else if (this.doc.selection) {
			var range = this.savedRange || this.doc.selection.createRange();
			//range.select();
			//range.collapse(true);			
			//range.pasteHTML(range.htmlText + content);
			range.pasteHTML(content);
			range.collapse(true);
			range.select();
		}
		this.saveSelection();
	},
	wrapBy: function(wrapper,after) {
		after = after || "";
		this.restoreSelection();
		this.focus();
		if (this.win.getSelection) {
			wrapper = as.create(wrapper);
			var range = this.savedRange || this.win.getSelection().getRangeAt(0);			
			if (navigator.userAgent.match(/webkit/i)) {
				var selection = range.extractContents();
				wrapper.appendChild(selection);
				this.appendContent(wrapper);
				this.doc.execCommand("RemoveFormat",false,null);
			}
			else {
				this.doc.execCommand("RemoveFormat",false,null);
				range.surroundContents(wrapper);
			}
		}
		else if (this.doc.selection) {
			var wrapStart = wrapper.match(/<(.(?!(<\/)))+>/,"")[0];
			var wrapEnd = wrapper.match(/<\/.+/)[0];
			var range = this.savedRange || this.doc.selection.createRange();			
			this.doc.execCommand("RemoveFormat",false,null);
			var fHtml = range.htmlText.replace(/<\/?p[^>]*>/gi,"").replace(/<\/?span[^>]*>/gi,"");
			this.doc.selection.clear();
			range.pasteHTML(wrapStart + fHtml + wrapEnd/* + after*/);
		}
		this.saveSelection();
	},
	saveSelection: function() {
		try {
			setTimeout(as.bind(this.rSaveSelection,this),200);
		}
		catch(e) {
			
		}
	},
	rSaveSelection: function() {
		try {
			this.clearFormat();
			this.textarea.value = this.editorArea.innerHTML;
			this.savedRange = this.win.getSelection ? this.win.getSelection().getRangeAt(0) : this.doc.selection.createRange();
			this.fireSelectionListeners();
		}
		catch(e) {}
	},
	clearFormat: function() {
		function cleanHTML(html) {
			html = html.replace(/<o:p>\s*<\/o:p>/g, '') ;
			html = html.replace(/<o:p>.*?<\/o:p>/g, '&nbsp;') ;
			html = html.replace( /\s*mso-[^:]+:[^;"]+;?/gi, '' ) ;
			html = html.replace( /\s*MARGIN: 0cm 0cm 0pt\s*;/gi, '' ) ;
			html = html.replace( /\s*MARGIN: 0cm 0cm 0pt\s*"/gi, "\"" ) ;
			html = html.replace( /\s*TEXT-INDENT: 0cm\s*;/gi, '' ) ;
			html = html.replace( /\s*TEXT-INDENT: 0cm\s*"/gi, "\"" ) ;
			html = html.replace( /\s*TEXT-ALIGN: [^\s;]+;?"/gi, "\"" ) ;
			html = html.replace( /\s*PAGE-BREAK-BEFORE: [^\s;]+;?"/gi, "\"" ) ;
			html = html.replace( /\s*FONT-VARIANT: [^\s;]+;?"/gi, "\"" ) ;
			html = html.replace( /\s*tab-stops:[^;"]*;?/gi, '' ) ;
			html = html.replace( /\s*tab-stops:[^"]*/gi, '' ) ;
			html = html.replace( /\s*face="[^"]*"/gi, '' ) ;
			html = html.replace( /\s*face=[^ >]*/gi, '' ) ;
			html = html.replace( /\s*FONT-FAMILY:[^;"]*;?/gi, '' ) ;
			//html = html.replace( /\s*width:[^;"]*;?/gi, '' ) ;
			//html = html.replace( /\s*height:[^;"]*;?/gi, '' ) ;
			html = html.replace( /\s*table-layout:[^;"]*;?/gi, '' ) ;
			html = html.replace( /\s*border-collapse:[^;"]*;?/gi, '' ) ;
			html = html.replace( /\s*font-size:[^;"]*;?/gi, '' ) ;
			html = html.replace( /\s*color:[^;"]*;?/gi, '' ) ;
			html = html.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3") ;
			html = html.replace( /<FONT[^>]*>(.*?)<\/FONT>/gi, '$1' ) ;
			html = html.replace(/<\\?\?xml[^>]*>/gi, '' ) ;
			html = html.replace(/<\/?\w+:[^>]*>/gi, '' ) ;
			html = html.replace(/<\!--.*?-->/g, '' ) ;
			html = html.replace( /<(U|I|STRIKE)>&nbsp;<\/\1>/g, '&nbsp;' ) ;
			html = html.replace( /<H\d>\s*<\/H\d>/gi, '' ) ;
			html = html.replace( /<(\w+)[^>]*\sstyle="[^"]*DISPLAY\s?:\s?none(.*?)<\/\1>/ig, '' ) ;
			html = html.replace( /<(\w[^>]*) language=([^ |>]*)([^>]*)/gi, "<$1$3") ;
			html = html.replace( /<(\w[^>]*) onmouseover="([^\"]*)"([^>]*)/gi, "<$1$3") ;
			html = html.replace( /<(\w[^>]*) onmouseout="([^\"]*)"([^>]*)/gi, "<$1$3") ;
			html = html.replace( /<(\w[^>]*) onclick="([^\"]*)"([^>]*)/gi, "<$1$3") ;
			html = html.replace( /<(\w[^>]*) onmousedown="([^\"]*)"([^>]*)/gi, "<$1$3") ;
			html = html.replace( /<(\w[^>]*) onmouseout="([^\"]*)"([^>]*)/gi, "<$1$3") ;
			html = html.replace( /<([^\s>]+)(\s[^>]*)?>\s*<\/\1>/g, '' ) ; 
			return html ; 
		}
		function removeSet(set) {			
			for (var i=0,l=set.length;i<l;i++) {
				as.remove(set[0]);
			}
		}
		//var tables = as.w("table",this.doc).filter(function() {return !as.parent(this,"div.as-insert-from")});
		//removeSet(tables.set);
		//removeSet(as.$("p.MsoNormal",this.doc));
		//removeSet(as.$("font",this.doc));
		removeSet(as.$("meta",this.doc));
		removeSet(as.$("title",this.doc));
		
		var beforeHTML = this.docBody.innerHTML;
		var afterHTML = cleanHTML(beforeHTML);
		if (beforeHTML == afterHTML) return;
		
		this.docBody.innerHTML = cleanHTML(this.docBody.innerHTML);
		this.setEnd();
	},
	clearBeforeLoad: function() {		
		function removeTagWrap(tag) {			
			var re = new RegExp("<//?" + tag + "[^>]+>","gi");
			this.docBody.innerHTML = this.docBody.innerHTML.replace(re,"");
		}
		function removeSet(set) {			
			for (var i=0,l=set.length;i<l;i++) {
				as.remove(set[0]);
			}
		}
		removeTagWrap.call(this,"font");
		removeSet(as.$("meta",this.doc));
		removeSet(as.$("title",this.doc));
		var tables = as.w("table",this.doc).filter(function() {return !as.parent(this,"div.as-insert-from")});
		removeSet(tables.set);
		as.w("p.MsoNormal",this.doc).each(function() {
			this.className = this.className.replace(/\bMsoNormal\b/g,"");
		});
		this.docBody.innerHTML = this.docBody.innerHTML.replace(/(\s)+/gi,"$1");
	},
	restoreSelection: function() {
		if (!this.savedRange) return;
		var selection;
		this.editorArea.focus();
		if (this.win.getSelection) {
			selection = this.win.getSelection();			
			selection.removeAllRanges();
			selection.addRange(this.savedRange);
		}
		else if (this.savedRange.select) {
			this.savedRange.select();
		}
	},
	saveData: function() {
		this.textarea.value = this.editorArea.innerHTML;
	},
	restoreData: function() {
		this.editorArea.innerHTML = this.textarea.value;
	}
}
function EditorToolbarSmiles() {}
EditorToolbarSmiles.prototype = {
	path: '/js/aseditor/i/smiles/',
	list: ['smile.gif','sad.gif','wink.gif','tongue.gif','glass.gif','grin.gif','open-mouth.gif','cry.gif','kiss.gif','crazy.gif','saliva.gif','devil.gif'],
	init: function(editor) {
		this.editor = editor;
		this.link = this.editor.addToolbarElement({className: 'smiles'});
		this.link.title = "Смайлы";
		this.createPopup();
		as.e.click(this.link,this.showPopup,this);
	},
	createPopup: function() {
		this.popup = as.append("<ul class='aseditor-smiles-popup'></ul>",document.body);
		as.foreach(this.list,as.bind(function(item) {
			as.append("<li><img src='" +this.path + item + "' /></li>",this.popup);
		},this));
		as.e.click(this.popup,this.chooseImage,this);
		as.e.click(document.body,this.checkClick,this);
		as.e.click(this.editor.docBody,this.checkClick,this);
	},
	checkClick: function(e) {
		if (!as.parent(e.target,this.popup) && e.target != this.popup && e.target != this.link && e.target.parentNode != this.link) {
			this.hidePopup();
		}
	},
	showPopup: function(e) {
		e.preventDefault();
		if (this.popupShown) {
			this.hidePopup();
			return;
		}
		var linkCS = as.getElementPosition(this.link);
		this.popup.style.display = "block";
		as.style(this.popup,{
			top: linkCS.top + linkCS.height - 9 + "px",
			left: linkCS.left - this.popup.offsetWidth + 42 + "px"
		});
		this.popupShown = true;
		this.link.className += " active";
	},
	hidePopup: function() {
		this.popup.style.display = "none";
		this.popupShown = false;
		this.link.className = this.link.className.replace(/\bactive\b/gi,'');
	},
	chooseImage: function(e) {
		if (e.target.tagName.toLowerCase() != "img") return;
		this.hidePopup();
		this.editor.appendContent("<img src='" + e.target.src + "' />");
	}
}
function EditorToolbarImageUpload() {}
EditorToolbarImageUpload.prototype = {
	tabSet: {
		file: {},
		site: {}
	},
	imgFloat: true,
	loaderUrl: "/js/aseditor/i/uploading-loader.gif",
	loadedUrl: "/js/aseditor/i/uploaded-loader.gif",
	itemToInsertText: 'изображение',
	popupClassName: 'image-upload-content',
	init: function(editor) {
		this.editor = editor;
		this.link = this.editor.addToolbarElement({className: 'image'});
		this.editable = false;
		this.link.title = "Фотография";
		as.e.click(this.link,this.tryShowPopup,this);
		as.e.click(this.editor.docBody,this.checkClickTarget,this);
				
		this.pullSpans();
	},
	pullSpans: function() {
		as.w("span.photo-video-container",this.editor.doc).each(function() {
			var parent = this;
			while(parent.parentNode.tagName.toLowerCase() != "body") {
				parent = parent.parentNode;
			}
			as.before(this,parent);
			var img = as.$$("img",this);
			if (!img) {
				as.remove(this);
			}
			img.className = "photo-video";
			if (as.is(this,"span.video-container")) {
				img.className += " video";
			}
			var videoLink = as.$$("a",this), video = "";
			var descIns = as.$$("ins",this), desc = "";
			if (videoLink) {
				video = videoLink.href
			}
			if (descIns) {
				desc = descIns.innerHTML;
			}
			img.alt = desc;
			img.title = video;
			this.className.match(/\bno-float\b/) || (img.className += " float");
			as.after(img,this);
			as.remove(this);
		});
	},
	tryShowPopup: function(e) {
		e && e.preventDefault();
		this.popup ? this.showPopup() : this.createPopup();
		this.editable = false;
	},
	hidePopup: function() {
		this.popup.hide();
		this.setDefaults();
	},
	showPopup: function() {
		this.popup.show();
	},
	checkClickTarget: function(e) {
		if (as.is(e.target,"img.photo-video") && !as.is(e.target,"img.video")) {
			this.editImage(e.target);
		}
	},
	editImage: function(image) {
		this.tryShowPopup();
		this.editable = image;		
		
		this.siteFormInput.value = image.src;
		var isFloat = image.className.match(/\bfloat\b/);
		this.floatFS.each(function() {
			this.checked = false;
			if ((this.value == 1 && isFloat) || (this.value == 0 && !isFloat)) {
				this.checked = true;
			}
		});
		var desc = image.alt || "";
		var video = image.title || "";
		this.siteFormDescription.value = desc;
		this.selectedImage = image.src;
		this.showAppendButton();
	},
	createPopup: function() {
		var content = 
			"<div class='"+this.popupClassName+"'>" +
				"<h3>Выбрать "+this.itemToInsertText+"</h3>" + 
				"<div class='work-place'>" + 

				"</div>" +
			"</div>";
		this.popup = new ASPopup().init({popupType: 'aseditor-popup',closeType: 'ByAwayClick',relativeTo: this.link, defaultContent: content});
		this.workPlaceDiv = as.$$("div.work-place",this.popup.popupContent);
		as.e.click(this.popup.popupContent,this.onAppendButtonClick,this);
		this.fillPopupContent();
	},
	fillPopupContent: function() {
		/**** other sites images ****/
		this.siteForm = as.append(
			"<form method='POST' enctype='multipart/form-data'>" +
				"<h4>Укажите путь:</h4>" +
				"<input type='text' class='src' />" +
				"<fieldset class='upload'>" + 
				"<h4>Или загрузите файл с вашего компьютера:</h4>" +
				"<input type='file' class='file' name='image' />" +
				"</fieldset>" +
				"<h4>Описание</h4>" + 
				"<input type='text' class='desc' />" +
				"<h4>Обтекание текста</h4>" +
				"<fieldset class='float'><label><input type='radio' name='float' value='1' /> да</label> <label><input type='radio' checked='checked' name='float' value='0' /> нет</label></fieldset>" +
				"<input type='button' value='Отмена' class='cancel' />" +
			"</form>",
			this.workPlaceDiv
		);
		this.showAppendButton();
		this.hideAppendButton();
		this.siteFormInput = as.$$('input.src',this.siteForm);
		this.fileFormInput = as.$$('input.file',this.siteForm);
		this.siteFormDescription = as.$$('input.desc',this.siteForm);
		this.floatFS = as.w("fieldset.float input",this.siteForm);
		as.e.keyup(this.siteFormInput,this.onSiteFormKeyup,this);
		as.e.mouseup(this.siteFormInput,function() {
			if (this.siteFormInput.value == "") {
				setTimeout(as.bind(arguments.callee,this),20);
				return;
			}
			this.onSiteFormKeyup({target: this.siteFormInput});
		},this);
		as.e.click(as.$$("input.cancel",this.popup.popupContent),function(e) {
			e.preventDefault();
			this.hidePopup();
		},this);
		this.fileChangeEvent();
		new AsynchUploader().init(this.siteForm,this.onImageUpload,this);
	},
	fileChangeEvent: function() {
		as.e.change(this.fileFormInput,function() {
			this.siteFormInput.disabled = true;
			this.siteForm.submit();
			this.hideAppendButton();
			this.hideLoader();
			this.showLoader();
			this.removeWarning();
		},this);
	},
	onImageUpload: function(url) {
		if (!url) {
			this.hideLoader();
			this.showWarning(arguments[1]);
			return;
		}
		this.loader.src = this.loadedUrl;
		this.loader.className += " uploaded-loader";
		this.selectedImage = url;
		this.showAppendButton();
	},
	showWarning: function(warning) {
		this.warning = as.before("<p class='warning'>" + warning + "</p>",this.siteForm);
	},
	removeWarning: function() {
		as.remove(this.warning);
	},
	showLoader: function() {
		this.loader = as.before("<img class='uploading-loader' src='"+this.loaderUrl+"' />",this.fileFormInput);
	},
	hideLoader: function() {
		as.remove(this.loader);
	},
	onSiteFormKeyup: function(e) {
		if (e.target.value != "") {
			this.selectedImage = e.target.value;
			this.showAppendButton();
			this.fileFormInput.disabled = true;
			this.removeWarning();
		}
		else {
			this.selectedImage = null;
			this.hideAppendButton();
		}
	},
	showAppendButton: function() {
		if (!this.appendButton) {
			this.appendButton = as.append("<a href='#' class='button'><span>Вставить "+this.itemToInsertText+"</span></a>",as.$$("form",this.workPlaceDiv));
		}		
		this.appendButton.className = this.appendButton.className.replace(/\binactive\b/gi,"");
	},
	hideAppendButton: function() {
		this.appendButton.className += " inactive";
	},
	onAppendButtonClick: function(e) {
		if (as.parent(e.target,"a.button") || as.is(e.target,"a.button")) {
			e.preventDefault();
			if (this.appendButton.className.match(/\binactive\b/)) return;
			var imgFloat;
			this.floatFS.each(function() {
				if (this.checked) {
					if (this.value == "1") {
						imgFloat = " float";
					}
					else {
						imgFloat = "";
					}
				}
			});
			var desc = this.siteFormDescription.value;
			var src = this.selectedImage;
			var appendingImage = "<img class='photo-video" + imgFloat + "' src='" + src + "' alt='" + desc + "' />";
			if (this.editable) {
				this.editable.src = src;
				this.editable.className = "photo-video" + imgFloat;
				this.editable.alt = desc;
				this.editor.saveSelection();
				//this.editor.setSelection(this.editable);
			}
			else {
				this.editor.appendContent(appendingImage);
			}
			this.hidePopup();
			this.pullSpans();
		}
	},
	setDefaults: function() {
		this.siteFormInput.value = "";
		this.siteFormInput.disabled = false;
		this.siteFormDescription.value = "";
		this.hideAppendButton();
		this.hideLoader();
		this.selectedImage = null;
		this.floatFS.each(function() {
			if (this.value == 0) this.checked = true;
		});
		this.fileFormInput = as.after("<input type='file' class='file' name='image' />",this.fileFormInput);
		this.fileChangeEvent();
		as.remove(as.$$("input.file",this.siteForm));
	}
}
function EditorToolbarVideo() {}
EditorToolbarVideo.prototype = new EditorToolbarImageUpload();
EditorToolbarVideo.prototype.itemToInsertText = "видео";
EditorToolbarVideo.prototype.popupClassName = 'image-upload-content video-insert-content';
EditorToolbarVideo.prototype.init = function(editor) {
	this.editor = editor;
	this.link = this.editor.addToolbarElement({className: 'video'});
	this.link.title = "Видео";
	as.e.click(this.link,this.tryShowPopup,this);
	as.e.click(this.editor.docBody,this.checkClickTarget,this);
	this.pullSpans();
}
EditorToolbarVideo.prototype.checkClickTarget = function(e) {
	if (as.is(e.target,"img.video")) {
		this.editImage(e.target);
	}
}
EditorToolbarVideo.prototype.editImage = function(image) {
	this.tryShowPopup();
	this.editable = image;
	
	this.siteFormInput.value = image.title;
	var isFloat = image.className.match(/\bfloat\b/);
	this.floatFS.each(function() {
		this.checked = false;
		if ((this.value == 1 && isFloat) || (this.value == 0 && !isFloat)) {
			this.checked = true;
		}
	});
	this.siteFormDescription.value = image.alt;
	this.selectedVideo = image.title;
	this.selectedImage = "http://img.youtube.com/vi/" + this.selectedVideo.match(/youtube.com\/watch\?v=[^&]+/)[0].replace("youtube.com/watch?v=","") + "/0.jpg";
	this.showAppendButton();
}
EditorToolbarVideo.prototype.onSiteFormKeyup = function(e) {
	if (e.target.value.match(/youtube\.com\/watch\?v=\w+/)) {
		this.selectedVideo = e.target.value;
		this.showAppendButton();
	}
	else {
		this.selectedImage = null;
		this.selectedVideo = "";
		this.hideAppendButton();
	}
}
EditorToolbarVideo.prototype.onAppendButtonClick = function(e) {
	if (as.parent(e.target,"a.button") || as.is(e.target,"a.button")) {
		e.preventDefault();
		if (this.appendButton.className.match(/\binactive\b/)) return;
		var imgFloat;
		this.floatFS.each(function() {
			if (this.checked) {
				if (this.value == "1") {
					imgFloat = " float";
				}
				else {
					imgFloat = "";
				}
			}
		});		
		var desc = this.siteFormDescription.value;
		var src = "http://img.youtube.com/vi/" + this.siteFormInput.value.match(/youtube.com\/watch\?v=[^&]+/)[0].replace("youtube.com/watch?v=","") + "/0.jpg";
		var appendingImage = "<img src='" + src + "' class='photo-video video" + imgFloat + "' alt='" + desc + "' title='" + this.selectedVideo + "' />";
		if (this.editable) {
			this.editable.className = 'photo-video video' + imgFloat;
			this.editable.src = src;
			this.editable.title = this.selectedVideo;
			this.editable.alt = desc;
			this.editor.saveSelection();
		}
		else {
			this.editor.appendContent(appendingImage);
		}
		this.hidePopup();
	}
}
/***************************************** BOLD ITALIC STRIKE ***/
function EditorToolbarBold() {}
EditorToolbarBold.prototype = {
	init: function(editor) {
		this.editor = editor;
		this.link = this.editor.addToolbarElement({className: 'bold'});
		this.link.title = "Жирный";
		as.e.click(this.link,this.setBold,this);
		as.e.keydown(this.editor.doc,function(e){
			if (e.keyCode == 66 && e.ctrlKey) {
				e.preventDefault();
				this.setBold(e);
			}
		},this);
		this.editor.addSelectionListener("font-weight",this.onSelect,this);
	},
	setBold: function(e) {
		e.preventDefault();
		if (!this.editor.savedRange) return;
		if (window.getSelection && this.editor.savedRange.collapsed) return;
		if (document.selection && (this.editor.savedRange.htmlText == "" || this.editor.savedRange.htmlText == undefined)) return;
		this.editor.doc.execCommand("Bold",false,null);
		this.editor.saveSelection();
		this.editor.focus();
	},
	onSelect: function(value) {
		if (value == "bold" || value == "700") {
			this.link.className += " bold-active";
		}
		else {
			this.link.className = this.link.className.replace(/\bbold-active\b/gi,"");
		}
	}
}
function EditorToolbarItalic() {}
EditorToolbarItalic.prototype = {
	init: function(editor) {
		this.editor = editor;
		this.link = this.editor.addToolbarElement({className: 'italic'});
		this.link.title = "Курсив";
		as.e.click(this.link,this.setItalic,this);
		as.e.keydown(this.editor.doc,function(e){
			if (e.keyCode == 73 && e.ctrlKey) {
				e.preventDefault();
				this.setItalic(e);
			}
		},this);
		this.editor.addSelectionListener("font-style",this.onSelect,this);
	},
	setItalic: function(e) {
		e.preventDefault();
		if (!this.editor.savedRange) return;
		if (window.getSelection && this.editor.savedRange.collapsed) return;
		if (document.selection && (this.editor.savedRange.htmlText == "" || this.editor.savedRange.htmlText == undefined)) return;
		this.editor.doc.execCommand("Italic",false,null);
		this.editor.saveSelection();
		this.editor.focus();
	},
	onSelect: function(value) {
		if (value == "italic") {
			this.link.className += " italic-active";
		}
		else {
			this.link.className = this.link.className.replace(/\bitalic-active\b/gi,"");
		}
	}
}
function EditorToolbarStrike() {}
EditorToolbarStrike.prototype = {
	init: function(editor) {
		this.editor = editor;
		this.link = this.editor.addToolbarElement({className: 'strike'});
		this.link.title = "Strikethrough";
		as.e.click(this.link,this.setStrike,this);
		this.editor.addSelectionListener("text-decoration",this.onSelect,this);
	},
	setStrike: function(e) {
		e.preventDefault();
		if (!this.editor.savedRange) return;
		if (window.getSelection && this.editor.savedRange.collapsed) return;
		if (document.selection && (this.editor.savedRange.htmlText == "" || this.editor.savedRange.htmlText == undefined)) return;
		this.editor.doc.execCommand("StrikeThrough",false,null);
		this.editor.saveSelection();
		this.editor.focus();
	},
	onSelect: function(value) {
		if (value == "line-through") {
			this.link.className += " strike-active";
		}
		else {
			this.link.className = this.link.className.replace(/\bstrike-active\b/gi,"");
		}
	}
}
/*****************************************\\ BOLD ITALIC STRIKE \\***/
/***************************************** LISTS ***/
function EditorToolbarOrderedList() {}
EditorToolbarOrderedList.prototype = {
	init: function(editor) {
		this.editor = editor;
		this.link = this.editor.addToolbarElement({className: 'ol'});
		this.link.title = "Нумерованный список";
		as.e.click(this.link,this.setOL,this);
		this.editor.addSelectionListener("ol",this.onSelect,this);
	},
	setOL: function(e) {
		e.preventDefault();
		if (!this.editor.savedRange) return;
		if (window.getSelection && this.editor.savedRange.collapsed) return;
		if (document.selection && (this.editor.savedRange.htmlText == "" || this.editor.savedRange.htmlText == undefined)) return;
		this.editor.doc.execCommand("InsertOrderedList",false,null);
		this.editor.appendContent("<br />");
		this.editor.saveSelection();
		this.editor.focus();
	},
	onSelect: function(value,node) {
		if (node.tagName == "ol" || as.parent(node,"ol")) {
			this.link.className += " ol-active";
		}
		else {
			this.link.className = this.link.className.replace(/\bol-active\b/gi,"");
		}
	}
}
function EditorToolbarUnorderedList() {}
EditorToolbarUnorderedList.prototype = {
	init: function(editor) {
		this.editor = editor;
		this.link = this.editor.addToolbarElement({className: 'ul'});
		this.link.title = "Ненумерованный список";
		as.e.click(this.link,this.setUL,this);
		this.editor.addSelectionListener("ul",this.onSelect,this);
	},
	setUL: function(e) {
		e.preventDefault();
		if (!this.editor.savedRange) return;
		if (window.getSelection && this.editor.savedRange.collapsed) return;
		if (document.selection && (this.editor.savedRange.htmlText == "" || this.editor.savedRange.htmlText == undefined)) return;
		this.editor.doc.execCommand("InsertUnorderedList",false,null);
		this.editor.appendContent("<br />");
		this.editor.saveSelection();
		this.editor.focus();
	},
	onSelect: function(value,node) {
		if (node.tagName == "ul" || as.parent(node,"ul")) {
			this.link.className += " ul-active";
		}
		else {
			this.link.className = this.link.className.replace(/\ul-active\b/gi,"");
		}
	}
}
/*****************************************\\ LISTS \\***/
/***************************************** JUSTIFY ***/
function EditorToolbarAlignLeft() {}
EditorToolbarAlignLeft.prototype = {
	init: function(editor) {
		this.editor = editor;
		this.link = this.editor.addToolbarElement({className: 'alignLeft'});
		this.link.title = "По левому краю";
		as.e.click(this.link,this.setAL,this);
	},
	setAL: function(e) {
		e.preventDefault();
		this.editor.doc.execCommand("JustifyLeft",false,null);
		this.editor.saveSelection();
		this.editor.focus();
	}
}
function EditorToolbarAlignRight() {}
EditorToolbarAlignRight.prototype = {
	init: function(editor) {
		this.editor = editor;
		this.link = this.editor.addToolbarElement({className: 'alignRight'});
		this.link.title = "По правому краю";
		as.e.click(this.link,this.setAR,this);
	},
	setAR: function(e) {
		e.preventDefault();
		this.editor.doc.execCommand("JustifyRight",false,null);
		this.editor.saveSelection();
		this.editor.focus();
	}
}
function EditorToolbarAlignCenter() {}
EditorToolbarAlignCenter.prototype = {
	init: function(editor) {
		this.editor = editor;
		this.link = this.editor.addToolbarElement({className: 'alignCenter'});
		this.link.title = "По центру";
		as.e.click(this.link,this.setAC,this);
	},
	setAC: function(e) {
		e.preventDefault();
		this.editor.doc.execCommand("JustifyCenter",false,null);
		this.editor.saveSelection();
		this.editor.focus();
	}
}
/*****************************************\\ JUSTIFY \\***/
/***************************************** CUT ***/
function EditorToolbarCut() {}
EditorToolbarCut.prototype = {
	cutDefaultContent: "<span class='cut'><ins>Удалить cut</ins></span>",
	cutDefaultInnerContent: "<ins>Удалить cut</ins>",
	init: function(editor) {
		this.editor = editor;
		this.link = this.editor.addToolbarElement({className: 'cut'});
		this.link.title = "Cut";
		as.e.click(this.link,this.tryInsertCut,this);
		as.e.click(this.editor.docBody,this.tryRemoveCut,this);
		this.editor.addSelectionListener("cut",this.tryOnCutChange,this);
	},
	tryInsertCut: function(e) {
		e.preventDefault();
		if (!this.editor.savedRange) return;
		var cuts = as.w("span.cut",this.editor.doc);
		cuts.each(function() {
			as.remove(cuts.set[0]);
		});
		this.editor.appendContent(this.cutDefaultContent);
		this.editor.withCut = as.$$("span.cut",this.editor.doc);
		this.editor.saveSelection();
		this.editor.focus();
	},
	tryRemoveCut: function(e) {
		var cut = as.parent(e.target,"span.cut");
		if (cut) {
			this.removeCut();
		}
	},
	removeCut: function() {
		as.remove(this.editor.withCut);
		this.editor.withCut = null;
	},
	tryOnCutChange: function() {
		setTimeout(as.bind(this.onCutChange,this),0);
	},
	onCutChange: function() {
		if (!this.editor.withCut) return;
		var _self_ = this;
		as.w("span.cut",this.editor.doc).each(function() {
			if (this != _self_.editor.withCut) {
				as.remove(this);
			}
		})
		if (this.editor.withCut.innerHTML != this.cutDefaultInnerContent) {
			this.editor.withCut.innerHTML = this.cutDefaultInnerContent;
		}
	}
}
/*****************************************\\ CUT \\***/
/***************************************** QUOTE ***/
function EditorToolbarQuote() {}
EditorToolbarQuote.prototype = {
	init: function(editor) {
		this.editor = editor;
		this.link = this.editor.addToolbarElement({className: 'quote'});
		this.link.title = "Цитата";
		as.e.click(this.link,this.wrapByQuote,this);
	},
	wrapByQuote: function(e) {
		e.preventDefault();
		if (!this.editor.savedRange) return;
		if (window.getSelection && this.editor.savedRange.collapsed) return;
		if (document.selection && (this.editor.savedRange.htmlText == "" || this.editor.savedRange.htmlText == undefined)) return;
		this.editor.wrapBy("<span class='aseditor-font-quote'></span>");
		this.editor.saveSelection();
		this.editor.focus();
	}
}
/*****************************************\\ QUOTE \\***/
/***************************************** LINK ***/
function EditorToolbarLink() {}
EditorToolbarLink.prototype = {
	init: function(editor) {
		this.editor = editor;
		this.link = this.editor.addToolbarElement({className: 'link'});
		this.link.title = "Ссылка";
		as.e.click(this.link,this.tryShowPopup,this);
	},
	tryShowPopup: function(e) {
		e.preventDefault();
		if (!this.editor.savedRange) return;
		if (window.getSelection && this.editor.savedRange.collapsed) return;
		if (document.selection && (this.editor.savedRange.htmlText == "" || this.editor.savedRange.htmlText == undefined)) return;
		this.popup ? this.showPopup() : this.createPopup();
	},
	showPopup: function() {
		this.popup.show();
		this.onKeyup();
	},
	hidePopup: function() {
		this.popup.hide();
		this.setDefaults();
	},
	createPopup: function() {
		var content = 
			"<div class='make-link-content'>" +
				"<h3>Сделать ссылкой</h3>" + 
				"<div class='work-place'>" + 
					"<h4>Куда будем ссылаться</h4>" +
					"<input type='text' class='href' value='http://' />" +
					"<h4>Описание</h4>" +
					"<input type='text' class='desc' />" +
					"<input type='button' value='Отмена' class='cancel' />"
				"</div>" +
			"</div>";
		this.popup = new ASPopup().init({popupType: 'make-link-popup',relativeTo: this.link, closeType: 'ByAwayClick', defaultContent: content});
		this.showAppendButton();
		this.hideAppendButton();
		this.addEvents();
		this.onKeyup();
	},
	addEvents: function() {
		this.hrefInput = as.$$('input.href',this.popup.popupContent);
		this.descInput = as.$$('input.desc',this.popup.popupContent);
		as.e.keyup(this.hrefInput,this.onKeyup,this);
		as.e.mouseup(this.hrefInput,function() {
			if (this.hrefInput.value == "") {
				setTimeout(as.bind(arguments.callee,this),20);
				return;
			}
			this.onKeyup();
		},this);
		as.e.click(this.popup.popupContent,this.onAppendButtonClick,this);
		as.e.click(as.$$("input.cancel",this.popup.popupContent),function(e) {
			e.preventDefault();
			this.hidePopup();
		},this);
	},
	onKeyup: function(e) {
		if (this.hrefInput.value.match(/http:\/\//)) {
			this.linkHref = this.hrefInput.value;
			this.showAppendButton();
		}
		else {
			this.selectedImage = null;
			this.hideAppendButton();
		}
	},
	showAppendButton: function() {
		if (!this.appendButton) {
			this.appendButton = as.append("<a href='#' class='button'><span>Сделать ссылку</span></a>",as.$$("div.work-place",this.popup.popupContent));
		}
		this.appendButton.className = this.appendButton.className.replace(/\binactive\b/gi,"");
	},
	hideAppendButton: function() {
		this.appendButton.className += " inactive";
	},
	onAppendButtonClick: function(e) {
		if (as.parent(e.target,"a.button") || as.is(e.target,"a.button")) {
			e.preventDefault();
			if (this.appendButton.className.match(/\binactive\b/)) return;
			var appendingLink = "<a href='" + this.linkHref + "' title='"+this.descInput.value+"'></a>";
			this.editor.wrapBy(appendingLink);
			this.editor.saveSelection();
			this.hidePopup();
			this.editor.focus();
		}
	},
	setDefaults: function() {
		this.hrefInput.value = "http://";
	}
}
/*****************************************\\ LINK \\***/
/***************************************** FONT ***/
function EditorToolbarFont() {}
EditorToolbarFont.prototype = {
	fonts: {header: 'Заголовок',quote: 'Цитата',text: 'Текст'},
	init: function(editor) {
		this.editor = editor;
		this.link = this.editor.addToolbarElement({className: 'font'});
		this.link.title = "Выбор размера кегля";
		as.e.click(this.link,this.tryShowPopup,this);
	},
	tryShowPopup: function(e) {
		e.preventDefault();
		if (!this.editor.savedRange) return;
		if (window.getSelection && this.editor.savedRange.collapsed) return;
		if (document.selection && (this.editor.savedRange.htmlText == "" || this.editor.savedRange.htmlText == undefined)) return;
		this.popup ? this.showPopup() : this.createPopup();
	},
	showPopup: function() {
		this.popup.show();
	},
	hidePopup: function() {
		this.popup.hide();
	},
	createPopup: function() {
		var content = as.create("<ul class='aseditor-font-selector'></ul>");
		for (var i in this.fonts) {
			as.append("<li class='aseditor-font-"+i+"'><a href=''>"+this.fonts[i]+"</a></li>",content);
		}
		this.popup = new ASPopup().init({popupType: 'font-selector-popup',relativeTo: this.link, closeType: 'ByAwayClick', defaultContent: content});
		this.addEvents();
	},
	addEvents: function() {
		var _self_ = this;
		as.w("li",this.popup.popupContent).click(this.wrapBy,this);
	},
	wrapBy: function(e) {
		e.preventDefault();
		var target = as.is(e.target,"li") ? e.target : as.parent(e.target,"li");
		this.editor.wrapBy("<span class='" + target.className + "'></span>","<br />");
		this.editor.saveSelection();
		this.editor.focus();
		this.hidePopup();
	}
}
/*****************************************\\ FONT \\***/
/***************************************** HTML ***/
function EditorToolbarHTML() {}
EditorToolbarHTML.prototype = {
	init: function(editor) {
		this.editor = editor;
		this.wysiwyg = true;
		this.link = this.editor.addToolbarElement({className: 'html'});
		this.link.title = "Исходный код";
		
		this.moveTextarea();
		as.e.click(this.link,this.switchEditor,this);
	},
	moveTextarea: function() {
		as.after(this.editor.textarea,this.editor.editor);
		as.style(this.editor.textarea,{
			width: this.editor.docBody.clientWidth + "px",
			height: (this.editor.defaultSize.height || "250") + "px"
		});
	},
	switchEditor: function(e) {
		e.preventDefault();
		if (this.wysiwyg) {
			this.editor.editor.className += " as-height-hidden";
			this.editor.textarea.style.display = "block";
			this.wysiwyg = false;
			this.link.className += " html-active";
			this.showOverlay();
		}
		else {
			this.editor.editor.className = this.editor.editor.className.replace(/\bas-height-hidden\b/gi,"");
			this.editor.textarea.style.display = "none";
			this.wysiwyg = true;
			this.link.className = this.link.className.replace(/\bhtml-active\b/ig,'');
			this.hideOverlay();
			
			this.editor.docBody.innerHTML = this.editor.textarea.value;
			this.editor.clearFormat();
		}
	},
	showOverlay: function() {
		this.overlay = as.append("<div class='overlay'></div>",this.editor.toolbar);
	},
	hideOverlay: function() {
		as.remove(this.overlay);
	}
}
/*****************************************\\ HTML \\***/
function EditorToolbarWord() {}
EditorToolbarWord.prototype = {
	init: function(editor) {
		this.editor = editor;
		this.link = this.editor.addToolbarElement({className: 'word'});		
		this.link.title = "Вставка текста из стороннего редактора";
		as.e.click(this.link,this.tryShowPopup,this);
	},
	tryShowPopup: function(e) {
		e.preventDefault();
		this.popup ? this.showPopup() : this.createPopup();
	},
	showPopup: function() {
		this.popup.show();
	},
	hidePopup: function(e) {
		e && e.preventDefault();
		this.popup.hide();
	},
	createPopup: function() {
		var content = as.create("<div class='insert-from-word-content'></div>");
		as.append("<h3>Вставка текста из стороннего редактора</h3>",content);
		as.append("<form><textarea></textarea></form>",content);
		as.append("<div class='actions'><a class='button cancel' href='#'>Отмена</a><a class='button inactive insert' href='#'>Вставить</a></div>",content);
		this.popup = new ASPopup().init({popupType: 'insert-from-word', relativeTo: this.link, closeType: "ByAwayClick", defaultContent: content});
		
		this.textarea = as.$$("textarea",content);
		this.textarea.onclick = function() {return {toolbar: []};}		
		this.insert = as.$$("a.insert",content);
		this.cancel = as.$$("a.cancel",content);
		this.view = as.$$("a.view",content);
		
		this.turnEditorOn();
		
		this.addEvents();
	},
	addEvents: function() {
		as.e.click(this.insert,this.formatAndInsert,this);
		as.e.click(this.cancel,this.hidePopup,this);
	},
	turnEditorOn: function() {
		this.wordEditor = new ASEditor().init(this.textarea);
		this.wordEditor.clearFormat = function() {};
		this.wordEditor.addSelectionListener("insert-from-word",this.checkContent,this);
	},
	turnEditorOff: function() {
		this.wordEditor.turnOff();
		as.remove(this.wordEditor.editorContainer);
	},
	checkContent: function() {
		if (this.textarea.value == "" || this.textarea.value == "<br>") {
			this.deactivateButtons();
		}
		else {
			this.activateButtons();
		}
	},
	deactivateButtons: function() {
		this.insert.className += " inactive";
	},
	activateButtons: function() {
		this.insert.className = this.insert.className.replace(/\binactive\b/gi,"");
	},
	cleanHTML: function(html) {
		html = html.replace(/<o:p>\s*<\/o:p>/g, '') ;
		html = html.replace(/<o:p>.*?<\/o:p>/g, '&nbsp;') ;
		html = html.replace( /\s*mso-[^:]+:[^;"]+;?/gi, '' ) ;
		html = html.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3") ;
		html = html.replace( /<\\?font[^>]+>/gi,"" ) ;
		html = html.replace(/<\\?\?xml[^>]*>/gi, '' ) ;
		html = html.replace(/<\/?\w+:[^>]*>/gi, '' ) ;
		html = html.replace(/<\!--.*?-->/g, '' ) ;
		html = html.replace( /<(U|I|STRIKE)>&nbsp;<\/\1>/g, '&nbsp;' ) ;
		html = html.replace( /<H\d>\s*<\/H\d>/gi, '' ) ;
		html = html.replace( /<(\w+)[^>]*\sstyle="[^"]*DISPLAY\s?:\s?none(.*?)<\/\1>/ig, '' ) ;
		html = html.replace( /<(\w[^>]*) language=([^ |>]*)([^>]*)/gi, "<$1$3") ;
		html = html.replace( /<([^\s>]+)(\s[^>]*)?>\s*<\/\1>/g, '' ) ;
		html = html.replace(/style=(")[^"]+(")/gi,"");
		html = html.replace(/style=(')[^"]+(')/gi,"");
		html = html.replace(/class="MsoNormal"/gi,"");
		html = html.replace(/class='MsoNormal'/gi,"");
		return html ; 
	},
	formatAndInsert: function(e) {
		e.preventDefault();
		if (this.insert.className.match(/\binactive\b/)) return;
		this.wordEditor.saveSelection();
		this.textarea.value = this.cleanHTML(this.textarea.value);
		var insertContent = "<div class='as-insert-from'>" + this.textarea.value + "</div>";
		this.editor.appendContent(insertContent);
		this.textarea.value = "";
		
		this.hidePopup();
	}
}/*****************************************\\ YAP \\***/
function base64_encode( data ) {	// Encodes data with MIME base64
	// 
	// +   original by: Tyler Akins (http://rumkin.com)
	// +   improved by: Bayron Guevara

	var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var o1, o2, o3, h1, h2, h3, h4, bits, i=0, enc='';

	do { // pack three octets into four hexets
		o1 = data.charCodeAt(i++);
		o2 = data.charCodeAt(i++);
		o3 = data.charCodeAt(i++);

		bits = o1<<16 | o2<<8 | o3;

		h1 = bits>>18 & 0x3f;
		h2 = bits>>12 & 0x3f;
		h3 = bits>>6 & 0x3f;
		h4 = bits & 0x3f;

		// use hexets to index into b64, and append result to encoded string
		enc += b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
	} while (i < data.length);

	switch( data.length % 3 ){
		case 1:
			enc = enc.slice(0, -2) + '==';
		break;
		case 2:
			enc = enc.slice(0, -1) + '=';
		break;
	}

	return enc;
}


function EditorToolbarYap() {}
EditorToolbarYap.prototype = {
	imgSrc: "/js/aseditor/i/yap-place.gif",
	imgCN: "yap-widget",
	init: function(editor) {
		this.editor = editor;
		this.link = this.editor.addToolbarElement({className: 'yap'});
		this.link.title = "Виджет";
		as.e.click(this.link,this.tryShowPopup,this);
	},
	tryShowPopup: function(e) {
		e.preventDefault();
		this.popup ? this.showPopup() : this.createPopup();
	},
	showPopup: function() {
		this.popup.show();
	},
	hidePopup: function(e) {
		e && e.preventDefault();
		this.popup.hide();
	},
	createPopup: function() {
		var content = as.create("<div class='yap-insert-content'></div>");
		as.append("<h3>Вставка виджета</h3>",content);
		as.append("<h4>Скопируйте сюда полученный код</h4>",content);
		as.append("<form><textarea></textarea></form>",content);
		as.append("<div class='actions'><a class='button cancel' href='#'>Отмена</a><a class='button inactive insert' href='#'>Вставить</a></div>",content);
		this.popup = new ASPopup().init({popupType: 'yap-popup', relativeTo: this.link, closeType: "ByAwayClick", defaultContent: content});
		
		this.textarea = as.$$("textarea",content);
		this.insert = as.$$("a.insert",content);
		this.cancel = as.$$("a.cancel",content);
		
		this.addEvents();
	},
	addEvents: function() {
		as.e.click(this.insert,this.encodeAndInsert,this);
		as.e.click(this.cancel,this.hidePopup,this);
		as.e.keyup(this.textarea,this.checkActive,this);
	},
	deactivateButtons: function() {
		this.insert.className += " inactive";
	},
	activateButtons: function() {
		this.insert.className = this.insert.className.replace(/\binactive\b/gi,"");
	},
	checkActive: function() {
		this[((this.textarea.value == "") ? "de" : "")+"activateButtons"]();
	},
	encodeAndInsert: function(e) {
		e.preventDefault();
		if (this.insert.className.match(/\binactive\b/)) return;
		var b64 = base64_encode(this.textarea.value);
		var img = "<img src='" + this.imgSrc + "' class='" + this.imgCN + "' title='" + b64 + "' />";
		this.editor.appendContent(img);
		this.hidePopup();
	}
}
/*******************************************************************************************\\ EDITOR \\*/
function initEditor() {
	as.w("textarea.aseditor").each(function() {new ASEditor().init(this)});
}

