﻿var RadE_HasRules = false;
if (typeof(RadEditorCommandList) == "undefined")
{
	RadEditorCommandList = new Array();
}


/*
  Standart function to call the webservice in order to get the search results
*/
function getServiceResults(url, soap, xml) { 
    try { 
      if (xml.length > 0) { 
      var xmlHTTP; 
      if(window.XMLHttpRequest){ 
	  //For Firefox, Safari, Opera 
         xmlHttp = new XMLHttpRequest(); 
        } 
      else if(window.ActiveXObject){ 
      //For IE 5 
         xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
        } else if(window.ActiveXObject){  
      //For IE 6+ 
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); 
        } 
      // xmlHttp = new ActiveXObject(\"Microsoft.XMLHTTP\"); 
      xmlHttp.open("POST", url, false); 
      xmlHttp.setRequestHeader("SOAPAction", soap); 
      xmlHttp.setRequestHeader("Content-Type", "text/xml"); 
      xmlHttp.send(xml); 
      //alert(xmlHttp.responseText); 
      return xmlHttp.responseXML.documentElement; 
      //return xmlHttp.responseText; 
      } 
     } 
     catch(e) { 
         alert(e.message); 
     } 
 }
 
 function enc(str) {return encodeURI(str);}

 
 /*
   do the search and display the result
   
   var @searchTerm : the search term the user provided
   var @theTable : the results table
   var @theDiv: the DOM object to add the results to
   var @newWin: the popup window in which the search interface is displayed
   var @editor : the calling editor object (to which we add the selected course)
   
 */
 function search(searchTerm,theTable,theDiv,newWin,editor){  
 
    var URL = "http://www.oranim.ac.il/sites/heb/_layouts/alphonfilter.asmx"; 
    var SoapAction = "http://alphonfilter/locateCourses"; 

    var UpdateXML = '<?xml version=\"1.0\" encoding=\"utf-8\"?>'; 
    UpdateXML += '<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" '; 
    UpdateXML += 'xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" '; 
    UpdateXML += 'xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">'; 
    UpdateXML += '<soap:Body>'; 

    UpdateXML +='<locateCourses  xmlns=\"http://alphonfilter/\">'; 

    UpdateXML += '<searchTerm>'; 
    UpdateXML += enc(searchTerm); 
    UpdateXML += '</searchTerm>'; 

    UpdateXML += '</locateCourses>'; 
    UpdateXML += '</soap:Body>'; 
    UpdateXML += '</soap:Envelope>'; 

	//send the requst to get the courses matching the search term
    var webserv = getServiceResults(URL, SoapAction, UpdateXML); 
    var len=theTable.rows.length;
   


   if (len>0)
    for (var i=0; i<len; i++)
      {theTable.deleteRow(0);}
 

    var courses=webserv.getElementsByTagName('Course'); 

    //"alert(users[0].getAttributeNode('Name').text); 
    //"alert(users[0].getAttributeNode('Name').value); 
	
	theDiv.innerHTML="נמצאו " +courses.length+ " קורסים ";

	//iterate over all the courses,  add thier name, a link to thier site and a link to add them to the editor
    for (var i=0; i<courses.length; i++)
    {
	//alert(i);
      var course=courses[i]; 
      var newRow = theTable.insertRow(-1);

   
     newCell = newRow.insertCell(0);
     newCell.innerHTML = course.getAttributeNode("Name").value;
newCell.style.fontFamily='arial, sans-serif';	
 
     newCell = newRow.insertCell(1);
	 //a trick, to the the course's name and id into the onclick function
     newCell.id=course.getAttributeNode("Id").value+";"+course.getAttributeNode("Name").value;	
newCell.style.fontFamily='arial, sans-serif';
	 
     newCell.innerHTML = "<a  style='cursor:pointer; color=blue;  text-decoration: underline;'>הוספת קורס</a>" ;
	 
	//add the link the the course's site to the editor, and close the search window 
	 var fun=function (e) 
			{ editor.PasteHtml("<a target='_blank' href=\"http://www.oranim.ac.il/sites/heb/Courses/Pages/CourseInfoPage.aspx?CourseId="+escape(e.srcElement.parentNode.id.split(";")[0].replace("'","''"))+"\">"+e.srcElement.parentNode.id.split(";")[1]+"</a>"); newWin.close(); };
            
			
            if (newCell.addEventListener)
                newCell.addEventListener("click" , fun , false);
            else if (newCell.attachEvent)
                newCell.attachEvent("onclick" , fun);
	 
	 

     newCell = newRow.insertCell(2);
     newCell.innerHTML = "<a target='_blank' href='http://www.oranim.ac.il/sites/heb/Courses/Pages/CourseInfoPage.aspx?CourseId="+escape(course.getAttributeNode("Id").value.replace("'","''") )+"'  >צפיה בקורס</a>" ;
     newCell.style.fontFamily='arial, sans-serif'; 
 
    }

  } 


