/*****************************************************************************
******************************************************************************

f_funx.js

Written by Chris Harding and Joshua McKinney
© Copyright F1 Solutions Pty Ltd 2003

This file holds the code for general functions used by all pages.

Production Version 2.0 - June 2007

******************************************************************************
*****************************************************************************/


/* Function: isValidDate(strDate)                          */
/* This function returns true if the date specified by     */
/* strDate is a valid date, otherwise false.               */
/* *** NOT IMPLEMENTED YET *** FOR FUTURE USE ***          */
/* INPUTS : string                                         */
/* OUTPUTS: true                                           */
function isValidDate(strDate) {
	return true;
}


/*******************************************/
/*  varBTY: convert bool value to yes/no   */
/*******************************************/

/* Function: varBTY(pvarBool)                              */
/* This function returns yes if the value specified by     */
/* pvarBool is true, otherwise no.                         */
/* INPUTS : boolean                                        */
/* OUTPUTS: yes/no                                         */
function varBTY(pvarBool) {
	if(pvarBool=="true" || pvarBool==true)
		return "yes";
	else
		return "no";
}


/*******************************************/
/*  varNTS: convert null to string         */
/*******************************************/

/* Function: varNTS(pvarObj,pstrOther)                     */
/* This function returns the string representation of the  */
/* object specified by pvarObj, if it is null then it      */
/* returns the string specified by pstrOther or an empty   */
/* string.                                                 */
/* INPUTS : object, string/null                            */
/* OUTPUTS: string                                         */
function varNTS(pvarObj,pstrOther) {
	if(pvarObj==null) {
		if(pstrOther)
			return pstrOther;
		else
			return "";
	}
	else
		return pvarObj;
}



/* Function: varETS(pvarObj,pstrOther)                     */
/* This function returns the string representation of the  */
/* object specified by pvarObj, if it is an empty string   */
/* then it returns the string specified by pstrOther or an */
/* empty string.                                           */
/* INPUTS : object, string/null                            */
/* OUTPUTS: string                                         */
function varETS(pvarObj,pstrOther) {
	var strTemp = varNTS(pvarObj, pstrOther);
	if(strTemp=="") {
		if(pstrOther)
			return pstrOther;
		else
			return "";
	}
	else
		return pvarObj;
}


/**************************************************/
/*  varNANTZ: convert NaN or null to zero         */
/**************************************************/

/* Function: varNANTZ(pvarQty)                             */
/* This function returns the value specified by pvarQty or */
/* if it is NaN or null then it returns 0.                 */
/* INPUTS : object                                         */
/* OUTPUTS: int                                            */
function varNANTZ(pvarQty) {
	if(isNaN(pvarQty) || (pvarQty==null))
		return 0;
	else
		return pvarQty;
}



/* Function: format(expr, decplaces)                       */
/* This function formats the number specified by expr to   */
/* the number of decimal places specified by decplaces.    */
/* INPUTS : double, int                                    */
/* OUTPUTS: double                                         */
function format(expr, decplaces) {
	// raise incoming value by power of 10 times the
	// number of decimal places; round to an integer; convert to string
	var str = "" + Math.round(eval(expr) * Math.pow(10,decplaces));
	// pad small value strings with zeros to the left of rounded number
	while (str.length <= decplaces) {
		str = "0" + str;
	}
	// establish location of decimal point
	var decpoint = str.length - decplaces;
	// assemble final result from: (a) the string up to the position of
	// the decimal point; (b) the decimal point; and (c) the balance
	// of the string. Return finished product.
	return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
}


/*******************************************/
/*  chr: return intNumber of strChar       */
/*******************************************/

/* Function: chr(intNumber, strChar)                       */
/* This function returns the character specified by        */
/* strChar the number of times specified by intNumber.     */
/* INPUTS : int, char                                      */
/* OUTPUTS: string                                         */
function chr(intNumber, strChar) {
	var strString="";
	for(k=0;k<intNumber;k++) {
		strString+=strChar;
	}
	return strString;
}



/* Function: padString(strVar, intCharCount)               */
/* This function returns the string specified by strVar    */
/* padded with spaces to the maximum length specified by   */
/* intCharCount.                                           */
/* INPUTS : string, int                                    */
/* OUTPUTS: string                                         */
function padString(strVar, intCharCount) {
	strVar+="";
	return strVar.substr(0,intCharCount) + chr(intCharCount-strVar.substr(0,intCharCount).length," ");
}


