var mTimerIds = new Array ();

function getPrefs ()
// Set preferences used for new window
{
  	return 'toolbar=no,scrollbars=yes,location=no,statusbar=no,menubar=no,resizable=yes,top=150,';  	
}

function showDownloadDialog (newTag)
// Show a pop-up containing the current list of uploaded files for download and the means to add / remove them
{
	setIframeFocus ();

	if (newTag)
		clearParsCookie ();
	var url = "Download.php";
  	var prefs = getPrefs () + 'width=700,height=290';  
  	crossDomainPopup (url, 'downloadcookie', insertDownloadResults, 250, prefs).timer();	
}

function showImageDialog (newTag)
// Show a pop-up containing the current list of uploaded images and the means to add / remove them
// If newImage is true, clear the cookie that passes parameters to the dialogue box
{
	setIframeFocus ();

	if (newTag)
		clearParsCookie ();
	var url = "ImageUpload.php";
  	var prefs = getPrefs () + 'width=700,height=540';  
  	crossDomainPopup (url, 'imageloadcookie', insertImageResults, 250, prefs).timer();
}

function showLinkDialog (newTag)
// Show a pop-up containing options for inserting a link
{
	setIframeFocus ();

	if (newTag)
		clearParsCookie ();
	var url = "Link.php";
  	var prefs = getPrefs () + 'width=580,height=470';  
  	crossDomainPopup (url, 'linkcookie', insertLinkResults, 250, prefs).timer();	
}

function showMailDialog (newTag)
// Show a pop-up containing options for inserting a mail link
{
	setIframeFocus ();

	if (newTag)
		clearParsCookie ();
	var url = "Mail.php";
  	var prefs = getPrefs () + 'width=620,height=380';  
  	crossDomainPopup (url, 'mailcookie', insertMailResults, 250, prefs).timer();	
}

function showImageLinkDialog (newTag)
// Show a pop-up containing the current list of uploaded images and the means to add / remove them
{
	setIframeFocus ();

	if (newTag)
		clearParsCookie ();
	var url = "ImageLink.php";
  	var prefs = getPrefs () + 'width=700,height=743';  
  	crossDomainPopup (url, 'imagelinkcookie', insertImageLinkResults, 250, prefs).timer();
}

function crossDomainPopup (url, cookie, setContent, freq, prefs) 
// Create a pop-up for image selection.
// Also create a cookie that's used for communicating between the pop-up and the 
// Page Editor. The cookie is checked by the Page Editor at regular intervals to see
// if the pop-up has been closed by the user.
// This function is given:
// url        The url to load
// cookie     The name of the cookie to store the data in.
// setContent A function to store the value in once the cookie is populated.
//            This can be a simple wrapper around setting a node.value in a 
//            posting form, etc.
// [freq]     The amount of time to run the interval on in millis. 
//            Defaults to 250.
// [prefs]    The prefs to the load the url with.
{ 
  	SymtaxInserter = new Object();
  	SymtaxInserter.win = open (url, 'EiyPopup', prefs);
  	SymtaxInserter.setContent = setContent;
  	SymtaxInserter.cookie = cookie;
	inhibitInput();
  	SymtaxInserter.timer = function() 
	{
    	var id = window.setInterval (this.checkIfClosed, (freq) ? freq : 250);
		mTimerIds.push (id);
  	}

  	SymtaxInserter.checkIfClosed = function() 
	{
		// N.B. must use 'typeof' test as any attempts at using .closed (or .anything) on a window return 'permission denied
		// for about 1 second after the window has closed
		if (SymtaxInserter.win && (typeof(SymtaxInserter.win.closed) != 'unknown') && SymtaxInserter.win.closed)
		{
			// Clear all timers - some may have been set but the pop-up blocked
			var i, timLen = mTimerIds.length;
			for (i = 0; i < timLen; i++)
			{
				window.clearInterval(mTimerIds[i]);
			}
			mTimerIds.length = 0;
			
			var cookieContents = getCookie(SymtaxInserter.cookie);
			allowInput();
			if (!isEmpty (cookieContents))
				SymtaxInserter.setContent (cookieContents);  // Call previously given fn to store cookie results
		}
	}
  	return SymtaxInserter;
}

