var _gPageChange=0;

function _gPageChanged(){
	_gPageChange=1;
}

function _gIsPageChanged(){
	if(_gPageChange)
	    return true;
	return false;
}

function _gPageNotChanged(){
    _gPageChange=0;
}

function pageChangeOk(){
	if(_gPageChange)
	{
		var chk = window.confirm("To save changes click 'Cancel' and click 'Save'.\nTo discard any changes click 'OK'.");
		if(chk){
		    _gPageNotChanged();
			return true;
		}
	}
	else
		return true;
}
	
function HTMLfind()
{
    var x = new ActiveXObject("WScript.Shell")
    x.SendKeys("^f");
}

function openHTMLfind(windowObj)
{
    showModelessDialog('../inc/find.html', windowObj,'dialogWidth:385px; dialogHeight:100px; scroll:no; status:no; help:no;');
}

function searchtype(){
	var retval = 0;
	var matchcase = 0;
	var matchword = 0;
	retval = matchcase + matchword;
	return(retval);
}

// find the text I want
function findtext(startAgain){
	if (document.all.strSearch.value.length < 1) {
		//alert("Please enter text in the \"Find what:\" field.");
	}
	else {
		var searchval = document.all.strSearch.value;
		if(startAgain){ 
		    rng.expand("textedit");
		    rng.collapse();
		}
		else rng.collapse(false);
		if (rng.findText(searchval, 1000000000, searchtype())) {
			rng.select();
		}
		else {
			var startfromtop = confirm("Your word was not found.\nWould you like to start again from the top?");
			if (startfromtop) {
				rng.expand("textedit"); // selects everything
				rng.collapse(); // collapse at the beginning
				rng.select(); // create the selection
				findtext(); // start again
			}
		}
	}
}

function openCenterWindow(url,name,width,height)
{
	var hg=height;
	var w=width;
	var l = (screen.availWidth - w) / 2;
	var t = (screen.availHeight - hg) / 2;

//	var features = "width="+w+",height="+hg+",left="+l+",top="+t;
//	features += ",screenX="+l+",screenY="+t;
//	features += ",scrollbars=1,resizable=1,location=0";
//	features += ",menubar=0,toolbar=0,status=1,dependent=1";
//	var h = window.open(url,'',features);
//	h.focus();	
	
	var features = "dialogwidth:"+w+"px;dialogheight:"+hg+"px;scroll:yes;resizable:yes;status:yes;";
	var h = showModalDialog(url,null,features);	
	if(h){
	    var t = h.split("~");
	    if(t.length>1){
	        var d = t[1];
	        for(i=2;i<t.length;i++)
	            d += "~" + t[i];
	        window.returnValue = d;	        
	    }
	    var t1 = t[0].split("$!$");
	    if(t1.length>1)
	        window.open(t1[0], t1[1]);                   	    
	    else
	        window.location = t[0];
	}	
}

function openReportWindow(url)
{
	var h=600;
	var w=800;
	var l = (screen.availWidth - w) / 2;
	var t = (screen.availHeight - h) / 2;

	var features = "width="+w+",height="+h+",left="+l+",top="+t;
	features += ",screenX="+l+",screenY="+t;
	features += ",scrollbars=0,resizable=1,location=0";
	features += ",menubar=0,toolbar=0,status=1";
	var h = window.open(url,'',features);
	h.focus();	
}

function toolBarOver(e)
{
	if (!e)
	var e=window.event;
	var S=e.srcElement;
	while (S.tagName!="TD")
	{S=S.parentElement;}
	S.className="toolbarTDO";
}

function toolBarOut(e)
{
	if (!e)
	var e=window.event;
	var S=e.srcElement;
	while (S.tagName!="TD")
	{S=S.parentElement;}
	S.className="toolbarTD";
}

function toolbarCancel()
{
	window.history.back();
}

function submitForm(formObj){		
	var check= validateForm(formObj);
	if(check==false)
		return check;
	formObj.submit();
}	

function confirmDelete(){
	return confirm("Are you sure you want to delete record?");
}

