/* Common javascript functions for the Waterexchange
/  AUTHOR:	Jared Pritchard
/  DATE:	From 20-Jan-05
/  VERSION:	V1.0
/
*/

// Get browser type & version
ver=parseInt(navigator.appVersion);
ie4=(ver>3  && navigator.appName!="Netscape")?1:0;
ns4=(ver>3  && navigator.appName=="Netscape")?1:0;
ns3=(ver==3 && navigator.appName=="Netscape")?1:0;
useLocalhost = 0;
localHost = 'http://localhost:8080';
serverURL = 'http://www.waterexchange.com.au';
serverURL_s = 'https://www.waterexchange.com.au';

if (useLocalhost == 1)
{
	serverURL = localHost;
	serverURL_s = localHost;
}


// Attach a file
function attachFiles ( objectType, objectId, defaultDescr, allowUpload, allowView, allowDelete )
{
	// Defaults
	allowUpload	= allowUpload 	== undefined ? 1 : allowUpload ;
	allowView	= allowView 	== undefined ? 1 : allowView ;
	allowDelete	= allowDelete 	== undefined ? 1 : allowDelete ;

	var url = '/cgi-bin/zonetrade/attach.cgi?action=list&objectType=' + objectType + '&objectId=' + objectId
		+ '&allowUpload='	+ allowUpload
		+ '&allowView='		+ allowView
		+ '&allowDelete='	+ allowDelete
		+ '&defaultDescr='	+ defaultDescr ;
	openWindow( url, 'attachFile', '', 500, 350, false );
}

// Select / deselect all checkboxes with names of 'checkboxName' (according to state of 'selectAllObj')
function selectAll ( selectAllObj, checkboxName )
{
	// Find out if we are turning all boxes ON or OFF
	var newValue = selectAllObj.checked ;

	// Look through all forms on the page
	for (var f = 0; f < document.forms.length; f++ )
	{
		var form = document.forms[f];
		if ( form )
		{
			// Get checkbox object
			var chkObject = form[checkboxName];
			if ( chkObject )
			{
				if ( chkObject.length )
				{
					// Valid object, and has length
					// So, loop through each element, checking them if possible
					for ( var i = 0; i < chkObject.length; i++ )
					{
						// Set to new value, if checked is a property of the element
						try { chkObject[i].checked = newValue }
						catch (err) {}
					}
				}
				else
				{
					// Valid object, but no length
					// So, try to set the OBJECT's checked status to true
					// (assuming we had a single checkbox object returned,
					// instead of an array of checkboxes)
					try { chkObject.checked = newValue }
					catch (err) {}
				}
			}
		}	
	}

}

// Toggle all checkboxes that share the supplied checkbox name
function toggleCheckboxes ( checkboxName )
{
	// Look through all forms on the page
	for (var f = 0; f < document.forms.length; f++ )
	{
		var form = document.forms[f];
		if ( form )
		{
			// Get checkbox object
			var chkObject = form[checkboxName];
			if ( chkObject && chkObject.length )
			{
				// Valid object, and has length
				// So, loop through each element, checking them if possible
				for ( var i = 0; i < chkObject.length; i++ )
				{
					// Set to new value, if checked is a property of the element
					try { chkObject[i].checked = !chkObject[i].checked }
					catch (err) {}
				}
			}
		}	
	}
}

// Add & remove classnames function: hesido 
function classChange( elem, addClass, remClass )
{ 
	if ( !elem.className ) elem.className = ''; 
	var clsnm = elem.className; 
	if ( addClass && !clsnm.match(RegExp("\\b"+addClass+"\\b")) )
		clsnm = clsnm.replace(/(\S$)/,'$1 ')+addClass; 
	if ( remClass )
		clsnm = clsnm.replace(RegExp("(\\s*\\b"+remClass+"\\b(\\s*))*","g"),'$2'); 
	elem.className=clsnm; 
}

