//****************************************************************************************************************
function UpdateWys()
{
	var CurrentState = document.getElementById('wysiwyg_1').style.display;
	if(CurrentState != 'none'){
		document.getElementById('source_1').value = htmlFormat(document.getElementById('edit_1').innerHTML);
		}
}

function editSelection(pi_ControlId)
{

	var lo_Element = getSelectedElement(pi_ControlId);
	var li_Dialog = -1;
	//NOTE: Switch the dialog pop-up based on the container tag.
	switch(lo_Element.tagName.toLowerCase())
	{
		case 'table' : li_Dialog = 0; break;
		case 'img' : li_Dialog = 1; break;
		case 'a' :
			if((lo_Element.getAttribute('id') == 'email') || (lo_Element.getAttribute('id') == 'contact'))
			{
				li_Dialog = 3;
			}
			else
			{
				li_Dialog = 2;
			}
			break;
		default : return;
	}
	doDialog(pi_ControlId,li_Dialog,false,lo_Element);
}
//****************************************************************************************************************


//****************************************************************************************************************
function getSelectedElement(pi_ControlId)
{
	if(document.selection.type == 'Control')
	{
		var lo_ControlSelection = document.selection.createRange();
		return lo_ControlSelection(0);
	}
	else
	{
		var lo_Selection = document.selection.createRange();
		var lo_Element = lo_Selection.parentElement();
		return lo_Element;
	}
}
//****************************************************************************************************************


//****************************************************************************************************************
function getRangeContent(pi_ControlId)
{
	if(document.selection.type == 'Control')
	{
		var lo_ControlSelection = document.selection.createRange();
		return lo_ControlSelection(0).outerHTML;
	}
	else
	{
		return document.selection.createRange().text;
	}
}
//****************************************************************************************************************


//****************************************************************************************************************
function getRange(pi_ControlId)
{
	var lo_Selection = document.selection;
	(lo_Selection.type != 'None' ) && lo_Selection.clear();
	var lo_Range = lo_Selection.createRange();
	lo_Range.parents = [];
	if(lo_Selection.type == 'Control')
	{
		lo_Range.control = true;
		lo_Range.parents.push(lo_Range.item(0));
		lo_Range.parent = lo_Range.item(0).parentElement;
	}
	else
	{
		lo_Range.control = false;
		lo_Range.parent = lo_Range.parentElement();
	}
	while(lo_Range.parent && lo_Range.parent.id != 'edit_' + pi_ControlId)
	{
		lo_Range.parents.push(lo_Range.parent);
		lo_Range.parent = lo_Range.parent.parentElement;
	}
	return lo_Range;
}
//****************************************************************************************************************


//****************************************************************************************************************
function callCommand(pi_ControlId, ps_Arguments)
{
	if(!ps_Arguments) return;
	var la_Arguments = ps_Arguments.split('|');
	if(!la_Arguments[1])
	{
		doCommand(pi_ControlId,la_Arguments[0],null);
	}
	else
	{
		doCommand(pi_ControlId,la_Arguments[0],la_Arguments[1]);
	}
}
//****************************************************************************************************************


//****************************************************************************************************************
function doDialog(pi_ControlId, pi_DialogId, pb_Selection, pa_Arguments)
{
	//NOTE: Check the user has made a selection where required before continuing.
	if(pb_Selection)
	{
		var lo_Selection = getRangeContent(pi_ControlId);
		if(lo_Selection.length == 0)
		{
			alert('You must make a selection before you can perform this action.');
			return;
		}
		else //NOTE: Pass the selection accross to the calling script so we can populate the content of our element with the selection.
		{
			pa_Arguments = lo_Selection;
		}
	}
		
	var lo_Editor = document.getElementById('edit_' + pi_ControlId);
	var ls_QsArguments = '';
	//NOTE: If we are modifying a link pass the parameters accross to the server to perform data checks.
	if((pa_Arguments) && (pa_Arguments.tagName))
	{
		//NOTE: If we are selecting a link then we need to make sure the whole link is selected.
		if(pa_Arguments.tagName.toLowerCase() == 'a')
		{
			if(getRangeContent(pi_ControlId) != pa_Arguments.innerText)
			{
				alert('You must select the entire link before you can perform this action.');
				return;
			}
		}
		if(	(pa_Arguments.tagName.toLowerCase() == 'a') &&
			(	(pa_Arguments.getAttribute('id') == 'contact') ||
				(pa_Arguments.getAttribute('id') == 'dynamic')))
		{
			var ls_Href = pa_Arguments.href.toString();
			//NOTE: if the link is a javascript link extract the url from the function call.
			if(ls_Href.substring(0,10) == 'javascript')
			{
				//NOTE: Assign our RegEx for js argument matches.
				var lre_Args = new RegExp(/'\?([^']*)'/g);
				while ((la_Arg = lre_Args.exec(ls_Href)) != null)
				{
					ls_QsArguments = new String(RegExp.$1);
				}
			}
			else
			{
				ls_QsArguments = ls_Href.replace(/\?/g,'');
			}
		}
	}
	//alert(ls_QsArguments);
	var lo_Return = showModalDialog(('wysiwyg/dialog.aspx?DLG=' + pi_DialogId.toString() + '&ARG=' + encodeURL(ls_QsArguments)), pa_Arguments, 'scroll:0; help:0; unadorned:1; center:1; status:0; dialogWidth:300px; dialogHeight:360px');
	lo_Editor.setActive();
	lo_Return && getRange(pi_ControlId).pasteHTML(lo_Return);
}
//****************************************************************************************************************


