// #################################################
// Author: Simon Stirley
// Created Date: 6th June 2005
// Company: webtechy.co.uk
//
// Modified By: Ben Weeks
// Modified Date: 5th July 2005
//
// Modified By: Simon Stirley
// Modified Date: 21st July 2005
// Modified Comment: adjustments for new Telerik 
// controls. Button alterations, all new control IDs
//
// Modified By: Ben Weeks
// Modified Date: 12th October 2005
// Modified Comment: Split functionality up into 
// separate functions with function names reflecting 
// what they do. The disabling buttons has also
// need to be redone as way telerik is built is 
// different (namely buttons don't have ID's) so had
// to reference by using CLASS and TITLE. Using this
// functionality, there's probably a similar method-
// ology that could be used to loop through the 
// teleriks so we don't need to know their ID's.
//
// #################################################

var iPopulateTimeID;

var aListOfTeleriks = new Array();
// 1 on Councillor details template
aListOfTeleriks[0] =  "_ctl32_EWebEditProPlaceholder1_AuthoringModeControlsContainer_Editor_ctl32_EWebEditProPlaceholder1_AuthoringModeControlsContainer"; 
// 3 on standard template (Births/Marriage/Death)
aListOfTeleriks[1] = "_ctl38_phRelevantLinks_AuthoringModeControlsContainer_Editor_ctl38_phRelevantLinks_AuthoringModeControlsContainer";
aListOfTeleriks[2] =  "_ctl41_idMainBody_AuthoringModeControlsContainer_Editor_ctl41_idMainBody_AuthoringModeControlsContainer";
aListOfTeleriks[3] =  "_ctl41_idMoreInformation_AuthoringModeControlsContainer_Editor_ctl41_idMoreInformation_AuthoringModeControlsContainer";
// 1 on Listing page (Site/Council/Intro)
aListOfTeleriks[4] =  "_ctl33_RadEditorPlaceHolderControl1_AuthoringModeControlsContainer_Editor_ctl33_RadEditorPlaceHolderControl1_AuthoringModeControlsContainer";
// 2 on news pages
aListOfTeleriks[5] =  "_ctl39_UcNewsDetailLayout1_UcNewsCaption1_phCaption_AuthoringModeControlsContainer_Editor_ctl39_UcNewsDetailLayout1_UcNewsCaption1_phCaption_AuthoringModeControlsContainer";
aListOfTeleriks[6] =  "_ctl39_UcNewsDetailLayout1_UcNewsBody1_EWebEditProPlaceholder1_AuthoringModeControlsContainer_Editor_ctl39_UcNewsDetailLayout1_UcNewsBody1_EWebEditProPlaceholder1_AuthoringModeControlsContainer";
// 1 on search results page edit
aListOfTeleriks[7] =  "_ctl36_RadEditorPlaceHolderControl1_AuthoringModeControlsContainer_Editor_ctl36_RadEditorPlaceHolderControl1_AuthoringModeControlsContainer";
// 1 more on the A-Z template
aListOfTeleriks[8] =  "_ctl33_RadEditorPlaceHolderControl1_AuthoringModeControlsContainer_Editor_ctl33_RadEditorPlaceHolderControl1_AuthoringModeControlsContainer";

// This array should tell us how many different types of Telerik ID's there are on the site.
//alert(aListOfTeleriks.length);

var aListOfButtonTitles = new Array();
aListOfButtonTitles[0] = "Flash Manager";
aListOfButtonTitles[1] = "Media Manager";
aListOfButtonTitles[2] = "Horizontal Ruler";
aListOfButtonTitles[3] = "SuperScript";
aListOfButtonTitles[4] = "Subscript";
aListOfButtonTitles[5] = "Insert Code Snippet";
aListOfButtonTitles[6] = "Font Name";
aListOfButtonTitles[7] = "Size";
aListOfButtonTitles[8] = "Foreground Color";
aListOfButtonTitles[9] = "Background Color";
aListOfButtonTitles[10] = "Apply CSS Class";
aListOfButtonTitles[11] = "Custom Links";
aListOfButtonTitles[12] = "Paste from Word";
aListOfButtonTitles[13] = "Paste As Html";

//aListOfButtonTitles[0] = "Image Manager (CTRL+G)";

function WaitForPageToLoad()
{
	try
	{
		if (window.status = "Ready")
		{
//			var aaa = GetElementsByTitleAndClass("RadETool",aListOfButtonTitles[6]);
//			debugger;

			clearInterval(iPopulateTimeID);
			// OK, page has now loaded, we can call our functions.
			//alert("webtechy: Alter telerik");
			AlterSaveButton();
			SetTeleriksBackgroundColor()
			AlterOnPasteEvent();
			DisableButtons();

		}	
	}
	catch(er)
	{
	  alert(er.message);
	}
}