/****************************************************************
** [I Can] Has Class? (Matt Kruse)
****************************************************************/
/* 
** Kruse's hasClass, with slight modification 
** Determine if an object or class string contains a given class.
** see http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/b68cac304ee6de78/e445c1df18698a3f?lnk=gst&q=hasclass&rnum=3
*/
function hasClass (obj, className)
{
	if (typeof(obj) == 'undefined' || obj==null || !RegExp) { return false; } //should I be checking all my objects for undefined? I feel like it never comes up --N.S. at 9:51:57 PM EST on Wednesday, July 18 2007
	var re = new RegExp("(^|\\s)" + className + "(\\s|$)");
	if (typeof(obj)=="string") {
		return re.test(obj);
	}
	else if (typeof(obj)=="object" && obj.className) {
		return re.test(obj.className);
	}
	return false;
}


// Create a window as specified
function openWindow( theURL, winName, features, popW, popH, noFocus ) {

	// Format as necessary
	var winLeft = (screen.width - popW) / 2;
	var winUp = (screen.height - popH) / 2;
	var center = 'width='+popW+',height='+popH+',left='+winLeft+',screenX='+winLeft+',top='+winUp+',screenY='+winUp;

	// Open the window, and focus on it (unless told not to)
	win = window.open(theURL,winName,features+','+center);
	if ( noFocus ) {
		window.focus ();
	} else {
		win.focus ();
	}
}

// Open a page on demand (easy call from CGI etc.)
function opener ( theURL, features, width, height ) {

	var wNumber = Math.floor( Math.random() * 50 );
	openWindow( theURL, 'oP' + wNumber, 'resizable=yes,scrolling=yes,toolbar=yes,' + features, width, height, 0 );

}

// Open a pop-up screen to display an 'OK' or 'ERROR' message
function popMsg ( status, message, delay ) {



  var generator=window.open('','name','height=400,width=500');
  
  generator.document.write('<html><head><title>Popup</title>');
  generator.document.write('</head><body>');
  generator.document.write('<p>' + message + '</p>');
  generator.document.write('<p><a href="javascript:self.close()"> Close</a> the popup.</p>');
  generator.document.write('</body></html>');
  generator.document.close();







/*	var popUrl = 	'http://www.waterexchange.com.au/cgi-bin/zonetrade/z.cgi/cs' +
			'?action=popMsg' +
			'&status=' + status +
			'&message=' + message +
			'&delay=' + delay
			;

	openWindow ( popUrl, 'popMsg', 'resizable=yes', 500, 150, 0 );*/
}

// Make an object transparent (returns whether successful)
function fade50 ( fadeObj )
{
	if ( fadeObj != null )
	{
		fadeObj.className = 'fade50';
		return true;
	}

	return false;
}


// Play a sound
function playSound( id, soundName ) {
	if (!ie4) { id += 'N'; }	// If netscape, add N to the end of ID (eg. 'click' = 'clickN')
	var source = '/sounds/' + soundName + '.wav';
	var player = document.getElementById(id);
	if (ie4) { player.src = source; }
	if ((ns4 || ns3) && navigator.javaEnabled() && navigator.mimeTypes['audio/x-midi'] && self.document.player.IsReady()) {
		player.play()
	}
}

// Play a sound by file
function playSoundFile( player, soundFile ) {
	if (!ie4) { id += 'N'; }	// If netscape, add N to the end of ID (eg. 'click' = 'clickN')
	var source = soundFile;
	if (ie4) { player.src = source; }
	if ((ns4 || ns3) && navigator.javaEnabled() && navigator.mimeTypes['audio/x-midi'] && self.document.player.IsReady()) {
		player.play()
	}
}

/* Stop the sound from playing */
function stopSound( id ) {
	if (!ie4) { id += 'N'; }	// If netscape, add N to the end of ID (eg. 'click' = 'clickN')
	var player = document.getElementById(id);
	if (ie4) { player.src = 'silence.wav'; }
	if ((ns4 || ns3) && navigator.javaEnabled() && navigator.mimeTypes['audio/x-midi']) {
		player.stop()
	}
}

/* Icon buttons */
function changeIcon( buttonId, state ) {
	button = document.getElementById( buttonId );
	button.className = ('iconButton' + state);
	// Play sound later
}