RadEditorCommandList["SearchCourse"] = function(commandName, editor, oTool)
{
            var newWin=window.open('','title','height=400,width=450,scrollbars=1');
			
			if (newWin.document.getElementById("main_table")!=null)
			   {
			       newWin.focus();
				   return false;
			   }
            newWin.document.write('<html ><head><title></title></head>');
            newWin.document.write('<body>');
            newWin.document.write('<div dir=rtl style="font-family: arial, sans-serif;">');

            newWin.document.write('<table id="main_table">');
            
			newWin.document.write('<tr>');
			newWin.document.write('<td>');

			newWin.document.write('<input id="search_term" type=text value="" />');
			newWin.document.write('<input id="search_btn" type=button value="חיפוש" />');
			
			newWin.document.write('</td>');
			newWin.document.write('</tr>');

			newWin.document.write('<tr>');
			newWin.document.write('<td>');
			newWin.document.write('<div id="res_div" style="font-family: arial, sans-serif;"></div>');
			
			newWin.document.write('</td>');
			newWin.document.write('</tr>');

			newWin.document.write('<tr>');
			newWin.document.write('<td>');
				newWin.document.write('<table id="res_table">');
				
				newWin.document.write('</table>');
	
			newWin.document.write('</td>');
			newWin.document.write('</tr>');

			newWin.document.write('</table>');
			
            newWin.document.write('</div>');
            newWin.document.write('</body>');
            newWin.document.write('</html>');
			
			//newWin.focus();
			
            var resDiv=newWin.document.getElementById("res_div");
			var resTable=newWin.document.getElementById("res_table");
			var searchBtn=newWin.document.getElementById("search_btn");
			var searchTerm=newWin.document.getElementById("search_term");
			
            var fun=function (e) 
			{search(searchTerm.value,resTable,resDiv,newWin,editor); };
            
            if (searchBtn.addEventListener)
                searchBtn.addEventListener("click" , fun , false);
            else if (searchBtn.attachEvent)
                searchBtn.attachEvent("onclick" , fun);

			if (window.focus) {newWin.focus()}
			return false;
				//newWin.focus();
			//alert(resDiv);
			//alert(resTable);
}



RadEditorCommandList["MOSSRightToLeft"] = function(commandName, editor, oTool)
{
	Telerk_MOSS_SetDirectionOfSelection(editor,"rtl");
}

RadEditorCommandList["MOSSLeftToRight"] = function(commandName, editor, oTool)
{
	Telerk_MOSS_SetDirectionOfSelection(editor,"ltr");
}

RadEditorCommandList["MOSSHelp"] = function(commandName, editor, oTool)
{
	HelpWindowKey('WCMHTMLEditor');
}

RadEditorCommandList["ToggleSource"] = function(commandName, editor, oTool)
{
	//todo: call the source dialog as the MOSS editor does
	editor.SetMode(2);
}

