var emailFilter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9_\.\-])+\.)+([a-zA-Z0-9])+$/;

// detect whether it's opera. if so, behave a bit differently
var isOpera = false;
if (navigator.userAgent.indexOf("Opera") != -1) {
    isOpera = true;
}

function submitLink(f) {
	var msg = "";
	var hrefFilter = /^http:\/\/.*$/; 

	if (!hrefFilter.test(f.href.value)) {
		msg += "Please provide valid link target, beginning with http://\n";
	}
	if (f.label.value.length==0) {
		msg += "Please provide a label.\n";
	}
	if (f.description.value.length==0) {
		msg += "Please provide a description.\n";
	}
	var oneChecked = false;
//	alert(f.branchCount);
//	alert(f.branchCount.value);
	var count = Number(f.branchCount.value);
	for (var i = 0; i < count; i++) {
	    if (eval("f.Branch_" + i + ".checked")) {
	        oneChecked = true;
	        break;
	    }
	}
	if (!oneChecked) {
		msg += "Please select at least one area for this link to appear in.\n";
	}

	if (msg == "") {
		f.submit();
	} else {
		alert(msg);
	}
}

function showExtraCategories() {
    document.getElementById('extraCategories').style.display="";
    document.getElementById('extraCategoriesTrigger').style.display="none";
}

// To do - rationalise showUploader / hideUploader / newCategory() to accept input type

function showDocumentUploader () {
    document.getElementById("documentUploaderButton").style.display="none";
    document.getElementById("DocumentUploadCtrlInner").style.display="";
}
function hideDocumentUploader () {
    document.getElementById("documentUploaderButton").style.display="";
    document.getElementById("DocumentUploadCtrlInner").style.display="none";
}

function showImageUploader () {
    document.getElementById("imageUploaderButton").style.display="none";
    document.getElementById("ImageUploadCtrlInner").style.display="";
}
function hideImageUploader () {
    document.getElementById("imageUploaderButton").style.display="";
    document.getElementById("ImageUploadCtrlInner").style.display="none";
}

function newDocumentCategory() {
	var newDocumentCategory = getValidName ("Please enter the name of the new category.\n\nPlease note that category names are for your convenience only and never appear to the user.",/^([a-zA-Z0-9_\- ])+$/,"");
    if (newDocumentCategory!= null) {
        if (isOpera) {
            document.minicon.location= level + "utils/documentHandler.asp?action=newCategory&name=" + newDocumentCategory;
        } else {
            window.frames.minicon.location= level + "utils/documentHandler.asp?action=newCategory&name=" + newDocumentCategory;
        }
    }
}

function newImageCategory() {
    var newImageCategory = getValidName ("Please enter the name of the new category.\n\nPlease note that category names are for your convenience only and never appear to the user.",/^([a-zA-Z0-9_\- ])+$/,"");
    if (newImageCategory!= null) {
        if (isOpera) {
            document.minicon.location= level + "utils/imageHandler.asp?action=newCategory&name=" + newImageCategory;
        } else {
            window.frames.minicon.location= level + "utils/imageHandler.asp?action=newCategory&name=" + newImageCategory;
        }
    }
}
function hideBackups(categoryID,subCategoryID,pID) {
    document.getElementById("adminBlock3").innerHTML="<a class=\"btn\" target=\"minicon\" href=\"utils/manageBackups.asp?categoryID=" + categoryID + "&subCategoryID=" + subCategoryID + "&pageID=" + pID + "&action=list\">View backups</a><br/>";
}

function addImageOption(currentLibrary,newValue,newText) {
    document.getElementById("library_" + currentLibrary).options[document.getElementById("library_" + currentLibrary).options.length] = new Option(newText,newValue);
    document.getElementById("library_" + currentLibrary).selectedIndex = (document.getElementById("library_" + currentLibrary).options.length-1);
    showImageLibraryControls(newValue);
}

function addDocumentOption(currentLibrary,newValue,newText) {
    document.getElementById("library_" + currentLibrary).options[document.getElementById("library_" + currentLibrary).options.length] = new Option(newText,newValue);
    document.getElementById("library_" + currentLibrary).selectedIndex = (document.getElementById("library_" + currentLibrary).options.length-1);
    showDocumentLibraryControls(newValue);
}

