// ###########################
// # Author: Ben Weeks       #
// # Company: webtechy.co.uk #
// ###########################

var oPropertiesWindow;
var iPopulateTimeID;
var iIterations = 0;
var iMaxIterations = 100;
var sInformationSuppliedBy = "Suffolk Coastal District Council";
var iMaxDescriptionLetters = 500;
var sNewsDetailBody = "NewsDetailBody";

function AlterPagePropertiesOnClick()
{

	if (document.getElementById("PagePropertiesAnchor"))
	{
		// Then the "Page Properties" button exists in the console menu.
		oButton = document.getElementById("PagePropertiesAnchor")
		newFunction = oButton.onclick;
		// Nifty little call below to add a function to the onClick event of the button.
		oButton.onclick = new Function("WaitToPopulate();" + newFunction.toString().replace(/\n/g,'').replace(/function anonymous\(\)\{/,'').replace(/\}$/,''));	
	}
	if (document.getElementById("SubmitAnchor"))
	{
		// Do the same for the "Submit" button. *These links work slightly differently so this won't work.
		//oButton = document.getElementById("SubmitAnchor")
		//newFunction = oButton.onclick;
		//oButton.onclick = new Function("WaitToPopulate();" + newFunction.toString().replace(/\n/g,'').replace(/function anonymous\(\)\{/,'').replace(/\}$/,''));	
	}
	if (document.getElementById("ApproveAnchor"))
	{
		// Do the same for the "Approve" button. *These links work slightly differently so this won't work.
		//oButton = document.getElementById("ApproveAnchor")
		//newFunction = oButton.onclick;
		//oButton.onclick = new Function("WaitToPopulate();" + newFunction.toString().replace(/\n/g,'').replace(/function anonymous\(\)\{/,'').replace(/\}$/,''));	
	}
}

function WaitToPopulate()
{
	// Waiting for Page Properties window to open ...
	window.status = "Waiting for Page Properties window to load "
	iPopulateTimeID = setInterval("PopulateWindow()",500)
}

function PopulateWindow()
{
	iIterations = iIterations + 1;
	// Show that we are progressing with the wait and it hasn't crashed.
	window.status = window.status + ".";

	// Check to see if we've been checking for too long and something has gone wrong.
	if (iIterations < iMaxIterations)
	{
		// By looking in /OneSuffolk/CMS/WebAuthor/Client/Windows.js
		// we can see that the Page Properties window has a handler
		// of "pWindow" - however, this variable is unfortunately 
		// local to that function and I do not have permissions to 
		// change it.

		// Focus on the window (unfortunately if the window isn't open,
		// then it will try and open it.
		oPropertiesWindow = window.open("", "WBC_winPagePropsDlg");
		oPropertiesWindow.focus();

		// Check to see if the page has loaded (the submit button 
		// is at the bottom - not ideal but can't find a better 
		// way of doing it).
		if (oPropertiesWindow.document.getElementById("idSubmitBtn"))
		{
			// Then we have found the window, so stop checking.
			clearInterval(iPopulateTimeID);
			// Now we need to populate the window.
			FillFields();
		}
	}
	else
	{
		// The window has taken too long to load, so
		// clear the timer to prevent the users
		// browser crashing.
		clearInterval(iPopulateTimeID);
		alert("The page could not be automatically filled,\nas the page took too long to load.");
	}
	// Set the focus back to the pop-up.
	oPropertiesWindow.focus();
}

