//Global messages
var g_IsDirtyMsg = "No changes detected, nothing to update.";
var g_confirmMsg = "";
//Row select variables
var selectedRowColor = null;
var selectedRow = null;

function checkStringSize(elemCheck,intMax) {
	var elemReport = null;

	if (arguments.length = 3) {
		elemReport = arguments[2];
	}
	if(elemCheck) {
		if(elemCheck.value.length > intMax) {
			alert("String is beyond limit (" + intMax + ")");
			elemCheck.value = elemCheck.value.substring(0,intMax);
		} else {
			//update elemReport if it exists
			if(elemReport) {
				elemReport.innerHTML = elemCheck.value.length;
			}
		}
	}
}

function reformatDigits(elem) {
	var strTemp = '';
	if(elem) {
		strTemp = stripCharsNotInBag(elem.value,'0123456789');
		//strTemp = reformat10(strTemp,"(",3,") ",3,"-",4);
		elem.value = strTemp;
	} else {
		alert('Not a document element.');
	}
}

function reformatDate(elem) {
	var strTemp = '';
	if(elem) {
		strTemp = stripCharsNotInBag(elem.value,'0123456789/');
		//strTemp = reformat10(strTemp,"(",3,") ",3,"-",4);
		elem.value = strTemp;
	} else {
		alert('Not a document element.');
	}
}

// Removes all characters which appear in string bag from string s.

function stripCharsInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;

}



// Removes all characters which do NOT appear in string bag 
// from string s.

function stripCharsNotInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}

function reformat10 (s)

{   var arg;
    var sPos = 0;
    var resultString = "";
    var strTemp = "";

	if(reformat10.arguments[0].length < 1) return resultString;
    for (var i = 1; i < reformat10.arguments.length; i++) {
      arg = reformat10.arguments[i];
       if (i % 2 == 1) resultString += arg;
       else {
			strTemp = s.substring(sPos, sPos + arg);
			resultString += strTemp;
			if (strTemp.length == arg){
	            sPos += arg;
	        }
	        else {
				break;
			}
        }
    }
    return resultString;
}

/*
Description
History		Date			Author				Description
			04/24/2001		Michael Bartha		Created
*/
function selectAllOptions() {
	var objElem = null;
	var strError = "";

	for(var j = 0;j<arguments.length;j++) {
		objElem = arguments[j];

		if(objElem) {
			if(objElem.type != "select-multiple" || objElem.type != "select-one") {
				var count = objElem.options.length;
				for(var i = 0;i<count;i++) {
					objElem.options[i].selected = true;
				}
			}
			else {
				strError += "Argument " + j + ": Object is not a select.\n"
			}
		}
		else {
			strError += "Argument " + j + ": Object does not exist.\n"
		}
	}
	if (strError.length > 0)
	{
		//alert(strError);
	}
}

/*
Description
History		Date			Author				Description
			03/16/2001		Michael Bartha		Created
*/
function popUpWinOptions(strOptions) {
	this.options = strOptions || "";
	this.win = null;
	this.updateParent = false
}

var popUpWin = new popUpWinOptions();

function openWindow(strURL) {
	var querystr = "&popup=true";

	if(arguments.length == 2) {
		//value supplied
		querystr = "";
	}

	if(!popUpWin.win) {
		//format url
		strURL += querystr
		//open window
		popUpWin.win = window.open(strURL,"",popUpWin.options);
	}
	else {
		//set focus to pop-up
		popUpWin.win.focus();
	}
}

function closeWindow() {
	if(window.opener) {
		window.opener.closeWindow();
		if(popUpWin.updateParent) {
			window.opener.document.location.reload(true);
		}
	}
	else {
		popUpWin.win = null;
	}
}

