var EditorReady = false;
var userAgent = navigator.userAgent;
var Opera = (userAgent.indexOf('Opera') != -1);
var MSIE = (userAgent.indexOf('MSIE') != -1);
function EditorStatus(status){
	if(status == 'ready')
		EditorReady = true;
	
	if(status == 'lock')
		EditorReady = false;	
	
}

function setWidth(width){
get_selection_bounds(document.getElementById('wysiwyg_iframe').contentWindow).start.width = width;
}
function setHeight(height){
get_selection_bounds(document.getElementById('wysiwyg_iframe').contentWindow).start.height = height;
}

function hideOperationParams(){
	document.getElementById('operation_params').innerHTML = '';
}


function closest_parent_by_tag_name(node, tag_name){
   tag_name = tag_name.toLowerCase()
   var p = node
   do{
      if(tag_name == '' || p.nodeName.toLowerCase() == tag_name) return p
   }while(p = p.parentNode)

   return node
}

function get_selected_tags(editor_window, tag_name){
   if(tag_name){
      tag_name = tag_name.toLowerCase();
   }else{
      tag_name = '';
   }
   var bounds = get_selection_bounds(editor_window);
   if(!bounds) return null;

   bounds['start'] = closest_parent_by_tag_name(bounds['start'], tag_name);
   bounds['end'] = closest_parent_by_tag_name(bounds['end'], tag_name);
   return find_tags_in_subtree(bounds, tag_name)
}


function wysiwyg_init(textarea_id, iframe_id){
   var textarea = document.getElementById(textarea_id);
   var iframe = document.getElementById(iframe_id);
   if(iframe && textarea && iframe.offsetWidth){
      iframe.contentWindow.document.designMode = 'On';
      try{iframe.contentWindow.document.execCommand("useCSS", false, true);
      }catch(e){}
      wysiwyg_textarea2iframe(textarea_id, iframe_id);
   }
}

function wysiwyg_switch_mode(textarea_id, iframe_id){
   var textarea = document.getElementById(textarea_id)
   var iframe = document.getElementById(iframe_id)
   if(iframe && textarea){
      if(textarea.offsetWidth){
         iframe.style.display = '';
         textarea.style.display = 'none';
         wysiwyg_init(textarea_id, iframe_id);
         iframe.focus();
      }else{
         textarea.style.display = '';        
         iframe.style.display = 'none';
         textarea.value = iframe.contentWindow.document.body.innerHTML;
         textarea.focus();
      }
   }
   EditorReady = !EditorReady;
}

function wysiwyg_textarea2iframe(textarea_id, iframe_id){
   try{
      document.getElementById(iframe_id).contentWindow.document.body.innerHTML = document.getElementById(textarea_id).value
   }catch(e){
      setTimeout("wysiwyg_textarea2iframe('" + textarea_id + "', '" + iframe_id + "')", 0)
   }
}

function Table_Create(Rows,Cells,Border,Width,Cellspacing,Cellpadding,TAlign,TDsAlign){
	if(!Border) Border = 0;
	if(!Width) Width = 200;
	if(!Cellspacing) Cellspacing = 0;
	if(!Cellpadding) Cellpadding = 0;
	if(!TAlign) TAlign = 'center';
	if(!TDsAlign) TDsAlign = 'center';
	
	var TableOut = "<table align='"+TAlign+"' id='DynamicTbl_1' border='"+Border+"' cellspacing='"+Cellspacing+"' cellpadding='"+Cellpadding+"' width='"+Width+"'>";
	for(var CurrentRow = 0; CurrentRow < Rows; CurrentRow++){
		TableOut += "<tr>";
		for(var CurrentCell = 0; CurrentCell < Cells; CurrentCell++){
			TableOut += "<td align='"+TDsAlign+"'>&nbsp;</td>";
		}
		TableOut += "</tr>";
	}
	TableOut += "</table>";
	
	return TableOut;
}

function getColors(Func){
	var HttpRequest = new JsHttpRequest();
	HttpRequest.onreadystatechange = function() {
        		if (HttpRequest.readyState == 4){
        			 document.getElementById('operation_params').innerHTML = HttpRequest.responseJS.data;
        		}
        		else{
        			document.getElementById('operation_params').innerHTML = "<span class=Gallery1>Загрузка цветовой гаммы...</span>";
				}
    		}
    				
    HttpRequest.open('POST', '/ajax.request.php', true);
    HttpRequest.send({o:'getColors',f:Func});
}