function FillFields()
{
	//alert("fillfields");
	// We should really check to see if all the elements exist on the page.
	try
	{
		// Grey out boxes (problem: these will become live again if there is a problem, as the page is refreshed!)
		oPropertiesWindow.document.getElementById("idIndexPage").disabled = true;
		oPropertiesWindow.document.getElementById("idFollowLinks").disabled = true;
		oPropertiesWindow.document.getElementById("idHideWhenPublished").disabled = true;
		oPropertiesWindow.document.getElementById("idHideThemeNav").disabled = true;
		oPropertiesWindow.document.getElementById("idPostCode").disabled = true;
		oPropertiesWindow.document.getElementById("ddlParish").disabled = true;
		oPropertiesWindow.document.getElementById("ppWard").disabled = true;
		oPropertiesWindow.document.getElementById("ppDivision").disabled = true;
		oPropertiesWindow.document.getElementById("ppPoliticalType").disabled = true;
	}
	catch(er)
	{
		// Something went wrong :-(
		alert("An error occurred and not all\nthe data fields could be\ndisabled. This is most\nlikely due to the Page Properties\nwindow changing recently.");	
	}
	try
	{
		// Grab the data.
		var sTitle = document.title;
		var sDetail;

		if (document.getElementById(sNewsDetailBody))
		{
			if (document.getElementById(sNewsDetailBody))
			{
				// Check to see if a child element exists (i.e. we're trying to just grab the first paragraph, so looking for <div></div> of <p></p>)
				if (document.getElementById(sNewsDetailBody).firstChild)
				{
					// Check to see if the child actually contains any text.
					//alert(document.getElementById(sNewsDetailBody).firstChild.innerHTML);
					if (document.getElementById(sNewsDetailBody).firstChild.innerHTML)
					{
						sDetail = document.getElementById(sNewsDetailBody).firstChild.innerText;
					}
					else
					{
						// update:SS 12/4/2006. No child node means paras not cleanly defined, try using what is before first <br>
						var iPos = document.getElementById(sNewsDetailBody).innerHTML.indexOf("<BR");
						if (iPos < 0) {
						  iPos = document.getElementById(sNewsDetailBody).innerHTML.indexOf("<br");
						}
						if (iPos >=0)
						{
						  sDetail = document.getElementById(sNewsDetailBody).innerHTML.substr(0,iPos);
						}
						else
						{
						  sDetail = document.getElementById(sNewsDetailBody).innerHTML;
						}
					}
				}
				else
				{
					// update:SS 12/4/2006. No child node means paras not cleanly defined, try using what is before first <br>
					var iPos = document.getElementById(sNewsDetailBody).innerHTML.indexOf("<BR");
					if (iPos < 0) {
					  iPos = document.getElementById(sNewsDetailBody).innerHTML.indexOf("<br");
					}
					if (iPos >=0)
					{
					  sDetail = document.getElementById(sNewsDetailBody).innerHTML.substr(0,iPos);
					}
					else
					{
					  sDetail = document.getElementById(sNewsDetailBody).innerHTML;
					}
				}
			}
		}
		else
		{
			alert("The descriptive text could not be automatically entered into the page properties, please enter this manually.");
		}

		// Fill the Description field.
		// Get the first X number characters as don't want to copy whole news article.
		// But first we want to find out where the first space is after the first X
		// number of characters.
		var sString;
		if (sDetail.length > iMaxDescriptionLetters)
		{
			// Then we need to chop down the length of the string as it's too long.
			var iSpacePosition = sDetail.indexOf(" ",iMaxDescriptionLetters)
			if (iSpacePosition < iMaxDescriptionLetters + 10)
			{
				sString = sDetail.substr(0,iSpacePosition) + "...";
			}
			else
			{
				sString = sDetail.substr(0,iMaxDescriptionLetters) + "...";
			}
		}
		else
		{
			sString = sDetail.substr(0,iMaxDescriptionLetters);
		}
		// Set the string (as long as it doesn't already contain anything).
		if (oPropertiesWindow.document.getElementById("idDescription").innerText == "")
		{
			oPropertiesWindow.document.getElementById("idDescription").innerText = sString;
			// We shall also therefore assume this page has't been opened before,
			// so we automatically click the "Publish to Portal". If they had opened it
			// before they would probably (should) enter a description, and therefore
			// might have chosen to leave "publish to portal" unticked.
			oPropertiesWindow.document.getElementById("idPublishToPortal").click();
		}
	}
	catch(er)
	{
		// Something went wrong :-(
		alert("An error occurred and the\ndescription field could not\nbe automatically filled. This is\nmost likely due to the Page\nProperties window changing\nrecently.");	
	}
	try
	{	
		// Set the "Information Supplied By" field (as long as it doesn't already contain anything).
		if (oPropertiesWindow.document.getElementById("ppInformationSuppliedBy").value == "")
		{
			oPropertiesWindow.document.getElementById("ppInformationSuppliedBy").value = sInformationSuppliedBy;
		}
	}
	catch(er)
	{
		// Something went wrong :-(
		alert("An error occurred and the\n'Information Supplied By' could\nnot be automatically filled. This\nis most likely due to the Page\nProperties window changing\nrecently.");	
	}
	
	// Set the status of the window back to normal.
	window.status = "";
}
