//===============================================================================
// Begin:	Main Menu.
// Author:	John Wakefield
//===============================================================================
var timerID = 0;

function initialise_menu()
{
	// In printer friendly pages, there is no menuBar - so check before proceeding.
	if (document.getElementById("menuBar"))
	{
		var bar = document.getElementById("menuBar").childNodes;
		for(var i=0;i < (bar.length);i++)
		{
			var menu=(bar[i].getAttribute("menu"))
			if(menu)
			{
				document.getElementById(menu).style.visibility = "hidden"
				bar[i].onmouseover = new Function("bar_onmouseover('"+bar[i].id+"')")
				bar[i].onmouseout = new Function("bar_onmouseout('"+bar[i].id+"')")
				bar[i].onclick = new Function("menu_onclick('"+bar[i].id+"')")
				var Items = document.getElementById(menu).childNodes
				for(var j=0; j<(Items.length); j++)
				{
					var menuItem = (Items[j].id)
					if(document.getElementById(menuItem).getAttribute("cmd") != null)
					{
						document.getElementById(menuItem).onclick = new Function("menu_onclick('"+document.getElementById(menuItem).id+"')")
					} 
					document.getElementById(menuItem).onmouseover = new Function("menu_onmouseover('"+Items[j].id+"')")
					document.getElementById(menuItem).onmouseout = new Function("menu_onmouseout('"+Items[j].id+"')")
				}
			}
		}  
	}	
}

function hide_menu()
{
	var bar = document.getElementById("menuBar").childNodes;
	for(var i=0;i < bar.length;i++)
	{
		var menu=(bar[i].getAttribute("menu"))
		if(menu)
		{
			document.getElementById(menu).style.visibility = "hidden"
		}
	}
}

function offset_y(obj)
{
	if (typeof(obj) != 'object' || obj == null)
	{	
		return 0
	}
	else
	{
		return obj.offsetTop + offset_y(obj.offsetParent)
	}
}

function bar_onmouseover(obj)
{

	ClearTimer()
	hide_menu()
	var bar = document.getElementById(obj)
	//For Netscape:
	bar.setAttribute("class","rootmenu_selected_item")
	//For IE:
	bar.className="rootmenu_selected_item"
	window.status = document.getElementById(obj).getAttribute("cmd")
	var menu = (document.getElementById(obj).getAttribute("menu"))
	var items = document.getElementById(menu).childNodes

	if(items.length != 0)
	{
		document.getElementById(menu).style.visibility = "visible";
		//Set width for Netscape otherwise it is 100%
		document.getElementById(menu).style.width="200";
		document.getElementById(menu).style.display = "block";
		document.getElementById(menu).style.top = offset_y(document.getElementById(obj));
		document.getElementById(menu).style.left = 150;
	}
}

function bar_onmouseout(obj)
{
	StartTimer()
	var bar = (document.getElementById(obj))
	bar.className="rootmenu_item"
	bar.setAttribute("class","rootmenu_item")
	window.status = document.getElementById(obj).getAttribute("cmd")
}

function menu_onmouseout(obj)
{
	StartTimer()
	document.getElementById(obj).setAttribute("class","submenu_item")
	document.getElementById(obj).className = "submenu_item"
	window.status = ""
}

function menu_onmouseover(obj)
{
	ClearTimer()
	document.getElementById(obj).setAttribute("class","submenu_selected_item")
	document.getElementById(obj).className = "submenu_selected_item"
	window.status = document.getElementById(obj).getAttribute("cmd")
}

function menu_onclick(obj)
{
	var cmd = document.getElementById(obj).getAttribute("cmd")
	if (cmd.length > 3)
	{
		if (cmd.substring(0,1) == "~")
		{
			window.open(cmd.substring(1,cmd.length));
		}
		else
		{
			location.href=cmd;
		}
	}
}

function StartTimer()
{
	timerID = setTimeout("FireTimer()", 1000)
}

function ClearTimer()
{
	clearTimeout(timerID)
}

function FireTimer()
{
	if(timerID)
	{
		clearTimeout(timerID)
		hide_menu()
	}
}
//===============================================================================
// End:	Main Menu.
//===============================================================================

