// Copyright 2005 Intresys Inc.
// browser detection
var agt = navigator.userAgent.toLowerCase();
var gbNN = (navigator.appName.indexOf("Netscape") != -1);
var gbNN4 = (null!=document.layers);
var gbOpera = (agt.indexOf("opera")!=-1); // Opera (mozilla/4.0 (compatible; msie 6.0; windows nt 5.1; en) opera 8.02)
var gbSafari = (agt.indexOf("safari") != -1); // Safari (mozilla/5.0 (macintosh;u; ppc mac os x; en) applewebkit/124 (khtml, like gecko) safari/125)
var gbNN6 = (agt.indexOf("mozilla/5")!=-1 && !gbSafari); // use as NN6/Mozilla/Firefox
var gbIE = (agt.indexOf("msie") != -1 && !gbOpera);
var gbIE5 = ((agt.indexOf("msie 5")!=-1 || agt.indexOf("msie 6")!=-1) && !gbOpera);
var gbWebTV = (agt.indexOf("webtv")!=-1);
var gbDom = (gbNN6 || gbIE5 || gbOpera);

var WIN = (agt.indexOf("win")!=-1);
var MAC = (agt.indexOf("mac")!=-1);

//.........................................................................................
// is Acrobat Reader installed check
var acrobat = new Object();
acrobat.installed = false;
acrobat.version = '0.0';
// up to Adobe Acrobat 7 detection script
function checkForAcrobat(startVersion) {
	if (navigator.plugins && navigator.plugins.length) { // for non IE browsers
		for (var x=0; x<navigator.plugins.length; ++x) {
			if (navigator.plugins[x].description.indexOf('Adobe Acrobat') != -1) {
				acrobat.version = parseFloat(navigator.plugins[x].description.split('Version ')[1]);
				if (acrobat.version.toString().length == 1) acrobat.version += '.0';
				if (acrobat.version >= startVersion) acrobat.installed = true; // begin from startVersion param
				break;
			}
		}
	} else if (window.ActiveXObject) { // for IE
		try {
			oAcro7 = new ActiveXObject('AcroPDF.PDF.1');
			if (oAcro7) {
				acrobat.installed = true;
				acrobat.version = '7.0';
				return;
			}
		} catch(e) {}
		try {
			oAcro4 = new ActiveXObject('PDF.PdfCtrl.1');
			if (oAcro4) {
				acrobat.installed = true;
				acrobat.version = '4.0';
				return;
			}
		} catch(e) {}
		for (var x = 6; x > 1; --x) { // begin from startVersion param
			try {
				oAcro = eval("new ActiveXObject('PDF.PdfCtrl."+x+"');");
				if (oAcro) {
					if (x >= startVersion) acrobat.installed = true;
					acrobat.version = x+'.0';
					return;
				}
			} catch(e) {}
		}
	}
}
checkForAcrobat(4); // run Acrobat check (ignore Acrobat versions below 4)
// legacy API
function acrobatInstalled() { return acrobat.installed; }

//.........................................................................................
// is Macromedia Flash Player installed check
function flashInstalled(version) {
	result = false; 
	if (!gbIE || gbOpera || (MAC && gbIE5)) {
		if (navigator.plugins && navigator.plugins.length > 0) {
			x = navigator.plugins["Shockwave Flash"];
			if (x) {
				if (x.description) {
					if (x.description.charAt(x.description.indexOf('.')-1) >= version) {
						result = true;
					}
				}
			}
		}
	} else {
		document.write('<script type="text/vbscript" language="VBScript">on error resume next\nresult = IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.' + version + '"))</script>');
	}
	return result;
}

//.........................................................................................
// confirm functions

function myconfirm(_url,_action,_object) { 
	if (confirm('Do you really want to '+_action+' this '+_object+' ?')) location.href = _url;
}

function doWarn(_url,_warn) { 
	if (confirm(_warn)) location.href = _url;
}

//.........................................................................................
// new String object type with str property
function String2(str) { this.str = str; }
// leading, trailing or all spaces trim functions
function trimStr() { return this.str.replace(/^\s*/, '').replace(/\s*$/, ''); }
function ltrimStr() { return this.str.replace(/^\s*/, ''); }
function rtrimStr() { return this.str.replace(/\s*$/, ''); }
// trim properties
String2.prototype.trim = trimStr;
String2.prototype.ltrim = ltrimStr;
String2.prototype.rtrim = rtrimStr;
// usage example:
//   tttt = new String2(courtName);
//   tttt.trim();
// or
//   (new String2(obj[i].value)).trim()


