﻿/*************************************************
Global variable definitions
*************************************************/
var root = "/";
// used from the rsh.js
var root_rsh = root + "content/_rsh/";
var root_lightbox = root + "content/_lightbox/";

var xConstMapDefaultLat = 52.54;
var xConstMapDefaultLong = -2.12;

/*************************************************
General utilities
*************************************************/
/* General utilities - checks response for an error */
function CheckResponse(request) {
	var errorIndex = request.responseText.indexOf("ERROR");
	if (errorIndex > 0 && errorIndex < 10) {
		errorMessage = request.responseText.substring(errorIndex + 5);
		$("ErrorDiv").style.display = "block";
		$("ErrorDiv").innerHTML = errorMessage;
		MasterFooterRefresh();
		return false;
	} else {
		$("ErrorDiv").style.display = "none";
		MasterFooterRefresh();
		return true;
	}
}

/* General utilities - uses new window to report AJAX call error */
function ReportError(request) {
	if (window.location.host.toLowerCase() != "faithconnections.aws.net") {
		document.body.innerHTML = request.responseText;
	} else {
		window.status = "... error ...";
	}
}

/* General utilities - writes a cookie*/
function SetCookie(name, value) {
	// expires in seven days
	var ExpireDate = new Date();
	ExpireDate.setDate(ExpireDate.getDate() + 7);
	document.cookie = name + "=" + escape(value) + ";expires=" + ExpireDate.toGMTString();
}
/* General utilities - reads a cookie*/
function GetCookie(name) {
	if (document.cookie.length > 0) {
		start = document.cookie.indexOf(name + "=");
		if (start != -1) {
			start += name.length + 1;
			end = document.cookie.indexOf(";", start);
			if (end == -1)
				end = document.cookie.length;
			return unescape(document.cookie.substring(start, end));
		}
	}
	return null;
}
/* General utilities - calls a function when enter in the input is hitted */
function CallFunctionOnEnter(event, func) {
	var keyCode = null;

	if (event.which)
		keyCode = event.which;
	else if (event.keyCode)
		keyCode = event.keyCode;

	if (keyCode == 13) {
		func();
		return false;
	}
	return true;
}

/*************************************************
Master page - Footer IE problem
*************************************************/
function MasterFooterRefresh() {
	$("MasterFooterDiv").hide();
	$("MasterFooterDiv").show();
}

/*************************************************
Master page - Sign in
*************************************************/
function AccountsLoginShowHide() {
	var signInDiv = $("MasterSignInDiv");
	if (signInDiv.getStyle("top") != "-190px") {
		new Effect.Move(signInDiv, { x: 15, y: -190, mode: 'absolute', duration: 1 });
		$("MasterHeaderMenuPersonItemDiv").focus();
		if ($("UserTitle") != null)
			window.setTimeout('$("UserTitle").style.visibility = "visible";', 800);
		if ($("ChartType") != null)
			window.setTimeout('$("ChartType").style.visibility = "visible";', 800);
	} else {
		new Effect.Move(signInDiv, { x: 15, y: 123, mode: 'absolute', duration: 1 });
		window.setTimeout('$("Email").focus();', 1000);
		if ($("UserTitle") != null)
			$("UserTitle").style.visibility = "hidden";
		if ($("ChartType") != null)
			$("ChartType").style.visibility = "hidden";
	}
}
function AccountsLoginPasswordFocus() {
	$("Password").focus();
}
function AccountsLoginSubmit() {
	var parameters = {
	  email: $("Email").value,
	  password: $("Password").value,
	  rememberMe: ($("RememberMe").checked ? "true" : "")
	};
	new Ajax.Request(
    root + "Accounts/Login",
		{
			method: 'post',
			parameters: parameters,
			onSuccess: AccountsLoginSubmitCompleted,
			onFailure: ReportError
		}
  );
	}
function AccountsLoginSubmitCompleted(request) {
	if (request.responseText == "OK") {
		$("MasterSignInResultDiv").innerHTML = "";
		window.location.reload();
	} else {
		$("MasterSignInBodyBackgroundDiv").style.height = "193px";
		$("MasterSignInBottomBarDiv").style.top = "298px";
		$("MasterSignInFooterDiv").style.top = "225px";
		$("MasterSignInResultDiv").innerHTML = request.responseText;
		$("Email").focus();
	}
}

/*************************************************
Master page - Search
*************************************************/
/* Starts a map page and invokes search for specified query */
function Search() {
	var queryInput = $("query");
	if (queryInput != null) {
		xSelectMode('Search');
		queryInput.value = $("MasterSearch").value;
		xSearch();
	} else {
		window.location = root + "Map#Mode=Search&Query=" + $("MasterSearch").value;
	}
}