//===============================================================================
// Begin:	Ticker.
//			This script animates a ticker consisting of a div containing the
//			message text. The div is shifted to the left by shiftBy pixels every
//			interval.
// Author:	John Wakefield
//===============================================================================
var ticker = null; /* ticker object */

function initialise_ticker()
{
	var username = document.getElementById('txtUsername');
	if (username !== null)
	{
		username.focus();
	}
	ticker = new Ticker('ticker', 'tickerID', 1, 10);
	ticker.start();
}

function clrlabel()
{
	if (document.getElementById("lblMessage") != null)
	{
		document.getElementById("lblMessage").style.visibility = "hidden"
	}
}

function Ticker(name, id, shiftBy, interval)
{
	this.name     = name;
	this.id       = id;
	this.shiftBy  = shiftBy ? shiftBy : 1;
	this.interval = interval ? interval : 100;
	this.runId	= null;

	this.div = document.getElementById(id);

	var node = this.div.firstChild;
	var next;

	while (node)
	{
		next = node.nextSibling;
		if (node.nodeType == 3)
		this.div.removeChild(node);
		node = next;
	}
	this.left = 560;
	this.shiftLeftAt = this.div.firstChild.offsetWidth;
	this.div.style.height	= this.div.firstChild.offsetHeight;
	this.div.style.width = 2 * screen.availWidth;
	this.div.style.visibility = 'visible';
}

function startTicker()
{
	this.stop();
	this.left -= this.shiftBy;
	if (this.left <= -this.shiftLeftAt)
	{
		this.left = 560;
		this.div.appendChild(this.div.firstChild);
		
		this.shiftLeftAt = this.div.firstChild.offsetWidth;
	}
	this.div.style.left = (this.left + 'px');
	this.runId = setTimeout(this.name + '.start()', this.interval);
}

function stopTicker()
{
	if (this.runId)
		clearTimeout(this.runId);
	this.runId = null;
}

function changeTickerInterval(newinterval)
{
	if (typeof(newinterval) == 'string')
		newinterval =  parseInt('0' + newinterval, 10); 
		
	if (typeof(newinterval) == 'number' && newinterval > 0)
		this.interval = newinterval;
		this.stop();
		this.start();
}

/* Prototypes for Ticker */
Ticker.prototype.start = startTicker;
Ticker.prototype.stop = stopTicker;
Ticker.prototype.changeInterval = changeTickerInterval;		
//===============================================================================
// End:		Ticker.
//===============================================================================

//===============================================================================
// Begin:	Check Submit Button.
// Author:	Debbie Derman.
//===============================================================================
function checkSubmitButton()
	{
	if (document.forms(0).rblLegal_0.checked == true)
		enableSubmitButton(document.forms(0).btnSubmit)
	else
		disableSubmitButton(document.forms(0).btnSubmit)
	}
function disableSubmitButton(button)
	{
	if (typeof button.disabled != 'undefined')
		button.disabled = true;
	else if (!button.buttonDisabled)
		{
		button.oldValue = button.value;
		button.oldOnclick = button.onclick;
		button.value = 'DISABLED';
		button.onclick = cancelAction;
		button.buttonDisabled = true;
		}
	}
function enableSubmitButton(button)
	{
	if (typeof button.disabled != 'undefined')
		button.disabled = false;
	else if (button.buttonDisabled)
		{
		button.value = button.oldValue;
		button.onclick = button.oldOnclick;
		button.buttonDisabled = false;
		}
	}
// Function to hide controls.
function HideControls()
	{
		document.getElementById('tblEntryType').style.visibility='hidden';
		document.getElementById('tblSeries').style.visibility='hidden';
		document.getElementById('tblUnits').style.visibility='hidden'
	}
//-->
//===============================================================================
// End:		Check Submit Button.
//===============================================================================

//===============================================================================
// Begin:	NewWindow.
//			This script opens a new window and centre's it as an option.
// Author:	Fitz Adom.
//===============================================================================
function NewWindow(mypage, myname, w, h, pos, infocus)
{
	if (pos=="random")
	{
		myleft=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;mytop=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;
	}
	if (pos=="center")
	{
		myleft=(screen.width)?(screen.width-w)/2:100;mytop=(screen.height)?(screen.height-h)/2:100;
	}
	else if ((pos!='center' && pos!="random") || pos==null)
	{
		myleft=0;mytop=20
	}
	settings="width=" + w + ",height=" + h + ",top=" + mytop + ",left=" + myleft + ",scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no";win=window.open(mypage,myname,settings);
	
	win.focus();
}
//-->
//===============================================================================
// End:		NewWindow.
//===============================================================================