var arInput = "";
function addLibraryImage () {
    if (arInput[0] != "") {
        var theHTML = "\n<img src=\'/downloadImage.asp?fileID=" + arInput[0] + "\' width=\'" + arInput[1] + "\' height=\'" + arInput[2] + "\' alt=\'" + arInput[4] + "\' title=\'" + arInput[4] + "\' />";
		var oRTEeditor = FCKeditorAPI.GetInstance('body');
		oRTEeditor.InsertHtml(theHTML);
//        document.editPageForm.body.value += theHTML;
//        document.editPageForm.body.focus();            
	}
}
function addLibraryDocument () {
    if (arInput[0] != "") {

var theHTML = "\n<a href=\"" + level + "download.asp?fileID=" + arInput[0] + "\" title=\"" + arInput[2] + "\" />"+ arInput[2] +"</a>";
var oRTEeditor = FCKeditorAPI.GetInstance('body');
oRTEeditor.InsertHtml(theHTML);

        //var theHTML = "\n<a href=\"" + level + "documentLibrary/" + arInput[0] + "."+arInput[3]+"\" title=\"" + arInput[2] + "\" />"+ arInput[2] +"</a>";
		//var oRTEeditor = FCKeditorAPI.GetInstance('body');
		//oRTEeditor.InsertHtml(theHTML);
		
//		document.editPageForm.body.value += theHTML;
//      document.editPageForm.body.focus();            
    }
}

function removeSelectedOption(selectorID) {
    document.getElementById(selectorID).options[document.getElementById(selectorID).selectedIndex]=null;
    document.getElementById(selectorID).selectedIndex=0;
    hideLibraryControls();
}


function deleteLibraryDocument () {
    var loc = level + "utils/documentHandler.asp?action=checkUsage&ID=" + arInput[0] + "&selectorID=" + prevV;
    if (isOpera) {
        document.minicon.location = loc;
    } else {
        window.frames.minicon.location=loc;
    }
}

function deleteLibraryImage () {
    var loc = level + "utils/imageHandler.asp?action=checkUsage&ID=" + arInput[0] + "&selectorID=" + prevV;
    if (isOpera) {
        document.minicon.location = loc;
    } else {
        window.frames.minicon.location=loc;
    }
}

function showDocumentLibraryControls(input) {
    if (input=="") {
        return;
    }
    arInput = input.split("|");
    document.getElementById("sampleDocument").innerText = arInput[0] + "." + arInput[3];
    document.getElementById("sampleDocumentFilesize").innerText = arInput[1];
    document.getElementById("DocumentLibCtrl").style.display="";
    hideDocumentUploader();
}
function showImageLibraryControls(input) {
    if (input=="") {
        return;
    }
    arInput = input.split("|");
    document.getElementById("sampleImage").src = level + "downloadImage.asp?fileID=" + arInput[0];
    document.getElementById("sampleImage").title = arInput[4] + " (preview)";
    document.getElementById("sampleImage").width = 135;
    document.getElementById("sampleImageFilesize").innerText = arInput[3] + " [" + arInput[1] + " x " + arInput[2] + "px]";
    document.getElementById("ImageLibCtrl").style.display="";
    hideImageUploader();
}
function hideLibraryControls() {
    document.getElementById("ImageLibCtrl").style.display="none";
}


var prevVi = 0;
var prevV = 0;
function showImageLibrary(v) {
    if (v==-1) {
        document.getElementById("ImageUploadCtrl").style.display="none";
        return;
    }
    if (prevV != 0) {
    
		if(document.getElementById("ImageLib_" + prevV) != null) {
			 document.getElementById("ImageLib_" + prevV).style.display="none";
		}
	
	//    document.getElementById("ImageLib_" + prevV).style.display="none";
    }
    prevV = v;
    document.getElementById("ImageLib_" + v).style.display="";
    document.getElementById("library_" + v).selectedIndex=0;
    hideLibraryControls();
    document.getElementById("ImageUploadCtrl").style.display="";
    document.newImageForm.currentLibrary.value=v;
    hideImageUploader();
    //alert(document.newImageForm.currentLibrary.value);
}

