/* 
	Filename:	library.js
	Author:		Graham Langley
	Version:	1.03
*/

function actionConfirm(form, action, message)	{
	
	if( window.confirm( message )) {
		
		form.action.value = action;
		form.submit();
	}
}

function cookieGet( name ) {
	
	var nameEQ = name + '=';
	var ca = document.cookie.split(';');
	
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function cookieSet( name, value, days )	{	

		if ( days ) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = '; expires='+date.toGMTString();
		}
		else var expires = '';
			document.cookie = name+'='+value+expires+'; path=/';			
}

function cookieDelete(name)	{
		cookieSet(name, '', -1);
}

/* 
    Function:   dateDayName( date )
    Usage:      Return the Day name passed in <date>
*/
function dateDayName( d ) {

    var now = new Date();
    var days = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
    
    return days[d.getDay()];
}

/*
	Function:	dateFormatDDMMYYYY( date )
	Usage:		Formats a Javascript date into UK dd/mm/yy format
*/

function dateFormatDDMMYYYY( d ) {

    var day = d.getDate();
    var month = (d.getMonth()+1);
    var year = (d.getYear()-100)
    
    var ddmmyyy = '';

    if (year > 1900) {
        year += 100;
    } else {
        year += 2000;
    }
    
    if (day < 10)   {
        ddmmyyy = '0';
     }
     ddmmyyy += day + '/';
     
     if (month < 10)   {
        ddmmyyy += '0';
     }
     ddmmyyy += month + '/';
          
     ddmmyyy += year;
     
     return ddmmyyy;
}

/*
	Function:	deleteSelectionConfirm()
	Usage:		Checks to see that one or more records have been selected and then confirms the deletion
*/
function deleteSelectionConfirm( form, checkbox_name )	{

	var selected = toggleIsOneSelected( checkbox_name );
	
	if (selected == true)	{
		
		return actionConfirm( form, 'delete_selection', 'Are you sure you want to delete the selected record(s)?');
		
	} else	{
		alert('Please select one or more records and try again.');
		
		return false;
	}
}