//===============================================================================
// Begin:	OpenAsPopup
//			This script opens a popup window.
// Parameters:	
// filename :	File name or url 
//				eg. 'http://www.qca.org.uk/nq/ks/proxy_qualifications.asp'
// windowname:	Window name.
// properties:	Properties of the pop-up window
//				eg. 'height=580,width=625,scrollbars=yes,resizable=yes,left=178,top=100,status=yes'
// Author:	Abdul Majid.
//===============================================================================
function OpenAsPopup(filename,windowname,properties) 
{
    mywindow = window.open(filename,windowname,properties);
}

//===============================================================================
// Begin:	SetScrollPosition
//			This script is to set the windows scroll position.
// Parameters:	
// sFormName:	Name of the form in which PageX and PageY parameters are present.
// Author:	Suja Venkataramani.
//===============================================================================
function SetScrollPosition(sFormName)
{
	window.scrollTo(document.all(sFormName).PageX.value, document.all(sFormName).PageY.value);
}

//===============================================================================
// Begin:	SetScrollCoords
//			This script is to store the windows scroll position.
// Parameters:	
// sFormName:	Name of the form in which PageX and PageY parameters are present.
// Author:	Suja Venkataramani.
//===============================================================================
function SetScrollCoords(sFormName)
{
	var myPageX;
	var myPageY;
	if (document.all){
		myPageX = document.body.scrollLeft;
		myPageY = document.body.scrollTop;
		}
	else{
		myPageX = window.pageXOffset;
		myPageY = window.pageYOffset;
		}
	document.all(sFormName).PageX.value = myPageX;
	document.all(sFormName).PageY.value = myPageY;
}

//
//Split the query string into it's name value pairs and
//add them to the Args() array which can then be accessed
//with the following syntax:
//getArgs()['Type']
//
function getArgs() { 
	var Args = new Object(); 
	var query = location.search.substring(1); 
	var pairs = query.split("&"); 
	for (var i = 0; i < pairs.length; i++) 
	{ 
		var pos = pairs[i].indexOf('='); 
		if (pos == -1) continue; 
		var argname = pairs[i].substring(0,pos); 
		var value = pairs[i].substring(pos+1); 
		Args[argname] = unescape(value); 
	} 
	return Args;
}

//
//set the focus on the control and scroll to the control
//
function scrollIntoView(control){
    control.focus(); 
    control.scrollIntoView(true);
}

//
//toggle the visibility of an object
//
function setObjectVisibility(id){
    var obj = document.getElementById(id);
    obj.style.display = obj.style.display == 'none' ? 'block' : 'none';
}

//
//Calculate and validate the UCI number of a student
//
function calculateUciCheck(source, arguments){
    var strInput = '';   
    if(document.frmMain.txtUCINo){
	    strInput = document.frmMain.txtUCINo.value;
	}
	else if(document.frmMain.CandidateEdit_txtUCINo){
	    strInput = document.frmMain.CandidateEdit_txtUCINo.value;
	}
	//Added for DiDA
	else if(document.frmMain.txtUCINumber){
		strInput = document.frmMain.txtUCINumber.value;
	}
	else{
	    strInput = document.frmMain.didaEdit_txtUCINo.value;
	}
    var regYear = parseInt(strInput.substring(6, 8));
	var uab = 0;
	//validation
	if(strInput.length != 12){
		source.errormessage = 'Invalid UCI number length.';
		arguments.IsValid=false;
		return;		
	}
    else if(isNaN(regYear)){
		source.errormessage='The UCI registration year must be numeric.';
		arguments.IsValid=false;
		return;
    }
	else if(isNaN(strInput.substring(0, 4))){
		source.errormessage = 'The UCI number contains an invalid centre number .';
		arguments.IsValid=false;
		return;
	}
	else if (strInput.substring(5, 6) != 0){
	    var centreNumberCheck;
	    if(document.getElementById('txtBaseCentreNumber')){
		    centreNumberCheck = parseInt(document.getElementById('txtBaseCentreNumber').value.substring(0, 1));
        }else{
            centreNumberCheck = parseInt(window.opener.document.getElementById('txtBaseCentreNumber').value.substring(0, 1));
        }
		if(strInput.substring(5, 6).toUpperCase() != 'B' || (strInput.substring(5, 6).toUpperCase() == 'B' && (strInput.substring(0, 1) != 9))){
			source.errormessage='The UCI number contains an invalid board identifier.';
			arguments.IsValid=false;
			return;
		}
	}
	else if(isNaN(strInput.substring(6, 11))){
		source.errormessage = 'Invalid UCI number.';
		arguments.IsValid=false;
		return;
    }
    uab = 2;
	//calculate modulus 17 value
	var inputIndex = 0;
	var calcTotal = 0;
	var cpValue;
	var i;
	for (i = 16; i>=5; i--){
		cpValue = parseInt(strInput.charAt(inputIndex));
		if(i == 11 && strInput.substring(5, 6).toUpperCase() == 'B')
			cpValue = 11 * uab;
		else
			cpValue *= i;
			
		calcTotal += cpValue;
		inputIndex++;
	}	
	var opValue = calcTotal % 17;
	//assign letter according to expression
	var alpha = new Array ("A","B","C","D","E","F","G","H","K","L","M","R","T","V","W","X","Y")

	document.frmMain.checkDigit.value = alpha[opValue];
}