function getImgFileName (baseName, extension)
// Generate the file name for the given image base name and ext
{
	// Create full path for image file including a random number to ensure the browser
	// properly reflects updates to the image during the editing process
	var srcFile = 'http://www' + getDomain("notRoot") + '/PageLibraryAssets/' + baseName + '.' + extension;
	var randomNum = Math.floor (Math.random( )* 99);
	srcFile += ("?" + randomNum);
	return srcFile;
}

function setMarginStyle (obj, align, marginLeft, marginRight, marginTop, marginBottom)
{
	if (align == "centre")
	{
		obj.style.marginLeft = "auto";
		obj.style.marginRight = "auto";
		obj.style.marginTop = marginTop + "px";
		obj.style.marginBottom = marginBottom + "px";
	}
	else if ((marginLeft != 0) || (marginRight != 0) || (marginTop != 0) || (marginBottom != 0))
	{
		obj.style.marginLeft = marginLeft + "px";
		obj.style.marginRight = marginLeft + "px";
		obj.style.marginTop = marginTop + "px";
		obj.style.marginBottom = marginBottom + "px";
	}
}

function getMarginText (align, marginLeft, marginRight, marginTop, marginBottom)
// Return css style text for given margins
{
	if (align == "centre")
		var marginText = "margin: " + marginTop + "px auto " + marginBottom +  "px; ";
	else if ((marginLeft == 0) && (marginRight == 0) && (marginTop == 0) && (marginBottom == 0))
		var marginText = "";
	else
		var marginText = "margin: " + marginTop + "px " + marginRight + "px " + marginBottom + "px " + marginLeft + "px; ";

	return marginText;
}

function setBorderStyle (obj, border)
{
	switch (border)
	{
		case "" :
		case "none" :
		obj.style.borderStyle = "none";
		break;
		
		case "thin" :
		obj.style.borderStyle = "solid";
		obj.style.borderWidth = "1px";
		break;
		
		case "thick" :
		obj.style.borderStyle = "solid";
		obj.style.borderWidth = "3px";
		break;
	}
}
		
function getBorderText (border)
{
	var borderText;
	switch (border)
	{
		case "" :
		case "none" :
		borderText = "border-style: none; ";
		break;
		
		case "thin" :
		borderText = "border-style: solid; border-width: 1px; ";
		break;
		
		case "thick" :
		borderText = "border-style: solid; border-width: 3px; ";
		break;
	}
	return borderText;
}
		
function getImgDimsText (imgWidth, imgHeight)
{
	var imgDimsText = "width: " + imgWidth + "px; height: " + imgHeight + "px; ";
	return imgDimsText;
}

function setAlignStyle (obj, align)
{
	switch (align)
	{
		case "left" :
		obj.style.cssFloat = "left";
		obj.style.styleFloat = "left";
		break;
		
		case "right" :
		obj.style.cssFloat = "right";
		obj.style.styleFloat = "right";
		break;
		
		case "centre" :
		obj.style.display = "block";
		obj.style.textAlign = "center";
		break;
		
		default:
		break;
	}
}
			
function getAlignText (align)
{
	switch (align)
	{
			case "left" :
			var alignText = "float: left; ";
			break;
			
			case "right" :
			var alignText = "float: right; ";
			break;
			
			case "centre" :
			var alignText = "display: block; text-align: center; ";
			break;
			
			default:
			var alignText = "";
			break;
	}
	return alignText;
}

function addImgAttributes (imgNode, pars)
{
	var srcFile = getImgFileName (pars[0], pars[1]);
	imgNode.setAttribute ("src", srcFile);
	var align = pars[4].toLowerCase();
	setAlignStyle (imgNode, align);
	setMarginStyle (imgNode, align, pars[8], pars[9], pars[10], pars[11]);
	setBorderStyle (imgNode, pars[3].toLowerCase());
	imgNode.style.width = pars[6] + "px";
	imgNode.style.height = pars[7] + "px";
	imgNode.setAttribute ("title", pars[2]);
	imgNode.setAttribute ("alt", pars[2]);
}

function addAnchorAttributes (doc, anchorNode, pars)
{
	anchorNode.setAttribute ("href", pars[0]);
	if (pars[1] == "newwin")
		anchorNode.setAttribute ("target", "_blank");
	var content = doc.createTextNode (pars[2]);
	anchorNode.appendChild (content);
}

function addDownloadAttributes (doc, anchorNode, pars)
{
	anchorNode.setAttribute ("href", pars[0]);
	var content = doc.createTextNode (pars[1]);
	anchorNode.appendChild (content);
}