/*************************************************
Master page - Make content semi-transparent
*************************************************/
function PageBodyHide() {
	$("MasterBodyForegroundDiv").style.display = "block";
	// get height of the whole page - minus top header, bottom header, footer height
	var bodyHeight = $("MasterContainerDiv").getHeight() - (92 + 31 + 46);
	$("MasterBodyForegroundDiv").style.height = bodyHeight.toString() + "px";
	$("MasterBodyForegroundDiv").innerHTML = "<img src='" + root + "Content/img/AjaxLoader.gif'/>";
}
function PageBodyShow() {
	$("MasterBodyForegroundDiv").style.display = "none";
	$("MasterBodyForegroundDiv").style.height = "0px";
	$("MasterBodyForegroundDiv").innerHTML = "";
}
/*************************************************
Accounts - New account page
*************************************************/
var accountsNewMode = null;
function AccountsSwitchMode(value) {
	accountsNewMode = value;

	$("UserTitle").disabled = (accountsNewMode != "user");
	$("UserFirstName").readOnly = (accountsNewMode != "user");
	$("UserLastName").readOnly = (accountsNewMode != "user");
	$("UserPosition").readOnly = (accountsNewMode != "user");
	$("UserPhone").readOnly = (accountsNewMode != "user");
	$("UserEmail").readOnly = (accountsNewMode != "user");

	$("OrganisationName").readOnly = (accountsNewMode != "organisation");
	$("OrganisationAddress1").readOnly = (accountsNewMode != "organisation");
	$("OrganisationAddress2").readOnly = (accountsNewMode != "organisation");
	$("OrganisationBoroughId").disabled = (accountsNewMode != "organisation");
	$("OrganisationTown").readOnly = (accountsNewMode != "organisation");
	$("OrganisationPostCode").readOnly = (accountsNewMode != "organisation");
	$("OrganisationWeb").readOnly = (accountsNewMode != "organisation");

	$("ConfirmationPassword").readOnly = (accountsNewMode != "confirmation");
	$("ConfirmationPasswordCheck").readOnly = (accountsNewMode != "confirmation");
	$("ConfirmationCaptcha").readOnly = (accountsNewMode != "confirmation");

	if (accountsNewMode == "user") {
		$("AccountsNewLeftDiv").removeClassName("SemiTransparent");
		$("AccountsNewLeftForegroundDiv").style.display = "none";
	} else {
		$("AccountsNewLeftDiv").addClassName("SemiTransparent");
		$("AccountsNewLeftForegroundDiv").style.display = "block";
	}

	if (accountsNewMode == "organisation") {
		$("AccountsNewMiddleDiv").removeClassName("SemiTransparent");
		$("AccountsNewMiddleForegroundDiv").style.display = "none";
		$("OrganisationName").focus();
	} else {
		$("AccountsNewMiddleDiv").addClassName("SemiTransparent");
		$("AccountsNewMiddleForegroundDiv").style.display = "block";
	}

	if (accountsNewMode == "confirmation") {
		$("AccountsNewRightDiv").removeClassName("SemiTransparent");
		$("AccountsNewRightForegroundDiv").style.display = "none";
		$("UserTitleDiv").style.display = "block";
		$("UserInformationDiv").style.display = "block";
		$("OrganisationTitleDiv").style.display = "block";
		$("OrganisationInformationDiv").style.display = "block";
	} else {
		$("AccountsNewRightDiv").addClassName("SemiTransparent");
		$("AccountsNewRightForegroundDiv").style.display = "block";
		$("UserTitleDiv").style.display = "none";
		$("UserInformationDiv").style.display = "none";
		$("OrganisationTitleDiv").style.display = "none";
		$("OrganisationInformationDiv").style.display = "none";
	}

	if (accountsNewMode == "user")
		$("UserTitle").focus();

	if (accountsNewMode == "organisation")
		$("OrganisationName").focus();

	if (accountsNewMode == "confirmation")
		$("ConfirmationPassword").focus();
}
/* Accounts - new account, validate user part */
function AccountsValidateUser() {
	if (accountsNewMode != "user")
		return;

	PageBodyHide();
	var params = $("MainForm").serialize(true);
	new Ajax.Request(
    root + "Accounts/ValidateNewUser",
	{
		method: 'post',
		parameters: params,
		onSuccess: AccountsValidateUserCompleted,
		onFailure: ReportError
	}
  );
}
/* Accounts - new account, user part validated */
function AccountsValidateUserCompleted(request) {
	PageBodyShow();
	if (!CheckResponse(request))
		return;
	AccountsSwitchMode("organisation");
}
/* Accounts - new account, back to user part */
function AccountsBackToUser() {
	if (accountsNewMode != "organisation")
		return;

	$("ErrorDiv").style.display = "none";
	AccountsSwitchMode("user");
}
/* Accounts - new account, validate organisation part */
function AccountsValidateOrganisation() {
	if (accountsNewMode != "organisation")
		return;

	PageBodyHide();
	var params = $("MainForm").serialize(true);
	new Ajax.Request(
    root + "Accounts/ValidateNewOrganisation",
	{
		method: 'post',
		parameters: params,
		onSuccess: AccountsValidateOrganisationCompleted,
		onFailure: ReportError
	}
  );
}
/* Accounts - new account, organisation part validated */
function AccountsValidateOrganisationCompleted(request) {
	PageBodyShow();
	if (!CheckResponse(request))
		return;
	AccountsSwitchMode("confirmation");

	var summary = eval("(" + request.responseText + ")");
	$("UserInformationDiv").innerHTML = summary.UserInformation;
	$("OrganisationInformationDiv").innerHTML = summary.OrganisationInformation;
}
/* Accounts - new account, back to organisation part */
function AccountsBackToOrganisation() {
	if (accountsNewMode != "confirmation")
		return;

	$("ErrorDiv").style.display = "none";
	AccountsSwitchMode("organisation");
}
/* Accounts - new account, validate confirmation part */
function AccountsValidateConfirmation() {
	if (accountsNewMode != "confirmation")
		return;

	PageBodyHide();
	var params = $("MainForm").serialize(true);
	new Ajax.Request(
    root + "Accounts/ValidateNewConfirmation",
	{
		method: 'post',
		parameters: params,
		onSuccess: AccountsValidateConfirmationCompleted,
		onFailure: ReportError
	}
  );
}
/* Accounts - new account, organisation part validated */
var accountsCaptchaImageUrl = null;
function AccountsValidateConfirmationCompleted(request) {
	if (!CheckResponse(request)) {
		if (accountsCaptchaImageUrl == null)
			accountsCaptchaImageUrl = $("CaptchaImage").src;
		$("CaptchaImage").src = accountsCaptchaImageUrl + "?random=" + Math.random();
		$("ConfirmationCaptcha").value = "";
		PageBodyShow();
		return;
	}

	$("UserTitle").disabled = false;
	$("UserTitle").style.visibility = "hidden";
	$("OrganisationBoroughId").disabled = false;
	$("OrganisationBoroughId").style.visibility = "hidden";
	$("MainForm").submit();
}
/* Accounts index - send user password */
function AccountsSendPassword(userId) {
   window.location = root + "Accounts/SendPasswordFromAdmin?UserId=" + userId + "&UrlReferrer=" + escape(window.location);
}