/*	Function:	getObject()
	Usage:		Retreives a reference to an object
*/
function getObject( n, d) {

  var p,i,x; 

  if(!d)

      d=document;
   
   if(n != undefined)
   {
	   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=getObject(n,d.layers[i].document);

  if(!x && d.getElementById)

      x=d.getElementById(n);

  return x;
}

/*
	Function:	inputFocus()
	Usage:		Assigns input focus to either the Search bar or input field on the current detail form
*/
function inputFocus()	{

	var focus_id = document.getElementById('focus');
	
	if ( focus_id.value != '' )	{
				
		var input_id = document.getElementById(focus_id.value);
				
		input_id.focus();
		input_id.select();
	}	
	else {
		document.search.search_string.focus();
	}
}
		
/*
	Function:	listAddItem( <text>, <select> to )	
	Usage:		Adds an option to a select list.
*/
function listAddItem( text, to )	{

	if( document.getElementById(text).value != '')	{

		var list = document.getElementById(to);
		var option=document.createElement('option');
		var value = document.createTextNode(document.getElementById(text).value);

		option.appendChild(value);
	
		list.appendChild(option);
	}
}

/*
	Function:	listDeleteItem( list )
	Usage:		Deletes the currently selected item in a select list
*/
function listDeleteItem( id )	{
	
	list = document.getElementById(id)
	
	list.remove(list.selectedIndex);
}

/*
	Function:	listMoveItem( <select> from, <select> to )	
	Usage:		Move the currently selected item in a select list from one list to another.
*/
function listMoveItem( from, to )	{
	var lstFrom = document.getElementById(from);
	var lstTo = document.getElementById(to);

	var iItem = lstFrom.selectedIndex;
		
	if( iItem < 0)
	  return;
		  
   lstTo.appendChild(lstFrom.options.item(iItem));
   
   listSetSize(lstTo, lstFrom);
}

/*
	Function:	listSetSize( <select> from, <select> to )
	Usage:		Forces a redraw of both lists in a from/to environment
*/
function listSetSize( lst1, lst2)	{
	
    lst1.size = listGetSize(lst1);
    lst2.size = listGetSize(lst2);
}

/*
	Function:	listGetSize( <select> list )
	Usage:		Returns the number of items in a select list
*/
function listGetSize(list)	{
	
	var length = list.childNodes.length;
    var nsLen = 0;
    	
    for(i=0; i<length; i++){
   	    if(list.childNodes.item(i).nodeType==1)
       	    nsLen++;
	    }
    return nsLen;
}

/* 
	Function:	listSearch( list, value )
	Usage:		Searches for <value> in <list> and returns true/false
*/
function listSearch( id, text )	{

	var found = false;
	var list = document.getElementById(id);
	
	for(i=0; i<list.length; i++)  {
	  
		if (list.options[i].text == text)	{
			found = true;
			
			break;
		}
	}
	return found;
}

/*
    Function:   listSelectedOption( list )
    Usage:      Returns the currently selected option in <list>
*/
function listSelectedOption( list ) {

    var i = list.selectedIndex;
    
	return list.options[i].value;
}

/* 
	Function:	listSet( list, selected value )
	Usage:		Selects <value> in <list>
*/
function listSet( id, value )	{

	var list = document.getElementById(id);
	
	if (list == null) {
	
	   pageErrors = true;
	
	   alert('listSet error for list: '+id);	   	  
	}
	
	for(i=0; i<list.length; i++)  {

		if (list.options[i].value == value)	{

			list.selectedIndex = i;
			
			break;
		}
	}
}

/* 
	Function:	listSort( list )
	Usage:		Sort a list into alphabetical order
*/
function listSort( id )	{

	var list = document.getElementById(id);
	
	arrTexts = new Array();
	
	for(i=0; i<list.length; i++)  {
	  arrTexts[i] = list.options[i].text;
	}
	
	arrTexts.sort();
	
	for(i=0; i<list.length; i++)  {
	  list.options[i].text = arrTexts[i];
	  list.options[i].value = arrTexts[i];
	}
}

/* 
	Function:	listSortNumeric( list )
	Usage:		Sort a list into alphabetical order
*/
function listSortNumeric( id )	{

	var list = document.getElementById(id);
	
	arrTexts = new Array();
	
	for(i=0; i<list.length; i++)  {
	  arrTexts[i] = list.options[i].text;
	}
	
	arrTexts.sort(function(a,b){return b - a});
	
	for(i=0; i<list.length; i++)  {
	  list.options[i].text = arrTexts[i];
	  list.options[i].value = arrTexts[i];
	}
}

/*	
	Function:	listToText()
	Usage:		Converts a multiple value selection list to a pipe delimited text string
*/	
function listToText( lst, txt ) {
	
	var toText = document.getElementById(txt);
	var lstFrom = document.getElementById(lst);
	var items = listGetSize(lstFrom);

	for (i = 0; i < items; i++)	{
		toText.value += lstFrom.options[i].text 
			
		if ( i < (items-1)) {
			toText.value += '|'
		}
	}
	return true;
}
	
	
function listMoveUp(obj) {

	obj = (typeof obj == 'string') ? document.getElementById(obj) : obj;
	
	if (obj.tagName.toLowerCase() != 'select' && obj.length < 2)
		return false;
	
	var sel = new Array();
	
	for (var i=0; i<obj.length; i++) {
		if (obj[i].selected == true) {
			sel[sel.length] = i;
		}
	}
	
	for (i in sel) {
		if (sel[i] != 0 && !obj[sel[i]-1].selected) {
			var tmp = new Array((document.body.innerHTML ? obj[sel[i]-1].innerHTML : obj[sel[i]-1].text), obj[sel[i]-1].value, obj[sel[i]-1].style.color, obj[sel[i]-1].style.backgroundColor, obj[sel[i]-1].className, obj[sel[i]-1].id);
			if (document.body.innerHTML) obj[sel[i]-1].innerHTML = obj[sel[i]].innerHTML;
			else obj[sel[i]-1].text = obj[sel[i]].text;
				obj[sel[i]-1].value = obj[sel[i]].value;
				obj[sel[i]-1].style.color = obj[sel[i]].style.color;
				obj[sel[i]-1].style.backgroundColor = obj[sel[i]].style.backgroundColor;
				obj[sel[i]-1].className = obj[sel[i]].className;
				obj[sel[i]-1].id = obj[sel[i]].id;
					if (document.body.innerHTML) obj[sel[i]].innerHTML = tmp[0];
					else obj[sel[i]].text = tmp[0];
					obj[sel[i]].value = tmp[1];
					obj[sel[i]].style.color = tmp[2];
					obj[sel[i]].style.backgroundColor = tmp[3];
					obj[sel[i]].className = tmp[4];
					obj[sel[i]].id = tmp[5];
					obj[sel[i]-1].selected = true;
					obj[sel[i]].selected = false;
		}
	}
}

function listMoveDown(obj) {
	obj = (typeof obj == 'string') ? document.getElementById(obj) : obj;
	if (obj.tagName.toLowerCase() != 'select' && obj.length < 2)
		return false;
	var sel = new Array();
	for (var i=obj.length-1; i>-1; i--) {
		if (obj[i].selected == true) {
			sel[sel.length] = i;
		}
	}
	for (i in sel) {
		if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
			var tmp = new Array((document.body.innerHTML ? obj[sel[i]+1].innerHTML : obj[sel[i]+1].text), obj[sel[i]+1].value, obj[sel[i]+1].style.color, obj[sel[i]+1].style.backgroundColor, obj[sel[i]+1].className, obj[sel[i]+1].id);
			if (document.body.innerHTML) obj[sel[i]+1].innerHTML = obj[sel[i]].innerHTML;
			else obj[sel[i]+1].text = obj[sel[i]].text;
			obj[sel[i]+1].value = obj[sel[i]].value;
			obj[sel[i]+1].style.color = obj[sel[i]].style.color;
			obj[sel[i]+1].style.backgroundColor = obj[sel[i]].style.backgroundColor;
			obj[sel[i]+1].className = obj[sel[i]].className;
			obj[sel[i]+1].id = obj[sel[i]].id;
			if (document.body.innerHTML) obj[sel[i]].innerHTML = tmp[0];
			else obj[sel[i]].text = tmp[0];
			obj[sel[i]].value = tmp[1];
			obj[sel[i]].style.color = tmp[2];
			obj[sel[i]].style.backgroundColor = tmp[3];
			obj[sel[i]].className = tmp[4];
			obj[sel[i]].id = tmp[5];
			obj[sel[i]+1].selected = true;
			obj[sel[i]].selected = false;
		}
	}
}