function showDocumentLibrary(v) {
    if (v==-1) {
        document.getElementById("DocumentUploadCtrl").style.display="none";
        return;
    }
    if (prevV != 0) {
        document.getElementById("DocumentLib_" + prevV).style.display="none";
    }
    prevV = v;
    document.getElementById("DocumentLib_" + v).style.display="";
    document.getElementById("library_" + v).selectedIndex=0;
    hideLibraryControls();
    document.getElementById("DocumentUploadCtrl").style.display="";
    document.newDocumentForm.currentLibrary.value=v;
    hideDocumentUploader();
    //alert(document.newImageForm.currentLibrary.value);
}



function showImageImporter( ) {
    document.getElementById("styleMixer").style.display="none";
    document.getElementById("documentLibrary").style.display="none";
    document.getElementById("imageLibrary").style.display="";
}
function showDocumentImporter( ) {
    document.getElementById("styleMixer").style.display="none";
    document.getElementById("documentLibrary").style.display="";
    document.getElementById("imageLibrary").style.display="none";
}
function showStyleMixer( ) {
	document.getElementById("styleMixer").style.display="";
    document.getElementById("styleMixerEdit").style.display="none";
	document.getElementById("documentLibrary").style.display="none";
    document.getElementById("imageLibrary").style.display="none";
}
function showStyleEditMixer( colour, weight, other, name ) {
    document.getElementById("styleMixerEdit").style.display="";
    document.getElementById("documentLibrary").style.display="none";
    document.getElementById("imageLibrary").style.display="none";
	document.getElementById("styleMixer").style.display="none";

	// Set the value of the fields
    document.styleMixerEdit.colourEdit.value = colour;
    document.styleMixerEdit.weightEdit.value = weight;
    document.styleMixerEdit.decorationEdit.value = other;
	document.styleMixerEdit.styleNameEdit.value = name;
}
function addStyle () {
    if (document.styleMixer.styleName.value == "") {
        alert("Please name your style");
        return;
    }
    var newStyle="." + document.styleMixer.styleName.value
         + "{color:" + document.styleMixer.colour.value
         + ";font-weight:" + document.styleMixer.weight.value
         + ";text-decoration:" + document.styleMixer.decoration.value
         + ";}"
    // put the new style in the editing window and reload the page.
    document.editPageForm.newStyle.value=newStyle;
    document.editPageForm.pageAction.value="addStyle";
    document.editPageForm.body.value;
    document.editPageForm.submit();
}

function editStyle () {
    var newStyle="." + document.styleMixerEdit.styleNameEdit.value
         + "{color:" + document.styleMixerEdit.colourEdit.value
         + ";font-weight:" + document.styleMixerEdit.weightEdit.value
         + ";text-decoration:" + document.styleMixerEdit.decorationEdit.value
         + ";}"
    // put the new style in the editing window and reload the page.
    document.editPageForm.newStyle.value=newStyle;
    document.editPageForm.pageAction.value="editStyle";
    document.editPageForm.body.value;
    document.editPageForm.submit();
}

function deleteStyle () {
   
	var cnf = confirm('Are you sure?');
	if (cnf)
	{
	var newStyle="." + document.styleMixerEdit.styleNameEdit.value
         + "{color:" + document.styleMixerEdit.colourEdit.value
         + ";font-weight:" + document.styleMixerEdit.weightEdit.value
         + ";text-decoration:" + document.styleMixerEdit.decorationEdit.value
         + ";}"
    // put the new style in the editing window and reload the page.
    document.editPageForm.newStyle.value=newStyle;
    document.editPageForm.pageAction.value="deleteStyle";
    document.editPageForm.body.value;
    document.editPageForm.submit();
	}
}


function updateStyleMixerPreview () {
    document.getElementById("styleMixerPreview").style.color=document.styleMixer.colour.value;
    document.getElementById("styleMixerPreview").style.fontWeight=document.styleMixer.weight.value;
    document.getElementById("styleMixerPreview").style.textDecoration=document.styleMixer.decoration.value;
}
function updateStyleMixerEditPreview () {
    document.getElementById("updateStyleMixerEditPreview").style.color=document.styleMixerEdit.colourEdit.value;
    document.getElementById("updateStyleMixerEditPreview").style.fontWeight=document.styleMixerEdit.weightEdit.value;
    document.getElementById("updateStyleMixerEditPreview").style.textDecoration=document.styleMixerEdit.decorationEdit.value;
}
function insertURL(target) {
    var urlText = prompt("Please enter the hyperlink you would like to link to.\ne.g. http://www.google.com/");
    var linkText = prompt("Please enter the text you would like this link to have.\ne.g. Google search engine");
    target.value += "[url=|" + urlText + "|]" + linkText + "[/url]";
}
function insertFancyText(tagOpen,target,tagClosed) {
    var spanText = prompt("Please enter the styled text you would like to insert.\nThis will be appended to the current editor contents.");
    target.value += tagOpen + spanText + tagClosed;
}
function insertStyledText(styleName) {
    var spanText = prompt("Please enter the styled text you would like to insert.\nThis will be appended to the current editor contents.");
    document.editPageForm.body.value += "\n<span class=\"" + styleName + "\">" + spanText + "</span>";
    document.editPageForm.body.focus();
}

