//  Copyright 2005 Dreams of Babylon. All rights reserved.

var agt=navigator.userAgent.toLowerCase();

var gbIE = (agt.indexOf("msie") != -1);
var gbNN = (navigator.appName.indexOf("Netscape") != -1);

var gbNN4 = (null!=document.layers)
var gbOpera = (agt.indexOf("opera")!=-1)
var gbNN6 = (agt.indexOf("mozilla/5")!=-1)
var gbIE5 = (agt.indexOf("msie 5")!=-1 || agt.indexOf("msie 6")!=-1)
var gbWebTV = (agt.indexOf("webtv")!=-1)

gbDom = (gbNN6 || gbIE5 || gbOpera)
gbIE4 = (gbIE && !(gbDom||gbNN4))

var WIN = ((agt.indexOf("win")!=-1) || (agt.indexOf("32bit")!=-1));
var MAC = (agt.indexOf("mac")!=-1);

//.........................................................................................
// is Acrobat Reader installed check
function acrobatInstalled() {
	result = false; 
	if (!gbIE || !WIN || gbOpera) {
		if (navigator.mimeTypes["application/pdf"]) {
			result = (navigator.mimeTypes["application/pdf"].enabledPlugin != null);
		}
	} else {
		document.write('<script language="VBScript">on error resume next\nresult = IsObject(CreateObject("PDF.PdfCtrl.5"))</script>');
	}
	return result;
}
//.........................................................................................
// 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 "CustomerService" + '\x40' + "lanzy" + '\x2E' + "c" + '\x6F' + "m";
}
//.........................................................................................
// 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;

//-----------------------------------------------------------------------------
// 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>
//-----------------------------------------------------------------------------
// images preload functions

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;
}

//.........................................................................................
/** Remove all occurrences of a token in a string
*   s  string to be processed
*   t  token to be removed
*  returns new string
*/
function remove(s, t) {
	i = s.indexOf(t);
	r = "";
	if (i == -1) return s;
	r += s.substring(0,i) + remove(s.substring(i + t.length), t);
	return r;
}
//.........................................................................................	


/* ***************************
** Most of this code was kindly 
** provided to me by
** Andrew Clover (and at doxdesk dot com)
** http://and.doxdesk.com/ 
** in response to my plea in my blog at 
** http://worldtimzone.com/blog/date/2002/09/24
** It was unclear whether he created it.
*/
function utf8(wide) {
  var c, s;
  var enc = "";
  var i = 0;
  while(i<wide.length) {
    c= wide.charCodeAt(i++);
    // handle UTF-16 surrogates
    if (c>=0xDC00 && c<0xE000) continue;
    if (c>=0xD800 && c<0xDC00) {
      if (i>=wide.length) continue;
      s= wide.charCodeAt(i++);
      if (s<0xDC00 || c>=0xDE00) continue;
      c= ((c-0xD800)<<10)+(s-0xDC00)+0x10000;
    }
    // output value
    if (c<0x80) enc += String.fromCharCode(c);
    else if (c<0x800) enc += String.fromCharCode(0xC0+(c>>6),0x80+(c&0x3F));
    else if (c<0x10000) enc += String.fromCharCode(0xE0+(c>>12),0x80+(c>>6&0x3F),0x80+(c&0x3F));
    else enc += String.fromCharCode(0xF0+(c>>18),0x80+(c>>12&0x3F),0x80+(c>>6&0x3F),0x80+(c&0x3F));
  }
  return enc;
}

function
encodeURIComponentNew(s) {

	if(typeof encodeURIComponent == "function") {
		return encodeURIComponent(s);
	}

	var hexchars = "0123456789ABCDEF";
	var s = utf8(s);
	var enc = "";
	for (var i= 0; i<s.length; i++) {
		var c = s.charCodeAt(i);
		enc += "%" + hexchars.charAt(c>>4)+hexchars.charAt(c & 0xF);
	}
	return enc;
}