/* Show or hide an element (usually a DIV tag) */
function toggleView( elementId )
{
	var toggleElement = document.getElementById( elementId );
	if ( toggleElement.className == 'hideDiv' )
	{
		toggleElement.className = 'showDiv';
	}
	else
	{
		toggleElement.className = 'hideDiv';
	}
}


/*
 *	Loading overlay -
 *	When a form is submitted, we now have the option of presenting a loading screen which will
 *	inform the user that action is underway. Useful for forms which take longer to process, or
 *	are intolerant to being resubmitted.
 *
 *	To use this function properly:
 *	- In the HTML page, load common.js && common.css (script & style respectively)
 */

// Can set this to 'false' which will then skip the loading screen the next time it is invoked.
// Good for allowing 'onSubmit' calls for forms, then toggling it off for certain submit buttons
// that don't need it, or open in a new screen etc. which will leave it showing
var allowLoading = true;

// Generate & write the layer which will appear over the page
var overlayText = "<div id='loadingOverlay' class='hide'></div>";
document.write(overlayText);
//setTimeout( function() { classChange( getObj( 'loadingOverlay' ).obj, 'hide', 'show' ); }, 1000 );


// Call this function from the page (form) to show loading
// For example <form onSubmit="return showLoading( testVals() )">
// testVals() will be a local function which checks the values on the form for errors/syntax etc.
function showLoading( returnVal )
{
	// If our test on form's values fails, so does this function!
	if (returnVal == false)
	{
		allowLoading = true;	// Make sure the overlay is allowed next time
		return false;
	}

	// Are we forbidden from showing the overlay this time around?
	if (allowLoading == false)
	{
		allowLoading = true;	// Allow it for next time
		return true;			// No errors, just not showing the overlay, so return 'true'
	}

	// All is OK, will return true, so show loading layer, and start timer which will update it's position if user scrolls
	// document.getElementById("loadingOverlay").className = 'showDiv';
	classChange( getObj( 'loadingOverlay' ).obj, 'show', 'hide' );
	repositionOverlayOnScroll();

	return true;
}

// Hide the loading screen again
function hideLoading( returnVal ) {
	// If our test on form's values, or whatever, fails; so does this function!
	if (returnVal == false) {
		return false;
	}

	// All is OK, will return true, so hide loading layer
	document.getElementById("loadingOverlay").className = 'hideDiv';
	return true;
	
}

// Reposition the 'loading' overlay as user scrolls
function repositionOverlayOnScroll ( )
{
	var divLayer = document.getElementById("loadingOverlay");	// Layer we will be adjusting
	var oX;	// Offset X (pixels scrolled)
	var oY;	// Offset Y
	var sW;	// Screen width
	var sH; // Screen height

	// Get widths & offsets
	if ( ie4 == 1 )
	{
		// For IE
		oX = document.body.scrollLeft;
		oY = document.body.scrollTop;
		sW = document.body.clientWidth;
		sH = document.body.clientHeight;
	}
	else
	{
		// Other browsers (Netscape/Firefox ...)
		oX = window.pageXOffset;
		oY = window.pageYOffset;
		sW = window.innerWidth;
		sH = window.innerHeight;
	}

	divLayer.style.left = oX;
	divLayer.style.top = oY;
	divLayer.style.width = sW;
	divLayer.style.height = sH;

	// Check for scrolling again in 1/10 of a second
	setTimeout( "repositionOverlayOnScroll ()", 100 );
}

// Toggle between "minimized" & "restored" modes for GUI content
function guiToggle( guiName, buttonId )
{
	var gui = document.getElementById('gui_' + guiName);
	var currentState = false;
	if (gui.className == 'showDiv') { currentState = true; }

	if (currentState == true)
	{
		// Currently on, so turn off
		gui.className = 'hideDiv';
		buttonId.className = 'gui_button_restore';
	}
	else
	{
		// Currently off, so turn on
		gui.className = 'showDiv';
		buttonId.className = 'gui_button_minimize';
	}
}

// Preload images (esp. for javascript functions which display new images, so browser doesn't have to load them on the fly. Keeps the interface smooth)
function MM_preloadImages()
{
	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];
			}
	}
}