function newPage(categoryID,subCategoryID) {
    var newPageName = getValidName("Please name the new page.",/^([a-zA-Z0-9_\- ])+$/,"");
    if (newPageName==undefined) {
        return;
    }
    var newPageFileName = getValidName("Please give the new page a filename ending in .asp (e.g. myFile.asp).",/^([a-zA-Z0-9_\-])+\.asp+$/,newPageName + ".asp");
    if (newPageFileName==undefined) {
        return;
    }
    document.location = pageName + "?categoryID=" + categoryID + "&subCategoryID=" + subCategoryID + "&pageAction=newPage&newPageName=" + newPageName + "&newPageFileName=" + newPageFileName;
}
function deletePage(categoryID,subCategoryID,pID) {
    if (confirm("Are you sure you want to delete this page?\n\nTHIS WILL DELETE ALL BACKUPS OF THIS PAGE AS WELL.")) {
        document.location = pageName + "?categoryID=" + categoryID + "&subCategoryID=" + subCategoryID + "&pageID=" + pID + "&pageAction=deletePage";
    }
}
function newSubCategory (categoryID) {
    var newSubCategoryName = getValidName("Please name the new category.",/^([a-zA-Z0-9_\- ])+$/,"");
    if (newSubCategoryName==undefined) {
        return;
    }
    document.location = pageName + "?categoryID=" + categoryID + "&pageAction=newSubCategory&newSubCategoryName=" + newSubCategoryName;
}
function deleteSubCategory(categoryID,subCategoryID) {
    if (confirm("Are you sure?\n\nThis will delete EVERY page in this subcategory!")) {
        document.location = "page.asp?categoryID=" + categoryID + "&subCategoryID=" + subCategoryID + "&pageAction=deleteSubCategory";
    }
}
function confirmLink(link,text) {
    if (confirm(text)) {
        document.location = link;
    }
}
function renameSubCategory(categoryID,subCategoryID,currentName) {
    var newSubCategoryName = getValidName("Please rename the category.",/^([a-zA-Z0-9_\- ])+$/,currentName);
    if (newSubCategoryName==undefined) {
        return;
    }
    //alert("page.asp?categoryID=" + categoryID + "&pageAction=renameSubCategory&subCategoryID=" + subCategoryID + "&newSubCategoryName=" + newSubCategoryName);
    document.location = "page.asp?categoryID=" + categoryID + "&pageAction=renameSubCategory&subCategoryID=" + subCategoryID + "&newSubCategoryName=" + newSubCategoryName;
}
    
function clonePage(categoryID,subCategoryID,pID) {
    var newPageName = getValidName("Please give the new page a title.",/^([a-zA-Z0-9_\- ])+$/);
    if (newPageName==undefined) {
        return;
    }
    var newPageFileName = getValidName("Please give the new page a filename in the format pageName.asp",/^([a-zA-Z0-9_\-])+\.asp+$/,newPageName + ".asp");
    if (newPageFileName==undefined) {
        return;
    }
    document.location = pageName + "?categoryID=" + categoryID + "&subCategoryID=" + subCategoryID + "&pageID=" + pID + "&pageAction=clonePage&newPageName=" + newPageName + "&newPageFileName=" + newPageFileName;
}
	