function TableInsert(Table){
	Table+="<br>";
	if(WysiwygInsert(Table)){
		document.getElementById('operation_params').innerHTML = '';
	}
}

function Table_InsertRow(TableId,Row){
	var Table = document.getElementById(TableId);
	var rowNum = parseFloat(Row);
	if(rowNum >= 0 && rowNum <= Table.rows.length){
		Table.insertRow(Row);
		Table_InsertCell(TableId,Row);
	}
}

function Table_InsertCell(TableId,Row){
	var Table = document.getElementById(TableId);
	var rowNum = parseFloat(Row);
	var NumOfMaxRowCells = Table.rows[0].cells.length;
	
	for(var CurrentCell = 0; CurrentCell < NumOfMaxRowCells; CurrentCell++){
		Table.rows[rowNum].insertCell(CurrentCell);
		Table.rows[rowNum].cells[CurrentCell].innerHTML = CurrentCell;
	}
}

function get_selection_bounds(editor_window){
   var range, root, start, end, stext;

   if(editor_window.getSelection){ // Gecko, Opera
      var selection = editor_window.getSelection()
      // Выделение, вообще говоря, может состоять из нескольких областей.
      // Но при написании редактора нас это не должно заботить, берем 0-ую:
      range = selection.getRangeAt(0);
      stext  = range.text;
      start = range.startContainer;
      end = range.endContainer;
      root = range.commonAncestorContainer;

      if(start.nodeName.toLowerCase() == "body") return null;
      // если узлы текстовые, берем их родителей
      if(start.nodeName == "#text") start = start.parentNode;
      if(end.nodeName == "#text") end = end.parentNode;

      if(start == end) root = start;

   }else if(editor_window.document.selection){ // MSIE
      range = editor_window.document.selection.createRange()
      stext  = range.text;
	  if(!range.duplicate) return null;
      
      var r1 = range.duplicate();
      var r2 = range.duplicate();
      r1.collapse(true);
      r2.moveToElementText(r1.parentElement());
      r2.setEndPoint("EndToStart", r1);
      start = r1.parentElement();
      
      r1 = range.duplicate();
      r2 = range.duplicate();
      r2.collapse(false);
      r1.moveToElementText(r2.parentElement());
      r1.setEndPoint("StartToEnd", r2);
      end = r2.parentElement();
      
      root = range.parentElement();
      if(start == end) root = start;
   }else return null;
   
   return {
         root: root,
         start: start,
         end: end,
		 text: stext
      }
}

function WysiwygInsert(htmltext){
	var WysiwygArea = get_selection_bounds(document.getElementById('wysiwyg_iframe').contentWindow).start;

	var NotBody = WysiwygArea.onload;
	//if(EditorReady)
	if(!NotBody){
		WysiwygArea.innerHTML += htmltext;
		return true;
	}else{
		alert('Укажите в редакторе куда вставить элемент!');
		return false;
	}
}

function getCreateTableParams(){ /// Rows,Cells,Border,Width,Cellspacing,Cellpadding,TAlign,TDsAlign
	 var TableParams = "<table><tr><td>Столбцов:</td><td><input style='width:30px;' type=text id='cTableNumCells' value=1></td>";
	 TableParams+= "<td>Строк:</td> <td><input style='width:30px;' type=text id='cTableNumRows' value=1></td>";
	 TableParams+= "<td>Border:</td> <td><input style='width:30px;' type=text id='cTableBorder' value=1></td> ";
	 TableParams+= "<td>Ширина:</td> <td><input style='width:30px;' type=text id='cTableWidth' value=200> </td>";
	 TableParams+= "<td>Cellspacing:</td> <td><input style='width:30px;' type=text id='cTableCellspacing' value=1></td> ";
	 TableParams+= "<td>Cellpadding:</td> <td><input style='width:30px;' type=text id='cTableCellpadding' value=1></td> ";
	 TableParams+= "<td>Align:</td> <td><input style='width:50px;' type=text id='cTableTAlign' value='center'></td> ";
	 TableParams+= "<td>TdsAlign:</td> <td><input style='width:50px;' type=text id='cTableTDsAlign' value='center'></td></tr>";
	 TableParams+= "<tr><td colspan=16><input type=button onclick=TableInsert(Table_Create(cTableNumRows.value,cTableNumCells.value,cTableBorder.value,cTableWidth.value,cTableCellspacing.value,cTableCellpadding.value,cTableTAlign.value,cTableTDsAlign.value)) value='                                          Вставить таблицу                                            '><button onclick=hideOperationParams()>Отменить?</button></td></tr></table>"; 
	 
	 document.getElementById('operation_params').innerHTML = TableParams;
}