RadEditorCommandList["MOSSInsertTable"] = function(commandName, editor, oTool)
{
	//todo: change the dialog to use the moss default (after firefox is fixed)
	editor.Fire("TableWizard");
}

RadEditorCommandList["MOSSImageManager"] = function(commandName, editor, oTool)
{
	var docEditor = editor.Document;
	var params = editor.GetDialogParameters("MOSSParams");
	var configObj=new AssetPickerConfig("");
	configObj.ClientID=editor.Id;
	configObj.DefaultAssetLocation="";
	configObj.DefaultAssetImageLocation="";
	configObj.CurrentWebBaseUrl=params["CurrentWebBaseUrl"];
	configObj.ManageHyperlink=false;
	configObj.AllowExternalUrls=params["AllowExternalUrls"];
	var bInserting=false;
	var elemToReplace=null;
	var imageAssetObj=new ImageAsset("");

	elemToReplace=editor.GetSelectedElement();
	if (elemToReplace && elemToReplace.tagName && elemToReplace.tagName.toUpperCase() == "BODY")
	{
		//if there is no selection or selection is the whole content body
		elemToReplace = null;
	}
	var elemImage=FormJSRTE_GetNearestContainingParentElementOfTypes(editor.ContentWindow.frameElement.id, elemToReplace, new Array("IMG"));
	if(!elemImage)
	{
		bInserting=true;
		elemImage=docEditor.createElement("IMG");
		elemImage.border=0;
	}
	configObj.ReturnCallback=function(newAssetUrl, newAssetText, currentConfig, dialogReturnedData)
	{
		if (dialogReturnedData)
		{
			if (elemToReplace !=null)
			{
				var parentEl = elemToReplace.parentNode;
				parentEl.replaceChild(elemImage, elemToReplace);
				return;
			}
			else if (bInserting)
			{
				var tempDiv = docEditor.createElement("DIV");
				tempDiv.appendChild(elemImage);
				editor.PasteHtml(tempDiv.innerHTML);
				tempDiv = null;
			}
		}
	}
	var dialogReturnedData=imageAssetObj.LaunchModalDialogOnElement(configObj, elemImage, true, !bInserting );
}

RadEditorCommandList["MOSSLinkManager"] = function(commandName, editor, oTool)
{
	var docEditor = editor.Document;
	var params = editor.GetDialogParameters("MOSSParams");
	var configObj=new AssetPickerConfig("");
	configObj.ClientID=editor.Id;
	configObj.DefaultAssetLocation="";
	configObj.DefaultAssetImageLocation="";
	configObj.CurrentWebBaseUrl=params["CurrentWebBaseUrl"];
	configObj.AllowExternalUrls=params["AllowExternalUrls"];
	var bInserting=false;
	var elemToReplace=null;
	var linkAsset=new LinkAsset("");
	var innerLinkHTML=null;
	linkAsset.ManageLinkDisplayText=false;
	var elemLink=FormJSRTE_GetNearestContainingParentElementOfTypes(editor.ContentWindow.frameElement.id, editor.GetSelectedElement(), new Array("A"));
	if(!elemLink)
	{
		bInserting=true;
		elemLink=docEditor.createElement("A");
		if (elemLink==null) return;
		var editorSelection = editor.GetSelection();
		if (editorSelection.IsControl())
		{
			elemToReplace=editor.GetSelectedElement();
		}
		else
		{
			innerLinkHTML = editorSelection.GetHtmlText();
		}
	}
	else
	{
		innerLinkHTML=elemLink.innerHTML;
	}
	configObj.ReturnCallback=function(newAssetUrl, newAssetText, currentConfig, dialogReturnedData)
	{
		if (dialogReturnedData)
		{
			var linkText = "";
			if (editor.isIE)
				linkText = elemLink.innerText;
			else
				linkText = elemLink.textContent;
			if(innerLinkHTML && innerLinkHTML != "")
			{
				elemLink.innerHTML=innerLinkHTML;
			}
			else if(linkText == "")
			{
				if(linkAsset.AssetText && linkAsset.AssetText !="")
				{
					linkText=linkAsset.AssetText;
				}
				else
				{
					linkText=linkAsset.AssetUrl;
				}
				elemLink.innerHTML += linkText;
			}
			if (elemToReplace !=null)
			{
				var parentEl = elemToReplace.parentNode;
				parentEl.replaceChild(elemLink, elemToReplace);
				linkAsset.FixupIconsAndEmptyAnchors(elemLink);
				return;
			}
			else if (bInserting)
			{
				var selection=docEditor.selection;
				if (selection !=null)
				{
					var textRange=selection.createRange();
					if (textRange !=null)
					{
						var text=textRange.text;
						if (text && text !="" && !text.match(/^\s+$/))
						{
							textRange.execCommand("Unlink");
							elemLink.innerHTML=textRange.htmlText;
							linkAsset.FixupIconsAndEmptyAnchors(elemLink);
						}
						var tempDiv = docEditor.createElement("DIV");
						tempDiv.appendChild(elemLink);
						textRange.pasteHTML(tempDiv.innerHTML);
					}
				}
				else
				{
					//if we cannot get the selection, use the editor paste function instead
					var tempDiv = docEditor.createElement("DIV");
					tempDiv.appendChild(elemLink);
					editor.PasteHtml(tempDiv.innerHTML);
					tempDiv = null;
				}
			}
			else
			{
				linkAsset.FixupIconsAndEmptyAnchors(elemLink);
			}
		}
	}
	linkAsset.LaunchModalDialogOnElement(configObj, elemLink, true, !bInserting );
}