function addImgLinkAttributes (doc, frameWin, pars)
{
	var srcFile = getImgFileName (pars[0], pars[1]);
	var align = pars[3].toLowerCase();
	
	var aNode = doc.createElement ("a");
	aNode.setAttribute ("href", pars[10]);
	if (pars[11] == "newwin")
		aNode.setAttribute ("target", "_blank");

	var imgNode = doc.createElement ("img");
	aNode.appendChild (imgNode);

	if ((align == "left") || (align == "right"))
	{
		insertNodeAtSelection_DOM (frameWin, aNode, "");
		setMarginStyle (imgNode, align, pars[6], pars[7], pars[8], pars[9]);
		setAlignStyle (imgNode, align);
	}
	else if (align == "in-line")
	{
		var outerNode = doc.createElement ("span");
		insertNodeAtSelection_DOM (frameWin, outerNode, "");
		outerNode.appendChild (aNode);
		setMarginStyle (outerNode, align, pars[6], pars[7], pars[8], pars[9]);
		outerNode.style.verticalAlign = "middle";
	}
	imgNode.setAttribute ("src", srcFile);
	imgNode.setAttribute ("title", pars[2]);
	imgNode.setAttribute ("alt", pars[2]);
	imgNode.style.border = "none";
	imgNode.style.width = pars[4] + "px";
	imgNode.style.height = pars[5] + "px";
}

function addMailAttributes (doc, anchorNode, pars)
{	
	var recipient = escape (pars[0]);
	anchorNode.setAttribute ("href", "../Mail/Query.php?rec=" + recipient + "&subj=Enquiry regarding");
	var content = doc.createTextNode (pars[1]);
	anchorNode.appendChild (content);
}

function getImageHtml (pars)
// Generate the html for the image indicated in the given encoded parameters
{
	// Determine parameters by splitting text string obtained from the dialogue box's cookie
	var baseName = pars[0];
	var extension = pars[1];
	var hoverText = pars[2];
	var align = pars[4].toLowerCase();
	var zoom = pars[5].toLowerCase();
	var fullImgWidth = pars[12];
	var fullImgHeight = pars[13];

	var srcFile = getImgFileName (baseName, extension);
	var marginText = getMarginText (align, pars[8], pars[9], pars[10], pars[11]);
	var borderText = getBorderText (pars[3].toLowerCase());
	var imgDimsText = getImgDimsText (pars[6], pars[7]);
		
	if (zoom == "zoom")
	{
		// Insert anchor to allow user to zoom the pic
		imgStr = '<a href="javascript:;" onclick= "zoomPic (';
		imgStr += ("'" + baseName + '.' + extension + "', " + fullImgWidth + ", " + fullImgHeight + ');">');
	}
	else
		var imgStr = "";

	imgStr += '<img src= "' + srcFile + '"';
	
	var alignText = getAlignText (align);

	imgStr += (' alt= "' + hoverText + '" style= "' + borderText + imgDimsText + marginText + alignText);
	imgStr += '" />';
	if (zoom == "zoom")
		imgStr += "</a>";

	return imgStr;
}

function getImageLinkHtml (pars)
// Generate the html for the image link indicated in the given encoded parameters
{
	// Determine parameters by splitting text string obtained from the dialogue box's cookie
	var baseName = pars[0];
	var extension = pars[1];
	var hoverText = pars[2];
	var align = pars[3].toLowerCase();

	var srcFile = getImgFileName (baseName, extension);
	var marginText = getMarginText (align, pars[6], pars[7], pars[8], pars[9]);
	var alignText = getAlignText (align);
	var imgDimsText = getImgDimsText (pars[4], pars[5]);
	
	var href = ' href="' + pars[10] + '"';
	
	var newwin = (pars[11] == "newwin") ? ' target= "_blank"' : "";
		
	if ((align == "left") || (align == "right"))
	{
		var imgStr = '<a ' + href + newwin + '><img src= "' + srcFile + '" alt= "'
							 + hoverText + '" style= "border: none; ' + imgDimsText + alignText + marginText + '" /></a>\n';
	}
	else if (align == "in-line")
	{
		var imgStr = '<span style= "vertical-align: middle">\n<a ' + href + newwin + '><img src= "' + srcFile + '" alt= "'
								+ hoverText + '" style= "border: none; ' + imgDimsText + '" /></a>\n</span>\n';
	}

	return imgStr;
}