//.........................................................................................
// shorten the textareas
function textarealimit(areaObj, limit) {
	try {
		text = (new String2(areaObj.value)).trim();
		if (text.length >= limit-1) {
			alert('You have reached the space limit (' + limit + ' characters) for this field.');
			areaObj.value = text.substring(0,limit-2);
		}
	} catch(e) {}
}

//.........................................................................................
/** calendar picker
* 	usage in html page:
* 	<a href="javascript:PickDate(self.document.forms[0].elements['DueDate'])">some image</a>
*/
// default properties of calendar window
if (gbNN6) {
	dFeatures = 'dialogWidth: 185em; dialogHeight: 170em; dialogTop: 250em; dialogLeft: 300em; center: Yes; resizable: Yes; status: no; ';
} else {
	//dFeatures = 'dialogWidth: 147pt; dialogHeight: 150pt; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: no;';
	dFeatures = 'dialogWidth: 13em; dialogHeight: 13em; edge: Raised; center: Yes; help: Yes; resizable: Yes; status: no;';
}
function xShowModalDialog(sURL, elTarget, sFeatures) {
    if (sFeatures == null || sFeatures == '') sFeatures = dFeatures;
	if (window.showModalDialog) {
        sRtn = window.showModalDialog ( sURL, elTarget, sFeatures );
        if (sRtn!="") elTarget.value = sRtn;
		return false;
    }
    sFeatures = sFeatures.replace(/ /gi,'');
    aFeatures = sFeatures.split(";");
    sWinFeat = "directories=0,menubar=0,titlebar=0,toolbar=0,";
    for ( x in aFeatures )
    {
        aTmp = aFeatures[x].split(":");
        sKey = aTmp[0].toLowerCase();
        sVal = aTmp[1];
        switch (sKey)
        {
            case "dialogheight":
                sWinFeat += "height="+sVal+",";
                pHeight = sVal;
                break;
            case "dialogwidth":
                sWinFeat += "width="+sVal+",";
                pWidth = sVal;
                break;
            case "dialogtop":
                sWinFeat += "screenY="+sVal+",";
                break;
            case "dialogleft":
                sWinFeat += "screenX="+sVal+",";
                break;
            case "resizable":
                sWinFeat += "resizable="+sVal+",";
                break;
            case "status":
                sWinFeat += "status="+sVal+",";
                break;
            case "center":
                if ( sVal.toLowerCase() == "yes" )
                {
                    sWinFeat += "screenY="+((screen.availHeight-pHeight)/2)+",";
                    sWinFeat += "screenX="+((screen.availWidth-pWidth)/2)+",";
                }
                break;
        }
    }
	sURL += "?field=" + elTarget.id + "&form=" + elTarget.form.name;
    modalWin = window.open(String(sURL), "Calendar", sWinFeat);
	modalWin.focus();
}
function PickDate(contextPath, elTarget) {
	try {
		xShowModalDialog(contextPath + "/calendar.html", elTarget, "");
	} catch(e) {}
}

//.........................................................................................
/** auto center popup window script
* 	usage in html page:
* 	<a href="http://www.google.com" onclick="NewWindow(this.href,'name','500','500','yes');return false">Google</a>
*/
var win = null;
function NewWindow(mypage,myname,w,h,scroll) {
	LeftPosition = (screen.width) ? (screen.width-w)/2.5 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2.5 : 0;
	settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable,offscreenBuffering=false,status';
	win = window.open(mypage,myname,settings);
	win.offscreenBuffering = false;
	win.focus();
}

win = null;
function NewWindowWithBars(mypage,myname,w,h) {
	LeftPosition = (screen.width) ? (screen.width-w)/2.5 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2.5 : 0;
	settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars,resizable,toolbar,menubar,offscreenBuffering=false,status';
	win = window.open(mypage,myname,settings);
	win.offscreenBuffering = false;
	win.focus();
}