function getValidName (message,filter,defaultValue) {
    var validName;
//        var pageNameFilter  = /^([a-zA-Z0-9_\-])+\.asp+$/;
//        var pageNameFilter  = /^([a-zA-Z0-9_\- ])+$/;
        
    var i = 0;
    var nameAccepted = false;
   while (!nameAccepted) {
        i = i + 1;
        validName = prompt(message,defaultValue);
            
        // make sure that the page name is not null (i.e. user cancelled)
        if (validName==null) {
            return;
        }

        // check validity of page name
        if (!filter.test(validName)) {
            message = "Page name is invalid; please name this page in the format pageName.asp";
        } else {
            nameAccepted=true;
        }
    }
    return validName;
}
function queryLink(message,target) {
    var value = prompt(message);
    if (value!=null) {
        document.location=target+value;
    }
}

/* *************************************************** */

function getQuickEventDetails(date) {
    /*
    if (isOpera) {
        document.minicon.location = level + "utils/eventsHandler.asp?action=quickList&date=" + date;
    } else {
        window.frames.minicon.location = level + "utils/eventsHandler.asp?action=quickList&date=" + date;
    }
    */
}

var MONTH_NAMES = ["???","Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var dateFilter  = /^([0-9]{1,2})+\-([a-zA-Z]{3,4})+\-([0-9]{4})+$/;
var integerFilter = /^([0-9]{1,2})$/;
var targetField;
var monthMatch = MONTH_NAMES[dCurMonth+1] + "-" + dCurYear;

function highLight(myElement) {
    if (!isNaN(parseInt(myElement))) {
        myElement.style.background="#FFFFFF";
        myElement.style.color="#666666";
    } else {
//        document.getElementById('dateHL').style.visibility="hidden";
    }
}
function unHighLight(myElement) {
    myElement.style.background='';
    myElement.style.color='';
    
}
function trim(s) {
  while (s.substring(0,1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length-1,s.length) == ' ') {
    s = s.substring(0,s.length-1);
  }
  return s;
}

function fSetSelectedDay(myDate, pageName, categoryID){
//	alert("myDate is: "+myDate);
//	alert("pageName is: "+pageName);
//	alert("categoryID is: "+categoryID);
	var dateField1 = myDate;
//	var dateField1 = trim(myElement.substring(0,2));
    if (dateField1 != "" || dateField != undefined || !isNaN(dateField)) {
		document.location=pageName + "?categoryID="+categoryID+"&date=" + dateField1 + "-" + calendarForm.tbSelMonthYear.value;
    } else {
	    document.location=pageName + "?categoryID="+categoryID+"&date=" + 1 + "-" + calendarForm.tbSelMonthYear.value;
	}
}

function fGetDaysInMonth(iMonth, iYear) {
    var dPrevDate = new Date(iYear, iMonth, 0);
    return dPrevDate.getDate();
}

/**
 * Hides a non-null layer
 */
function hideIfExists(layerID) {
    if (document.getElementById(layerID) != null) {
        document.getElementById(layerID).style.visibility='hidden';
    }        
}

/**
 * Shows a non-null layer
 */
function showIfExists(layerID) {
    if (document.getElementById(layerID) != null) {
        document.getElementById(layerID).style.visibility='visible';
    }        
}

/**
 * Try to convert to dates.
 * if user entered their own dates, we can't check, but if they used
 * the calendar or followed the date format we're OK to run a test.
 * Otherwise, return false
 */ 
function cDate (s) {

    var strSD = new String(s);
    
    if (dateFilter.test(s)) {
    
        var sd = new Date();
        
        var arSD = strSD.split("-");

        var monthIndex = 0;

        // find the month #
        for (var i = 0; i < MONTH_NAMES.length; i++) {
            if (
                    String(MONTH_NAMES[i]).toLowerCase()
                        ==
                    String(arSD[1]).toLowerCase()
                )
            {
                monthIndex = i-1;   // -1 to account for ??? being at 0 position
                break;
            }
        }

        sd.setMonth(monthIndex);
        // set up the date        
        sd.setDate(arSD[0]);
        sd.setYear(arSD[2]);
        return sd;
    } else {
        alert ("WARNING - invalid date detected");
        return false;
    }
}


/**
 * Function to set the values of the Date selectors
 * @param theForm The form bearing the date selectors
 */
function resizeDateSelectors(monthYear, dropDay, dropMonthYear) {

    var tmp = monthYear.split("-");
    var month = tmp[0];
    var year = tmp[1];

    var m;
    switch (month) {
        case "Jan": m = 0;break;
        case "Feb": m = 1;break;
        case "Mar": m = 2;break;
        case "Apr": m = 3;break;
        case "May": m = 4;break;
        case "Jun": m = 5;break;
        case "Jul": m = 6;break;
        case "Aug": m = 7;break;
        case "Sep": m = 8;break;
        case "Oct": m = 9;break;
        case "Nov": m = 10;break;
        case "Dec": m = 11;break;
    }
    var y = year;
    var days;

    // find number of days in current month
    if ( (m == 3) || (m == 5) || (m == 8) || (m == 10) ) {
        days = 30;
    }
    else if (m == 1) {
        // check for leapyear - Any year divisible by 4, except those divisible by 100 (but NOT 400)
        if ( (Math.floor(y/4) == (y/4)) && ((Math.floor(y/100) != (y/100)) || (Math.floor(y/400) == (y/400))) )
            days = 29
        else
            days = 28
    }
    else {
        days = 31;
    }
    // if (days in new month > current days) then we must add the extra days to
    // the selector
    var oldLen = dropDay.length;
    if (days > oldLen) {
        dropDay.length = days;
        for (i = oldLen; i < days; i++) {

            if ((i+1)==31) {
                dropDay.options[i].text = (i+1) + "st";
            }
            else {
                dropDay.options[i].text = (i+1) + "th";
            } 

            dropDay.options[i].value = i + 1;
        }
    } else if(days < oldLen) {
        dropDay.length = days;
    }
}

function showEditEventForm(id, eventArray) {
	// Close all other forms
	splitString = String(eventArray).split("|||")
	for (var i = 1; i< splitString.length; i++) {
		if (splitString[i]!='')	{
			document.getElementById('editEventForm'+String(splitString[i])).style.display='none';
		}
	}
	document.getElementById('addEventForm').style.display='none';

	// open selected form
	if (document.getElementById('editEventForm'+id).style.display=='none')
	{
			document.getElementById('editEventForm'+id).style.display='';
	} else {
			document.getElementById('editEventForm'+id).style.display='none';
	}
}

function showAddEventForm(eventArray) {
	// Close all other forms
	splitString = String(eventArray).split("|||")
	for (var i = 1; i< splitString.length; i++) {
		if (splitString[i]!='')	{
			document.getElementById('editEventForm'+String(splitString[i])).style.display='none';
		}
	}
	if (document.getElementById('addEventForm').style.display=='none')
	{
			document.getElementById('addEventForm').style.display='';
	} else {
			document.getElementById('addEventForm').style.display='none';
	}
}
function showRegisterForm() {
    document.getElementById('form3').style.display='none';document.getElementById('form4').style.display='';
}

function addUser() {
    var msg = "";
    if (document.form4.email.value=="") {
        msg += "Please enter an email address\n";
    }
    if (document.form4.password.value=="") {
        msg += "Please enter a password\n";
    }
    else if (document.form4.password.value!=document.form4.password2.value) {
        msg += "Your passwords do not match\n";
    }
    else if (document.form4.password.value.length < 6) {
        msg += "Please make your password at least 6 characters long.\n";
    }
    if (document.form4.forename.value=="") {
        msg += "Please enter your name\n";
    }
    if (document.form4.surname.value=="") {
        msg += "Please enter your surname\n";
    }
    if (document.form4.membershipNo.value=="") {
        msg += "Please enter your membership number\n";
    }
    if (msg == "") {
        document.form4.submit();
    } else {
        alert(msg);
    }
}

function addUserAdmin() {
    var msg = "";
    if (document.form4.surname.value=="") {
        msg += "Please enter your surname\n";
    }
    if (document.form4.membershipNo.value=="") {
        msg += "Please enter your membership number\n";
    }
    if (msg == "") {
        document.form4.submit();
    } else {
        alert(msg);
    }
}

function newDocumentFormSubmit(form) {
    var msg = "";
    if (form.name.value=="") {
        msg += "Please enter an document name\n";
    }
    if (form.newDocument.value=="") {
        msg += "Please enter a file\n";
    } else {
		var tmpNewFile = form.newDocument.value; 
		var tmpExt = ""; 
		tmpExt = tmpNewFile.slice(tmpNewFile.length-3,tmpNewFile.length);

		if ((tmpExt != "txt") && (tmpExt != "doc") && (tmpExt != "xls") && (tmpExt != "ppt") && (tmpExt != "pdf") && (tmpExt != "csv") && (tmpExt != "pot") && (tmpExt != "dot") && (tmpExt != "xml")) {
	        msg += "This file type is not permitted for upload for security reasons\n";
		}
	}
    if (msg == "") {
        form.submit();
    } else {
        alert(msg);
    }
}

function forgottenPassword() {
    if (document.form3.username.value=="") {
        alert("Please enter your email address and we will email your password to you.");
        return;
    }
    if (!emailFilter.test(document.form3.username.value)) {
        alert("Please enter a valid email address and we will email your password to you.");
    } else {
        window.location="page.asp?categoryID=3&subCategoryID=24&pageID=307&action=emailPW&e=" + document.form3.username.value;
    }
}

function showQuickLinks() {
    document.getElementById('QuickLinks').style.display="";
}
function hideQuickLinks() {
    document.getElementById('QuickLinks').style.display="none";
}

function showBranches() {
    document.getElementById('Branches').style.display="";
}
function hideBranches() {
    document.getElementById('Branches').style.display="none";
}

function confirmDelete(targetPage) {
    if (confirm("Are you sure?")) {
        window.location.href=targetPage;
    }
}
function AddForm (level, category, categoryid) {

	var title = prompt("Please enter the title of the form.", "title");
	var subject = prompt("Please enter the subject of the form.", "subject");
	var message = prompt("Please enter the message that a user will see upon completion.", "Thank you for completing our form. Your information has been received by our staff.");
	var email = prompt("Please enter email address to send the form to.", "apm@apm.org.uk");	
//	var category = //prompt("Please enter the category ID.", "4");
//	var categoryid = //prompt("Please enter the sub category ID.", "30");

	var theHTML = "<form name=\"form"+title+"\" action=\"enquirySend.asp\" method=\"post\"><input type=\"hidden\" name=\"subject\" value=\""+subject+"\"><input type=\"hidden\" name=\"emailTo\" value=\""+email+"\"><input type=\"hidden\" name=\"title\" value=\""+title+"\"><input type=\"hidden\" name=\"message\" value=\""+message+"\"><input type=\"hidden\" name=\"categoryID\" value=\""+category+"\"><input type=\"hidden\" name=\"subCategoryID\" value=\""+categoryid+"\"><input type=\"submit\" name=\"formSubmit\" value=\"Send\" /></form>";

	var oRTEeditor = FCKeditorAPI.GetInstance('body');
	oRTEeditor.InsertHtml(theHTML);
}

function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function PopulateFilename(formName) {
	formName.filename.value = "event" + Left(formName.name.value, 8);
}

var sReceivedVal;
var bContinue = false;

function makeRequest(url) {

	var http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
			// See note below about this line
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Giving up - Cannot create an XMLHTTP instance');
		return false;
	}
	http_request.onreadystatechange = function() { alertContents(http_request); };
	http_request.open('GET', url, true);
	http_request.send(null);

}