function insertImageResults (codedPars)
// Put image (as described by codedPars) in iFrame
// text contains following parameters:
// baseName¬extension¬hoverText¬border¬align¬zoom¬imgWidth¬imgHeight
//      ¬marginLeft¬marginRight¬marginTop¬marginBottom¬fullImgWidth
{
	var pars = codedPars.split ("\xAC");
	var frameWin = document.getElementById (VisEd.frameId).contentWindow; 
  	if (Detect.IE()) 
  	{
		var doc = frameWin.document;
    	var range = doc.selection.createRange();
		var html = getImageHtml (pars);
	  	try 
		{
		 	var range = doc.selection.createRange();			 
			var isCollapsed = (range.text == '');
			range.pasteHTML (html);

			if (!isCollapsed) 
			{
				// move selection to html contained within the surrounding node
				range.moveToElementText(range.parentElement().childNodes[0]);
				range.select();
			}
		 } 
		 catch(e)
		 {
			 VisEd.addDebugMsg('Failed to insert img tag');
		 }
	}
	else		// It's not IE
	{
		// Determine parameters by splitting text string obtained from the dialogue box's cookie
		var baseName = pars[0];
		var extension = pars[1];
		var align = pars[4].toLowerCase();
		var zoom = pars[5].toLowerCase();
		var fullImgWidth = pars[12];
		var fullImgHeight = pars[13];
		
  		var doc = (frameWin.contentDocument) ? frameWin.contentDocument : document;

		if (zoom == "zoom")
		{
			// Put an anchor at the selection
			var anchorNode = doc.createElement("a");
			insertNodeAtSelection_DOM (frameWin, anchorNode, "");
			anchorNode.setAttribute ("href", "javascript:;");
			anchorNode.setAttribute ("onclick", "zoomPic ('" + baseName + "." + extension + "', " + fullImgWidth + ", " + fullImgHeight + ");");		

			// Put an image at the selection & set its attributes
			var imgNode = doc.createElement("img");
			anchorNode.appendChild (imgNode);
			addImgAttributes (imgNode, pars);
		}
		else
		{
			// Put an image at the selection & set its attributes
			var imgNode = doc.createElement("img");
			insertNodeAtSelection_DOM (frameWin, imgNode, "");
			addImgAttributes (imgNode, pars);
		}
	}  // It's not IE
}	

function insertDownloadResults (codedPars)
{
	if (!isEmpty(codedPars))
	{
		var pars = codedPars.split ("\xAC");
		if (Detect.IE())
		{
			var html = '<a href="' + pars[0] + '">' + pars[1] + '</a>';			
			insertHtmlIntoTextArea_IE (html);
		}
		else	// It's not IE
		{
			var frameWin = document.getElementById (VisEd.frameId).contentWindow; 
			var doc = (frameWin.contentDocument) ? frameWin.contentDocument : document;
	
			var anchorNode = doc.createElement("a");
			insertNodeAtSelection_DOM (frameWin, anchorNode, "");
			addDownloadAttributes (doc, anchorNode, pars);
		}
	}
}

function insertLinkResults (codedPars)
{
	if (!isEmpty(codedPars))
	{
		var pars = codedPars.split ("\xAC");
		if (Detect.IE())
		{
			var html = '<a href="' + pars[0] + '"';
			if (pars[1] == "newwin")
				html += ' target= "_blank"';
				
			html += '>' + pars[2] + '</a>';			
			insertHtmlIntoTextArea_IE (html);
		}
		else	// It's not IE
		{
			var frameWin = document.getElementById (VisEd.frameId).contentWindow; 
			var doc = (frameWin.contentDocument) ? frameWin.contentDocument : document;
	
			var anchorNode = doc.createElement("a");
			insertNodeAtSelection_DOM (frameWin, anchorNode, "");
			addAnchorAttributes (doc, anchorNode, pars);
		}
	}
}

function insertMailResults (codedPars)
{
	if (!isEmpty(codedPars))
	{
		var pars = codedPars.split ("\xAC");
		if (Detect.IE())
		{
			var recipient = escape (pars[0]);		
			var html = '<a href= "../Mail/Query.php?rec=' + recipient + '&subj=Enquiry regarding">' + pars[1] + '</a>';			
			insertHtmlIntoTextArea_IE (html);
		}
		else	// It's not IE
		{
			var frameWin = document.getElementById (VisEd.frameId).contentWindow; 
			var doc = (frameWin.contentDocument) ? frameWin.contentDocument : document;
	
			var anchorNode = doc.createElement("a");
			insertNodeAtSelection_DOM (frameWin, anchorNode, "");
			addMailAttributes (doc, anchorNode, pars);
		}
	}
}