//****************************************************************************************************************
function doCommand(pi_ControlId, ps_Command, ps_Argument)
{
	//NOTE: Get our WYSIWYG and source dom objects.
	var lo_Editor	= document.getElementById('edit_' + pi_ControlId);
	var lo_Source	= document.getElementById('source_' + pi_ControlId);
	
	//NOTE: Do our requested command.
	document.execCommand(ps_Command, false, ps_Argument);

	//NOTE: Set our source code to be the same as our WYSIWYG element.
	lo_Source.value = htmlFormat(lo_Editor.innerHTML);
}
//****************************************************************************************************************


//****************************************************************************************************************
//NOTE: Create our associated global variables for the keyCommand action.
var gb_InternalCopy = false;
//****************************************************************************************************************
function keyCommand(pi_ControlId)
{
	//NOTE: Capture copy event Ctrl+C.
	if((event.ctrlKey) && (event.keyCode == 67))
	{
		gb_InternalCopy = true;
	}	
	//NOTE: Capture on paste event Ctrl+V to head off external format copying.
	else if(	(event.ctrlKey) && 
				(event.keyCode == 86) && 
				(!gb_InternalCopy))
	{
		var ls_ClipboardText = window.clipboardData.getData('Text').toString();
		window.clipboardData.clearData();
		window.clipboardData.setData('Text',ls_ClipboardText)
		doCommand(pi_ControlId,'Paste');
		event.returnValue = false;	
	}
	//NOTE: Capture source code editor request Ctrl+Alt+H.
	else if((event.ctrlKey) && (event.altKey) && (event.keyCode == 72))
	{
		switchMode(pi_ControlId);
	}
}
//****************************************************************************************************************


//****************************************************************************************************************
function formatString(pi_ControlId, ps_Data)
{

	ps_Data = ps_Data.replace(/\n\r\n/g,'|');
	la_DataArray = ps_Data.split('|');
	ps_Data = '';
	for(var i = 0; i < la_DataArray.length; i++)
	{
		ps_Data = ps_Data + createContainer('p', la_DataArray[i].replace(/(^\s*)|(\s*$)/g,'')) + '\n';
	}
	return ps_Data;	
}
//****************************************************************************************************************


//****************************************************************************************************************
function createContainer(ps_Tag, ps_Data)
{
	var ls_Data = ps_Data;
	//NOTE: Wrap the tags round a document selection.
	if(!ps_Data) 
	{
		var lo_Selection = (document.all)? document.selection.createRange() : document.getSelection();
		ls_Data = lo_Selection.text;
		if(ls_Data.length > 0)
		{
			lo_Selection.text = '<' + ps_Tag + '>' + ls_Data + '</' + ps_Tag + '>';
		}
	}
	//NOTE: Wrap text round our static tags.
	else 
	{
		return '<' + ps_Tag + '>' + ls_Data + '</' + ps_Tag + '>';
	}
	window.focus();
}
//****************************************************************************************************************


//****************************************************************************************************************
function clearClipboard()
{
	gb_InternalCopy = false;	
}
//****************************************************************************************************************


//****************************************************************************************************************
function switchMode(pi_ControlId)
{
	//NOTE: Get our WYSIWYG and source dom objects.
	var lo_Wysiwyg	= document.getElementById('wysiwyg_' + pi_ControlId);
	var lo_Html		= document.getElementById('html_' + pi_ControlId);
	var lo_Editor	= document.getElementById('edit_' + pi_ControlId);
	var lo_Source	= document.getElementById('source_' + pi_ControlId);
	
	if((lo_Wysiwyg.style.display == 'block') || (!lo_Wysiwyg.style.display))
	{
		lo_Source.value = htmlFormat(lo_Editor.innerHTML);
		lo_Wysiwyg.style.display = 'none';
		lo_Html.style.display = 'block';
		lo_Source.focus();
	}
	else
	{
		lo_Editor.innerHTML = lo_Source.value;
		lo_Html.style.display = 'none';
		lo_Wysiwyg.style.display = 'block';
		document.getElementById('edit_tools_' + pi_ControlId).style.display = 'block';	
	}	
}
//****************************************************************************************************************