//===============================================================================
// Begin:	Calendar Javascript/Open pop up
//			
// Parameters:	
//			idname=webcontrol id
// Author:	Lasitha lansakaranayake.
//===============================================================================

var popUp; 

function OpenCalendar(idname, postBack)
{
		popUp = window.open('Calendar.aspx?formname=' + document.forms[0].name + 
		'&id=' + idname + '&selected=' + document.forms[0].elements[idname].value + '&postBack=' + postBack, 
		'popupcal', 
		'width=170,height=250,left=200,top=250');
}

//===============================================================================
// Begin:	Calendar Javascript/ Set date
//			
// Parameters:	
//			id=webcontrol id
// Author:	Lasitha lansakaranayake.
//===============================================================================

function SetDate(formName, id, newDate, postBack)
{
	eval('var theform = document.' + formName + ';');
	popUp.close();
	if (theform.elements[id].disabled == true || theform.elements[id].readOnly == true)
	{
		alert("Cannot set date as textbox is read-only.");
	}
	else
	{
		theform.elements[id].value = newDate;
		if (postBack)
		{
			__doPostBack(id,'');
		}
	}
}

//===============================================================================
//	Begin:	UpdateCounter.
//			This script updates a text box with a value equal to the length
//			of the text in the source subtracted from maxLength.
//	Author:	Paul French
//===============================================================================
function UpdateCounter(source, counter, maxLength)
{
	var oSource = document.getElementById(source);
	var oCounter = document.getElementById(counter)
	var nMaxLength = parseInt(maxLength);
	
	if (oSource.value.length > nMaxLength)
	{
		oSource.value = oSource.value.substr(0, nMaxLength);
	}
	
	oCounter.value = nMaxLength - oSource.value.length;
}

//===============================================================================
// Begin:	AllowNumericOnly.
// Author:	Abdul Majid.
//===============================================================================
function AllowNumericOnly(eventObject)
// Filters the keyborard to allow entering only numbers.
{
 var keyCode
 // get the keycode of the key that was pressed
 if (document.all) 
 {
  // IE
  eventObject = window.event;
  keyCode = eventObject.keyCode;
 } 
 else
 {
  // NN
  keyCode = eventObject.which;
 }        
 // 0 to 9.
 if (keyCode < 48 || keyCode > 57)
 {
  // don't stop special keys such as backspace (this only happens in certain browsers)
  // 8: Backspace, 13: Carriage Return, 45: Minus, 32: Space,0: Null.
  if (keyCode != 8 && keyCode != 13 && keyCode != 45 && keyCode != 32  && keyCode != 0)
  {
   if (document.all)
   {
    //IE
    eventObject.returnValue = false;
   }
   else
   {
    // NN
    return false;
   }
  }
 }
}

