var msgcheck;

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function doPreload() {
	MM_preloadImages('/img/topnav/aboutx.gif','/img/topnav/newsx.gif','/img/topnav/forumsx.gif','/img/topnav/clubsx.gif','/img/topnav/advicex.gif','/img/topnav/entertainmentx.gif','/img/societies/buttons/home_o.gif','/img/societies/buttons/clubnews_o.gif','/img/societies/buttons/members_o.gif','/img/societies/buttons/photos_o.gif','/img/societies/buttons/committee_o.gif','/img/societies/buttons/history_o.gif','/img/societies/buttons/forum_o.gif','/img/societies/buttons/joining_o.gif');
}

function evalForm() {
  f = document.forms.registration;
  var nonnumeral = /\D/;
  var alphatstart = /^\D/;
  var numatend = /\d\d$/;
  var email = /.{1,}[@].{1,}[.].{1,}/;
  
  if (f.username.value == "") {
    alert('You must choose a username');
	return false;
  } else if (f.firstname.value == "") {
    alert('You must enter your first name');
	return false;
  } else if (f.lastname.value == "") {
    alert('You must enter your last name');
	return false;
  } else if (f.studentno.value == "") {
    alert('You must enter your student number');
	return false;
  } else if (f.studentno.value.length != 7 || f.studentno.value.match(nonnumeral)) {
    alert('That\'s not a valid Stirling University Student Number');
	return false;
  } else if (f.email.value == "" || !f.email.value.match(email)) {
    alert('You must enter a valid email address');
	return false;
  } else if (f.uniusername.value == "") {
    alert('You must enter your university username');
	return false;
  } else if (!f.isPostGrad.checked && (f.uniusername.value.length < 4 || f.uniusername.value.length > 6 || !f.uniusername.value.match(alphatstart) || !f.uniusername.value.match(numatend))) {
    alert('That\'s not a valid Stirling University Username');
	return false;
  } else
    f.submit();
}

function goPrint(details) {
  printWin = window.open("/actinite/display.php?action=p&" + details,"Print", "height=" + Math.round(screen.height*0.66) + ", width=600, scrollbars");
  printWin.focus();
}

function goEmail(details) {
  emailWin = window.open("/actinite/display.php?action=e&" + details, "Email", "height=400, width=300");
  emailWin.focus();
}

function goMailer(type, recipient) {
  emailWin = window.open("/actinite/emailer.php?t=" + type + "&r=" + recipient, "Email", "height=400, width=300");
  emailWin.focus();
}

function glossary(glossRef) {
	glossWin = window.open("/glossary.php?g=" + glossRef, "Glossary", "height=400, width=400");
	glossWin.focus();
}

function goWin(winwidth, winheight, name, ref) {
	dimensions = "height=" + winheight +", width=" + winwidth + ", scrollbars=yes";
	newWin = window.open(ref, name, dimensions);
	newWin.focus();
}
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function MM_jumpMenuGo(selName,targ,restore){ //v3.0
  var selObj = MM_findObj(selName); if (selObj) MM_jumpMenu(targ,selObj,restore);
}
function goKarma(username) {
	goWin(300,240,"karma", "/tools/karmapopup.php?u=" + username);
}
function goChat() {
	chatWin = window.open("/interact/chat/chatroom.php", "Chat", "height=400, width=530, scrollbars=yes, resizable=yes");
	chatWin.focus();
}
function goEmergency(member,society) {
	goWin(450,400,"contacts", "/tools/emergency_contacts.php?mid=" + member + "&s=" + society);
}
function goMemberLog(forum, member, topic) {
		goWin(450,400,"warnings", "/tools/memberwarnings.php?mid=" + member + "&f=" + forum + "&t=" + topic);
}
function goMessenger(optstr) {
	messenger = window.open("/tools/messenger/index.php?" + optstr, 'messenger', "height=320,width=600,scrollbars=no");
	messenger.focus();
}

function nl2br(string) {
	while (string.indexOf('\r\n') != -1) {
		string = string.replace("\r\n", '<br />');
	}
	while (string.indexOf('\r') != -1) {
		string = string.replace("\r", '<br />');
	}
	while (string.indexOf('\n') != -1) {
		string = string.replace("\n", '<br />');
	}
	return string;
}

function goPreview(contentid) {
	activePreview = contentid;
	pane = document.getElementById('previewPane');
	closer = document.getElementById('closePane');
	container = document.getElementById(activePreview);
	text = container.value;
	
	// Is this HTML content, or does it need to be newline parsed?
	if (text.indexOf('[HTML]') != -1) {
		text = text.replace('[HTML]','');
	} else {
		text = nl2br(text);
	}
	pane.innerHTML = text;
	container.style.visibility = 'hidden';
	pane.style.visibility = 'visible';
	closer.style.visibility = 'visible';
}
function closePreview() {
	container = document.getElementById(activePreview);
	pane = document.getElementById('previewPane');
	closer = document.getElementById('closePane');
	container.style.visibility = 'visible';
	pane.style.visibility = 'hidden';
	closer.style.visibility = 'hidden';
}

