/*global jQuery */
(function($)  {
   $.fn.extend({
      runet_editor : function (options)  {
         
         $(this).each(function()  {
        	 var $$ = $(this);
        	 var id = ($.browser.mozilla) ? $$.attr("id") : 'reb_' + $$.attr("id");

        	 var buttons = '<div class="reb_bcontainer"><div class="reb_b" id="b_'+id+'" style="background:transparent url(/img/icons/reb_bold_ru.gif) no-repeat" /><div class="reb_b" id="i_'+id+'" style="background:transparent url(/img/icons/reb_italic_ru.gif) no-repeat" /><div class="reb_b" id="u_'+id+'" style="background:transparent url(/img/icons/reb_underline_ru.gif) no-repeat" /><div class="reb_b" id="em_'+id+'" style="background:transparent url(/img/icons/reb_emotions.gif) no-repeat" /><div class="reb_b" id="img_'+id+'" style="background:transparent url(/img/icons/image.gif) no-repeat" /><div class="reb_b" id="video_'+id+'" style="background:transparent url(/img/icons/video.gif) 50% 70% no-repeat" /></div><div style="clear:left;" />';
        	 var smileys = '<div id="emdiv_'+id+'" class="reb_bcontainer" style="display:none;"><div id="def_sm_'+id+'" style="display:none;"><div class="reb_b" id="em_smiley-cool_'+id+'" style="background:transparent url(/img/icons/smiley-cool.gif) no-repeat" /><div class="reb_b" id="em_smiley-cry_'+id+'" style="background:transparent url(/img/icons/smiley-cry.gif) no-repeat" /><div class="reb_b" id="em_smiley-embarassed_'+id+'" style="background:transparent url(/img/icons/smiley-embarassed.gif) no-repeat" /><div class="reb_b" id="em_smiley-foot-in-mouth_'+id+'" style="background:transparent url(/img/icons/smiley-foot-in-mouth.gif) no-repeat" /><div class="reb_b" id="em_smiley-frown_'+id+'" style="background:transparent url(/img/icons/smiley-frown.gif) no-repeat" /><div class="reb_b" id="em_smiley-innocent_'+id+'" style="background:transparent url(/img/icons/smiley-innocent.gif) no-repeat" /><div class="reb_b" id="em_smiley-kiss_'+id+'" style="background:transparent url(/img/icons/smiley-kiss.gif) no-repeat" /><div class="reb_b" id="em_smiley-laughing_'+id+'" style="background:transparent url(/img/icons/smiley-laughing.gif) no-repeat" /><div class="reb_b" id="em_smiley-money-mouth_'+id+'" style="background:transparent url(/img/icons/smiley-money-mouth.gif) no-repeat" /><div class="reb_b" id="em_smiley-sealed_'+id+'" style="background:transparent url(/img/icons/smiley-sealed.gif) no-repeat" /><div class="reb_b" id="em_smiley-smile_'+id+'" style="background:transparent url(/img/icons/smiley-smile.gif) no-repeat" /><div class="reb_b" id="em_smiley-surprised_'+id+'" style="background:transparent url(/img/icons/smiley-surprised.gif) no-repeat" /><div class="reb_b" id="em_smiley-tongue-out_'+id+'" style="background:transparent url(/img/icons/smiley-tongue-out.gif) no-repeat" /><div class="reb_b" id="em_smiley-undecided_'+id+'" style="background:transparent url(/img/icons/smiley-undecided.gif) no-repeat" /><div class="reb_b" id="em_smiley-wink_'+id+'" style="background:transparent url(/img/icons/smiley-wink.gif) no-repeat" /><div class="reb_b" id="em_smiley-yell_'+id+'" style="background:transparent url(/img/icons/smiley-yell.gif) no-repeat" /></div></div><div style="clear:left;" />';
        	 var imgs = '<div id="imgdiv_'+id+'" class="reb_bcontainer" style="display:none;"><select id="albums_'+id+'"><option>Загрузка альбомов</option></select> <select id="picinput_'+id+'" style="display: none;"><option id="picinput_m_'+id+'">маленькая</option><option id="picinput_l_'+id+'">большая</option></select> <input class="ppi_off" id="picinput_b_'+id+'" style="display: none;" type="image" src="/img/big.png"> <input class="ppi_on" id="picinput_s_'+id+'" style="display: none;" type="image" src="/img/small.png"><div class="pic_block" id="pics_block_'+id+'" style="display:none; background-color: white;"><span style="color: gray;">загрузка изображений...</span></div><div id="picdiv_'+id+'" style="display: none;"><button style="display: none;" id="photoins_'+id+'" class="bluebut">Вставить</button><button style="display: inline;" id="photoins2_'+id+'" class="bluebut">Закрыть</button><br><br></div><div style="clear:left;" />';
        	 
        	 if($.browser.mozilla) {
	        	 var panel = this.panel = $(buttons).addClass('panel');
	        	 this.element = $('<div></div>').append(panel).append( $(smileys)).append( $(imgs));
	        	 
	        	 $($$).css("display","block").addClass("runet_editor_block").before(this.element);
        	 } else {
        		 var editor = this.editor = $('<iframe class="runet_editor_block"></iframe>').attr('id',id);
	        	 var panel = this.panel = $(buttons).addClass('panel');
	        	 this.element = $('<div></div>').append(panel).append( $(smileys)).append( $(imgs)).append(editor);
	
	        	 $($$).before(this.element);
        	 }
        	 
        	 $('#em_' + id).click(function() {
        	 	 $('#imgdiv_'+id).slideUp('side');
        		 $.get("/photos/smiles_ajax/"+id, function(data){
					if (data) $('#emdiv_'+id).html(data);
					else $('#def_sm_'+id).show('side');
					$('#emdiv_'+id).slideToggle('side');
				 });
        	 });
        	 $('#img_' + id).click(function() {
	      	 	 $.get("/photos/albums_ajax/", function(data){
						 		$('#albums_'+id).html(data);
						 });
        	 	 $('#emdiv_'+id).slideUp('side');
        		 $('#imgdiv_'+id).slideToggle('side');
        	 });
        	 $('#albums_'+id).change(function() {
        	 	var albumid = $('select[@id=albums_'+id+'] option:selected').val();
        	 	if (albumid > 0) {
	        	 	 $.get("/photos/album_ajax/"+albumid+"/"+id, function(data){
							 		$('#pics_block_'+id).html(data);
							 		$('#pics_block_'+id).slideDown('slow');
							 		//document.getElementById('picinput_'+id).style.display = 'inline';
							 		document.getElementById('picinput_b_'+id).style.display = 'inline';
							 		document.getElementById('picinput_s_'+id).style.display = 'inline';
							 });
        	 	} else {
        	 		 $('#pics_block_'+id).slideUp('slow');
        	 		 //document.getElementById('picinput_'+id).style.display = 'none';
        	 		 document.getElementById('picinput_b_'+id).style.display = 'none';
        	 		 document.getElementById('picinput_s_'+id).style.display = 'none';
        	 	}
        	 });

        	 initIframe(id);
        	 function initIframe(id) {
        		 var iframe = ($.browser.msie) ? frames[id] : document.getElementById(id);
            	 var iWin = ($.browser.msie) ? iframe.window : iframe.contentWindow;
            	 var iDoc = ($.browser.msie) ? iframe.document : iframe.contentDocument;        	 
            	 
            	 if (!iDoc.designMode) alert("Визуальный режим редактирования не поддерживается Вашим браузером");
            	 else iDoc.designMode = ($.browser.msie) ? "On" : "on";
            	 
            	 if(iDoc) {
            		 iDoc.open();
            		 iDoc.write('<html><head xmlns="http://www.w3.org/1999/xhtml"><title>blank_page</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><style>img {border:0;}</style></head><body class="mceContentBody"></body></html>');
    	        	 iDoc.close();
    	        	 
    	        	 iDoc.contentEditable = 'true';
            	 }
            	 
            	 $('#photoins_' + id).click(function() {
            		 iWin.focus();
            		   var picurl = $('#picinput_'+id).val();
            		   var picurl2 = $('#picinput_urlid_'+id).val();
            	     //iWin.document.execCommand('insertImage', false, picurl);
            	     
            	     var isIE = /*@cc_on!@*/false;
									 var SelectionRange = isIE ? iWin.document.selection.createRange() : iWin.getSelection().getRangeAt(0);
										
									 // вставим картинку
									 var html = "<a href=\""+picurl2+"\"><img src='"+picurl+"' /></a>";
										
									 if (isIE) {
									     // тут все просто
									     SelectionRange.pasteHTML(html);
									 } else {
									     // для остальных используем вспомогательный тег
									     SelectionRange.deleteContents();
									     var el = document.createElement("SPAN");
									     iWin.document.getElementsByTagName("BODY")[0].appendChild(el);
									 
									     // Firefox не поймет, если вы сразу замените outerHTML. В версиях ниже 3-ей такое свойство вообще у него отсутствует.
									     el.innerHTML = html;
									     SelectionRange.insertNode(el);
									     el.outerHTML = html;
									 }
            	 });
            	 $('#photoins2_' + id).click(function() {
            		 $('#imgdiv_'+id).slideUp('side');
            	 });
            	 $('#b_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand("bold", null, "");
            	 });
            	 $('#i_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand("italic", null, "");
            	 });
            	 $('#u_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand("underline", null, "");
            	 });
            	 $('#picinput_b_' + id).click(function() {
            	 	 $('#picinput_s_' + id).attr('class', 'ppi_off');
            	 	 $('#picinput_b_' + id).attr('class', 'ppi_on');
            		 document.getElementById('picinput_m_'+id).selected='';
            		 document.getElementById('picinput_l_'+id).selected='selected';
            	 });
            	 $('#picinput_s_' + id).click(function() {
            	 	 $('#picinput_b_' + id).attr('class', 'ppi_off');
            	 	 $('#picinput_s_' + id).attr('class', 'ppi_on');
            	 	 document.getElementById('picinput_l_'+id).selected='';
            		 document.getElementById('picinput_m_'+id).selected='selected';
            	 });
            	 $('#em_smiley-cool_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand('insertImage', false, '/img/icons/smiley-cool.gif');
            	 });
            	 $('#em_smiley-cry_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand('insertImage', false, '/img/icons/smiley-cry.gif');
            	 });
            	 $('#em_smiley-embarassed_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand('insertImage', false, '/img/icons/smiley-embarassed.gif');
            	 });
            	 $('#em_smiley-foot-in-mouth_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand('insertImage', false, '/img/icons/smiley-foot-in-mouth.gif');
            	 });
            	 $('#em_smiley-frown_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand('insertImage', false, '/img/icons/smiley-frown.gif');
            	 });
            	 $('#em_smiley-innocent_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand('insertImage', false, '/img/icons/smiley-innocent.gif');
            	 });
            	 $('#em_smiley-kiss_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand('insertImage', false, '/img/icons/smiley-kiss.gif');
            	 });
            	 $('#em_smiley-laughing_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand('insertImage', false, '/img/icons/smiley-laughing.gif');
            	 });
            	 $('#em_smiley-money-mouth_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand('insertImage', false, '/img/icons/smiley-money-mouth.gif');
            	 });
            	 $('#em_smiley-sealed_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand('insertImage', false, '/img/icons/smiley-sealed.gif');
            	 });
            	 $('#em_smiley-smile_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand('insertImage', false, '/img/icons/smiley-smile.gif');
            	 });
            	 $('#em_smiley-surprised_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand('insertImage', false, '/img/icons/smiley-surprised.gif');
            	 });
            	 $('#em_smiley-tongue-out_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand('insertImage', false, '/img/icons/smiley-tongue-out.gif');
            	 });
            	 $('#em_smiley-undecided_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand('insertImage', false, '/img/icons/smiley-undecided.gif');
            	 });
            	 $('#em_smiley-wink_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand('insertImage', false, '/img/icons/smiley-wink.gif');
            	 });
            	 $('#em_smiley-yell_' + id).click(function() {
            		 iWin.focus();
            	     iWin.document.execCommand('insertImage', false, '/img/icons/smiley-yell.gif');
            	 });
            	 
            	 
        	 }
        	 
        	 function setEmot(picurl,picurl2) {
        	     iWin.focus();
            		 //var picurl = $('#picinput_'+id).val();
            		 //var picurl2 = $('#picinput_urlid_'+id).val();
            	     //iWin.document.execCommand('insertImage', false, picurl);
            	     
            	     var isIE = /*@cc_on!@*/false;
									 var SelectionRange = isIE ? iWin.document.selection.createRange() : iWin.getSelection().getRangeAt(0);
										
									 // вставим картинку
									 var html = "<a href=\""+picurl2+"\"><img src='"+picurl+"' /></a>";
										
									 if (isIE) {
									     // тут все просто
									     SelectionRange.pasteHTML(html);
									 } else {
									     // для остальных используем вспомогательный тег
									     SelectionRange.deleteContents();
									     var el = document.createElement("SPAN");
									     iWin.document.getElementsByTagName("BODY")[0].appendChild(el);
									 
									     // Firefox не поймет, если вы сразу замените outerHTML. В версиях ниже 3-ей такое свойство вообще у него отсутствует.
									     el.innerHTML = html;
									     SelectionRange.insertNode(el);
									     el.outerHTML = html;
									 }
        	 }
        	 function setBold() {
        	     iWin.focus();
        	     iWin.document.execCommand("bold", null, "");
        	 }
        	 function setItal() {
        	     iWin.focus();
        	     iWin.document.execCommand("italic", null, "");
        	 }
        	 function setUnder() {
        	     iWin.focus();
        	     iWin.document.execCommand("underline", null, "");
        	 }
         });
         return $(this);
      }
   });

   $.fn.extend({
	   getContent : function (options)  {
			 var $$ = $(this);
		  	 var id = ($.browser.mozilla) ? $$.attr("id") : 'reb_' + $$.attr("id");
	   
			 var iframe = ($.browser.msie) ? frames[id] : document.getElementById(id);
		  	 var iWin = ($.browser.msie) ? iframe.window : iframe.contentWindow;
		  	 var iDoc = ($.browser.msie) ? iframe.document : iframe.contentDocument;        	 
	   
	   		 return $(iDoc).find('body').html();
   		}
   });
   
})(jQuery);
   