/* Accounts index - activate/block account */
function AccountsConfirmUser(userId) {
	window.location = root + "Accounts/Confirm?UserId=" + userId + "&UrlReferrer=" + escape(window.location);
}
/* Accounts index - edit account */
function AccountsEditUser(userId) {
	window.location = root + "Accounts/Edit?UserId=" + userId + "&UrlReferrer=" + escape(window.location);
}
/* Accounts index - search form submit */
function AccountsSearch()
{
  $("FilterForm").submit();
 }
 /* Accounts index - change column ordering */
 function GridOrder(column) {
 	$("Order").value = column;
 	$("FilterForm").submit();
 }
 /* Accounts edit - cancel and return back */
function AccountsEditCancel() {
	var urlReferrer = $("UrlReferrer").value;
	if (urlReferrer != "")
		window.location = urlReferrer;
	else
		window.location = root + "Accounts/Manage";
}
/* Accounts edit - validate inputs and submit form in validation succeeds */
function AccountsEditValidate() {
	PageBodyHide();
	var params = $("MainForm").serialize(true);
	new Ajax.Request(
    root + "Accounts/Validate",
	{
		method: 'post',
		parameters: params,
		onSuccess: AccountsEditValidateCompleted,
		onFailure: ReportError
	}
  );
}
/* Accounts edit - validation completed */
function AccountsEditValidateCompleted(request) {
	if (!CheckResponse(request)) {
		PageBodyShow();
		return;
	}
	$("MainForm").submit();
}

function DocumentsSearch() {
    $("FilterForm").submit();
}

/*************************************************
Search
*************************************************/
/* Toggles switched on/off for subject type */
function DisabledTypesSwitch(type) {
	var enabledValue = $("DisabledTypes").value == null || $("DisabledTypes").value.indexOf(type) == -1;
	DisabledTypesSet(type, !enabledValue);
}
/* Sets switched on/off for subject type */
function DisabledTypesSet(type, enabledValue) {
	var iconTd = $(type + "IconTd");
	var textTd = $(type + "TextTd");
	if (enabledValue) {
		$("DisabledTypes").value = $("DisabledTypes").value.replace(type + ",", "");
		iconTd.title = "Hide";
		iconTd.className = type + "Td";
		textTd.title = "Hide";
		textTd.className = "EnabledTd";
	} else {
		if ($("DisabledTypes").value == null)
			$("DisabledTypes").value = type + ",";
		else
			$("DisabledTypes").value += type + ",";
		iconTd.title = "Show";
		iconTd.className = "BW" + type + "Td";
		textTd.title = "Show";
		textTd.className = "DisabledTd";
	}
}

/*************************************************
Edit screens
*************************************************/
/* Registers Scriptaculous autocompleter with tag list input */
function TagListAutoCompleteRegister() {
	new Ajax.Autocompleter("TagList", "TagListAutoCompleteDiv", root + "TagCloud/AutoComplete", { paramName: "query", updateElement: TagListAutoCompleteUpdateElement });
}
/* Event handler for selecting value from Scriptaculous tag list autocompleter */
function TagListAutoCompleteUpdateElement(selectedLi) {
	var selectedName = selectedLi.innerHTML;
	var tagListValue = $("TagList").value;
	var lastIndexOfComma = tagListValue.lastIndexOf(",");
	if (lastIndexOfComma == -1)
		tagListValue = selectedName;
	else
		tagListValue = tagListValue.substring(0, lastIndexOfComma + 1) + " " + selectedName;
	$("TagList").value = tagListValue;
}
/* Switches tabs in edit screens */
function TabSwitch(linkElement) {
	var divElement = linkElement.parentNode;
	for (var i = 0; i < divElement.parentNode.childNodes.length; i++) {
		var element = divElement.parentNode.childNodes[i];
		if (element == divElement && element.className != "BoxTabSelectedDiv") {
			element.className = "BoxTabSelectedDiv";
			$(element.id.substring(0, element.id.length - 6) + "ContentDiv").style.display = "block";
		}
		if (element != divElement && element.className == "BoxTabSelectedDiv") {
			element.className = "BoxTabItemDiv";
			$(element.id.substring(0, element.id.length - 6) + "ContentDiv").style.display = "none";
		}
	}
	MasterFooterRefresh();
}

/*************************************************
Activities edit
*************************************************/
/* Leaves activity editing page */
function ActivitiesCancel() {
	var activityIdInput = $("ActivityId");
	var organisationIdInput = $("OrganisationId");
	if (activityIdInput)
		window.location = root + "Map#ActivityId=" + activityIdInput.value;
	else if (organisationIdInput)
		window.location = root + "Map#OrganisationId=" + organisationIdInput.value;
	else
		window.history.go(-1);
}
/* Validates activity editing form */
function ActivitiesValidate() {
	PageBodyHide();
	var params = {
		Name: $("Name").value,
		Description: $("Description").value,
		Web: $("Web").value,
		DemographicGroupId: $("DemographicGroupId").value,
		Date: $("Date").value,
		People: $("People").value,
		Men: $("Men").value,
		Women: $("Women").value,
		TagList: $("TagList").value,
		DocumentState: $("DocumentState").value
	};

	new Ajax.Request(
    root + "Activities/Validate",
	{
		method: 'post',
		parameters: params,
		onSuccess: ActivitiesValidateCompleted,
		onFailure: ReportError
	}
  );
}
/* If the validation is OK, the form is submitted */
function ActivitiesValidateCompleted(request) {
	if (!CheckResponse(request)) {
		PageBodyShow();
		return;
	}
	$("MainForm").submit();
}
/* Confirms and deletes sctivity */
function ActivitiesDelete(activityId) {
	if (confirm("Do you really want to delete this activity?")) {
		new Ajax.Request(
			root + "Activities/Delete",
			{
				method: 'post',
				parameters: { ActivityId : activityId },
				onSuccess: ActivitiesDeleteCompleted,
				onFailure: ReportError
			}
		);
	}
}
/* If the activity was succesfully deleted display organisation detail page, 
	otherwise display the error message. */
function ActivitiesDeleteCompleted(request) {
	var result = eval("(" + request.responseText + ")");
	if (result.ErrorMessage) {
		alert(result.ErrorMessage);
	} else if (result.OrganisationId) {
		xSelectDetailFromText(result.OrganisationId, "O");
	}
}