function getMakeALinkParams(){ 
	 formatText('CreateLink',prompt("Введите ссылку!",'http://'));
}

function getAddPhotoParams(){
	
	var PhotoParams = "<table>";
	
	PhotoParams+= "<tr><td colspan=2 class=Gallery1>Тип загрузки:</td><td colspan=2 class=Gallery1>Тип обработки:</td></tr>";
	PhotoParams+= "<tr><td><input type=radio name='num_images'></td><td>Загрузить одно фото</td><td><input type=radio name='process_type' id='process_type_vert' value='vert'></td><td>Большими вертикально одну под другой</td></tr>";
	PhotoParams+= "<tr><td><input type=radio name='num_images' checked></td><td>Загрузить серию фото</td><td><input type=radio name='process_type' id='process_type_preview' checked value='preview'></td><td>Разложить плиткой из саморасширяющихся превью 120x100 по 4 в ряд..</td></tr>";
	PhotoParams+= "</table>";
			
	PhotoParams+= "<table><tr><td>";
	PhotoParams+= "<input type=button onclick=uploadFilesForm('blogs','imagesOnLoadComplete') value='Выбрать фото...'><button onclick=hideOperationParams()>Отменить?</button>";
	PhotoParams+= "</td></tr></table>";
	
	document.getElementById('operation_params').innerHTML = PhotoParams;
}

function getAddVideoParams(){
	var VideoParams;
	
	VideoParams = "<table>";
	VideoParams+= "<tr><td colspan=2 class=Gallery1>Если видео с нашего портала:</td></tr>";
	VideoParams+= "<tr><td colspan=2>Введите полную ссылку на страницу с видео файлом http://video.ukrhome.net/watch/...! Если нет, то введите EMBED тег</td></tr>";
	VideoParams+= "<tr><td colspan=2><input type=text id='video_url' style='width:400px'></td></tr>";
	VideoParams+= "</table>";
	
	VideoParams+= "<table><tr><td>";
	VideoParams+= "<input type=button onclick=processVideo() value='Добавить'><button onclick=hideOperationParams()>Отменить?</button>";
	VideoParams+= "</td></tr></table>";
	document.getElementById('operation_params').innerHTML = VideoParams;
}

function getFontParams(){
	var Select;
	
	Select = "<table><tr><td>";
	Select+="<img src=/root/static/images/blogs/elements/fontsize1.jpg onclick=\"formatText('FontSize',1)\">";
	Select+="<img src=/root/static/images/blogs/elements/fontsize2.jpg onclick=\"formatText('FontSize',2)\">";
	Select+="<img src=/root/static/images/blogs/elements/fontsize3.jpg onclick=\"formatText('FontSize',3)\">";
	Select+="<img src=/root/static/images/blogs/elements/fontsize4.jpg onclick=\"formatText('FontSize',4)\">";
	Select+="<img src=/root/static/images/blogs/elements/fontsize5.jpg onclick=\"formatText('FontSize',5)\">";
	Select+="<img src=/root/static/images/blogs/elements/fontsize6.jpg onclick=\"formatText('FontSize',6)\">";
	Select+="<img src=/root/static/images/blogs/elements/fontsize7.jpg onclick=\"formatText('FontSize',7)\">";
	Select+="</td><td class='Size9 blue TableLineLeft TableLineRight TableLineTop TableLineBottom PaddingLeft6'><span class=Gallery1>Правка размера шрифта. <a class=Gallery1 href=javascript:void(0) onclick=hideOperationParams()>Отменить?</a></span><br>Выберите участок текста в редакторе и примините к нему необходимый размер шрифта.</td></tr></table>";
	
	document.getElementById('operation_params').innerHTML =	Select;
}

function addQuestion(cTableId){
	var oRows = document.getElementById(cTableId).getElementsByTagName('tr');
	var iRowCount = oRows.length;

	
	var x=document.getElementById(cTableId).insertRow(iRowCount);
	var y=x.insertCell(0);
	var z=x.insertCell(1);
	var m=x.insertCell(2);
	y.innerHTML='';
	z.innerHTML="Вариант ответа: <br><input type=text style='width:500px' name='vote_ansver["+cTableId+"][]' value=''><input type='button' value='  -  ' onclick=\"deleteQuestion(this,'"+cTableId+"')\"><input type='button' value='  +  ' onclick=\"addQuestion('"+cTableId+"')\">";
	//m.innerHTML="<input type='button' value='  -  ' onclick=\"deleteQuestion(this,'"+cTableId+"')\">";
}
			