/**
 * Converts certain characters in the string to their HTML-entity equivalents.
 *
 * The conversions peformed are:
 * <ul>
 *   <li><code>&amp;</code> (ampersand) becomes <code>&amp;amp;</code></li>
 *   <li><code>&quot;</code> (double quote) becomes <code>&amp;quot;</code></li>
 *   <li><code>&#039;</code> (single quote) becomes <code>&amp;#039;</code></li>
 *   <li><code>&lt;</code> (less than) becomes <code>&amp;lt;</code></li>
 *   <li><code>&gt;</code> (greater than) becomes <code>&amp;gt;</code></li>
 * </ul>
 * @return {String} The HTML-encoded string.
 */
String.prototype.HTMLEncode = function()  {
   return this.replace(/&/g, "&amp;") .
               replace(/</g, "&lt;")  .
               replace(/>/g, "&gt;")  .
               replace(/"/g, "&quot;").
               replace(/'/g, "&#039;");
};

function setEmot(id,picurl,picurl2){
   //var iframe = document.getElementById(iframe_id);
   //var iWin = iframe.contentWindow;
   var iframe = ($.browser.msie) ? frames[id] : document.getElementById(id);
   var iWin = ($.browser.msie) ? iframe.window : iframe.contentWindow;
   var iDoc = ($.browser.msie) ? iframe.document : iframe.contentDocument; 
   
   iWin.focus();
	 //var picurl = $('#picinput_'+id).val();
	 //var picurl2 = $('#picinput_urlid_'+id).val();
	 //iWin.document.execCommand('insertImage', false, picurl);
	 
	 var isIE = /*@cc_on!@*/false;
	 var SelectionRange = isIE ? iWin.document.selection.createRange() : iWin.getSelection().getRangeAt(0);		
	 // вставим картинку
	 var html = "<a href=\""+picurl+"\"><img src='http://runet.ru"+picurl2+"' /></a>";
						
	 if (isIE) {
		 // тут все просто
		 SelectionRange.pasteHTML(html);
	 } else {
		 // для остальных используем вспомогательный тег
		 SelectionRange.deleteContents();
		 var el = document.createElement("SPAN");
		 iWin.document.getElementsByTagName("BODY")[0].appendChild(el);
					 
		 // Firefox не поймет, если вы сразу замените outerHTML. В версиях ниже 3-ей такое свойство вообще у него отсутствует.
		 el.innerHTML = html;
		 SelectionRange.insertNode(el);
		 el.outerHTML = html;
	 }
}