function toggleAdvanced(formName) {
	f = document.getElementById(formName);
	lnk = document.getElementById('toggleLink');
	if (f.className == "basicform") {
		f.className = "advancedform";
		lnk.innerHTML = "SIMPLE OPTIONS";
	} else {
		f.className = "basicform";
		lnk.innerHTML = "ADVANCED OPTIONS";
	}
}

/*
	Written by Jonathan Snook, http://www.snook.ca/jonathan
	Add-ons by Robert Nyman, http://www.robertnyman.com
*/

function getElementsByClassName2(oElm, strTagName, strClassName){
		var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
		var arrReturnElements = new Array();
		strClassName = strClassName.replace(/\-/g, "\\-");
		var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
		var oElement;
		for(var i=0; i<arrElements.length; i++){
				oElement = arrElements[i];      
				if(oRegExp.test(oElement.className)){
						arrReturnElements.push(oElement);
				}   
		}
		return (arrReturnElements)
}

function insertMsg(msg_id, msg_sender, msg_sender_name, msg_text) {
	div = document.createElement('div');
	div.className = 'inline_msg';
	div.id = 'msg_'+msg_id;
	
	clnk = document.createElement('a');
	clnk.href = '#';
	clnk.className = 'inline_option';
	rlnk = clnk.cloneNode(true);
	clnk.onclick = function() {inline_close(msg_id); return false; };
	clnk.appendChild(document.createTextNode('DISMISS'));
	rlnk.onclick = function() {inline_reply(msg_id); return false; };
	rlnk.appendChild(document.createTextNode('REPLY'));
	div.appendChild(clnk);
	div.appendChild(rlnk);
	faeStr = document.createElement('b');
	faeStr.appendChild(document.createTextNode('Private message from ' + msg_sender_name));
	
	img = document.createElement('img');
	img.src = '/img/members/'+msg_sender+'.jpg';
	img.align = 'left';
	div.appendChild(img);
	
	div.appendChild(faeStr);
	div.appendChild(document.createElement('br'));
	p = document.createElement("p");
	p.innerHTML = msg_text;
	div.appendChild(p);
	form = document.createElement('form');
	form.style.display = 'none';
	form.id = 'reply_'+msg_id;
	label = document.createElement('label');
	label.appendChild(document.createTextNode('Reply:'));
	form.appendChild(label);
	ta = document.createElement('textarea');
	ta.id = 'ir_'+msg_id;
	ta.cols = 50;
	ta.rows = 4;
	form.appendChild(ta);
	hf = document.createElement('input');
	hf.id = 'recip_'+msg_id;
	hf.type = 'hidden';
	hf.value = msg_sender;
	form.appendChild(hf);
	button = document.createElement('input');
	button.value = 'Reply';
	button.type = 'button';
	button.onclick = function() { inline_send(msg_id); };
	form.appendChild(button);
	div.appendChild(form);
	clearer = document.createElement('div');
	clearer.className = 'clearer';
	div.appendChild(clearer);
	
	$('mainContent').insertBefore(div,$('mainContent').firstChild);
}

	function inline_close(id) {
		new Effect.Fade('msg_'+id, {duration: 0.5});
	}
	function inline_reply(id) {
		new Effect.BlindDown('reply_'+id, {duration: 0.5});
	}
	function inline_send(id) {
		msgtext = $('ir_'+id).value;
		recipient = $('recip_'+id).value;
		new Ajax.Request('/tools/messenger/send.php', { parameters: 'recipient='+recipient+'&msg='+msgtext});
		inline_close(id);
	}
	function checkForMsgs() {
		new Ajax.Request('/tools/messenger/getmsg.xml.php', { onSuccess : function(resp) { handleMsgResponse(resp.responseText); }});
		msgcheck = setTimeout('checkForMsgs()',30000);
	}
	
	function handleMsgResponse(text) {
		if (text == "LOGGED OUT") {
			clearTimeout(msgcheck);
		} else {
			var temp = new Array();
			temp = text.split('\n');
			if (temp.length > 0) {
				var m = new Array();
				for (i = 0; i < temp.length; i++) {
					post = temp[i].split('|||');
					if (post[0])
						insertMsg(post[0],post[3],post[4] + ' ' + post[1],post[2]);
				}
			}
		}
	}
	
	function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}


function noSpaces(obj) {
	obj.value = obj.value.replace(' ','');
}

function salutationBox(el) {
	otherel = el.id+'_other';
	if (el.value == "Other")
		dvalue = "";
	else {
		dvalue = "disabled";
		$(otherel).value = "";
	}
	$(otherel).disabled = dvalue;
}