/*
	Function:	roundNumber( number, decimals)
	Usage:		Rounds "number" to "decimals" decimal places
*/	
function roundNumber(num, dec) {
	
	var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec);
	
	return result;
}

/*	Function:	rowMouseOver( <table> id, row )
	Usage:		Formats the row and cells of a record listing table to cater for alternating styles for a "mouseover" event
*/
function rowMouseOver( id, row )	{

	var table = document.getElementById( id );

	var i = row.rowIndex;		
	
	row.className = 'mouseover';

	for ( x=0; x < row.cells.length; x++ ) {
            	
		var cell = row.cells[x];
	
		if ( i == (table.rows.length-1)  ) {
			cell.className = 'mouseover_last';
				
    	} else {
				
			if ( i % 2 == 0 )	{
   	        	cell.className = 'mouseover_odd';
											
			} else	{
   	        	cell.className = 'mouseover_even';
			}
       	}        
 	}
}

/*	Function:	rowMouseOut( row )
	Usage:		Formats the row and cells of a record listing table to cater for alternating styles for a "mouseout" event
*/
function rowMouseOut( id, row )	{

	var table = document.getElementById( id );

	var i = row.rowIndex;
		
	row.className = '';

	for ( x=0; x < row.cells.length; x++ ) {
            	
		var cell = row.cells[x];
	
		if ( i == (table.rows.length-1)  ) {
			cell.className = 'last';
				
    	} else {
				
			if ( i % 2 == 0 )	{
   	        	cell.className = 'odd';
											
			} else	{
   	        	cell.className = 'even';
			}
       	}        
 	}
}