function alertContents(http_request) {

	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			sReceivedVal = http_request.responseText;
			if(sReceivedVal != document.forms[0].filename.value) {
				if(confirm('The filename you entered for this event is being used by another event, the systems has discovered that the name ' + sReceivedVal + ' is free. Do you want to use this name?')) {
				document.forms[0].filename.value = sReceivedVal;
				document.forms[0].submit();
				}
			} else {
				document.forms[0].submit();
			}

		} else {
			alert('There was a problem with the request.');
		}
	}

}

function CheckAddNewEvent(formName, level) {
	// call a page at the root called CheckEventName.asp
	if(formName.name.value == '') {
		alert('Please enter a name');
		formName.name.focus();
		return false;
	}
	if(formName.filename.value == '') {
		alert('Please enter a filename');
		formName.filename.focus();
		return false;
	}
	
	bContinue = false;
	makeRequest(level + 'CheckEventName.asp?rand=' + Math.floor(Math.random() * 1000000) + '&name=' + formName.filename.value + '&level=' + level);
	return false;
}

// Populates the current day of the month
function populateDays() {
	var OptionList = document.forms[0].tbSelDay;
	for (x = OptionList.length; x >= 0; x--) {
		OptionList[x] = null;
	}

	var tbSelMonthYear = document.forms[0].tbSelMonthYear;
	var sSelOption = tbSelMonthYear.options[tbSelMonthYear.selectedIndex].value;
	var aParts = sSelOption.split('/');
	var sMonth = aParts[0];
	var sYear = aParts[1];

	var dim = daysInMonth(sMonth,sYear);
	for(i=1;i<dim + 1;i++) {
		AddToOptionList(OptionList, i, i);
	}
}