function confirmChildDelete(){
	return confirm("Are you sure you want to delete record?\n\nNOTE:This will delete all the child records refers to this record.");
}

function goBack(){
	history.back();
}

var prevRow;
var prevRowClassName;
function RowClicked(obj,clickedLocation,childGeneration)
{
    if(obj.className=="boxrowclicked")//same row clicked
        return false;
        
    if(childGeneration==1)
    {
        if(!window.parent.frames[0].pageChangeOk()) return false;
        window.parent.frames[0]._gPageNotChanged();
    }
    else if(childGeneration==2)
    {     
        if(!window.parent.parent.frames[0].pageChangeOk()) return false;
        window.parent.parent.frames[0]._gPageNotChanged();
    }
    
	if(prevRow)
		prevRow.className = prevRowClassName;

	prevRow = obj;
	prevRowClassName = obj.className;

	obj.className = "boxrowclicked";
	
	if(clickedLocation!="")
	{
	    if(childGeneration==1)
            window.parent.frames.right.location = clickedLocation; 
        else if(childGeneration==2)
            window.parent.parent.frames.right.location = clickedLocation; 
	}
}

function RowClickedPopup(obj,clickedLocation,childGeneration,width,height)
{
    //if(obj.className=="boxrowclicked")//same row clicked
    //    return false;
        
    if(childGeneration==1)
    {
        if(!window.parent.frames[0].pageChangeOk()) return false;
        window.parent.frames[0]._gPageNotChanged();
    }
    else if(childGeneration==2)
    {     
        if(!window.opener.parent.frames[0].pageChangeOk()) return false;
        window.opener.parent.frames[0]._gPageNotChanged();
    }
    else if(childGeneration==3)
    {     
        if(!window.opener.opener.parent.frames[0].pageChangeOk()) return false;
        window.opener.opener.parent.frames[0]._gPageNotChanged();
    }
    
	//if(prevRow)
	//	prevRow.className = prevRowClassName;
	//prevRow = obj;
	//prevRowClassName = obj.className;
	//obj.className = "boxrowclicked";
	
	if(clickedLocation!="")
	{
	    openCenterWindow(clickedLocation,childGeneration,width,height);
	}
}

function RowClickedPopup2(obj,clickedLocation,childGeneration,width,height)
{
  
	if(clickedLocation!="")
	{
	    openCenterWindow(clickedLocation,childGeneration,width,height);
	}
}

function FromTreeFramePageChangeOK(){
    if(!FromFramePageChangeOK()){
        window.parent.frames.right.focus();
        return false;
    }
    FromFramePageNotChanged(); 
    return true;
}

function LeftFrameRefresh(url){
    window.parent.frames.left.location = url;
}

function FromFramePageChangeOK()
{
    return window.parent.frames.toolbar.pageChangeOk();
}

function FromFramePageNotChanged()
{
    window.parent.frames.toolbar._gPageNotChanged();
}

function FromFramePageChanged()
{
    window.parent.frames.toolbar._gPageChanged();
}

function GridLineChanged(hidObj)
{
    hidObj.value=1;
}

function SelectAllClicked(obj,type)
{   
    var frm = document.forms[0];    
    var checkString="";
    if(type==1){
        checkString="_PER_READ1";
        frm._READWRITESELECTALL.checked = false;
        frm._NOACCESSSELECTALL.checked = false;
    }
    else if(type==2){
        checkString="_PER_READWRITE1";
        frm._READSELECTALL.checked = false;
        frm._NOACCESSSELECTALL.checked = false;
    }
    else if(type==3){
        checkString="_PER_NO_ACCESS1";
        frm._READWRITESELECTALL.checked = false;
        frm._READSELECTALL.checked = false;
    }
     
    for (var i=0; i<frm.elements.length; i++){
        if(frm[i].id.indexOf(checkString)>0){
            frm[i].checked = obj.checked;
        }
    }    
}

function RecordSavedMessage(){
    //alert('Record(s) Saved.');
}