// Swap an image for another
function swapImage ( imageId, newSrc )
{
	document.getElementById( imageId ).src = newSrc;
}

// Download a file or generated content
function download (fileName, scriptOveride)
{
	var script;
	if ( scriptOveride.length > 0 )
	{
		// May want to open another script in standard 'download' window first
		// (to create a file & then redirect to download script for example)
		script = scriptOveride;
	}
	else
	{
		script = 'cgi-bin/zonetrade/common.cgi?action=downloadFile&close=1&fileName=' + fileName;
	}

	// Open a window which will direct the user to the correct file
	openWindow( serverURL_s + '/' + script, 'File', 'scrolling=yes,resizable=yes', 350, 150 );
}

// Add a +- toggle button to toggle visibility of target
function addToggle ( target, defaultState )
{
	// Default toggle state is TRUE (open/visible)
	defaultState = (defaultState == null) ? true : defaultState;

	// Add button
	var toggleText = "<div class=\"toggle "+(defaultState == true ? 'on' : 'off')+"\" onClick=\"toggle(this,'"+target+"')\"></div>";
	document.write(toggleText);

	// Make sure target is in state reflecting button
	// But it has to happen LATER because chances are definition
	// of target has been run across yet
	setTimeout( function() {
			var targetObj = getObj( target );
			if (! targetObj.obj ) { return false; }
			if ( defaultState )
			{
				// Open by default, force it open
				classChange( targetObj.obj, 'show', 'hide' );
			}
			else
			{
				// Closed by default, force it shut
				classChange( targetObj.obj, 'hide', 'show' );
			}
		},
		100
	);

	return true;
}

// Toggle target on/off (visibility)
function toggle ( button, target )
{

	if ( typeof button != 'object' ) { return false; }
	var targetObj = getObj( target );
	if (! targetObj.obj ) { return false; }

	if ( hasClass (button, 'on') )
	{
		classChange( targetObj.obj, 'hide', 'show' );
		classChange( button, 'off', 'on' );
		return true;
	}
	else if ( hasClass (button, 'off') )
	{
		classChange( targetObj.obj, 'show', 'hide' );
		classChange( button, 'on', 'off' );
		return true;
	}
	else
	{
		return false;
	}
}




// Toggle the 'important' flag for a note
/*function noteFlagToggle ( iNoteId, sType, sFlagId )
{
	var popURL = 'http://www.waterexchange.com.au/cgi-bin/zonetrade/common.cgi?action=noteFlagToggle'
	//var popURL = 'http://localhost:8080/cgi-bin/zonetrade/common.cgi?action=noteFlagToggle'
	+ '&noteId=' + iNoteId
	+ '&type=' + sType
	+ '&flagId=' + sFlagId;
	openWindow( popURL, 'toggleFlag' + sFlagId, 'toolbar=no,resizable=yes,status=yes', '50', '50', 1 );
	self.focus();
}

// Update the note 'flag' on the page for the given flag
function updateFlagOnPage ( sFlagId, bResult )
{
	var suffix;
	if (bResult == 1)
	{
		suffix = '_o';
	}
	else
	{
		suffix = '';
	}

	document.getElementById( sFlagId ).src = '/images/common/flag' + suffix + '.gif';
}
*/


/*
 *	FORM CONTROL
 *	Handle form events
 */

function checkLogin ()
{
	var loginForm = document.getElementById('loginFormID');

	with ( loginForm )
	{
		var errMsg = '';

		// Make sure we have a user name and password, and a valid site section has been chosen for login
		var loginToValue = loginTo.options[ loginTo.selectedIndex ].value;
		if ( loginToValue < 1 || loginToValue > 3 )
		{
			errMsg += '- Select a site section to log in to\n';
		}
		if ( uid.value.length <= 0 )
		{
			errMsg += '- Enter your user ID\n';
		}
		if ( pin.value.length <= 0 )
		{
			errMsg += '- Enter your PIN number / password\n';
		}

		// If any error messages, display them & return false, otherwise, submit according to site section
		if ( errMsg.length > 0 )
		{
			showErr( errMsg );
			return false;
		}

	}

	return true;
}