function padStringRight(strVar, intCharCount) {
	strVar+="";
	return chr(intCharCount-strVar.substr(0,intCharCount).length," ") + strVar.substr(0,intCharCount);
}

function padStringCentre(strVar, intCharCount) {
	strVar+="";
	var s = strVar.substr(0,intCharCount);
	var i = s.length;
	return chr(Math.floor((intCharCount - i)/2), " ") + strVar.substr(0,intCharCount) + chr(Math.ceil((intCharCount - i)/2), " ") ;
}



/* Function: wrapLine(pvarString, pintLineLength)          */
/* This function returns the string specified by           */
/* pvarString wrapped to the line length specified by      */
/* pintLineLength.                                         */
/* INPUTS : string, int                                    */
/* OUTPUTS: string                                         */
function wrapLine(pvarString, pintLineLength) {
	// given the line length, wrap the line at " "
	//alert("wrapLine:\npvarString="+pvarString);
	var strTemp = pvarString;
	var strReturn = "";
	var intIndex = 0;
	var intNewIndex = 0;
	if(strTemp.length>pintLineLength) {
		while(intIndex+pintLineLength<strTemp.length) {
			intNewIndex=strTemp.lastIndexOf(" ", intIndex+pintLineLength);
			strReturn += strTemp.substring(intIndex, intNewIndex).replace(/^\s/,"") + "\n";
			intIndex = intNewIndex;
		}
		strReturn += strTemp.substring(intIndex, strTemp.length).replace(/^\s/,"");
	}
	else {
		strReturn = pvarString;
	}
	return strReturn;
}



/* Function: formatNumber(pintPlacesPre, pstrString)       */
/* This function returns the string specified by           */
/* pstrString with leading zeros to make the number the    */
/* length specified by pintPlacesPre.                      */
/* INPUTS : int, string                                    */
/* OUTPUTS: string                                         */
function formatNumber(pintPlacesPre, pstrString) {
	var strInput = new String(pstrString);
	var strReturn = "";
	var intLen = strInput.length;
	var intLoops = parseInt(pintPlacesPre) - intLen;
	if(intLoops > 0) {
		for(intFmt=0; intFmt < intLoops; intFmt++) {
			strReturn += "0";
		}
	}
	strReturn += pstrString;
	return(strReturn);
}



/* Function: DisplayError(pstrErrorNumber, pobjErrorObject)*/
/* This function displays an error dialog box with the     */
/* error number specified by pstrErrorNumber and the error */
/* details specified in the pobjErrorObject.               */
/* INPUTS : string, error                                  */
/* OUTPUTS: none                                           */
function DisplayError(pstrErrorNumber, pobjErrorObject) {
	var strBegin, strMiddle, strEnd;
	strBegin = "#########################################\n"+
	           " Dangerous Goods Ready Reckoner Error!\n"+
	           "\n"+
	           " An error has occured\n"+
	           " Please consult the troubleshooting page for\n"+
	           " further assistance.\n"+
	           "\n"

	strMiddle = " Error Number: "+formatNumber(3, pstrErrorNumber)+"\n"+
	            " Error Code: "+pobjErrorObject.number+"\n"+
	            " Error Description: "+pobjErrorObject.description+"\n"

	strEnd = "\n"+
	         "#########################################\n"
	alert(strBegin+strMiddle+strEnd);
	setCookie("dgrrerrordata", pstrErrorNumber);
	//location.href="troubleshooting.htm";

}

// - DS: Start
// - Removed - Start
/* Function: getDateTime()                                 */
/* This function returns the current date and time to the  */
/* second formatted in Australian format.                  */
/* INPUTS : none                                           */
/* OUTPUTS: string                                         */
//function getDateTime() {
//	var d, s = "";
//	d = new Date();
//	s += formatNumber(2,d.getDate()) + "/";
//	s += formatNumber(2,(d.getMonth() + 1)) + "/";
//	var year = new String(d.getYear()).substring(2);
//    var yearPrefix = '20';
//  if (year.length == 1) {
//        yearPrefix = '200';  
//  }
//	s +=  yearPrefix + year;//formatNumber(4,d.getYear());
//	s += " ";
//	s += formatNumber(2,d.getHours()) + ":";
//	s += formatNumber(2,d.getMinutes()) + ":";
//	s += formatNumber(2,d.getSeconds());
//	return(s);
//}
// - Removed - End 