RadEditorCommandList["MOSSTemplateManager"] = function (commandName, editor, oTool)
{
	if (!RadE_HasRules)
	{
		RTE2_InstantiateStaticSafeHtmlRules();
		RadE_HasRules = true;
	}
	var docEditor = editor.Document;
	var params = editor.GetDialogParameters("MOSSParams");
	var configObj=new AssetPickerConfig("");
	configObj.ClientID=editor.Id;
	configObj.DefaultAssetLocation="";
	configObj.CurrentWebBaseUrl=params["CurrentWebBaseUrl"];
	configObj.AllowExternalUrls=params["AllowExternalUrls"];
	var bInserting=false;
	var elemToReplace=null;
	var fragmentId=null;
	var elemViewToEdit=FormJSRTE_GetNearestContainingParentElementOfTypes(editor.ContentWindow.frameElement.id, editor.GetSelectedElement(), new Array("SPAN"));
	if ((elemViewToEdit !=null) && (elemViewToEdit.id==g_strRTE2ReusableFragmentCommonToken))
	{
		fragmentId=elemViewToEdit.getAttribute("fragmentid");
	}
	var dialogInput=new Object();
	dialogInput.fragmentId=fragmentId;
	var callback=function(dialogOutput)
	{
		if ((dialogOutput !=null) && (dialogOutput.fragmentView !=null))
		{
			var selection=docEditor.selection;
			if (selection !=null)
			{
				if (selection.type=="Control")
				{
					var controlRange=selection.createRange();
					if (controlRange !=null)
					{
						controlRange.execCommand("Delete");
					}
				}
				if (selection.type !="Control")
				{
					var textRange=selection.createRange();
					if (textRange !=null)
					{
						var safeHtmlDocument=RadE_CreateTemporaryDocument();
						safeHtmlDocument.body.innerHTML=dialogOutput.fragmentView;
						var elements=RTE2_GetAllElements(safeHtmlDocument);
						//setting these to hardcoded values since they are not passed in the params[] array yet.
						var instanceVariables = new Object();
						instanceVariables.EditorOpenFromWebPart = false;
						instanceVariables.DisableCustomStyles = false;
						RTE2_ApplyContentFilters(elements, instanceVariables);
						textRange.pasteHTML(dialogOutput.fragmentView);
						RTE2_AlterReusableFragmentHighlights(docEditor.body, "ms-reusableTextView");
					}
				}
			}
			else
			{
				editor.PasteHtml(dialogOutput.fragmentView);
				RTE2_AlterReusableFragmentHighlights(docEditor.body, "ms-reusableTextView");
			}
		}
	};
	var dialogUrl=params["CurrentWebBaseUrl"]+"/_layouts/ReusableTextPicker.aspx";
	commonShowModalDialog(dialogUrl, "dialogHeight:600px; dialogWidth:800px; center:yes; resizable:yes; scroll:no; status:no;", callback, dialogInput);
}