function RecordDeletedMessage(){
    //alert('Record(s) Deleted.');
}
	function setPointer() {
	    if (document.all)
	        for (var i=0;i < document.all.length; i++)
	             document.all(i).style.cursor = 'wait';
	             
	}

	function resetPointer() {
	    if (document.all)
	        for (var i=0;i < document.all.length; i++)
	             document.all(i).style.cursor = 'default';
	}

	function flipImage(url)
	{
	    if (window.event.srcElement.tagName == "IMG" ) {
	        window.event.srcElement.src = url;
	    }
	}

	 function ReplaceComma(inputString){
		var InputString = new String(inputString);
		var CommaPos;
		if (InputString!="")
		{
			CommaPos=InputString.indexOf(',');
			while (CommaPos > 0) {
				InputString=InputString.replace(',','');	
				CommaPos=InputString.indexOf(',');
			}
		}
		return InputString;
	 }
	function ReplaceAmpersand(InputString){
		var InputString = new String(inputString);
		var CommaPos;
		if (InputString!="")
		{
			CommaPos=InputString.indexOf('&');
			while (CommaPos > 0) {
				InputString=InputString.replace('&','*');	
				CommaPos=InputString.indexOf('&');
			}
		}
		return InputString;
	 } 
	 
	   // CONSTANTS
	  var separator = ",";  // use comma as 000's separator
	  var decpoint = ".";  // use period as decimal point
	  var percent = "%";
	  var currency = "$";  // use dollar sign for currency

	  function formatNumber(number, format) {  // use: formatNumber(number, "format")
        
        if (number - 0 != number) return null;  // if number is NaN return null
	    var useSeparator = format.indexOf(separator) != -1;  // use separators in number
	    var usePercent = format.indexOf(percent) != -1;  // convert output to percentage
	    var useCurrency = format.indexOf(currency) != -1;  // use currency format
	    var isNegative = (number < 0);
	    number = Math.abs (number);
	    if (usePercent) number *= 100;
	    format = strip(format, separator + percent + currency);  // remove key characters
	    number = "" + number;  // convert number input to string

	     // split input value into LHS and RHS using decpoint as divider
	    var dec = number.indexOf(decpoint) != -1;
	    var nleftEnd = (dec) ? number.substring(0, number.indexOf(".")) : number;
	    var nrightEnd = (dec) ? number.substring(number.indexOf(".") + 1) : "";

	     // split format string into LHS and RHS using decpoint as divider
	    dec = format.indexOf(decpoint) != -1;
	    var sleftEnd = (dec) ? format.substring(0, format.indexOf(".")) : format;
	    var srightEnd = (dec) ? format.substring(format.indexOf(".") + 1) : "";

	     // adjust decimal places by cropping or adding zeros to LHS of number
	    if (srightEnd.length < nrightEnd.length) {
	      var nextChar = nrightEnd.charAt(srightEnd.length) - 0;
	      nrightEnd = nrightEnd.substring(0, srightEnd.length);
	      if (nextChar >= 5) nrightEnd = "" + ((nrightEnd - 0) + 1);  // round up

	      while (srightEnd.length > nrightEnd.length) {
	        nrightEnd = "0" + nrightEnd;
	      }

	      if (srightEnd.length < nrightEnd.length) {
	        nrightEnd = nrightEnd.substring(1);
	        nleftEnd = (nleftEnd - 0) + 1;
	      }
	    } else {
	      for (var i=nrightEnd.length; srightEnd.length > nrightEnd.length; i++) {
	        if (srightEnd.charAt(i) == "0") nrightEnd += "0";  // append zero to RHS of number
	        else break;
	      }
	    }

	     // adjust leading zeros
	    sleftEnd = strip(sleftEnd, "#");  // remove hashes from LHS of format
	    while (sleftEnd.length > nleftEnd.length) {
	      nleftEnd = "0" + nleftEnd;  // prepend zero to LHS of number
	    }

	    if (useSeparator) nleftEnd = separate(nleftEnd, separator);  // add separator
	    var output = nleftEnd + ((nrightEnd != "") ? "." + nrightEnd : "");  // combine parts
	    output = ((useCurrency) ? currency : "") + output + ((usePercent) ? percent : "");
	    if (isNegative) {
	      output = (useCurrency) ? "(" + output + ")" : "-" + output;
	    }
	    return output;
	  }

	  function strip(input, chars) {  // strip all characters in 'chars' from input
	    var output = "";  // initialise output string
	    for (var i=0; i < input.length; i++)
	      if (chars.indexOf(input.charAt(i)) == -1)
	        output += input.charAt(i);
	    return output;
	  }

	  function separate(input, separator) {  // format input using 'separator' to mark 000's
	    input = "" + input;
	    var output = "";  // initialise output string
	    for (var i=0; i < input.length; i++) {
	      if (i != 0 && (input.length - i) % 3 == 0) output += separator;
	      output += input.charAt(i);
	    }
	    return output;
	  }
	  