/* Function: getDateTime()                                 */
/* This function returns the current date and time to the  */
/* second formatted in Australian format.                  */
/* INPUTS : none                                           */
/* OUTPUTS: string                                         */
function getDateTime() {
	var d, s = "";
	d = new Date();
	s += formatNumber(2,d.getDate()) + "/";
	s += formatNumber(2,(d.getMonth() + 1)) + "/";
	var year = new String(d.getYear()).substring(2);
   	var yearPrefix = '20';
	if (year.length < 2 ) {
 	    s += yearPrefix + '0' + year;
 	 } else {
		s += yearPrefix + year;
	 }
	s += " ";
	s += formatNumber(2,d.getHours()) + ":";
	s += formatNumber(2,d.getMinutes()) + ":";
	s += formatNumber(2,d.getSeconds());
	return(s);
}
// - DS: End

/************************************/
/* function to replace non-numeric  */
/* chars from quantity field        */
/************************************/

/* Function: parseQty(strValue)                            */
/* This function returns the value specified by strValue   */
/* with all the non-numeric characters stripped from it.   */
/* INPUTS : string                                         */
/* OUTPUTS: string                                         */
function parseQty(strValue) {
	var re, r, orig;
	// regexp object matching all non-decimal chars
	re = /\D/;
	orig = strValue;
	// replace all non-decimal chars with empty string
	r = orig.replace(re, "");
	while (orig != r) {
		orig = r;
		r = orig.replace(re, "");
	}
	if(r=="")
		r=0;
	return r;
}



/*****************************************************************************
/* Function: getDateYMD()
/*
/*	PURPOSE
/*		returns the current date in the format of YYYY-MM-DD
/*	PARAMETERS
/*		none
/*	RETURNS
/*		string: current date in YYY-MM-DD format
/*	SIDE EFFECTS
/*		none
/*	MODIFICATION HISTORY
/*		2004-09-15 JDM
/*			Y2K fix. Added check for getYear returning two digit year.
/****************************************************************************/
function getDateYMD() {
	var d, y, s = "";
	d = new Date();
	y = d.getYear();
	if (y < 100) {
		y += 2000;
	}
	s += formatNumber(4, y) + "-";
	s += formatNumber(2, (d.getMonth() + 1)) + "-";
	s += formatNumber(2, d.getDate());
	return(s);
}
/* End Function getDateYMD()
/****************************************************************************/


/*****************************************************************************
/* Function: getFileNameToSave(defaultPath, defaultFilename, defaultExtension, dialogTitle, filter)
/*
/*	PURPOSE
/*		prompts the user to enter a filename.  Uses a common dialog box (cdl)
/*		if this is available.  Otherwise just uses a javascript prompt
/*		requires that a cdl called CommonDialog1 be on the formDGRR form.
/*	PARAMETERS
/*		string defaultPath: path to start browsing in cdl
/*		string defaultFilename: default filename displayed in save dlg box
/*				including extension
/*		string dialogTitle: title of the cdl
/*		string defaultExtension: default selected extension for cdl
/*		string filter: filter of files to show in cdl
/*	RETURNS
/*		string: filename to save to
/*		or null if user clicks cancel
/*	SIDE EFFECTS
/*		none
/*	MODIFICATION HISTORY
/*		2004-09-15 JDM
/*			moved this functionality away from the forms js files.
/*		2004-09-13 JDM
/*			common dialog functionality not working at present (Arrghh!)
/****************************************************************************/
function getFileNameToSave(defaultPath, defaultFilename, dialogTitle, defaultExtension, filter) {
	var sFilename = "";
	placardPremises();
	if (document.getElementById('frmDGRR')['CommonDialog1'].object != null) {
		with (document.frmDGRR.CommonDialog1) {
			// throw an error if the user cancels the dialog box.
			CancelError= true;
			MaxFileSize = 260;
			DialogTitle = dialogTitle;
			DefaultExt = defaultExtension;
			FileName = defaultFilename;
			Filter = filter;
			try {
				showSave();
				sFilename = FileName;
			} catch (e) {
				// Error numbers from MSDN doco
				var cdlCancel = 32755;
				var errObjectExpected = 5007;

				// real error number is stored in the low bytes of e.number
				var eNum = e.number & 0xFFFF;
				if (eNum == cdlCancel) {
					sFilename = null;
				} else if (eNum == errObjectExpected) {
					sFilename = prompt('Please enter the filename to save to including the path',
							defaultPath + defaultFilename);
				} else {
					throw (e);
				}
			} // end catch...
		} // end with...
	} else {
		// CommonDialog1 object does not exist or there are issues!!!
		sFilename = prompt('Please enter the filename to save to including the path',
						defaultPath + defaultFilename);
	}
	return sFilename;
}
/* End Function getFileNameToSave(defaultPath, defaultFilename, dialogTitle, defaultExtension, filter)
/****************************************************************************/