function AddToOptionList(OptionList, OptionValue, OptionText) {
   OptionList[OptionList.length] = new Option(OptionText, OptionValue);
}

function daysInMonth(month,year) {
	//alert(month);
	var m = [31,28,31,30,31,30,31,31,30,31,30,31];
	if (month != 2) return m[month - 1];
	if (year%4 != 0) return m[1];
	if (year%100 == 0 && year%400 != 0) return m[1];
	return m[1] + 1;
}

function init() {
	var currentTime = new Date();
	var month = currentTime.getMonth();
	var year = currentTime.getFullYear();
	var OptionList = document.forms[0].tbSelDay;

	var dim = daysInMonth(month+1,year);
	for(i=1;i<dim + 1;i++) {
		AddToOptionList(OptionList, i, i);
	}
}

function initValue(iValue) {
	populateDays();
	var OptionList = document.forms[0].tbSelDay;
	OptionList.selectedIndex = iValue - 1;
}

///////////////
function populateDaysNews() {
	var OptionList = document.forms[0].Day;
	for (x = OptionList.length; x >= 0; x--) {
		OptionList[x] = null;
	}

	var tbSelMonthYear = document.forms[0].MonthYear;
	var sSelOption = tbSelMonthYear.options[tbSelMonthYear.selectedIndex].value;
//	alert(sSelOption);
	var aParts = sSelOption.split('/');
	var sMonth = aParts[0];
	var sYear = aParts[1];
	var iMonth = parseInt(sMonth);
	var iYear = parseInt(sYear);

	// if this is the current month then fill to the current day
	var currentTime = new Date();
	var currMonth = currentTime.getMonth();
	var currDay = currentTime.getDate();
	var currYear = currentTime.getYear();

	if((iMonth == (currMonth + 1)) && (iYear == currYear)) {
		for(i2=1;i2<currDay + 1;i2++) {
			AddToOptionList(OptionList, i2, i2);
		}
	} else {
		// else fill to te number of days in the month
		var dim = daysInMonth(iMonth,iYear);
		for(i=1;i<dim + 1;i++) {
			AddToOptionList(OptionList, i, i);
		}
	}
}