function checkRow() {
	var e = event.srcElement;
	var eTR = getElem(e,'TR');
	var isTR = (eTR.tagName == 'TR' ? true : false);
	var bSet = true;
	if(isTR) {
		if(selectedRow) {
			//restore original
			selectedRow.className = selectedRowColor;
			if(selectedRow == eTR) {
				//toggle back
				/*
				selectedRow.className = selectedRowColor;
				selectedRow = null;
				selectedRowColor = null;
				bSet = false;
				*/
			}
		}
		if(bSet) {
			//highlight new row
			selectedRowColor = eTR.className;
			eTR.className = 'highlight';
			selectedRow = eTR;
		}
	}
}

function getElem(eSrc,sElem) {
	var e = eSrc;

	while (e.tagName != sElem) {
		e = e.parentElement;
	}
	return e;
}
//End of new functions

function setFN(strData) {
	frmSearchResults.fn.value=strData;
}

function setConfirmMsg(strData) {
	g_confirmMsg = strData;
}

function selectAllChecks(objElem) {
	if(objElem) {
		var count = objElem.length;
		for(var i = 0;i<count;i++) {
			if(objElem[i].type != "checkbox") {
				alert("Form element is not a checkbox.");
				break;
			}
			objElem[i].checked = true;
		}
	}
	else {
		alert("Object does not exist.");
	}
}

function clearAllChecks(objElem) {
	if(objElem) {
		var count = objElem.length;
		for(var i = 0;i<count;i++) {
			if(objElem[i].type != "checkbox") {
				alert("Form element is not a checkbox.");
				break;
			}
			objElem[i].checked = false;
		}
	}
	else {
		alert("Object does not exist.");
	}
}

function toggleEnabled(strElem) {
/*
	Purpose:	Toggles the enabled/disabled state of form elements
	Inputs:		strElem 	- string, the element that the window will be open next to
					Sample: 'frmTest.btnSubmit' -- element(s) that match name
							'frmTest.all' -- all elements on form
	Outputs:	None
	Notes:		None
	
	Date		Author			Description
	06/02/2000	Michael Bartha	Created function
*/
	var objElem;
	objElem = eval("document." + strElem);
	if(isNaN(objElem.length)) {
		if(objElem.disabled) {
			objElem.disabled = false;
		}
		else {
			objElem.disabled = true;
		}
	}
	else {
		if(objElem.type) {
			if((objElem.type).indexOf("select",0) >= 0) {
				//treat as single
				if(objElem.disabled) {
				objElem.disabled = false;
				}
				else {
					objElem.disabled = true;
				}
			}
		}
		else {
			for(x=0;x < objElem.length; x++) {
				if(objElem[x].disabled) {
					objElem[x].disabled = false;
				}
				else {
					objElem[x].disabled = true;
				}
			}
		}
	}
}


function copyitem(objTarget,strOption) {
	/*
	Purpose:	Creates a new option in a select element
	Inputs:		objTarget	- object reference to a select form element
				strName 	- string, value of item to be inserted
							the 0 position has the value, 1 has the view name
	Outputs:	newly created option is selected in form element
	Notes:		None
	
	Updates:	Date		Author			Description
				05/10/2000	Michael Bartha	Created function
				03/21/2001	Michael Bartha	Modified to report errors and use objects
	*/
	var objOption = null;
	var strValue = strOption;

	//check to see if third argument provided whicih will be value
	//otherwise option and value will be the same
	if(arguments.length == 3) {
		//value supplied
		strValue = arguments[2];
	}
	
	if(strOption.length > 0) {
		if(objTarget.type) {
			if((objTarget.type).indexOf("select",0) >= 0) {
				//alert(objBoxTarget.options.length);
				//0 position hold the value
				//1 position holds the viewed name
				//search for existing value
				if (!exists(arrSource[0],objTarget)) {
					//alert("inserting");
					objOption = new Option(strOption,strValue,false,false);
					objTarget.options[objTarget.options.length] = objOption;
				}
				//select newly inserted item
				objTarget.options[objTarget.options.length-1].selected = true;
			}
			else {
				alert("Target form element is not a select object.");
			}
		}
		else {
			alert("Target object is not a form element.");
		}
	}
	else {
		alert("No name was provided for option.");
	}
	
}