/*************************************************
News edit
*************************************************/
/* Validates news editing form */
function NewsValidate() {
	PageBodyHide();
	// update the value from TinyMCE editor
	$("Text").value = tinyMCE.getContent();

	var params = {
		Name: $("Name").value,
		Text: $("Text").value,
		TagList: $("TagList").value,
		DocumentState: $("DocumentState").value
	};

	new Ajax.Request(
    root + "News/Validate",
	{
		method: 'post',
		parameters: params,
		onSuccess: NewsValidateCompleted,
		onFailure: ReportError
	}
  );
}
/* If the validation is OK, the form is submitted */
function NewsValidateCompleted(request) {
	if (!CheckResponse(request)) {
		PageBodyShow();
		return;
	}
	$("MainForm").submit();
}
/* Confirms and deletes news */
function NewsDelete(newsId) {
	if (confirm("Do you really want to delete this news?"))
		window.location = root + "News/Delete?NewsId=" + newsId.toString();
}

/***************************************************
Location picker
***************************************************/
var map;
var locationType;
var locationShape;
var locationDefaultZoom = 14;
/* Loads the location picker map if it wasn't loaded yet */
function LocationLoadMap() {
	if (map != null)
		return;
		
	if (typeof (VEMap) == "undefined")
		window.setTimeout("LocationLoadMap();", 1000);
	else
		window.setTimeout("LocationLoadMapReally();", 1000);
}
	
function LocationLoadMapReally() {
	$("LocationHolderDiv").style.display = "block";
	$("LocationLoadingDiv").style.display = "none";
	map = new VEMap("LocationMapDiv");
	var currentLatitude = $("Latitude").value;
	var currentLongitude = $("Longitude").value;
	var loadLatitude = (currentLatitude != "" ? currentLatitude : xConstMapDefaultLat);
	var loadLongitude = (currentLongitude != "" ? currentLongitude : xConstMapDefaultLong);
	map.SetDashboardSize(VEDashboardSize.Small);
	map.LoadMap(new VELatLong(loadLatitude, loadLongitude), locationDefaultZoom, VEMapStyle.Hybrid, false, VEMapMode.Mode2D, false);
	map.ClearInfoBoxStyles();
	map.AttachEvent("onclick", LocationMapClick);

	LocationAddPushpin();
}
/* Event for click on map event. Picks the clicked place as a location. */
function LocationMapClick(event) {
	if (event.rightMouseButton) {
		var latlong = map.PixelToLatLong(new VEPixel(event.mapX, event.mapY));
		$("Latitude").value = latlong.Latitude;
		$("Longitude").value = latlong.Longitude;

		LocationAddPushpin();
		$("LocationNone").checked = false;
	}
}
/* Draws a pushpin on the right location on the map. */
function LocationAddPushpin() {
	if (map == null)
		return;
	if (locationShape != null)
		map.DeleteShape(locationShape);

	var currentLatitude = $("Latitude").value;
	var currentLongitude = $("Longitude").value;
	var subjectTypeInput = $("LocationSubjectTypeIcon");
	var subjectTypeIcon;
	if (subjectTypeInput) {
		subjectTypeIcon = subjectTypeInput.value;
	} else {
		subjectTypeIcon = "A" + $("DemographicGroupId").value;
		if (subjectTypeIcon == "A-1")
			subjectTypeIcon = "A1";
	}
	if (currentLatitude != "" && currentLongitude != "") {
		var point = new VELatLong($("Latitude").value, $("Longitude").value);
		locationShape = new VEShape(VEShapeType.Pushpin, point);
		var icon = "Icon" + subjectTypeIcon + ".gif";
		var typeName = "Activity";
		if (subjectTypeInput) {
			if (subjectTypeInput.value == "O")
				typeName = "Organisation";
			else if (subjectTypeInput.value == "N")
				typeName = "News";
		}
		locationShape.SetCustomIcon(root + "content/img/" + icon);
		locationShape.SetTitle("<div class='MapInfoBoxTitleDiv'>" + typeName + " location</div>");
		locationShape.SetDescription("<div class='MapInfoBoxDescriptionDiv'>To set other location right-click anywhere on the map.</div>");
		map.AddShape(locationShape);
	}
}
/* Searches for location specified in the address field. */
function LocationFind() {
	var location = $("Location").value;
	if (location == "") {
		alert("Please enter any part of the address into the Location field (ex. DY8 1TT).");
		return;
	}

	map.Find(null, location + ", United Kingdom", null, null, null, 1, false, false, false, false, LocationFindCompleted);
}
/* If the location was find, puts a pushpin on the map. */
function LocationFindCompleted(layer, resultsArray, places, hasMore, veErrorMessage)
{
  var result;
  if (places && places.length > 0) {
  	$("Latitude").value = places[0].LatLong.Latitude;
  	$("Longitude").value = places[0].LatLong.Longitude;
  	LocationAddPushpin();
  	$("LocationNone").checked = false;
  	map.SetCenterAndZoom(places[0].LatLong, locationDefaultZoom);
  } else {
    alert("Specified location wasn't found.")
  }
}
/* User clicks the "no location" checkbox */
function LocationNoneCheckboxChanged() {
	if ($("LocationNone").checked) {
		// reset the location
		$("Latitude").value = "";
		$("Longitude").value = "";
		LocationAddPushpin()
	} else {
		// tell the user to click the map
		alert("To set a location right-click anywhere on the map.")
		$("LocationNone").checked = true;
	}
}

/*************************************************
Report Abuse
*************************************************/
function ReportAbuse() {
	var activityIdInput = $("ActivityId");
	var organisationIdInput = $("OrganisationId");
	var url = root + "Abuse/Report";
	if (activityIdInput != null)
		url += "?ActivityId=" + activityIdInput.value;
	else if (organisationIdInput != null)
		url += "?OrganisationId=" + organisationIdInput.value;

	window.location = url;
}

