/* Global Variables */
var login_slide = null;
var mpop = null;

function $(id) { return document.getElementById(id); }

var Site = 
{
	// Allows a script element to be added to the DOM resulting in 
	// a parallel load
	AddScript : function(source)
	{
		var scriptElem = document.createElement('script');
		scriptElem.src = source;
		scriptElem.type = 'text/javascript';
		document.getElementsByTagName('head')[0].appendChild(scriptElem);
	},
	
	// Performs critical initializations that need to be done at load time
	Init : function()
	{
		if ($('login-form') != null)
			login_slide = new Spry.Effect.Slide('login-form', 
				{horizontal: true, from: '0%', to: '100%', toggle: true});

		mpop = new Site.ModalPopup('popup', 'popupBack');
	},
	
	RegisterConfirm : function()
	{
		if (confirm('Please note that you can not change your registered names without a valid reason in the future.'))
			return true;
		return false;	
	},
	
	// Toggles the login form in and out
	Login : function()
	{
		login_slide.start();
	},
	
	
	SendEmail : function(accountId)
	{
		var form = '<form class="generic" onsubmit="return Site.SendEmailSubmit()" method="post">' +
				   '<input id="input_AccountId" type="hidden" value="' + accountId + '" />' + 
				   '<table border="0" cellpadding="5" cellspacing="0" class="fulltable">' +
				   '<tr><td width="20%">Subject</td><td><input id="input_Subject" class="size5" type="text" /> <span class="error" id="s_subject"></span></td></tr>' +
				   '<tr><td colspan="2">Message<br /><textarea id="textarea_Message" rows="10"></textarea> <span class="error" id="s_message"></span></td></tr>' +
				   '<tr><td colspan="2"><input type="submit" value="Send" /> <input type="button" onclick="mpop.Close()" value="Cancel" /></td></tr>' + 
				   '</table>';
		mpop.Show(form, 500);
	},
	
	SendEmailSubmit : function()
	{
		var accountId = $("input_AccountId").value;
		var subject = $('input_Subject').value;
		var message = $('textarea_Message').value;
		Ajax.Mailer_SendEmail(accountId, subject, message);
		return false;
	},
	
	SendAdminEmail : function(accountId)
	{
		var form = '<form class="generic" onsubmit="return Site.SendAdminEmailSubmit()" method="post">' +
				   '<input id="input_AccountId" type="hidden" value="' + accountId + '" />' + 
				   '<table border="0" cellpadding="5" cellspacing="0" class="fulltable">' +
				   '<tr><td width="30%">Your Email Address</td><td><input id="input_From" class="size4" type="text" /> <span class="error" id="s_from"></span></td></tr>' +
				   '<tr><td width="20%">Subject</td><td><input id="input_Subject" class="size5" type="text" /> <span class="error" id="s_subject"></span></td></tr>' +
				   '<tr><td colspan="2">Message<br /><textarea id="textarea_Message" rows="10"></textarea> <span class="error" id="s_message"></span></td></tr>' +
				   '<tr><td colspan="2"><input type="submit" value="Send" /> <input type="button" onclick="mpop.Close()" value="Cancel" /></td></tr>' + 
				   '</table>';
		mpop.Show(form, 500);
	},
	
	SendAdminEmailSubmit : function()
	{
		var accountId = $("input_AccountId").value;
		var subject = $('input_Subject').value;
		var message = $('textarea_Message').value;
		var from = $('input_From').value;
		Ajax.Mailer_SendEmail(accountId, subject, message, from);
		return false;
	},

		
	ModalPopup : function(id, backid)
	{
		this.id = id;
		this.backid = backid;
		
		this.CreateDiv = function(id)
		{
			var div = document.createElement('div');
			div.id = id;
			div.style.top = '';
			document.getElementsByTagName('body')[0].appendChild(div);	
		}
		
		if ($(this.id) == null)
			this.CreateDiv(this.id);
		if ($(this.backid) == null)
			this.CreateDiv(this.backid);
			
		this.Show = function(content, width, height, top)
		{
			var offset = Site.GetOffset();
			var dim = Site.GetClientDimensions();
			var pagesize = Site.GetPageSize();
	
			$(this.id).innerHTML = content;
			$(this.id).style.visibility = 'hidden';
			$(this.id).style.display = 'block';
			
			if (this.backid != '')
			{
				$(this.backid).style.width = pagesize[0] + 'px';
				$(this.backid).style.height = pagesize[1] + 'px';
				$(this.backid).style.display = 'block';
			}
			
			$(this.id).style.width = (!width || width==null) ? 'auto' : width+'px';
			$(this.id).style.height = (!height || height==null) ? 'auto' : height+'px';
			$(this.id).style.left = (dim[0]/2 - $(this.id).offsetWidth/2) + 'px';
			if (!top || top==null)
			{
				if (dim[1] < $(this.id).offsetHeight)
					$(this.id).style.top = offset[1]+'px';
				else
					$(this.id).style.top = (offset[1]+(dim[1]/2 - $(this.id).offsetHeight/2)) + 'px';
			}
			else
				$(this.id).style.top = (offset[1] + top) +'px';
	
			$(this.id).style.visibility = 'visible';
		}
		
		this.Close = function()
		{
			$(this.id).innerHTML = '';
			$(this.id).style.display = 'none';
			if (this.backid != '')
				$(this.backid).style.display = 'none';
		}
	},
	
	GetClientDimensions : function()
	{
		var w,h;
		if(document.innerWidth){ 
			w = document.innerWidth;
			h = document.innerHeight;
		} 
		else if(document.documentElement.clientWidth) { 
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		} else if(document.body) { 
			w = document.body.clientWidth; 
			h = document.body.clientHeight; 
		}
		return new Array(w, h);
	},
	
	FindPosition : function(elem)
	{
	    var curleft = 0;
	    var curtop = 0;
	
		if (elem.offsetParent) {
			while (elem.offsetParent) {
				curleft += elem.offsetLeft
				curtop += elem.offsetTop
				elem = elem.offsetParent;
			}
		}
		else if (elem.x) {
			curleft += elem.x;
			curtop += elem.x;
		}
	    
	    return { x : curleft , y : curtop }
	},
	
	GetPageSize : function()
	{
		if (window.innerHeight && window.scrollMaxY) {// Firefox
			y = window.innerHeight + window.scrollMaxY;
			x = window.innerWidth + window.scrollMaxX;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			y = document.body.scrollHeight;
			x = document.body.scrollWidth;
		} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		
			y = document.body.offsetHeight;
			x = document.body.offsetWidth;
	  	}
		
		var dim = Site.GetClientDimensions();
		if (dim[1] > y)
			y = dim[1];
		
		return new Array(x, y);
	},
	
	GetOffset : function()
	{
		var x,y;
		if (self.pageYOffset) // all except Explorer
		{
			x = self.pageXOffset;
			y = self.pageYOffset;
		}
		else if (document.documentElement && document.documentElement.scrollTop)
			// Explorer 6 Strict
		{
			x = document.documentElement.scrollLeft;
			y = document.documentElement.scrollTop;
		}
		else if (document.body) // all other Explorers
		{
			x = document.body.scrollLeft;
			y = document.body.scrollTop;
		}
		return new Array(x, y);
	},
	
	
	Content :
	{
		
		ClearContent : function(contentId)
		{
			if (confirm('Are you sure you want to erase all content in this page? The process is irreversible!'))
				Ajax.ContentManager_ClearContent(contentId);	
			setTimeout("Site.Forum.Refresh()", 400);	//used to refresh the page.	
		},
		
		// Make an ajax call taking the group ID to update the admin panels (user, group users)
		UpdateAdminPanel : function()
		{
			var groups = $('select_Groups'); // groups dropdown select
			var gIndex = groups.selectedIndex; // the index that was seected
			var groupId = this.GetIdValue(groups[gIndex].id) > 0 ? this.GetIdValue(groups[gIndex].id) : 0;
			
			Ajax.ContentManager_UpdateAdminPanel(groupId);
		},
		
		// takes an id in the form string-whatever-id and returns the integer at the end
		GetIdValue : function(id)
		{
			var parts = id.split('-');
			return parseInt(parts[parts.length-1]);
		},
		
		AddUserToGroup : function()
		{
			var users = $('select_Users');
			//var uIndex = users.selectedIndex;
			var groups = $('select_Groups');
			var gIndex = groups.selectedIndex;
			for (var i=0; i < users.options.length; ++i)
				if (users.options[i].selected)
					Ajax.ContentManager_AddUserToGroup(this.GetIdValue(groups[gIndex].id), this.GetIdValue(users[i].id));
		},
		
		RemoveUserFromGroup : function()
		{
			var users = $('select_Users2');
			//var uIndex = users.selectedIndex;
			var groups = $('select_Groups');
			var gIndex = groups.selectedIndex;
			for (var i=0; i < users.options.length; ++i)
				if (users.options[i].selected)
					Ajax.ContentManager_RemoveUserFromGroup(this.GetIdValue(groups[gIndex].id), this.GetIdValue(users[i].id));
		},
		
		DeleteUser : function()
		{
			var users = $('select_Users');
			var groups = $('select_Groups')
			var gIndex = groups.selectedIndex;
			var groupID=groups[gIndex].id;
			var name = '';
			var userID = '';
			for (var i=0; i < users.options.length; ++i)
			{
				if (users.options[i].selected)
				{
					userID = users[i].id; 
					name = users[i].value;
					if (confirm('Are you sure you want to permanently remove ' + name + ' from the system?'))
					{
						Ajax.ContentManager_DeleteUser(userID, groupID);
					}					
				}
			}
		}, 
		
		/*
		DeleteGroup : function()
		{
			var groups = $('select_Users');
			var gi = groups.selectedIndex;
			if (confirm('Are you sure you want to delete this group?'))
				Ajax.ContentManager_DeleteGroup(this.GetIdValue(groups[gi].id));
		},*/
		
		DisplayGroupSelect : function()
		{
			Ajax.ContentManager_DisplayGroups2(); // fill the div above with a select box containing the groups
		},
		
		/*DisplayAddGroup : function()
		{
			$('addgroup').innerHTML = '<input id="input_NewGroupName" type="text" /> <input type="button" onclick="Site.AddGroup()" value="Add Group" /> <a onclick="Site.DisplayGroupSelect()">cancel</a>';
		},*/
		
		DisplayUsers : function()
		{
			// use the selected group's id to display the correct user list
			var gid = $('select_Groups')[$('select_Groups').selectedIndex].id;
			Ajax.ContentManager_DisplayUsers(gid); // display the users in the select box
			$('admButton1').value = 'Add User';
			$('admButton1').onclick = function () { Site.AddUserToGroup(); }
			$('admButton2').value = 'Delete User';
			$('admButton2').onclick = function () { Site.RemoveUserFromGroup(); } 	
		},
		
		/*DisplayUsersOrGroups : function()
		{
			if ($('radio_Users').checked)
			{
				// use the selected group's id to display the correct user list
				var gid = $('select_Groups')[$('select_Groups').selectedIndex].id;
				Ajax.ContentManager_DisplayUsers(gid); // display the users in the select box
				$('admButton1').value = 'Add User';
				$('admButton1').onclick = function () { Site.AddUserToGroup(); }
				$('admButton2').value = 'Delete User';
				$('admButton2').onclick = function () { Site.RemoveUserFromGroup(); } 
			}
			else 
			{
				Ajax.ContentManager_DisplayGroups(); // display the groups in the select box
				$('admButton1').value = 'Copy Group';
				$('admButton1').onclick = function () { Site.CopyGroup(); }
				$('admButton2').value = 'Delete Group';
				$('admButton2').onclick = function () { Site.DeleteGroup(); }
			}	
		},
		
		AddGroup : function()
		{
			var name = $('input_NewGroupName').value;
			Ajax.ContentManager_AddGroup(name);
		},
		
		CopyGroup : function()
		{
			var fromGroupId = $('select_Users')[$('select_Users').selectedIndex].id;
			var toGroupId = $('select_Groups')[$('select_Groups').selectedIndex].id;
			if ($('radio_Groups').checked)
				Ajax.ContentManager_CopyGroup(this.GetIdValue(fromGroupId), this.GetIdValue(toGroupId));
		},*/
		
		Search : function()
		{
			var searchKey = $('input_SearchKey').value;
			var groupId = $('select_Groups')[$('select_Groups').selectedIndex].id;
			
			Ajax.ContentManager_SearchUsers(searchKey, groupId);
			/*
			if ($('radio_Users').checked)
				
			else if ($('radio_Groups').checked)
				Ajax.ContentManager_SearchGroups(searchKey);
			*/	
		},
		
		ShowPermissions : function(contentId)
		{
			Ajax.ContentManager_ShowPermissions(contentId);
		},
		
		UpdatePermissions : function(contentId)
		{
			var group = $('select_AssignedGroup')[$('select_AssignedGroup').selectedIndex].id.split("-");
			var groupId = group[group.length - 1];
			
			var pub = $('input_Public').checked ? 1 : 0;
			var read = $('input_Read').checked ? 1 : 0;
			var write = $('input_Write').checked ? 1 : 0;
			Ajax.ContentManager_UpdatePermissions(contentId, groupId, pub, read, write);
		}
	},
	
	
	// The functions that are belonging to the Forum section are grouped here
	Forum : 
	{
		GetTopic : function(topicId)
		{
			Ajax.Forum_GetTopic(topicId);	
		},
		
		GetReply : function(replyId)
		{
			Ajax.Forum_GetReply(replyId);	
		},
		
		Refresh : function()
		{
			window.location = window.location.href;
		},
		
		ToForum : function()
		{
			var address = window.location.hostname + '/forum';
			window.location = "http://www.cisereupi.org/forum";
		},
		
		
		DeleteTopic : function(topicId)
		{
			if (confirm('Are you sure you want to permanently remove this topic and all its replies?'))
				Ajax.Forum_DeleteTopic(topicId);	
			setTimeout("Site.Forum.Refresh()", 400);	//used to refresh the page.	
		},
		
		DeleteTopicFromPost : function(topicId)
		{
			if (confirm('Are you sure you want to permanently remove this topic and all its replies?'))
				Ajax.Forum_DeleteTopic(topicId);	
			setTimeout("Site.Forum.ToForum()", 400);	//used to refresh the page.		
		},
		
		EditTopic : function(topicId)
		{
			var message = $('textarea_Message').value;
			Ajax.Forum_EditTopic(topicId, message);
			setTimeout("Site.Forum.Refresh()", 400);
			mpop.Close();
			return false;
		},
		
		DeleteReply : function(replyId)
		{
			if (confirm('Are you sure you want to permanently delete this reply?'))
				Ajax.Forum_DeleteReply(replyId);	
			setTimeout("Site.Forum.Refresh()", 400);	
		},
		
		
		EditReply : function(replyId)
		{
			var message = $('textarea_Message').value;
			Ajax.Forum_EditReply(replyId, message);
			setTimeout("Site.Forum.Refresh()", 400);
			mpop.Close();
			return false;
		},
		
		
		
		ApproveTopic : function(topicId)
		{
			Ajax.Forum_ApproveTopic(topicId);
			setTimeout("Site.Forum.Refresh()", 400);
		},		
		
		ApproveTopicRemote : function(topicId)
		{
			Ajax.Forum_ApproveTopic(topicId);
			setTimeout("Site.Forum.ToForum()", 400);
		},
		
		RejectTopicComment : function(topicId)
		{
			Ajax.Forum_RejectTopicComment(topicId);	
		},
		
		RejectTopic : function(topicId)
		{
			
			var message = $('textarea_Message').value;
			Ajax.Forum_RejectTopic(topicId, message);
			setTimeout("Site.Forum.ToForum()", 400);
			mpop.Close();
			return false;	
		},
		
		
		ApproveReply : function(replyId, topicId)
		{
			Ajax.Forum_ApproveReply(replyId, topicId);
			setTimeout("Site.Forum.Refresh()", 400);
		},
		
		ApproveReplyRemote : function(replyId, topicId)
		{
			Ajax.Forum_ApproveReply(replyId, topicId);			
			setTimeout("Site.Forum.ToForum()", 400);
		},
		
		
		RejectReplyComment : function(postId, methodId)
		{
			Ajax.Forum_RejectReplyComment(postId, methodId);	
		},
		
		RejectReply : function(postId, methodId)
		{
			
			var message = $('textarea_Message').value;
			Ajax.Forum_RejectReply(postId, message);
			if (methodId == 2)
				setTimeout("Site.Forum.ToForum()", 400)
			else				
				setTimeout("Site.Forum.Refresh()", 400);
			mpop.Close();
			return false;	
		},
		
		Subscribe : function($topicId, $userId)
		{
			Ajax.Forum_Subscribe($topicId, $userId);
			setTimeout("Site.Forum.Refresh()", 400);
			
		},
		
		UnSubscribe : function($topicId, $userId)
		{
			Ajax.Forum_UnSubscribe($topicId, $userId);
			setTimeout("Site.Forum.Refresh()", 400);
		},
		
		DisplayUsersOrGroups : function()
		{
			if ($('radio_Users').checked)
			{
				// use the selected group's id to display the correct user list 
				//(the users in the group will not be displayed)
				var groupid = this.GetIdValue($('select_Groups')[$('select_Groups').selectedIndex].id);
				
				// display the users in the select box, excluding the ones that are already in the group
				Ajax.ForumManager_DisplayUsers(groupid); 
				
				$('admButton1').value = 'Add User';
				$('admButton1').onclick = function () { Site.Forum.AddUserToGroup(); }
				$('admButton2').value = 'Deactivate';
				$('admButton2').style.visibility = "visible"; 
				$('admButton2').onclick = function () { Site.Forum.DeactivateUser(); }
				$('admButton3').value = 'Delete User';
				$('admButton3').style.visibility = "visible"; 
				$('admButton3').onclick = function () { Site.Forum.DeleteUser(); } 
			}
			else 
			{
				Ajax.ForumManager_DisplayGroups(); // display the groups in the select box
				$('admButton1').value = 'Delete Group';
				$('admButton1').onclick = function () { Site.Forum.DeleteGroup(); }
				$('admButton2').style.visibility = "hidden"; 
				//$('admButton2').onclick = null; 
				$('admButton3').style.visibility = "hidden";
				//$('admButton3').onclick = null;
			}	
		},
		
		
		Search : function()
		{
			var searchKey = $('input_SearchKey').value;
			var groupId = this.GetIdValue($('select_Groups')[$('select_Groups').selectedIndex].id);
			
			if ($('radio_Users').checked)
				Ajax.ForumManager_SearchUsers(searchKey, groupId);
			else if ($('radio_Groups').checked)
				Ajax.ForumManager_SearchGroups(searchKey);
				
		},
		
		
	
		DisplayAddGroup : function()
		{
			$('addgroup').innerHTML = '<input id="input_NewGroupName" type="text" />' + 
									  '<input type="button" onclick="Site.Forum.AddGroup()" value="Add Group" />' +
									  '<a onclick="Site.Forum.DisplayGroupSelect()">cancel</a>';
		},
		
		AddGroup : function()
		{
			var name = $('input_NewGroupName').value;
			Ajax.ForumManager_AddGroup(name);
			//this is calling the method from the file ajax.js.php under class Ajax, which is generated from 
			//the ajax.xml under folder config
		},
		
		DisplayGroupSelect : function()
		{
			Ajax.ForumManager_DisplayGroups2(); // fill the select box containing the groups
			
		},
		
		// Make an ajax call taking the group ID to update the admin panels (user, group users)
		UpdateAdminPanel : function()
		{
			var groups = $('select_Groups'); // groups dropdown select
			var gIndex = groups.selectedIndex; // the index that was selected
			if ($('radio_Users').checked)
				Ajax.ForumManager_UpdateAdminPanel(this.GetIdValue(groups[gIndex].id));
			else
				Ajax.ForumManager_UpdateAdminPanel(this.GetIdValue(groups[gIndex].id), 'false');
		},
		
		AddUserToGroup : function()
		{
			var users = $('select_Users');
			var groups = $('select_Groups');
			var gIndex = groups.selectedIndex;
			for (var i=0; i < users.options.length; ++i)
				if (users.options[i].selected)
					Ajax.ForumManager_AddUserToGroup(this.GetIdValue(groups[gIndex].id), this.GetIdValue(users[i].id));
			this.UpdateAdminPanel();
		},
		
		// takes an id in the form string-whatever-id and returns the integer at the end
		GetIdValue : function(id)
		{
			var parts = id.split('-');
			return parseInt(parts[parts.length-1]);
		},
		
		DeactivateUser : function()
		{
			var users = $('select_Users');
			var name = '';
			var userID = '';
			for (var i=0; i < users.options.length; ++i)
			{
				if (users.options[i].selected)
				{
					userID = this.GetIdValue(users[i].id); 
					name = users[i].value;
					if (confirm('Are you sure you want to deactivate user ' + name + ' ?'))
						Ajax.ForumManager_DeactivateUser(userID);
				}
			}
			this.UpdateAdminPanel();
		},
		
		DeleteUser : function()
		{
			var users = $('select_Users');
			var name = '';
			var userID = '';
			for (var i=0; i < users.options.length; ++i)
			{
				if (users.options[i].selected)
				{
					userID = this.GetIdValue(users[i].id); 
					name = users[i].value;
					if (confirm('Are you sure you want to permanently remove user ' + name + ' from the system?'))
						Ajax.ForumManager_DeleteUser(userID);
				}
			}
			this.UpdateAdminPanel();
		}, 
		
		RemoveUserFromGroup : function()
		{
			var users = $('select_Users2');
			var groups = $('select_Groups');
			var gIndex = groups.selectedIndex;
			for (var i=0; i < users.options.length; ++i)
				if (users.options[i].selected)
					Ajax.ForumManager_RemoveUserFromGroup(this.GetIdValue(groups[gIndex].id), this.GetIdValue(users[i].id));
			this.UpdateAdminPanel();
		},
		
		CopyGroup : function()
		{
			//note that if no group i selected, this functuion will produce an error.
			//While we could use the method as in the AddUserToGroup(), as going through the whole list and 
			//check whether any is selected, it is not worth it 
			var fromGroupId = $('select_Users')[$('select_Users').selectedIndex].id;
			var fromName = $('select_Users')[$('select_Users').selectedIndex].value;
			var toGroupId = $('select_Groups')[$('select_Groups').selectedIndex].id;
			var toName = $('select_Groups')[$('select_Groups').selectedIndex].value;
			
			if (confirm('Group ' + toName + ' will become a copy of group ' + fromName + ' and loses its original list!'))
				Ajax.ForumManager_CopyGroup(this.GetIdValue(fromGroupId), this.GetIdValue(toGroupId));
			this.UpdateAdminPanel();
		},
		
		DeleteGroup : function()
		{
			var groups = $('select_Users');
			var gi = groups.selectedIndex;
			for (var i=0; i < groups.options.length; ++i)
			{
				if (groups.options[i].selected)
				{
					groupID = this.GetIdValue(groups[i].id); 
					name = groups[i].value;
					if (confirm('Are you sure you want to delete group' + name + ' from the system?'))
						Ajax.ForumManager_DeleteGroup(groupID);					
				}
			}
		}// a comma is not needed after the last method (it causes errors in IE)
	}
}

//use alert()  to debug

Site.AddScript('/js/SpryEffects.js'); // load this script in parallel
window.onload = Site.Init; // Attach the initialization function