function copyitemObj2Obj(objSource,objTarget) {

	var objoption;
	var all = false;

	if(arguments.length == 3) {
		//value supplied
		all = arguments[2];
	}

	var intCount = objSource.options.length;//oBoxSource.options.length;
	for(var i = intCount-1; i>=0;i--) {
		if(!all) {
			if (objSource.options[i].selected) {
				//search for existing value
				if (!exists(objSource.options[i].value,objTarget)) {
					objoption = new Option(objSource.options[i].text,objSource.options[i].value,false,false);
					objTarget.options[objTarget.options.length] = objoption;
					objSource.options[i] = null;
				}
			}
		}
		else {
			//search for existing value
			//alert(oBoxSource.options[i].value);
			if (!exists(objSource.options[i].value,objTarget))	{
				objoption = new Option(objSource.options[i].text,objSource.options[i].value,false,false);
				objTarget.options[objTarget.options.length] = objoption;
				objSource.options[i] = null;
				//alert(oBoxSource.options.length);
			}
		}
	}
}

function exists(strItem,objBox) {
	/*
	Purpose:	Check for the existence of item in select box
	Inputs:		strItem	- string, the value of item to be inserted
				objBox 	- object, the select object to check
	Outputs:	true or false
	Notes:		None
	
	Updates:	Date		Author			Description
				05/10/2000	Michael Bartha	Created function
	*/
	//alert("Item: " + strItem);
	for(var i = 0; i< objBox.options.length;i++) {
		//alert("Match: " + item + " | " + objBox.options[i].value);
		if (objBox.options[i].value == strItem) {
			//match found
			return true;
		}
	}
	return false;
}


function IsDirty(eForm) {   
/*
Purpose:       Checks if any fields of a form's section has been changed.Form is divided
               into sections.Each section has a hidden field.The prefixes of hidden and other
               fields must be same.If any fields of a section has been changed,the value of 
               hidden field is set to True
Inputs:        eForm a form object
Outputs:       False if nothing changed,True if anything changed  
Errors:        
Notes:         


Updates:        Date                Author                      Description
				04/20/2000          Michael Bartha              created function
				04/20/2000          Ramazan Aksoy               added checking for each section
                01/30/2001			Michael Bartha				modifed to be NS4.x compatible
*/
    //a boolean to keep track of changing in the form
	var isFormDirty=false;
	//total number of form elements
	//var eForm = document.forms[eSrc];
	var iNumElems = eForm.elements.length;
	var eElem = null;
	var sElements = "type, name = value, [default]\n";
	
	//Check each element of form
	for (var i=0; i<iNumElems; i++) {
	   	eElem = eForm.elements[i];
	   	//Check text and textarea fields
		if ("text" == eElem.type || "textarea" == eElem.type){// || "hidden" == eElem.type) {
			//alert(eElem.name+"="+eElem.value);
			if (eElem.value != eElem.defaultValue) {  
				sElements += eElem.type + ", " + eElem.name + " = " + eElem.value + ", [" + eElem.defaultValue + "]\n"
				if(markDirty(eForm,eElem)) {
					isFormDirty=true;
				}		   	   
			}
		}
		else if ("checkbox" == eElem.type || "radio" == eElem.type) {
			if (eElem.checked != eElem.defaultChecked) {
				sElements += eElem.type + ", " + eElem.name + " = " + eElem.value + ", [" + eElem.defaultChecked + "]\n"
				//if changed get prefix of the field
				if(markDirty(eForm,eElem)) {
					isFormDirty=true;
				}	
			}
		}
		else if ("select-one" == eElem.type || "select-multiple" == eElem.type) {
			var cOpts = eElem.options;
			var iNumOpts = cOpts.length;
			var eOpt = null;
			var sDefault = '';
			var sSelected = '';

			//get default selected indexes
			for (var k=0;k<iNumOpts;k++ ) {
				eOpt = cOpts[k];
				//alert("defaultSelected:"+eOpt.defaultSelected+" /value:"+eOpt.value);
				if(eOpt.defaultSelected ){ //&& eOpt.value.length != 0) {
					sDefault += k + ',';
				}
			}
			sDefault = sDefault.substring(0,sDefault.length-1);

			//get selected indexes
			for (var j=0; j<iNumOpts; j++) {
				eOpt = cOpts[j];
				if (eOpt.selected) {
					sSelected += j + ',';
				}
			}
			sSelected = sSelected.substring(0,sSelected.length-1);
			//alert(eElem.name);
			//alert("default:"+sDefault+" /selected:"+sSelected);
			if(sDefault != sSelected) {
				sElements += eElem.type + ", " + eElem.name + " = " + sSelected + ", [" + sDefault + "]\n"
				//if changed get prefix of the field
				if(markDirty(eForm,eElem)) {
					isFormDirty=true;
				}
			}
		}
	}
	//show debug alert window
	if(IsDirty.arguments.length > 1) alert(sElements);
	//Check if form has been changed
	if(isFormDirty)	{
		//if yes,return true
		return true;
	}
	else {
		//if no,return no
		alert(g_IsDirtyMsg);
		return false;
	}
}