//.........................................................................................
/**	isNumeric function
	@returns boolean
	isReal:
		1 - validation of Real number
		other - validation of Integer number
*/
function IsNumeric(sText, isReal) {
	var IsNumber = true, dotCount = 0;
	var Char1 = sText.charAt(0);

	if (isReal == "1") { 
		var ValidChars = "0123456789."; 
	} else { 
		var ValidChars = "0123456789"; 
	}
	if (ValidChars.indexOf(Char1) == -1 && Char1 != "-" ) {
		IsNumber = false;
	} else {
		for (i = 1; i < sText.length && IsNumber == true; i++) {
			Char1 = sText.charAt(i);
			if (ValidChars.indexOf(Char1) == -1) {
				IsNumber = false;
			} else {
				if (Char1 == ".") { dotCount++; }
				if (dotCount > 1) { IsNumber = false; }
			}
		}
	}
	return IsNumber;
}

/*	validate value of html field
	dataType: 
		0 - Integer
		1 - real
*/
function inlineValidate(dataType, object) {
	var Char1 = '', newValue = '', isNum = false;
	switch(dataType) {
		case 0:
			var ValidChars = "-0123456789";
			isNum = IsNumeric(object.value,0); break;
		case 1:
			var ValidChars = "-0123456789.";
			isNum = IsNumeric(object.value,1); break;
	}
	if (!isNum) {
		alert('Enter valid value!');
		Char1 =  object.value.charAt(0);
		if (ValidChars.indexOf(Char1) != -1) { newValue += Char1; }
		for (i = 1; i < object.value.length; i++) {
			Char1 = object.value.charAt(i);
			if (ValidChars.indexOf(Char1) != -1 && Char1 != "-") { newValue += Char1; }
		}
		object.value = newValue;
	}
}

//.........................................................................................
/*	rounding function
	
*/
var precision = 2;
function roundOff(value, precision)
{
	var isNegative = value < 0;
	value = "" + Math.abs(value); //convert value to string
	precision = parseInt(precision);
	var whole = "" + Math.round(value * Math.pow(10, precision)); //whole value with all the digits multiplied by 10^precision
	var decPoint = whole.length - precision;
	if(!(decPoint < 0)) { 		//simplest situation (whole number of digits >= precision value)
		if (decPoint == 0) { 	//whole number of digits = precision value
			result = "0";
		} else { 				//whole number of digits > precision value
			result = whole.substring(0, decPoint);
		}
		result += ".";
		result += whole.substring(decPoint, whole.length);
	} else { 					//whole number of digits < precision value (ex. value=0.04)
		result = whole / Math.pow(10, precision);
	}
	return isNegative ? "-" + result: result;
}

//.........................................................................................

// function for open new window with title, inside text, width and height of window and submit button appearance
var winConsole = null;

function showWin( title, text, width, height, submitbutton ) {
		LeftPosition = (screen.width) ? (screen.width-width)/2 : 0;
		TopPosition = (screen.height) ? (screen.height-height)/2 : 0;
//        winConsole = window.open("", "", "width="+width+",height="+height+",toolbar=no,menubar=no,resizable=yes,scrollbars=yes");
		var winName = "popupWin" + Math.round(Math.random()*10000);
        winConsole = window.open("", winName, "width="+width+",height="+height+",top="+TopPosition+",left="+LeftPosition+",toolbar=no,menubar=no,resizable=yes,scrollbars=yes");
        winConsole.document.open("text/html");
		winConsole.document.writeln("<html><head>");
		winConsole.document.writeln("<title>" + title + "</title>");
		winConsole.document.writeln('<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">\n \
		<meta http-equiv="expires" content="0">\n\
		<link rel="Stylesheet" type="text/css" href="commonstyle.css">\n\
</head>\n\
<body bgcolor="White" leftmargin=0 rightmargin=0 topmargin=0 bottommargin=0 marginwidth=0 marginheight=0>\n\
	<table cellpadding=2 cellspacing=4 border=0><form name="mainform">\n\
	<tr>\n\
		<td><img src="images/spacer.gif" width=1 height=1 alt="" border=0></td>\n\
		<td class="title">' + title + '</td>\n\
	</tr>\n\
	<tr>\n\
		<td><img src="images/spacer.gif" width=1 height=1 alt="" border=0></td>\n\
		<td>\n\
			' + text + '\n\
		</td>\n\
	</tr>\n\
	<tr>\n\
		<td colspan=2><img src="images/spacer.gif" width=1 height=1 alt="" border=0></td>\n\
	</tr>\n\
	<tr>\n\
		<td><img src="images/spacer.gif" width=1 height=1 alt="" border=0></td>\n\
	    <td align="left">\n\
		');
		if ( submitbutton !=null && submitbutton != '' ) {
			winConsole.document.writeln(submitbutton);
		} else {
			winConsole.document.writeln('\n\
			<input name="cancel" type="button" value="Close" class="btn" onclick="window.close()">');
		}
		winConsole.document.writeln('\n\
		</td>\n\
	</tr></form>\n\
</table>\n\
</body></html>');
		winConsole.focus();
}