function AlterSaveButton()
{
	//alert("AlterSaveButton");
	try
	{

		if (document.getElementById("AuthoringReeditSaveAnchor"))
		{
			//alert("Re-editSaveAnchor found");
			// Then the Save button exists in the console menu.
			oButton = document.getElementById("AuthoringReeditSaveAnchor")
			newFunction = oButton.onclick;
			// Nifty little call below to add a function to the onClick event of the button.
			oButton.onclick = new Function("checkFrameBorderSyntax();" + newFunction.toString().replace(/\n/g,'').replace(/function anonymous\(\)\{/,'').replace(/\}$/,''));	
		}
		if (document.getElementById("AuthoringReeditSaveAndExitAnchor"))
		{
			// Then the Save button exists in the console menu.
			oButton = document.getElementById("AuthoringReeditSaveAndExitAnchor")
			newFunction = oButton.onclick;
			// Nifty little call below to add a function to the onClick event of the button.
			oButton.onclick = new Function("checkFrameBorderSyntax();" + newFunction.toString().replace(/\n/g,'').replace(/function anonymous\(\)\{/,'').replace(/\}$/,''));	
		}

	}
	catch (e)
	{
		alert("An error occured whilst completing the editor load process. Please close your browser and try again.");
	}
}

function SetTeleriksBackgroundColor()
{
	// Loop through the Telerik controls as multiple ones can exist.
	for (j=0; j < aListOfTeleriks.length; j++)
	{	
		// Ideally, I think a new solution for multiple 
		// Teleriks on one page needs to be found.
		try
		{
			document.getElementById("RadEContentHolder" + aListOfTeleriks[j]).style.backgroundColor = "red"; //"#FFFFFF";
		}
		catch(e)
		{
			// Oh well, we couldn't set the background color.
		}
	}
}

function AlterOnPasteEvent()
{
	// Loop through the Telerik controls as multiple ones can exist.
	for (j=0; j < aListOfTeleriks.length; j++)
	{
		try
		{
			//alert("Altering the onPaste event for the Telerik");
			//alert("RadEContentTextArea" + aListOfTeleriks[j]);
			document.getElementById("RadEContentHolder" + aListOfTeleriks[j]).onpaste = removeTags;
		}
		catch(e)
		{			
			//alert("onPaste set fail: " + e.message);
			// Oh well, we couldn't set the onPaste event.
		}
	} // End loop through Teleriks.
}

function DisableButtons()
{
	for (var k = 0; k < aListOfButtonTitles.length; k++)
	{
		//alert("Disabling " + aListOfButtonTitles[k]);

		oButtons = GetElementsByTitleAndClass("RadETool",aListOfButtonTitles[k])
		//alert(oButtons.length + " possibles");
		for (var l = 0; l < oButtons.length; l++)
		{
			//alert(oButtons[l].outerHTML);
			if (oButtons[l])
			{
				// If the disabling of drop-downs break stick in this debugger line and then check what parentElement level the onClick is at
				//debugger;					
				// Then the button exists in the console menu.
				//alert("test : found button - " + oButton.src);
				// blank the onClick event of the button.

				oButtons[l].onclick = "";
				oButtons[l].onmousedown = "";
				oButtons[l].onmouseup = "";
				oButtons[l].unselectable = "on";

				// apply opacity to 'grey' the button out
				oButtons[l].style.filter = "alpha(opacity:20)";
				
				// IF THE ITEM HAS A DROP DOWN LIST IT'S CURRENTLY NOT BEING DISABLED.
				// If this is a drop-down list we have to look right back to check for the handler
				// UPDATE 18-10-05. Latest version of Telerik we have to look down to child elements, 
				//it's in tables now with IMG tags that take the clicks and TD's that work drop-downs				
				try
				{
					// start from first child
					pButton = oButtons[l].children[0];//.parentElement.parentElement.parentElement;
					// check first-sibling of this, could be the down-arrow
					if (oButtons[l].children[1] != null)
					  {
					 	oButtons[l].children[1].onclick = "";
					 	oButtons[l].children[1].onmouseup = "";
					 	oButtons[l].children[1].onmousedown = "";
					  }
					// for all the first siblings in the tree ..
					while (pButton)
					{
						// clear all active elements
						pButton.onclick = "";
						pButton.onmouseup = "";
						pButton.onmousedown = "";
						// do the next sibling of the child too
						if (pButton.children[1] != null)
						  {
						 	pButton.children[1].onclick = "";
						 	pButton.children[1].onmouseup = "";
						 	pButton.children[1].onmousedown = "";
						  }
						// and take a step down ..
						pButton = pButton.children[0];
					}
				}
				catch (e)
				{

				}
				
			}
		}
	}
}