function markDirty(eForm,eElem) {
	var section;
	var isection;

	//if changed get prefix of the field
	section=(eElem.name).substring(0,(eElem.name).lastIndexOf("_"));
	//alert("section:"+section+" /Elem:"+eElem.name);
	//find the name of hidden field for this section
	isection = section + "_IsDirty";
	//field not of format tableName_field ignore
	if (section.length > 0) {
		//check for existence of isdirty field
		if(eForm.elements[isection]) {
			//set value of hidden field to true
			eForm.elements[isection].value="true";
			return true;
		}
		else {
			alert(	'**ERROR**\n==========\nForm: ' + eForm.name + '\n' +
					'Element: ' + eElem.name + '\n' +
					'You must add a hidden form element called: ' + isection + 
					'\nto log whether any form elements have changed');
			return false;
		}
	}
}

/*
var winExport = null;


Description	Opens Export Window, copys content and strip HTML
History		Date			Author				Description
			04/11/2001		Michael Bartha		Created

function openExport(objElem) {
	
	var strContent = "";
	var strOptions = "top=50,left=400,width=600,height=500,scrollbars=yes,resizable=yes,toolbar=no,location=no";
	var re;
	var strStripped = "";

	strContent = objElem.value;
	//strip HTML tags from source
	//re = new RegExp("(<.*>).*(<\/\1>)", "gi");
	re = new RegExp("(<.*>)(a)", "gi");
	re.multiline = true;
	//re = /(<.*>).*(<\/\1>)/;
	strStripped = strContent.replace(re, "$2, $1");

	if(!winExport) {
		winExport = window.open("","",strOptions);
		winExport.document.write("<html><head>");
		winExport.document.write("<title>Export Contents</title>");
		winExport.document.write("</head>");
		winExport.document.write("<body onunload='window.opener.winExport=null;'>");
		winExport.document.write("<textarea id='content' name='content' rows='28' cols='67'>");
		winExport.document.write(strStripped);
		winExport.document.write("</textarea>");
		winExport.document.write("</body></html>");
		winExport.onunload = new function(window.opener.winExport=null);
	}
	else {
		winExport.content.value = strStripped;
	}
	winExport.focus();
}

function cvt2currency(num) {
	//converts float to string with 2 decimals
	var pos;
	var dec;
	var newnum = num + '';
	if(!isNaN(num)) {
		var sNum = num + "";
		pos = sNum.indexOf(".",0);
		if(pos > 0) {
			dec = sNum.substring(pos);
			if(dec.length==2) newnum = num + "0";
			if(dec.length==3) newnum = num;
			if(dec.length>3) newnum = Math.round(num*100)/100;
		}
		else {
			//no decimal
			newnum = num + ".00";
		}
	}
	//alert(num + '\n' + pos + '\n' + dec + '\n');
	return newnum;
}

*/
