// 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 LANGUAGE=VBScript>on error resume next\nresult = IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.' + version + '"))</SCRIPT>');
	}
	return result;
}
//.........................................................................................
// Generate email string
function supportEmail() {
	return "commute" + '\x40' + "co.sanmateo" + '\x2E' + "ca" + '\x2E' + "us";
}
//.........................................................................................
// 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 
}

//.........................................................................................
// shorten the textareas

function textarealimit(fieldname, limit) {
	str = fieldname.value.trim();
	if (str.length >= limit-1) {
		alert('You have reached the space limit (' + limit + ' characters) for this field.');
		fieldname.value = str.substring(0,limit-2);
	}
}

// These functions will trim leading, trailing or all spaces from a string
// arg = the value you wish to have trimmed..

//===================================
function trimString(arg) {
//===================================
	str = this != window? this : str;
    str.replace(/^\s*/, '').replace(/\s*$/, ''); 
	return str;
}

//===================================
function ltrimString(arg) {
//===================================
	str = this != window? this : str;
    str.replace(/^\s*/, ''); 
	return str;
}

//===================================
function rtrimString(arg) {
//===================================
	str = this != window? this : str;
    str.replace(/\s*$/, ''); 
	return str;
}

//The above function is set up so that it can be added as a method to the 
//String.prototype:

String.prototype.trim = trimString;
String.prototype.ltrim = ltrimString;
String.prototype.rtrim = rtrimString;

//-----------------------------------------------------------------------------
// calendar picker

function PickDate(elTarget) {
  if (window.showModalDialog) {
    var sRtn;
    sRtn = showModalDialog("calendar.html","","center=yes;dialogWidth=147pt;dialogHeight=150pt;status=no");
    if (sRtn!="")
      elTarget.value = sRtn;
  } else
    alert("Internet Explorer 4.0 or later is required")
 }

// in html page:
// <a href="javascript:PickDate(self.document.forms[0].DueDate)">some image</a>
//-----------------------------------------------------------------------------
// auto center popup window script

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()
}

// in html page:
//<a href="http://www.google.com" onclick="NewWindow(this.href,'name','500','500','yes');return false">Google</a>
//-----------------------------------------------------------------------------

function newImage(arg) {
	if (document.images) {
		rslt = new Image();
		rslt.src = arg;
		return rslt;
	}
}

function changeImages() {
	//if (document.images && (preloadFlag == true)) {
		for (var i=0; i<changeImages.arguments.length; i+=2) {
			document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
		}
	//}
}

var preloadFlag = false;
function preloadImages() {
	if (document.images) {
/*		treebar_02_over = newImage("images/treebar_02-over.gif");
		menu_create_folder_down = newImage("images/menu_create_folder-down.gif"); */
		preloadFlag = true;
	}
}

//-----------------------------------------------------------------------------
/* 	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)
{
	value = "" + 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 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(dummyparam1, dummyparam2) {
	window.close();
}

function historyBack(dummyparam1, dummyparam2) {
	history.back();
}

function waitCursor(dummyparam1, dummyparam2) {
	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) { item(objName).focus(); }
			else { item(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;
}

//.........................................................................................
//.........................................................................................
/**
 * 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;
}