/*
	Function:	searchFocus()
	Usage:		Maintains input focus on the search string
*/
function searchFocus() {
	
	var search_string_id = document.getElementById('search_string');
			
	search_string_id.focus();
}

/*
	Function:	sidebarHide()
	Usage:		Hides the sidebar based on cookie setting
*/
function sidebarHide()	{
			
	var sidebar_id = document.getElementById('sidebar'); 
	var content_id = document.getElementById('content'); 
			
	sidebar_id.className = 'sidebar_invisible'; 
	content_id.className = 'content_wide';
			
	document['sidebar_toggle_image'].src = '/system/images/sidebar-show.gif';
	document['sidebar_toggle_image'].alt = 'Show Sidebar';
	document['sidebar_toggle_image'].title = 'Show Sidebar';
}

/*
	Function:	sidebarInitialise()
	Usage:		Initialises the display of the Sidebar
*/	
function sidebarInitialise()	{
		
	var show = cookieGet('sidebar');

	if (show == '0')	{
		sidebarHide();
	} else    {
	    sidebarSetToggleHeight();
	}
}

/*
	Function:	sidebarSetToggleHeight()
	Usage:		Automatically sizes the "toggle" div height
*/
function sidebarSetToggleHeight()    {
	
	document.getElementById('sidebar_toggle').style.height = document.getElementById('sidebar').offsetHeight + 'px';
}

/*
	Function:	sidebarToggle()
	Usage:		Toggles the display of the Sidebar
*/
function sidebarToggle()	{ 
				
	var sidebar_id = document.getElementById('sidebar'); 
	var content_id = document.getElementById('content'); 
			
	var sidebar_class = sidebar_id.className; 
			
	if (sidebar_class == 'sidebar_invisible') { 
		sidebar_id.className = 'sidebar'; 
		content_id.className = 'content'; 
				
		document['sidebar_toggle_image'].src = '/system/images/sidebar-hide.gif';
		document['sidebar_toggle_image'].alt = 'Hide Sidebar';
		document['sidebar_toggle_image'].title = 'Show Sidebar';										
				
		cookieSet( 'sidebar', '1', 365);
											
	} else { 
		sidebar_id.className = 'sidebar_invisible'; 
		content_id.className = 'content_wide'; 
					
		document['sidebar_toggle_image'].src = '/system/images/sidebar-show.gif';
		document['sidebar_toggle_image'].alt = 'Show Sidebar';
	
		cookieSet( 'sidebar', '0', 365);		
	} 
} 

/*
	Function:	stringToFloat( id )
	Usage:		Converts a form field string value to a floating point numeric value. 
				Resets the field to zero if not a number.
				Formats the field to the corresponding result.
*/
function stringToFloat( id )	{

	var id = document.getElementById( id );
	var nFloat = parseFloat( id.value );

	/* Invalid number? */
	if (isNaN(nFloat))	{
		/* Reset form field to zero */
		/*id.value = '0';*/
		id.value = '';
		
		return 0;
		
	} else	{
		nFloat = Math.round(nFloat * Math.pow(10,2)) / Math.pow(10,2);
		
		/* Update form field with formatted value */
		id.value = nFloat;
		
		return nFloat;
	}
}