function submitForm() {
}
//.........................................................................................

// example of work:
// input: <p align="right">oldHTML: whatever here, will be cut anyway</p>
// output: <p align="right">newText</p>
function saveHtmlFormatting(oldHTML, newText) {
	var beginHTML = "", endHTML = "";
	oldHTML = oldHTML.replace(/.*(<.+>)(.*)(<\/.+>).*/i, "$1$2$3");
	beginHTML = RegExp.$1;
	endHTML = RegExp.$3;
	return beginHTML + newText + endHTML;
}
//.........................................................................................

function closeWindow(param1, param2) {
	window.close();
}

function historyBack(param1, param2) {
	history.back();
}

function waitCursor(param1, param2) {
	if (document.body != null)
		document.body.style.cursor = 'wait';
}
// set focus on specified field
function setFocus(formName, arrayIndex, objName) {
	try {
		with (document.forms[formName]) {
			if (arrayIndex < 0) { elements[objName].focus(); }
			else { elements[objName][arrayIndex].focus(); }	
		}
	} catch(e) {}
}

//.........................................................................................
// functions for formatting the negative amounts
//

function jsReplaceChar(item, OldChar, NewChar) {
	var r = "";
	for(var i=0; i<item.length; i++) {
		if (item.charAt(i) == OldChar) { 
			r += NewChar; 
		} else {
			r += item.charAt(i);
		}
	}
	return r;
}

function jsRemoveChar(item, needlessChar) {
	var r = "";
	for (var i=0; i<item.length; i++) {
		if (item.charAt(i) != needlessChar) r += item.charAt(i);
	}
	return r;
}

function formatParenthesesToNumber(value) {
	var sStr = value;
	var comma = ',', leftParenthesis = '(', rightParenthesis = ')';
	
	sStr = jsRemoveChar(sStr,comma);
	sStr = jsReplaceChar(sStr, leftParenthesis,'-');
	sStr = jsRemoveChar(sStr, rightParenthesis);
	
	return sStr;
}

function formatNumberToParentheses(value) {
	var sStr = value;
	var leftParenthesis = '(', rightParenthesis = ')';
	
	if (sStr.indexOf('-') == 0) {
		sStr = jsReplaceChar(sStr, '-', leftParenthesis);
		sStr += rightParenthesis;
	}
	
	return sStr;
}

//.........................................................................................

function swapImage(imageName, newImage) {
    document.images[imageName].src = newImage;
}

//.........................................................................................
// functions for Ctrl+Shift+char shortcuts processing in IE5+ and NN6+
// 
keys = new Array();
elements = new Array();
//keys = ["s","i","o","t"];	// generated from webface, should appear on the page
//elements = ["submitb2tn", "lselect","o001","tform"];	// generated from webface, should appear on the page

alphabet = "@abcdefghijklmnopqrstuvwxyz"; // possible combinations of Ctrl+Shift+char_from_this_string

var keyactive = true;
function keyon() { keyactive = true; }
function keyoff() { keyactive = false; }

function getObject(id) {
	el = document.getElementById(id);
	return el;
}

function simulateClick(el) {
	// this function simulates a user click on element el
	// returns true if any action was successfully carried
	var result = false;	// whether any action was carried w/o error
	if (el) {
		try {	// try to set focus to the element to fire onblur event, if any
			el.focus();
		} catch (err) {}
		if (el.onclick) { // call onclick() if object has it
			try {
				el.onclick();
				result = true;
			} catch(err) {} 
		}
		if (el.type && el.form) { // if el is a form input
			var elType = el.type.toLowerCase();
			if (elType == "submit" || elType == "image") { // if el is a submit button or its analog
				try {
					el.form.submit();
					result = true;
				} catch(err) {}
			} 
		} else if (el.href) { // if el has href
			try {
				window.location.href = el.href;
				result = true;
			} catch(err) {}
		} else { // suppose el is a form and try to submit it
			try {
				el.submit();
				result = true;
			} catch (err) {}
		}
	}
	return result;
}