/*************************************************
Documents Tab
*************************************************/
function AddDocument(addBtn) {
    //purpose: add and update a document

    //docNum
    docNum = parseInt(addBtn.id.toString().match(/\d{1,}$/)[0]);
    var docNewNum = docNum + 1;		
    
    var addFile = document.getElementById("AddFile");    
    if (addFile.value.length > 0)
    {        
        //UPDATE?
        var updateBit = 0;
        if ($("AddedAuth" + docNum) != null) //update
            updateBit = 1;                    
        
        //Description (hidden input)
        if (!updateBit) {
            var addedDesc = document.createElement("input");
            addedDesc.id = "AddedDesc" + docNum; 
            addedDesc.name = addedDesc.id;
            addedDesc.type = "hidden";
            addedDesc.value = $("AddDesc").value;
            $("AddDescParent").appendChild(addedDesc);
            addedDesc.setAttribute("onchange", "UpdateState(this)");
        } else {
            var addedDesc = $("AddedDesc" + docNum);
            $("AddedDesc" + docNum).value = $("AddDesc").value;       
        }
        $("AddDesc").value = "";        
        
        //Authorization - hidden input
        if (!updateBit) {
            var addedAuth = document.createElement("input");    
            addedAuth.id = "AddedAuth" + docNum;
            addedAuth.name = addedAuth.id;
            addedAuth.type = "hidden";
            if ($("AddPublic").checked)
                addedAuth.value = "public";
            else if ($("AddPrivate").checked)
                addedAuth.value = "private";
            else
                addedAuth.value = "inner circle";   
            $("AddAuthParent").appendChild(addedAuth);
        } else {
            var addedAuth = $("AddedAuth" + docNum);
            if ($("AddPublic").checked)
                $("AddedAuth" + docNum).value = "public";
            else if ($("AddPrivate").checked)
                $("AddedAuth" + docNum).value = "private";
            else
                $("AddedAuth" + docNum).value = "inner circle";
        }
        $("AddPublic").checked = "selected";
        $("AddPrivate").checked = "";
                              
        //File - input
        var addFileNew = document.createElement("input");
        addFileNew.type = "file";
        addFileNew.id = "AddFile";
        addFileNew.name = addFileNew.id;
        addFileNew.className = addFile.className;
        addFileNew.size = addFile.size;
        addFileNew.accept = addFile.accept;
        //setAttribute("onchange", "UpdateState(this)");
        addFileNew.onchange = addFile.onchange;
        //forcing the user to change the path
        addFileNew.onkeypress = addFile.onkeypress;
        addFileNew.onkeydown = addFile.onkeydown;
        addFileNew.onkeyup = addFile.onkeyup;
                
        $("AddFileParent").replaceChild(addFileNew, addFile);
        addFile.id = "AddedFile" + docNum;
        addFile.name = addFile.id;
        addFile.style.display = "none";
        $("AddFileParent").appendChild(addFile);
        
        //ADD button
        if (!updateBit)
            addBtn.id = "AddBtn" + docNewNum;
        else {
            addBtn.id = "AddBtn" + $("AddDocLatestNum").value;            
            addBtn.innerText = "Add file";           
        //Title   
            $("AddTitle").innerHTML = "Add a new document:";
        }
        //update LATEST document NUMBER
        if (!updateBit)
            $("AddDocLatestNum").value = docNewNum;        

        //state
        $("DocumentState").value = "adding";                    
                
        //Li display doc info
        var AddedDocList = $("AddedDocumentList");
        if (!updateBit) {  
            var AddedListLi = document.createElement("li");
            var AddedListLiDiv = document.createElement("div");
            AddedListLi.id = "AddedDocumentLi" + docNum;
            AddedListLiDiv.id = "AddedDocumentLiDiv" + docNum; 
        } else {
            var AddedListLi = $("AddedDocumentLi" + docNum);
            var AddedListLiDiv = $("AddedDocumentLiDiv" + docNum);
        }                
        AddedListLiDiv.innerHTML = "<b>" + addFile.value + "</b> [" + addedAuth.value + "]";      
        AddedListLiDiv.innerHTML += " <a href='javascript: void(0);' onclick='DeleteAddedDocument(" + docNum + ")'>Delete</a>";
        AddedListLiDiv.innerHTML += " <a href='javascript: void(0);' onclick='EditAddedDocument(" + docNum + ")'>Edit</a>";   
        if (addedDesc.value.length > 0)
            AddedListLiDiv.innerHTML += "<br />" + addedDesc.value;
        
        if (!updateBit) {
            AddedDocList.appendChild(AddedListLi);
            AddedListLi.appendChild(AddedListLiDiv);
            document.getElementById("AddedDocumentsTable").style.display = "block";
           }
           MasterFooterRefresh();
    }
    else 
        alert("Please, choose a file.");       
}
function UpdateState(element)
{       
//used by file input and description input in Add new document form
// => the user is unable to edit, delete any document till he or she finishes adding a new onw
        if (element.value.length > 0)
        {
            $("DocumentState").value = "editing";
        }
        else
        {
            $("DocumentState").value = "adding";
        }
}