function isValidDate(dateStr) {
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; // requires 4 digit year

	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) {
		//--alert(dateStr + " Date is not in a valid format.")
		return false;
	}
	month = matchArray[1]; // parse date into variables
	day = matchArray[3];
	year = matchArray[4];
	if (month < 1 || month > 12) { // check month range
		alert("Month must be between 1 and 12.");
		return false;
	}
	if (day < 1 || day > 31) {
		alert("Day must be between 1 and 31.");
		return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		alert("Month "+month+" doesn't have 31 days!")
		return false;
	}
	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) {
			alert("February " + year + " doesn't have " + day + " days!");
			return false;
	   }
	}
	return true;
}

function isValidTime(timeStr) {
	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

	var matchArray = timeStr.match(timePat);
	if (matchArray == null) {
		//--alert("Time is not in a valid format.");
		return false;
	}
	hour = matchArray[1];
	minute = matchArray[2];
	second = matchArray[4];
	ampm = matchArray[6];

	if (second=="") { second = null; }
	if (ampm=="") { ampm = null }

	if (hour < 0  || hour > 23) {
		alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
		return false;
	}
	if (hour <= 12 && ampm == null) {
		if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
			alert("You must specify AM or PM.");
			return false;
	   }
	}
	if  (hour > 12 && ampm != null) {
		alert("You can't specify AM or PM for military time.");
		return false;
	}
	if (minute < 0 || minute > 59) {
		alert ("Minute must be between 0 and 59.");
		return false;
	}
	if (second != null && (second < 0 || second > 59)) {
		alert ("Second must be between 0 and 59.");
		return false;
	}
	return true;
}

function _gDateDiff(firstDate,firstTime,secondDate,secondTime) {
	date1 = new Date();
	date2 = new Date();
	diff  = new Date();

	if (isValidDate(firstDate)) { // Validates first date //-- && isValidTime(dateform.firsttime.value
		date1temp = new Date(firstDate);//-- + " " + firstTime
		date1.setTime(date1temp.getTime());
	}
	else return false; // otherwise exits

	if (isValidDate(secondDate)) { // Validates second date //-- && isValidTime(dateform.firsttime.value
		date2temp = new Date(secondDate);//-- + " " + secondTime);
		date2.setTime(date2temp.getTime());
	}
	else return false; // otherwise exits

	// sets difference date to difference of first date and second date

	diff.setTime(date1.getTime() - date2.getTime());

	timediff = diff.getTime();

	//--weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
	//--timediff -= weeks * (1000 * 60 * 60 * 24 * 7);

	days = Math.floor(timediff / (1000 * 60 * 60 * 24)); 
	timediff -= days * (1000 * 60 * 60 * 24);

	//--hours = Math.floor(timediff / (1000 * 60 * 60)); 
	//--timediff -= hours * (1000 * 60 * 60);

	//--mins = Math.floor(timediff / (1000 * 60)); 
	//--timediff -= mins * (1000 * 60);

	//--secs = Math.floor(timediff / 1000); 
	//--timediff -= secs * 1000;

	//--var temp = weeks + " weeks, " + days + " days, " + hours + " hours, " + mins + " minutes, and " + secs + " seconds";
	var temp = days;

	return temp; // form should never submit, returns false
}	  