/*	
	Function:	tableFormatCells( <table> id )
	Usage:		Formats the cells of a list table to cater for alternating styles
*/
function tableFormatCells( id )	{
	
	var table = document.getElementById( id );

	for ( y=1; y < table.rows.length; y++ ) {                  

		var row = table.rows[y];

		for ( x=0; x < row.cells.length; x++ ) {
            	
			var cell = row.cells[x];
	
            if ( y == (table.rows.length-1)  ) {
				cell.className = 'last';
				
    		} else {
				
				if ( y % 2 == 0 )	{
   	        		cell.className = 'odd';
											
				} else	{
   	        		cell.className = 'even';   	        		
				}
       	    }                                    
    	}
	}
}

/*
    Function:   timeFormatAMPM( date )
    Usage:      Return the time element of <date> as HH:MM AM/PM
*/
function timeFormatAMPM( d ) {

   var hour   = d.getHours();
   var minute = d.getMinutes();
   var ap = "AM";
   
   if (hour   > 11) { ap = "PM";             }
   if (hour   > 12) { hour = hour - 12;      }
   if (hour   == 0) { hour = 12;             }
   if (hour   < 10) { hour   = "0" + hour;   }
   if (minute < 10) { minute = "0" + minute; }

   var timeString = hour + ':' + minute + " " + ap;
   
   return timeString;
}

/*	Function:	toggleIsOneSelected( checkbox <name> )
	Usage:		Checks to see it at least one check box in a name range is selected
*/
function toggleIsOneSelected( checkbox_name ) {

	var atleastOneTrue=false;

	for (var i=0;i < getObject(checkbox_name).length;i++) {
		if (getObject(checkbox_name)[i].checked==true) {
			atleastOneTrue=true
			break;
		}
	}
	
	return atleastOneTrue;
}

/*	
	Function:	toggleSelect( state, <checkbox> name )
	Usage:		Toggles the checked state of a checkbox/group of checkboxes with the same name
*/
function toggleSelect( state, checkbox_name ) {

	if ( getObject(checkbox_name) ) {
		if ( typeof(getObject(checkbox_name).length ) == 'undefined') {
			getObject(checkbox_name).checked=state
		} else {
			for (var i = 0; i < getObject(checkbox_name).length; i++)
				getObject(checkbox_name)[i].checked=state
		}
	}
}

/*	
	Function:	toggleSelectAll( checkbox <name>, select all checkbox <name> )
	Usage:		Maintains the state of a "Select All" checkbox
*/
function toggleSelectAll( checkbox_name, selectall_checkbox_name ) {

	if (typeof(getObject(checkbox_name).length) == 'undefined') {
		getObject(selectall_checkbox_name).checked=getObject(checkbox_name).checked
	} else {
		var atleastOneFalse=false;
		for (var i = 0; i < getObject(checkbox_name).length; i++) {
			if (getObject(checkbox_name)[i].checked==false) {
				atleastOneFalse=true
				break;
			}
		}
		getObject(selectall_checkbox_name).checked=!atleastOneFalse
	}
}

/*
	Function:	userGet()
	Usage:		Retreives user login information from saved cookie file
*/
function userGet()	{
	
	var remember = cookieGet('user_remember');
	
	if ( remember == 'on' )	{
		
		document.getElementById('user_id').value = cookieGet('user_id');
		document.getElementById('user_password').value = cookieGet('user_password');
		document.getElementById('user_remember').checked = 'on';
	}
}

/*
	Function:	userSet()
	Usage:		Saves user login information to a cookie file
*/
function userSet()	{
	
	var remember = '';
	
	if ( document.getElementById('user_remember').checked == true )	{
		
		var remember = 'on';
	}

	cookieSet('user_remember', remember, 365);
		
	if ( remember == 'on' )	{
		
		cookieSet( 'user_id', document.getElementById('user_id').value, 365);
		cookieSet( 'user_password', document.getElementById('user_password').value, 365);			
	}
}
	