function EditAddedDocument(docNum)
{
    if ($("DocumentState").value != "editing") {    
        //File input
        var addFile = $("AddFile");
        var addedFile = $("AddedFile" + docNum);
        addedFile.id = "AddFile";
        addedFile.name = addedFile.id;
        addedFile.style.display = "block";  
        $("AddFileParent").replaceChild(addedFile, addFile);

        //Description input
        $("AddDesc").value = $("AddedDesc" + docNum).value;
        
        //Authorization input
        if ($("AddedAuth" + docNum).value == "public") {
            $("AddPublic").checked = "checked";
            $("AddPrivate").checked = "";
            if ($("AddInnerCircle")) { $("AddInnerCircle").checked = ""; }
        } else if ($("AddedAuth" + docNum).value == "private") {
            $("AddPublic").checked = "";
            $("AddPrivate").checked = "checked";
            if ($("AddInnerCircle")) { $("AddInnerCircle").checked = ""; }
        } else {
            $("AddPublic").checked = "";
            $("AddPrivate").checked = "";
            if ($("AddInnerCircle")) { $("AddInnerCircle").checked = "checked"; } else { $("AddPrivate").checked = "checked"; }
        }
        
        //ADD button
        var latestDocNum = $("AddDocLatestNum").value;
        $("AddBtn" + latestDocNum).innerText = "Update file";
        $("AddBtn" + latestDocNum).id = "AddBtn" + docNum;
        
        //Title
        $("AddTitle").innerHTML = "Edit document:";
        
        //state
        $("DocumentState").value = "editing";
    } 
    else 
        alertMessage();
}
function DeleteAddedDocument(docNum)
{
    if ($("DocumentState").value != "editing") {            
        //File input
        var addedFile = $("AddedFile" + docNum);
        if (addedFile != null)
            addedFile.parentNode.removeChild(addedFile);
        
        //Description input
        $("AddedDesc" + docNum).parentNode.removeChild($("AddedDesc" + docNum));
        
        //Authorization input        
        $("AddedAuth" + docNum).parentNode.removeChild($("AddedAuth" + docNum));

        //Li        
        var addedUl = $("AddedDocumentLi" + docNum).parentNode;
        addedUl.removeChild($("AddedDocumentLi" + docNum));
        if (addedUl.childNodes.length == 0)
            $("AddedDocumentsTable").style.display = "none";
    }
    else 
        alertMessage();                   
}
function DbDocumentDelete(docId) {
    if ($("DocumentState").value != "editing") {   
        //File
        if ($("DbFile" + docId) != null)
            $("DbFile" + docId).parentNode.removeChild($("DbFile" + docId));
        
        //Li            
        $("DbLi" + docId).parentNode.removeChild($("DbLi" + docId));

        //deleted files hidden input
        if ($("DbDocumentsDeleted").value.length > 0)
            $("DbDocumentsDeleted").value += "," + docId;
        else
            $("DbDocumentsDeleted").value = docId;
        if ($("DbUl").childNodes.length == 0)
            $("DbDocumentsTable").parentNode.removeChild($("DbDocumentsTable"));
    }
    else 
        alertMessage();        
}
function DbDocumentEdit(docId) {
    if ($("DocumentState").value != "editing") {           
        //File
        if ($("DbFile" + docId) != null) {        
            $("AddFile").style.display = "none";
            $("DbFile" + docId).style.display = "block";
        }
        
        //Description
        $("AddDesc").innerHTML = $("DbFileDesc" + docId).value;
        $("AddDesc").value = $("DbFileDesc" + docId).value;
        
        //Authorization
        if ($("DbFileAuth" + docId).value == "public") {
            $("AddPublic").checked = "checked";
            $("AddPrivate").checked = "";
            if ($("AddInnerCircle")) { $("AddInnerCircle").checked = ""; }
        } else if ($("DbFileAuth" + docId).value == "private") {
            $("AddPublic").checked = "";
            $("AddPrivate").checked = "checked";
            if ($("AddInnerCircle")) {$("AddInnerCircle").checked = ""; }
        } else {
            $("AddPublic").checked = "";
            $("AddPrivate").checked = "";
            if ($("AddInnerCircle")) { $("AddInnerCircle").checked = "checked"; } else { $("AddPrivate").checked = "checked"; }
        }
        
        //ADD button
        var latestDocNum = $("AddDocLatestNum").value;
        $("AddBtn" + latestDocNum).style.display = "none";
        
        //UPDATE button
        $("DbUpdate").style.display = "inline";
        $("DbUpdate").id = "DbUpdate" + docId;
        
        //Title
        if ($("DbFile" + docId) != null)
            //the file name has been already changed
            $("AddTitle").innerHTML = "Edit document:";
        else
            $("AddTitle").innerHTML = "Edit document: <b>" + $("DbLiName" + docId).innerHTML + "</b>";
        
        //state
        $("DocumentState").value = "editing";        
    }
    else 
        alertMessage();  
}
function DbDocumentUpdate(updateBtn) {
    //docId
    docId = parseInt(updateBtn.id.toString().match(/\d{1,}$/)[0]);    
    //File
    var addFile = $("AddFile");    
    if ($("DbFile" + docId) != null) {    
        $("AddFile").style.display = "block";
        $("DbFile" + docId).style.display = "none";        
    } 
    else {     
        if (addFile.value.length > 0) {
            var addFileNew = document.createElement("input");
            addFileNew.type = "file";
            addFileNew.id = "AddFile";
            addFileNew.name = addFileNew.id;
            addFileNew.className = addFile.className;
            addFileNew.size = addFile.size;
            addFileNew.accept = addFile.accept; 

            $("AddFileParent").replaceChild(addFileNew, addFile);
            addFile.id = "DbFile" + docId;
            addFile.name = addFile.id;
            addFile.style.display = "none";
            $("AddFileParent").appendChild(addFile);                
        }
    }        
    //Description
    $("DbFileDesc" + docId).value = $("AddDesc").value;
    $("AddDesc").value = "";    
    
    //Authorization
    if ($("AddPublic").checked)
        $("DbFileAuth" + docId).value = "public";
    else if ($("AddPrivate").checked)
        $("DbFileAuth" + docId).value = "private";
    else
        $("DbFileAuth" + docId).value = "inner circle"; 
        
    $("AddPublic").checked = "";
    $("AddPrivate").checked = "checked";        
    
    //Edited files hidden input    
    if ($("DbDocumentsEdited").value.length > 0)
        $("DbDocumentsEdited").value += "," + docId;
    else
        $("DbDocumentsEdited").value = docId;
    
    //UPDATE btn - hide
    updateBtn.style.display = "none";
    updateBtn.id = "DbUpdate";
        
    //ADD btn - show
    var latestDocNum = $("AddDocLatestNum").value;
    $("AddBtn" + latestDocNum).style.display = "inline";   
    
    //update Li
    $("DbLiDesc" + docId).innerHTML = $("DbFileDesc" + docId).value;
    $("DbLiAuth" + docId).innerHTML = $("DbFileAuth" + docId).value;
    if ($("DbFile" + docId) != null) {    
        $("DbLiName" + docId).innerHTML = $("DbFile" + docId).value;
        if (addFile.value.length > 0)    
            $("DbLiName" + docId).innerHTML = addFile.value;    
    }
    //Title
    $("AddTitle").innerHTML = "Add a new document:";
    $("AddFileTitle").innerHTML = "File:";
    
    //state
    $("DocumentState").value = "adding";        
}
function alertMessage() {
    alert("Please, first finish editing the file.");
}