function deleteQuestion(r,cTableId){
	var oRows = document.getElementById(cTableId).getElementsByTagName('tr');
	var iRowCount = oRows.length;
	if(iRowCount == 3){
		alert("В опросе должно быть как минимум 2 возможных ответа! Вы не оставляете вариантов))");
		return;
	}
	var i=r.parentNode.parentNode.rowIndex;
	document.getElementById(cTableId).deleteRow(i);
}

function deleteFullVote(cTableId){
	if(confirm("Вы точно хотите удалить этот опрос?"))
		document.getElementById(cTableId).outerHTML = "";
}

function deleteVote(VoteId,type){
	if(!confirm("Вы точно хотите удалить этот опрос? Он будет удален безвозвратно!")) return;
	if(!type) var type = 'not_active';

	var HttpRequest = new JsHttpRequest();
	HttpRequest.onreadystatechange = function() {
        		if (HttpRequest.readyState == 4){
        			if(type == 'active'){
						document.getElementById("activeVote_"+VoteId).outerHTML = "";
					}else{
						document.getElementById("VotesTable_"+VoteId).outerHTML = "";
					}
        			
        		}
        		else{
				}
    		}
    				
    HttpRequest.open('POST', '/ajax.request.php', true);
    HttpRequest.send({o:'deleteVote',v:VoteId,t:type});
    
		
}

function rmActiveVote(activeVoteArea,activeVoteId){
	document.getElementById(activeVoteArea).outerHTML="<input type='hidden' name='votesIds[]' value='"+activeVoteId+"'>";
}


function formatText(id, selected) {
  
	var WysiwygIframeId = "wysiwyg_iframe";
	var viewTextMode = 0;
    document.getElementById(WysiwygIframeId).contentWindow.focus();
 
	
	// When in Text Mode these execCommands are disabled
	var DeniedformatIDs = new Array("FontSize","FontName","Bold","Italic","Underline","Subscript","Superscript","Strikethrough","Justifyleft","Justifyright","Justifycenter","InsertUnorderedList","InsertOrderedList","Indent","Outdent","ForeColor","BackColor","InsertImage","InsertTable","CreateLink");
  
	// Check if button clicked is in disabled list
	for (var i = 0; i <= DeniedformatIDs.length;) {
		if (DeniedformatIDs[i] == id && !EditorReady) {
			alert ("Перейдите в режим визуального редактирования!");	
	  		return;
		}
	  i++;
	}
	
		switch(id){
			case "FontSize":
				document.getElementById(WysiwygIframeId).contentWindow.document.execCommand("FontSize", false, selected);
			break;
			
			case "FontName":
      			document.getElementById(WysiwygIframeId).contentWindow.document.execCommand("FontName", false, selected);
	 		break;
		
			case "ForeColor":
			case "BackColor":
			     // var currentColor = _dec_to_rgb(document.getElementById(WysiwygIframeId).contentWindow.document.queryCommandValue(id));
				 document.getElementById(WysiwygIframeId).contentWindow.document.execCommand(id, false, selected);
				// document.getElementById('operation_params').innerHTML = '';
			break;
		
			case 'InsertImage':
				// insert_image.html
			break;
			
			case 'InsertTable':
				// create_table
			break;
			
			case 'CreateLink':
				if(!selected){
					document.getElementById(WysiwygIframeId).contentWindow.document.execCommand("Unlink", false, selected);
				}else{
					document.getElementById(WysiwygIframeId).contentWindow.document.execCommand("CreateLink", false, selected);
				}
			break;
			
			case 'ViewSource':
				// viewSource(n);
			break;
			
			case 'ViewText':
				// viewText(n);
			break;
			
			default:
				document.getElementById(WysiwygIframeId).contentWindow.document.execCommand(id, false, null);
			break;	
			
		}
};

function blogCheckValues(){
	if(document.getElementById('blog_title').value.length >= 4)
		return true;
	else{
		alert('Заголовок блога слишком короткий или не введен вовсе! Минимум 4 символа :)');
	}
		
	return false;
}



onload = function(){
   wysiwyg_init('wysiwyg_textarea', 'wysiwyg_iframe');
   wysiwyg_switch_mode('wysiwyg_textarea', 'wysiwyg_iframe');
}