// function to display a popup window containing the title and html passed in.
// the open the print dialog
function openPrintWindow(Title, Content)
{
	var newWindow = window.open ("newWindow.html", 'Print', "height=400,width=500");
	newWindow.document.write('<HTML><HEAD><TITLE>' + Title + '</TITLE></HEAD><BODY>' + Content + '</BODY></HTML>');
	newWindow.document.close(); //This is important, without this the print statement won't work.
	newWindow.print();
}
//===============================================================================

/**
 * Register an event handler for a given element
 * @param {Object} target
 * @param {String} eventType
 * @param {Function} functionRef
 * @param {Boolean} capture
 */
function attachEventListener(target, eventType, functionRef, capture)
{
    if (typeof target.addEventListener != "undefined")
    {
        target.addEventListener(eventType, functionRef, capture);
    }
    else if (typeof target.attachEvent != "undefined")
    {
        target.attachEvent("on" + eventType, functionRef);
    }
    else
    {
        eventType = "on" + eventType;
        if (typeof target[eventType] == "function")
        {
            var oldListener = target[eventType];
            target[eventType] = function() {oldListener(); return functionRef();};
        }
        else
        {
            target[eventType] = functionRef;
        }
    }
}

/** 
* Tests if the key pressed is allowable as input for a numeric field.
* @param {Object} evt event object
* @return (boolean) 
*/
function numeralsOnly(evt) 
{
    var charCode = getCharCode(evt);
    if (charCode > 31 && (charCode < 48 || charCode > 57)) 
	{
	    if (evt.preventDefault)
	    {
	        evt.preventDefault();
	    }
        return false;
    }
    return true;
}

/**
 * Gets the character code from the event object
 * @param {Object} evt event object
 * @return {Number} character code
 */
function getCharCode(evt)
{
    return (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : 
        ((evt.which) ? evt.which : 0));
	
}

function clickButtonOnEnter(btnId, event)
{
	// Get the event object and character code in a portable way
	var e = event || window.event;			// Key event object
	var code = e.charCode || e.keyCode;		// Which key was pressed
	
	if (code === 13)
	{
		var btn = document.getElementById(btnId);
		if (btn)
		{
			btn.click();
		}
		if (e.preventDefault)
		{
			e.preventDefault();
		} 
		if (e.returnValue)
		{
			e.returnValue = false;
		}
		return false;	 
	}
	else
	{
		return true;
	}
}

// Hide the element that has the given Id
function hideElement(elementId)
{
	var elem = document.getElementById(elementId);
	if (elem)
	{
		elem.style.display = "none";
	}
}

function getParentByTagName(node, tagName)
{
	while (node.tagName.toLowerCase() != tagName)
	{
		node = node.parentNode;
	}
	return node;
}

// Populate a select element.
// Note the 'options' are assummed to have 'Txt' and 'Val' properties.
function populateDropDownList(selectElement, options, firstOptionText, firstOptionValue)
{
	var i;
	var optionsLength = options.length;
	selectElement.options.length = 0;
	if (firstOptionText !== null)
	{
		selectElement.options[0] = new Option(firstOptionText, firstOptionValue);
	}
	for (i = 0; i < optionsLength; ++i)
	{
		selectElement.options[selectElement.options.length] = new Option(options[i].Txt, options[i].Val);		
	}
}

function fnTrapKD(btn)
{	
	// don't do anything on multiline text boxes	
	if (document.activeElement.type == "textarea" || event.srcElement.type == "textarea")
		return;
	
	if (document.all)
	{
		if (event.keyCode == 13)
        { 
			event.returnValue=false;
			event.cancel = true;
			if (btn)
			{
				btn.click();
			} 
		}
    }
}

function PadDigits(n, totalDigits) {
    n = n.toString();
    var pd = '';
    if (totalDigits > n.length) {
        for (i = 0; i < (totalDigits - n.length); i++) {
            pd += '0';
        }
    }
    return pd + n.toString();
}

/*
function disabledfnTrapKD(btn)
{
	// empty temporary replacement function so that we can allow
	// the return key to function without a default button on multiline 
	// textboxes	
	alert(document.activeElement.type);
}

var originalfnTrapKD = fnTrapKD;

function stopDefaultButton()
{
	if ( originalfnTrapKD != null )
	{		
		//fnTrapKD = disabledfnTrapKD;
	}
}

function startDefaultButton()
{
	if ( originalfnTrapKD != null )
	{
		//fnTrapKD = originalfnTrapKD;
	}	
}
*/