/*************************************************
Organisation Edit
*************************************************/
/* Other faith - text box */
function OnChangeFaith(element) {
    var index = element.selectedIndex;    
    if (element.options[index].innerHTML == "Other")
        $("FaithOtherTr").style.visibility = "visible";
    else
        $("FaithOtherTr").style.visibility = "hidden";                            
}

/*Other BuildingUsedByOtherGroups*/
function DisplayBuildingOther(turnOn) {
    if (turnOn)
        $("BuildingOtherGroupsTr").style.visibility = "visible";
    else
        $("BuildingOtherGroupsTr").style.visibility = "hidden"; 
}

/* Leaves organisation editing page */
function OrganisationsEditCancel() {
	var organisationIdInput = $("OrganisationId");
	if (organisationIdInput != null)
		window.location = root + "Map#OrganisationId=" + parseInt(organisationIdInput.value);
	else
		window.history.go(-1);
}
function OrganisationsEditValidate() {
	PageBodyHide();
	var params = {
		OrganisationName: $("OrganisationName").value,
		OrganisationDescription: $("OrganisationDescription").value,
		OrganisationWeb: $("OrganisationWeb").value,
		OrganisationAddress1: $("OrganisationAddress1").value,
		OrganisationBoroughId: $("OrganisationBoroughId").value,
		OrganisationTown: $("OrganisationTown").value,
		OrganisationPostCode: $("OrganisationPostCode").value,		
		StaffFullTime: $("StaffFullTime").value,
        StaffPartTime: $("StaffPartTime").value,
        VolunteersNumMin: $("VolunteersNumMin").value,
        VolunteersNumMax: $("VolunteersNumMax").value,
        VolunteersHoursMin: $("VolunteersHoursMin").value,
        VolunteersHoursMax: $("VolunteersHoursMax").value,
        AttendaceMin: $("AttendaceMin").value,
        AttendaceMax: $("AttendaceMax").value,
        TagList: $("TagList").value,
        DocumentState: $("DocumentState").value
	};

	new Ajax.Request(
	root + "Organisations/Validate",
	{
		method: 'post',
		parameters: params,
		onSuccess: OrganisationsValidateCompleted,
		onFailure: ReportError
	}
  );
    return false;
}
function OrganisationsValidateCompleted(request) {
	if (!CheckResponse(request)) {
		PageBodyShow();
		return;
	}
	$("MainForm").submit();
}

/***************************************************
Organisation Edit - Resources Tab
***************************************************/
function OrganisationsResourcesSelectChange(mode) {
	$("Resources" + mode + "RemoveButton").show();
	$("Resources" + mode + "EditButton").show();
}

function OrganisationsResourcesEdit(mode) {
    if ($("ResState").value != "adding") {
        alert("Please, finish updating a resource.");
        return;
    }
    //buttons
    $("Resources" + mode + "AddButton").hide();
    $("Resources" + mode + "UpdateButton").show();
    $("Resources" + mode + "CancelButton").show();
    $("Resources" + mode + "EditButton").hide();
    $("Resources" + mode + "RemoveButton").hide();
    
    var selectElement = $("Resources" + mode + "Select");
	var selectedOption = selectElement.options[selectElement.selectedIndex];
    if (selectedOption.id.substr(0,2) == "Db") {
        //db resource, copy content to the form
        var resId = parseInt(selectedOption.id.toString().match(/\d{1,}$/)[0]);
        $("Resources" + mode + "NameInput").value = $("DbResName" + resId).value;
        $("Resources" + mode + "CountInput").value = $("DbResCount" + resId).value;
        $("ResState").value = "DbEditing" + resId;
    }
    else {    
        //copy content to the form
        var resNum = parseInt(selectedOption.id.toString().match(/\d{1,}$/)[0]);
        $("Resources" + mode + "NameInput").value = $("NewResName" + resNum).value;
        $("Resources" + mode + "CountInput").value = $("NewResCount" + resNum).value;
        $("ResState").value = "Editing" + resNum;
    }        
}

function OrganisationsResourcesAdd(mode) {
	var newName = $("Resources" + mode + "NameInput").value;	
	var newCount = $("Resources" + mode + "CountInput").value;
	var result = addOrUpdateResource(null, null, newName, newCount, mode);
	if (!result) return;
    // reset the text input
	$("Resources" + mode + "NameInput").value = "";
	$("Resources" + mode + "CountInput").value = "";			
}

function OrganisationsResourcesUpdate(mode) {
    //updated values
  	var updatedName = $("Resources" + mode + "NameInput").value;	
	var updatedCount = $("Resources" + mode + "CountInput").value;
    
   	var selectElement = $("Resources" + mode + "Select");
   	var selectedOption = selectElement.options[selectElement.selectedIndex];
    
    var result = false;
    if ($("ResState").value.substr(0,2) == "Db") {
        var resId = parseInt(selectedOption.id.toString().match(/\d{1,}$/)[0]);
        result = addOrUpdateResource(true, resId, updatedName, updatedCount, mode)	
        if (!result) return;
    }
    else {
        var resNum = parseInt(selectedOption.id.toString().match(/\d{1,}$/)[0]);
        result = addOrUpdateResource(false, resNum, updatedName, updatedCount, mode)	
        if (!result) return;
    }
    
	// reset the text input
	$("Resources" + mode + "NameInput").value = "";
	$("Resources" + mode + "CountInput").value = "";
	
	//state        
    $("ResState").value = "adding";

    //buttons
    $("Resources" + mode + "AddButton").show();
    $("Resources" + mode + "UpdateButton").hide();
    $("Resources" + mode + "CancelButton").hide();
}