/*****************************************************************************
/* Function: saveTextToFile(sFilename, sText)
/*
/*	PURPOSE
/*		saves provided text to provided filename.  creates directories if needed
/*		and user confirms that they want to create them.
/*		prompts for overwriting existing file.
/*	PARAMETERS
/*		string sFilename: name of file to save to
/*		string sText: text to save to file
/*	RETURNS
/*		boolean: whether save was successful
/*	SIDE EFFECTS
/*		folder created if user selects to create folder
/*		file overwritten if user confirms this
/*	MODIFICATION HISTORY
/*		2004-09-15 JDM
/*			initial dev
/****************************************************************************/

function saveTextToFile(sFilename, sText) {
	// old active X
	return true;
}
/* End Function saveTextToFile(sFilename, sText)
/****************************************************************************/
var newWindowHeight = 215;
var newWindowWidth = 430;

function openNewWindow(reportType) {
	if (!confirm(mustTrust)) {
		return;
	}
	var newWindow = window.open("", "pictureViewer", 
        "location=no, directories=no, replace=true, fullscreen=no, menubar=no, status=yes, toolbar=no, width=" 
	+ newWindowWidth + ", height=" + newWindowHeight + ", scrollbars=no");
	newWindow.document.writeln("<html><head>");
	newWindow.document.writeln('<link rel="stylesheet" type="text/css" href="include/pc_ie.css" />');
	newWindow.document.writeln('<link rel="stylesheet" type="text/css" href="include/dgrr.css" />');
	newWindow.document.writeln('<link rel="stylesheet" type="text/css" media="print" href="include/dgrr_prn.css" />');		
	// avoid the annoying 'Click to activate and use this control' IE issue 
	if (navigator.appName == 'Microsoft Internet Explorer') {	
		newWindow.document.writeln('<script type="text/javascript" src="include/1.2.0_alpha/embeddedcontent.js" defer="defer"></script>');
	} 
	//newWindow.document.writeln("<script>function closedWin() {confirm('close ?');return false;}</script>");
	newWindow.document.writeln("</head><body> ");
	newWindow.document.writeln('<table><tr><td><IMG alt="WorkSafe Victoria" src="images/vwa-shrink.jpg" ></td></tr><tr><td>');
	newWindow.document.writeln(insertApplet(reportType));
	newWindow.document.writeln("</td></tr></table></body>");
	newWindow.document.close();
}

// using inner html which is not best practice (htmlContent)
function insertApplet(reportType) {
	var _app = navigator.appName;
	var appletName = "VwaReportSaver", str = "";	
	if (_app == 'Mozilla' || _app == 'Netscape') {		
		str += '<object classid="java:'+appletName+'.class"';
		str += 'type="application/x-java-applet"';
		str += ' archive="SVwaReportSaver.jar" ';
		str += ' height="' + (newWindowHeight*0.8)  + '" width="' + (newWindowWidth*0.8) +'" >';  
	} else if (_app == 'Microsoft Internet Explorer') {
		str += '<object ';
		str += 'classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"';
		str += ' width="' + (newWindowWidth *0.8) +'" height="' + (newWindowHeight*0.8)  + '">';
		str += '<param name="code" value="' ;
		str += appletName;
		str += '">';
	} else {
		return '<p>Sorry, unsupported browser.</p>';
	}
	str += '<param name="WINDOWHEIGHT" value="'+newWindowHeight+'">';
	str += '<param name="archive" value="SVwaReportSaver.jar">';
	str += '<param name="version" value="Version 2.0 - June 2007">';
	str += '<param name="reportType" value="' + reportType + '">';
	str += '<param name="WINDOWTITLE" value="BorderLayout">';
	str += '<param name="BUTTONTEXT" value="Download Report">';
	str += '<param name="mayscript" value="true">';
	str += '</object>';	
	return str;
}

/*****************************************************************************
/* Function: createFolder(sFolderName)
/*
/*	PURPOSE
/*		recursively create the folder heirachy specified
/*	PARAMETERS
/*		string sFolderName: name of folder to create
/*	RETURNS
/*		true if folder was created or folder already exists
/*	SIDE EFFECTS
/*		heirachy of folders created
/*	MODIFICATION HISTORY
/*		2004-09-15 JDM
/*			initial dev
/****************************************************************************/
function createFolder(sFolderName) {
	// old active X
	return true;
}
/* End Function createFolder(sFolderName)
/****************************************************************************/