/** 
onkeypress event handler.
Usage. 
Please follow these steps:
1. In body of html write following script lines:

<script>
	if (keys && elements) { document.onkeypress = getkey; } // call keypress handler
</script>

2. Specify two arrays: DOM elements and keys which will be pressed and handled.
Example:
<script>
	keys[0]="n"; elements[0]="submitnewbtn";
	keys[1]="s"; elements[1]="submitbtn";
	keys[2]="l"; elements[2]="lselect";
</script>

Now if element with id="submitnewbtn" exists, for example:
<input id="submitnewbtn" type="submit" value="Save & New">
then pressing "n" key on keyboard will simulate mouse click on this button.
*/
function getkey(e) {
	if (!keyactive) return true;
	if (keys.length) { // if any key to be processed
		for (i=0; i<keys.length; i++) {
			kcode = alphabet.indexOf(keys[i]); // get keycode to be processed
			if (kcode == -1) {continue;}
			el = getObject(elements[i]); // get element whos action to be executed
			if (!el) {continue;}
			toExecute = false;
			if (e == null) { // ie
				pressedcode = event.keyCode;
				if (pressedcode == kcode) {toExecute = true;}
			} else { // mozilla
				pressedcode = e.which;
				if (pressedcode == (kcode + 64)) {toExecute = true;}
			}
			if (toExecute) { // execute action
				simulateClick(el);
			}
		}
	}
	return true;
}

//.........................................................................................
/**
 * Check/uncheck all checkboxes
 * @param fm - field name
 */
function unselectAll(fn){
	checkboxes = document.getElementsByName(fn);
	for (chi = 0; chi < checkboxes.length; chi++) checkboxes[chi].checked = 0;
}
function selectAll(fn){
	checkboxes = document.getElementsByName(fn);
	for (chi = 0; chi < checkboxes.length; chi++) checkboxes[chi].checked = 1;
}
//.........................................................................................
/**
 * change the case of input field content while typing
 */
function CaseToUpper(formName, arrayIndex, fName) {
	with (document.forms[formName]) {
		elements[fName].value = elements[fName].value.toUpperCase();
	}
}
//.........................................................................................

// set focus on specified field
function clearBg(formName, arrayIndex, objName) {
	try {
		with (document.forms[formName]) {
			elements[objName].style.backgroundColor = "";
		}
		return false;
	} catch(e) {}
}
//.........................................................................................
// search for a text chunk inside of DOM object
function searchTextNode(obj) {
	for (var i = 0; i < obj.childNodes.length; i++) {
		if (obj.childNodes.item(i).nodeType == 3) { // 3 - is text node
			return obj.childNodes.item(i);

		} else if (obj.childNodes.item(i).childNodes != null) {
			return searchTextNode(obj.childNodes.item(i));

		}
	}
	return null;
}
// returns first occurence of text containing in DOM object (cross-browser) 
// (analog of returning of part of innerText/textContent before any inner html)
function getNodeText(obj) {
	if( obj && obj.childNodes != null ) {
		//search text node
		var textNode = searchTextNode(obj);
		if (textNode != null) {
			return textNode.nodeValue; 
		}
	}
	return '';
}

// returns innerText/textContent of DOM object
function getObjText(obj) {
	if(obj) {
		if (gbIE || gbOpera) {
			return obj.innerText;
		} else {
			return obj.textContent;
		}
	}
	return '';
}
// set innerText/textContent for DOM object
function setObjText(obj, txtString) {
	if(obj) {
		if (gbIE || gbOpera) {
			obj.innerText = txtString;
		} else {
			obj.textContent = txtString;
		}
	}
}

//.........................................................................................
// perform form submittion
// requirements:
// 1. form must have "submit" field (example: <input type="submit" style="display:none">)
// also put this code on visible "submit" field: onclick="submitEnclosingForm(event);"
// 2. form must have explicit onsubmit event if we need to perform a javascript on submit
function submitEnclosingForm(event) {
	try {
		if (event.srcElement) { // not supported in mozilla
			node = event.srcElement;
		} else if (event.target) { // not supported in ie
			node = event.target;
		}
		for (node = node.parentNode; node != null; node = node.parentNode) {
			if (node.submit) {
				if (node.onsubmit) node.onsubmit();
				node.submit();
				break;
			}
		}
	} catch (e) {}
	return false;
}