/* support functions */
if (typeof(RadEditor) == "undefined")
{
	RadEditor = function () {};
}

RadEditor.EncodeUrl = function(url)
{
	if (window.encodeURIComponent)
	{
		return encodeURIComponent(url);
	}
	
	if (window.escape)
	{
		return escape(url);	
	}
	
	return url;
}

function GetDialogArguments(editor, commandName)
{
	var args = editor.GetDialogParameters(commandName);
	var argStr = "";
	for (var item in args)
	{
		argStr += "&" + item + "=" + RadEditor.EncodeUrl(args[item]);
	}
	return argStr;
}

function Telerk_MOSS_SetDirectionOfSelection(editor, strDirection)
{
	var rngSelection=editor.GetSelection();
	var strTagNames;
	strTagNames="|H1|H2|H3|H4|H5|H6|P|PRE|TD|DIV|BLOCKQUOTE|DT|DD|TABLE|HR|IMG|BODY|TR|UL|OL|";
	if (rngSelection.GetParentElement())
	{
		var elemSelectionParent=rngSelection.GetParentElement();
		while ((elemSelectionParent !=null) && (strTagNames.indexOf("|"+elemSelectionParent.tagName+"|")==-1))
		{
			elemSelectionParent=elemSelectionParent.parentNode;
		}
		if (elemSelectionParent)
		{
			Telerik_MOSS_SetDirectionOnElement(elemSelectionParent, strDirection);
		}
	}
}

function Telerik_MOSS_SetDirectionOnElement(element, strDirection)
{
	if ("ltr"==strDirection)
	{
		element.dir="ltr";
		element.align="left";
	}
	else if ("rtl"==strDirection)
	{
		element.dir="rtl";
		element.align="right";
	}
}

function RadE_CreateTemporaryDocument()
{
	// creating a temporary document for storing template content
	var iframe = document.createElement('iframe');
	document.body.appendChild(iframe);
	iframe.src = "javascript:'<html></html>'";
	iframe.frameBorder = '0';
	iframe.style.width = "0px";
	iframe.style.height = "0px";
	var doc = iframe.contentWindow.document;
	doc.open();
	doc.writeln('<head><style></style></head><body></body>');
	doc.close();
	if (!doc.body)
	{
		var oBody = doc.createElement("body");
		doc.appendChild(oBody);
	}
	if (doc.getElementsByTagName("head").length < 1)
	{
		var oHead = doc.createElement("head");
		oHead.style.visibility = "hidden";
		doc.body.parentNode.insertBefore(oHead, doc.body);
	}
	return doc;
}


function FormJSRTE_GetNearestContainingParentElementOfTypes(strBaseElementID, elem, aTagNames)
{
//this code belongs in form.js, however it is copied here as well since in some pages form.js is not loaded by default.
	var aTagNames_length=aTagNames.length;
	if (elem==null) return null;
	for (var i=0; i<aTagNames_length; i++)
	{
		if (elem.tagName==aTagNames[i])
		{
			return elem;
		}
	}
	var elemParent=elem.parentNode;
	while (elemParent !=null)
	{
		if (elemParent.id==strBaseElementID)
		{
			return null;
		}
		for (var i=0; i<aTagNames_length; i++)
		{
			if (elemParent.tagName==aTagNames[i])
			{
				return elemParent;
			}
		}
		elemParent=elemParent.parentNode;
	}
	return null;
}