function initNews() {
	var currentTime = new Date();
	var month = currentTime.getMonth();
	var year = currentTime.getFullYear();
	var days = currentTime.getDate();
	var OptionList = document.forms[0].Day;
	for(i=1;i<days+1;i++) {
		AddToOptionList(OptionList, i, i);
	}
	populateDaysNews();
}

function initNewsValue(iValue) {
//	initNews();
	populateDaysNews();
	var OptionList = document.forms[0].Day;
	OptionList.selectedIndex = iValue - 1;
}

function changeHomepageImages() {

	var generalImageID1;
	var generalImageID2;
	var generalImageID3;
	var generalImageID4;

	// randomise for first position
	generalImageID1 = parseInt((Math.random () * 4) + 1);

	generalImageID2 = generalImageID1;
	while (generalImageID2 == generalImageID1) { generalImageID2 = parseInt((Math.random () * 4) + 1) }
	generalImageID3 = generalImageID1;
	while ((generalImageID3 == generalImageID1) || (generalImageID3 == generalImageID2)) { generalImageID3 = parseInt((Math.random () * 4) + 1) }
	generalImageID4 = generalImageID1;
	while ((generalImageID4 == generalImageID1) || (generalImageID4 == generalImageID2) || (generalImageID4 == generalImageID3)) { generalImageID4 = parseInt((Math.random () * 4) + 1) }

	// set new images
	document.imagePosition1.src = 'downloadImage.asp?homepageImagePosition=1&homepageImageID=' + generalImageID1;
	document.imagePosition2.src = 'downloadImage.asp?homepageImagePosition=2&homepageImageID=' + generalImageID2;
	document.imagePosition3.src = 'downloadImage.asp?homepageImagePosition=3&homepageImageID=' + generalImageID3;
	document.imagePosition4.src = 'downloadImage.asp?homepageImagePosition=4&homepageImageID=' + generalImageID4;

	// delay and start again
	setTimeout('changeHomepageImages()',600000);
	return;
}