function insertImageLinkResults (codedPars)
{
	var pars = codedPars.split ("\xAC");
	var frameWin = document.getElementById (VisEd.frameId).contentWindow; 
  	if (Detect.IE()) 
  	{
	  	var doc = frameWin.document;
    	var range = doc.selection.createRange();
		var html = getImageLinkHtml (pars);
	  	try 
		{
		 	var range = doc.selection.createRange();			 
			var isCollapsed = (range.text == '');
			range.pasteHTML (html);

			if (!isCollapsed) 
			{
				// move selection to html contained within the surrounding node
				range.moveToElementText(range.parentElement().childNodes[0]);
				range.select();
			}
		 } 
		 catch(e)
		 {
			 VisEd.addDebugMsg('Failed to insert img link tag');
		 }
	}
	else // It's not IE
	{
		// Put a anchor & image nodes at the selection & set their attributes
  		var doc = (frameWin.contentDocument) ? frameWin.contentDocument : document;
		addImgLinkAttributes (doc, frameWin, pars);
	}  
}

function insertHtmlIntoTextArea_IE (html)
// Insert the given html text into the text area containing the page contents
{
	var frameWin = document.getElementById (VisEd.frameId).contentWindow; 
	var doc = frameWin.document;
	try 
	{
		var range = doc.selection.createRange();			 
		var isCollapsed = (range.text == '');
		range.pasteHTML (html);

		if (!isCollapsed) 
		{
			// move selection to html contained within the surrounding node
			range.moveToElementText(range.parentElement().childNodes[0]);
			range.select();
		}
	 } 
	 catch(e)
	 {
		 VisEd.addDebugMsg('Failed to insert requested tag');
	 }
}

function inhibitInput ()
// Prevent any user input to text area - needed when an html dialogue box is up
// Ensure user is warned if they try to enter text that they need to close the dialogue
// Also prevent any buttons except 'Submit' or 'Cancel' or 'Help' from being pressed
{
return;  // !!!!!FIX THIS !!!!!!!!!!!!!!!!!
	inhibitBtn ("previewIt");
	inhibitBtn ("deleteIt");
	inhibitBtn ("saveIt");
	disableAnchor ("Bold");
	disableAnchor ("Italic");
	disableAnchor ("Small");
	disableAnchor ("Bullet");
	disableAnchor ("Heading");
	disableAnchor ("HzLine");
	disableAnchor ("Break");
	disableAnchor ("Image");
	disableAnchor ("Table");
	disableAnchor ("Box");
	disableAnchor ("Download");
	disableAnchor ("Link");
	disableAnchor ("ImageLink");
	disableAnchor ("MailLink");
	disableAnchor ("Alter");
//	inhibitBtn ("PageContent");    // !!!!!FIX THIS !!!!!!!!!!!!!!!!!
}

function allowInput ()
// Allows full text entry and button selection
{
return;  // !!!!!FIX THIS !!!!!!!!!!!!!!!!!
	allowBtn ("previewIt");
	allowBtn ("deleteIt");
	allowBtn ("saveIt");
	enableAnchor ("Bold");
	enableAnchor ("Italic");
	enableAnchor ("Small");
	enableAnchor ("Bullet");
	enableAnchor ("Heading");
	enableAnchor ("HzLine");
	enableAnchor ("Break");
	enableAnchor ("Image");
	enableAnchor ("Table");
	enableAnchor ("Box");
	enableAnchor ("Download");
	enableAnchor ("Link");
	enableAnchor ("ImageLink");
	enableAnchor ("MailLink");
	enableAnchor ("Alter");
//	allowBtn ("PageContent");    // !!!!!FIX THIS !!!!!!!!!!!!!!!!!
}

function insertHzLine()
{
	insertTextIntoTextArea ("<line>");
}

function insertBreak()
{
	insertTextIntoTextArea ('<break>');
}

// ------------------------------------------------------------------------------------

function clearParsCookie ()
// Clear cookie used for uploading parameters to pop-up
{
	var cookieDomain = "www" + getDomain("root");
	var parameters = "";
	eraseCookie ('parametersCookie', cookieDomain);
	setCookie ('parametersCookie', parameters, cookieDomain);
}