function OrganisationsResourcesCancel(mode) {
    //buttons
    $("Resources" + mode + "AddButton").show()
    $("Resources" + mode + "UpdateButton").hide();
    $("Resources" + mode + "CancelButton").hide();
    //anable edit, remove buttons
    $("Resources" + mode + "EditButton").show();
    $("Resources" + mode + "RemoveButton").show();
    //content
    $("Resources" + mode + "NameInput").value = "";
    $("Resources" + mode + "CountInput").value = "";       
    //state
    $("ResState").value = "adding";   
}

function OrganisationsResourcesRemove(mode) {
    if ($("ResState").value != "adding") {
        alert("Please, finish updating a resource.");
        return;
    }
	var selectElement = $("Resources" + mode + "Select");
	var selectedOption = selectElement.options[selectElement.selectedIndex];
    if (selectedOption.id.substr(0,2) == "Db") {
        var resId = parseInt(selectedOption.id.toString().match(/\d{1,}$/)[0]);
        //remove hidden inputs
        $("ResourceParentDiv").removeChild($("DbResName" + resId));
        $("ResourceParentDiv").removeChild($("DbResCount" + resId));               
        //mark resource as deleted
        if ($("DbResDelete").value.length > 0)
            $("DbResDelete").value += "," + resId.toString();
        else
            $("DbResDelete").value = resId.toString();           
    } 
    else {       
        var resNum = parseInt(selectedOption.id.toString().match(/\d{1,}$/)[0]);
        //remove hidden inputs
        $("ResourceParentDiv").removeChild($("NewResName" + resNum));
        $("ResourceParentDiv").removeChild($("NewResCount" + resNum));     
        $("ResourceParentDiv").removeChild($("NewResMode" + resNum)); 
	}
    //delete option element
    selectElement.removeChild(selectedOption);
    $("Resources" + mode + "RemoveButton").hide();
    $("Resources" + mode + "EditButton").hide();
}

function addOrUpdateResource(db, id, name, count, mode) {			
	// validation
	name = trim(name);
	count = trim(count);
	// check for empty resource name
	if (name == "") {
		alert("Please enter a resource name.");
		return false;
	}
    // check for empty and non numerical resource count
	if (trim(count).length != "") {
	    if (!isNumeric(count)) { 
            alert("Count must be a number");
            return false;
        }
    }	                 
    // is it update? yes, remove old entries  	     
    if (id != null) {
        //remove option
        if (db)
            $("DbRes" + id).parentNode.removeChild($("DbRes" + id));
        else
            $("NewRes" + mode + id).parentNode.removeChild($("NewRes" + mode + id));
    } 
        
	var nameLowerCase = name.toLowerCase();    
	// check for duplicated resource name
	var selectElement = $("Resources" + mode + "Select");
	var selectElementOptions = selectElement.options;
	var selectElementLength = selectElementOptions.length;
	for (var i = 0; i < selectElementLength; i++) {
		if (selectElementOptions[i].value.toLowerCase() == nameLowerCase) {
			alert("This resource is already on the list.");
			return;
		}
	}
	// find the right place where to put the element
	var newIndex = -1;
	for (i = 0; i < selectElementLength; i++) {
		if (selectElementOptions[i].value.toLowerCase().localeCompare(nameLowerCase) < 1) {
			newIndex = i;
		}
	}
	newIndex++;
            
	// create a new element	
	var counter = null;
	var newOption = document.createElement("option");
	if (count != "")
	    newOption.text = name + " (" + count + ")";
	else
	    newOption.text = name;
	    
	if (id != null) {
	    if (db) {
	        newOption.id = "DbRes" + id;
	    }
	    else {
	        newOption.id = "NewRes" + mode + id;
	    }	    
	}
	else {	    	    
        try {
            counter = parseInt($("ResCounter").value.match(/\d{1,}$/)[0]);
        }
        catch (ex) {
            counter = 0;
        }    
        counter++;
	    newOption.id = "NewRes" + mode + counter.toString();	        
    }    
	// insert the option element into select
	try {
		selectElement.add(newOption, selectElementOptions[newIndex]); // FF and others
	}
	catch (ex) {
		selectElement.add(newOption, newIndex); // IE
	}

    if (id != null) {
        if (db) {
            $("DbResName" + id).value = name;
            $("DbResCount" + id).value = count;
            if ($("DbResEdit").value.length > 0)
                $("DbResEdit").value += "," + id;
            else
                $("DbResEdit").value = id;                                  
        }
        else {
            $("NewResName" + id).value = name;
            $("NewResCount" + id).value = count;
        }         
    }
    else {        
        //create Name hidden inputs
        var nameHiddenInput = document.createElement("input");
        nameHiddenInput.type = "hidden";
        nameHiddenInput.id = "NewResName" + counter;
        nameHiddenInput.name = nameHiddenInput.id;
        nameHiddenInput.value = $("Resources" + mode + "NameInput").value;    
        $("ResourceParentDiv").appendChild(nameHiddenInput);        
        
        //create Count hidden input    
        var countHiddenInput = document.createElement("input");
        countHiddenInput.type = "hidden";
        countHiddenInput.id = "NewResCount" + counter;
        countHiddenInput.name = countHiddenInput.id;
        countHiddenInput.value = $("Resources" + mode + "CountInput").value;
        $("ResourceParentDiv").appendChild(countHiddenInput); 
        
        //create Mode hidden input
        var modeHiddenInput = document.createElement("input");
        modeHiddenInput.type = "hidden";
        modeHiddenInput.id = "NewResMode" + counter;
        modeHiddenInput.name = modeHiddenInput.id;
        modeHiddenInput.value = mode;
        $("ResourceParentDiv").appendChild(modeHiddenInput); 

        
        //update ResCounter hidden input
        $("ResCounter").value = counter;
    }
    return true;   
}



// Helpers
function isNumeric(value) {
    if (value != null) {
        value = trim(value);
        if (value.toString().match(/^\d{1,}$/))
            return true;
    }
    return false;        
}
function trim(value) {
   var temp = value;
   var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
   if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
   var obj = /  /g;
   while (temp.match(obj)) { temp = temp.replace(obj, " "); }
   return temp;
  }