function checkFrameBorderSyntax()
{
// TEST:
	//var imagemgrframe = document.getElementById("RadWindowContentFrame0");
	//alert(imagemgrframe.innerHTML);
	//debugger;

	//alert("checkFrameBorderSyntax");
	try
	{
  	  // Go through all possible Teleriks at save time and try to remove faulty code ..
	  for (j=0; j < aListOfTeleriks.length; j++)
	  {
		if (document.getElementById("RadEContentHolder" + aListOfTeleriks[j]))
		{
		  //alert(document.getElementById("RadEContentHolder" + aListOfTeleriks[j]).innerHTML);
		  // search for 'borderColor=' which is being put into the table tag wrongly and screwing XHTML compatibility
		  var strContent = document.getElementById("RadEContentHolder" + aListOfTeleriks[j]).innerHTML;
		  //alert(strContent);
		  var iIndex = strContent.indexOf('bordercolor');
		  if (iIndex <= 0)
		  {
		    iIndex = strContent.indexOf('borderColor');
		  }



		  while (iIndex > 0)
		  {
			//alert("Found bad borderColor tag - fixing ..");
			var strPrefix = strContent.substr(0, iIndex);
			//alert(strPrefix);

			var iStart = iIndex + 13;
			var strBorderTag = " style=\"border-color:" ;
			strBorderTag += strContent.substr(iStart, 7);
			strBorderTag += "\"";
			//alert(strBorderTag);

			var strSuffix = strContent.substr(iIndex + 21, strContent.length - (iIndex + 21));
			//alert(strSuffix);

			strContent = strPrefix + strBorderTag + strSuffix;
			//alert(strContent);
			document.getElementById("RadEContentHolder" + aListOfTeleriks[j]).innerHTML = strContent;

			var iTempIndex = iIndex;
			iIndex = strContent.indexOf('bordercolor', iTempIndex);
			if (iIndex <= 0)
			{
			  iIndex = strContent.indexOf('borderColor', iTempIndex);
			}
		  }
		}
	  }
	}
	catch (e)
	{
	  alert("Error: " + e.message);
	}

}

function removeTags()
{
	var sPasteWarning = "You are trying to paste content, all HTML formating\nwill be removed to reduce the likelihood of badly\nformed HTML code being generated. All styling should\nbe applied using the Telerik RAD Editor.\n\nPress OK to continue or Cancel to abort.";
	//alert("remove tags");
	if (confirm(sPasteWarning))
	{
		//alert(sPasteWarning);
		try
		{
			var sTempText;
			sTempText = window.clipboardData.getData("Text")
			window.clipboardData.setData("Text", sTempText);
		}
		catch (e)
		{
			// HTML tags could not be removed.
		}
	}

}

var sSwitchtoLiveID = "SwitchToPresentationPublishedAnchor"; // This may change with subsequent releases.

function AlterButtonStates()
{ 
	//alert("Alterbuttonstates");
	try
	{
		// Waiting for Page to load ...
		if (document.getElementById("editConsole"))
		{
			iPopulateTimeID = setInterval("WaitForPageToLoad()", 1000);
		}
	}
	catch (e)
	{
		alert("An error occured whilst checking the editor load process. Please close your browser and try again.");
	}
}

function GetElementsByTitleAndClass(ClassName, Title)
{

	var AllObjects = new Array();
	var ReturnObject = new Array();
	var tempObjects = new Array();
	var j = 0;

	if (document.getElementsByTagName) 
	  {
		

	  try
	  {
		AllObjects = document.getElementsByTagName("TABLE");
		//alert(AllObjects.length);
		for(i = 0 ; i < AllObjects.length; i++)
		{
			if (AllObjects[i].className.indexOf("RadEDropDown") != -1 && AllObjects[i].title.indexOf(Title) == 0 && AllObjects[i].title.length == Title.length)
			{
			
				ReturnObject[j] = AllObjects[i];
				j++;
			}
			if (AllObjects[i].className.indexOf(ClassName) != -1 && AllObjects[i].title.indexOf(Title) == 0 && AllObjects[i].title.length == Title.length)
			{
			
				ReturnObject[j] = AllObjects[i];
				j++;
			}
		}

		AllObjects = document.getElementsByTagName("IMG");
		//alert(AllObjects.length);
		for(i = 0 ; i < AllObjects.length; i++)
		{
			if (AllObjects[i].className.indexOf(ClassName) != -1 && AllObjects[i].title.indexOf(Title) == 0 && AllObjects[i].title.length == Title.length)
			{
				ReturnObject[j] = AllObjects[i];
				j++;
			}
		}

		}
	  catch (e)
	  {
	    alert("error: " + e.message);
	  }



	  }
	else
	  {
		AllObjects = document.all;

		try
		{
	  	  for(i = 0 ; i < AllObjects.length; i++)
		    {
			if (AllObjects[i].className.indexOf(ClassName) != -1 && AllObjects[i].title.indexOf(Title) == 0 && AllObjects[i].title.length == Title.length)
			{
				ReturnObject[j] = AllObjects[i];
				j++;
			}
			if (AllObjects[i].className.indexOf("RadEDropDown") != -1 && AllObjects[i].title.indexOf(Title) == 0 && AllObjects[i].title.length == Title.length)
			{
		
				ReturnObject[j] = AllObjects[i];
				j++;
			}

		    }
		}
		catch (e)
		{
		  alert("error: " + e.message);
		}
	  }

	return ReturnObject;
}