//****************************************************************************************************************
function initEditor(pi_ControlId)
{
	//NOTE: Get our WYSIWYG and source dom objects.
	var lo_Editor	= document.getElementById('edit_' + pi_ControlId);
	var lo_Source	= document.getElementById('source_' + pi_ControlId);
	
	//NOTE: Set our source code to be the same as our WYSIWYG element.
	lo_Source.value = htmlFormat(lo_Editor.innerHTML);
}
//****************************************************************************************************************


//****************************************************************************************************************
function htmlCleanUp(ps_Data)
{
	//NOTE: get the html tags and loop through them
	tempregexp = new RegExp("<[^>]+>", "g");
	results = ps_Data.match(tempregexp);
	if(results) //If our wysiwyg is empty skip this process.
	{
		for (i=0; i < results.length; i++)
		{
			original = results[i];
					
			//NOTE: Temporarily strip the already quoted attributes and loop through them
			stripquoted = results[i].replace(/ [^=]+= *"[^"]*"/g,"");
			tempregexp = new RegExp(" [^=]+=[^ |>]+", "g");
			unquoted = stripquoted.match(tempregexp);
			if (unquoted)
			{
				for (j=0; j < unquoted.length; j++)
				{
					//NOTE: Add quotes to unquoted attributes					
					addquotes = unquoted[j].replace(/( [^=]+=)([^ |>]+)/g, "$1\"$2\"");
					results[i] = results[i].replace(unquoted[j],addquotes);
				}
			}
			//NOTE: convert tags to lowercase
			results[i] = results[i].replace(/<\/?[^>|^ ]+/, function(x) { return x.toLowerCase() })
			//NOTE: convert attributes to lowercase
			results[i] = results[i].replace(/ [^=]+="/g, function(y) { return y.toLowerCase() })
			//NOTE: finally replace the existing tag with the new tag
			ps_Data = ps_Data.replace(original, results[i]);
		}
	}
	return ps_Data;
}
//****************************************************************************************************************


//****************************************************************************************************************
function htmlFormat(ps_Data)
{	
	//NOTE: First clean up our html data.
	ps_Data = htmlCleanUp(ps_Data);
	//NOTE: Now clear out our absolute URL's for local references.
	ls_Host = document.URL.substring(0,(document.URL.lastIndexOf('/') + 1));
	pa_Data = ps_Data.split(ls_Host);
	if(pa_Data.length > 1)
	{
		ps_Data = '';	
		for(i = 0; i < pa_Data.length; i++)
		{
			ps_Data = ps_Data + pa_Data[i];
		}
	}	
	return ps_Data;
}
//****************************************************************************************************************


//****************************************************************************************************************
function cancelDialog()
{
	returnValue = false;
	window.close();
}
//****************************************************************************************************************


//****************************************************************************************************************
function GetImage(iOBH, sId, bWysiwyg, sMode, bParent)
{
	var ls_Path ='';
	if(bParent) ls_Path = '../';
	window.open(ls_Path + '?OBH=' + iOBH + '&UDF=' + sId + '&WYS=Y&MDE=' + sMode + '&PP=Y',"WIN_CMS" + sId,"toolbar=no,location=no,status=yes,scrollbars=yes,height=600,width=660,left=10,top=10");
}
//****************************************************************************************************************

//****************************************************************************************************************
function validateDialog(po_Element, ps_ValidationType, ps_ElementLabel)
{
	switch(ps_ValidationType)
	{
		case 'blank' :
			if(po_Element.value == '')
			{
				alert('The \'' + ps_ElementLabel + '\' field cannot be left blank.');	
			}
			break;
		case 'number' :
			if(!parseInt(po_Element.value) > 0)
			{
				alert('The \'' + ps_ElementLabel + '\' field needs to be a number greater than 0.');
			}
			break;
	}
	return;
}
//****************************************************************************************************************

//****************************************************************************************************************
function encodeURL(ps_Data)
{
	ps_Data = ps_Data.replace(/\?/g,'%3F');
	ps_Data = ps_Data.replace(/\&/g,'%26')
	ps_Data = ps_Data.replace(/\=/g,'%3D')
	return ps_Data;
}
//****************************************************************************************************************