var alerts="";
function showErrorAsAlert(showalert){// common function
	alerts = showalert;
	//alert("showErrorAsAlert   "+alerts);
}

if (window.top.document) window.top.document.title=document.title;

function chkIpAddr(ipval){
	//Matches a valid IP Address (###.###.###.###, all numbers being <= 255) 
	var ipAddress = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
	var bool = ipAddress.exec(ipval);
	if (!bool) { return false;} else {return true;}
}

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++) {   
        var c = s.charAt(i);         // Check that current character isn't whitespace.
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function getValFromBrwAplt(fldName){// for ex: fldName=time1 or the html text object name
	//alert("applet called me");
	document.getElementById(fldName).value = document.getElementById("filechooseaplt").getFileName();
}

function isValidPhNo(phVal){
	// Declaring required variables
	var digits = "0123456789";				// non-digit characters which are allowed in phone numbers
	var phoneNumberDelimiters = "()- "; 	// characters which are allowed in international phone numbers(a leading + is OK)
	var validWorldPhoneChars = phoneNumberDelimiters + "+";
	var minDigitsInIPhoneNumber = 10;		// Minimum no of digits in an international phone no.
	
	s=stripCharsInBag(phVal,validWorldPhoneChars);
	var goodPhNo = isInteger(s) && s.length >= minDigitsInIPhoneNumber;
	return goodPhNo
}

function isValidZip(field) {
	var valid = "0123456789-";
	var hyphencount = 0;var validZip=true;

	if (field.length!=5 && field.length!=10) {
		//alert("Please enter your 5 digit or 5 digit+4 zip code.");
		validZip =  false;
	}
	for (var i=0; i < field.length && validZip; i++) {
		temp = "" + field.substring(i, i+1);
		if (temp == "-") hyphencount++;
		if (valid.indexOf(temp) == "-1") {
			//alert("Invalid characters in your zip code.  Please try again.");
			validZip = false;
		}
		if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
			//alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.");
			validZip = false;
	   }
	}
	if (!validZip){
		//showError(";;ERR:Zip code should have 5 digit or 5 digit-4 digit code.");
	}
	return validZip;
}

function isEmail(string) {
	if (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
		return true;
	else
		return false;
}

//------------------------------------------------------------------------

function delSelectedItemListBox(selectobj){
	var k1 = selectobj.selectedIndex;
	if (k1 >= 0) selectobj.options[k1] = null;
}

//------------------------------------------------------------------------

function delItemsListBox(selectobj){
	if (selectobj == null) return;
	var k1 = selectobj.options.length;
	for(i=0;i<k1;i++){ 
		selectobj.options[0] = null;
	}
}

//------------------------------------------------------------------------

function addItemToListBox(selectobj,text,val){
// add new item to list box
	var len1 = selectobj.options.length;
	selectobj.options[len1] = new Option(); 
	selectobj.options[len1].text  = text;
	selectobj.options[len1].value = val;	
}

//------------------------------------------------------------------------

function addOurSiteFav(title,url,parenturl){
	
	if (document.leftbarFavForm){
		//alert('h1' + parenturl);
		document.leftbarFavForm.favTitle.value=title;
		//document.leftbarFavForm.favUrl.value=url;
		document.leftbarFavForm.favUrl.value=parenturl + ";;" + url ;
		document.leftbarFavForm.submit();
		//alert(document.leftbarFavForm.favTitle.value);
		showError(";;" + title + " "+getLocalString("addFavList"));		
	}

}

function addOurSiteFav(title,url,parenturl, tskpan, prjid, siteid){	
	//alert(title + "\n"+url+"\n"+parenturl+"\n"+tskpan +"\n"+prjid+"\n"+siteid);
	if (document.leftbarFavForm){
		//alert('h1' + parenturl);
		document.leftbarFavForm.favTitle.value=title;
		//document.leftbarFavForm.favUrl.value=url;
		document.leftbarFavForm.favUrl.value=parenturl + ";;" + url ;
		document.leftbarFavForm.submit();
		//alert(document.leftbarFavForm.favTitle.value);
		showError(";;" + title + " "+getLocalString("addFavList"));		
	}
	loadTskPan(tskpan, "main&prjid="+prjid+"&siteid="+siteid);
}

function isValidHexColor(colorval){
	var hexaStr="0123456789abcdef",validcode=true;
	colorval=colorval.toLowerCase();
	if (colorval.length != 6){
		validcode=false;
	} else {
		for (var i=0;i < 6 && validcode;i++){
			var c1 = colorval.charAt(i);
			if (hexaStr.indexOf(c1) < 0){
				validcode=false;
			}
		}
	}
	return validcode;
}

function isValidIPAddress(ipaddr) {

   var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
   if (re.test(ipaddr)) {
      var parts = ipaddr.split(".");
      if (parseInt(parseFloat(parts[0])) == 0) { return false; }
      for (var i=0; i<parts.length; i++) {
         if (parseInt(parseFloat(parts[i])) >= 255) { return false; }
      }
      return true;
   } else {
      return false;
   }

}


function isInteger(s){
    return !isNaN(s);
}

function strHasSpecialChars(c){
	var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?`~";
	var k = c.length;
	for (var i = 0; i < k; i++) {
	  	if (iChars.indexOf(c.charAt(i)) != -1) {
		  	return true;
	  	}
	}
	return false;
}

//------------------------------------------------------------------------

function hideError(){// common function
	document.getElementById('divjserrorslist').style.visibility = "hidden";
	document.getElementById('divjserrorslist').style.display = "none";
}

//------------------------------------------------------------------------
function showtip(){

	var msgObj = document.getElementById('divjserrorslist');
	if (msgObj == undefined){
		//alert("Message area not defined for this page");
		return;
	}
	var errDispObj = msgObj.style;
	//alert(errDispObj.display);
	if (errDispObj.display == "block"){
		errDispObj.visibility = "hidden";errDispObj.display = "none";	
		//alert('2');
	
	} else {
		showError("Tip 1\nTip 2 ",3);// tip
		errDispObj.display = "block";errDispObj.visibility = "visible";	
		//alert('1');

	}
}


//------------------------------------------------------------------------

function showError(msg){// common function
	showError(msg,1);// error
}

//------------------------------------------------------------------------
function getErrTblStart2(headClass,headTxt){
  	var errTblStart2 ="<tr class='text'> <td width='98%' class='" + headClass + "' align=center><b><a href='#no' class=noLinkLn name='errAlertStart' title='Status Message :" 
  						+ headTxt + "'><font color='#FFFFFF'>" + headTxt + "</font></a></b></td> </tr>";
    	return errTblStart2;
}

//------------------------------------------------------------------------

function showError(msg, msgtype){// common function
//	type 1, err ; 2 - alert ; 3 - tip(default is error); 4 - confirmation.. user click input
try{
	//msg has two types of errors 1. field errors like invalid,missing 2. general
	//errors like duplicate.. they r seperated by ;;
	var str0="";
	if (msg == null) msg="";
	rExp = /\n/gi;	
	var aryMsgs = msg.split(";;");
	// after ;; is the general message (either error(starts with "ERR:") or gen message)

	var msgObj = document.getElementById('divjserrorslist');
	if (msgObj == undefined){
		//alert("Message area not defined for this page");
		return;
	}

	var imgDir = "../imagesNew/error/";

	try {
		if (rootLevel!=undefined){
			if ( rootLevel == 0){imgDir = "imagesNew/error/";}
			if ( rootLevel == 2){imgDir = "../../imagesNew/error/";}	
		}
	} catch(e){
		
	}

	var headTxt 	= getLocalString("ERROR");
	var borderColor = "alertErrBrdr";
	var headClass="errRed";
	var msgDivWidth="100";
	if(navigator.appName == "Netscape"){
	 	msgDivWidth="99.5";
	}

	//alert("1 msgtype=" + msgtype);
	if (msgtype == 2 || msgtype == 4){
		//alert("2 msgtype=" + msgtype);
		headTxt 	= getLocalString("ALERT");
		borderColor = "alertGrnBrdr";
		headClass="alertGrn";
	} else if (msgtype == 3){
		//alert("3 msgtype=" + msgtype);
		headTxt 	= getLocalString("TIP");
		borderColor = "tipBrdrClr";
		headClass="tipBlu";
	}
	
	var errTblStart1 ="<table border=0 cellpadding=0 cellspacing=0 width='95%' align='center'>";
  	var errTblStart2 = getErrTblStart2(headClass,headTxt);
  	
	var errTblEnd1 = "<tr class='text'><td width='100%' align=center><div style='width:" + msgDivWidth + "%;' class='" + borderColor + "'>";  	
  	var errTblEnd2 = "</div></td></tr></table>";

	document.getElementById('divjserrorslist').style.display = "block";	
	document.getElementById('divjserrorslist').style.visibility = "visible";
	if (aryMsgs[0] != "") { //display field errors
		if (msgtype == 2){

		} else if (msgtype == 4){
			str0= msg ;
			var btn1="<input  onclick='confirmDelClick();' type='button' class='buttonstyle' value='"+ getLocalString("Ok")    +"' >";
			var btn2="<input  onclick='cancelDelClick();'  type='button' class='buttonstyle' value='"+ getLocalString("Cancel") +"'>";
			str0 += "&nbsp;" + btn1;
			str0 += "&nbsp;" + btn2 + "<br>&nbsp;";
		} else if (msgtype == 3){
			str0=  aryMsgs[0];
			str0 = str0.replace(rExp,"<br>");// for fields replace \n with <br>
		
		} else {// just errors
			try{
				if(locale && locale == "en"){// individual msgs in english only, very difficult for other languages
					str0=getLocalString("MissingInvalidvaluefor", [aryMsgs[0]]);
				}else{
					str0=getLocalString("MissingInvalidvalue");
				}
				str0 = str0.replace(rExp,", ").trim();// for fields replace \n with ,
				if ( str0.endsWith(",")){
					str0 = str0.substr(0,str0.length-2) + "<br>";//one for space, one for , so remove last 2
				}
			}catch(e){
			   str0=getLocalString("MissingInvalidvalue");
			}
		}
		document.getElementById('divjserrorslist').innerHTML=errTblStart1 + errTblStart2 + errTblEnd1 + str0 + errTblEnd2;
		if( msgtype != 4 && alerts == "1"){
			str0 = str0.replace("<br>","");
		 	alert(str0);
		 }
	}else
	if (aryMsgs.length == 2) {
		if (aryMsgs[1] != "") {//display general errors
			var str1=aryMsgs[1];
			str1 = str1.replace(rExp,"<br>");// for msgs replace \n with <br>
			if (aryMsgs[0] != "") { //display field errors + general errors
				str1 =getLocalString(str0.trim()) + "<br>" + getLocalString(str1.trim());
				document.getElementById('divjserrorslist').innerHTML = errTblStart1 + errTblStart2 + errTblEnd1 + str1  + errTblEnd2;
			} else {// means either err gen message OR gen msg like updated
				if (str1.indexOf("ERR:") == 0){ // gen errmsg
					str1 = str1.replace("ERR:","");
					str1 = getLocalString(str1);
					document.getElementById('divjserrorslist').innerHTML = errTblStart1 + errTblStart2 + errTblEnd1 + str1  + errTblEnd2;
				} else {// general message like update
					borderColor = "alertGrnBrdr";
					errTblEnd1 = "<tr class='text'><td width='100%' colspan=3 align=center><div style='width:" + msgDivWidth + "%;' class='"+borderColor+"'>";
					str1 = getLocalString(str1);
					errTblStart2 = getErrTblStart2("alertGrn",getLocalString("ALERT"));
					document.getElementById('divjserrorslist').innerHTML = errTblStart1 + errTblStart2 + errTblEnd1 +  str1  + errTblEnd2;
				}
			
			}
			
		}
		if( alerts == "1"){
			str1 = str1.replace("<br>","");
			alert(str1);
		 }
	}	
	
	if (document.getElementById("errAlertStart")) document.getElementById("errAlertStart").focus();
	
} catch(e){
			//unExpectedErr(e,"showError(),commonjs.js");return -99;
			//alert("Error occurred: " + e.name + " - " + e.message + "(commonjs.js)");
}
}

//------------------------------------------------------------------------

// function to limit the number of characters in a textbox or textarea
function LimitText(fieldObj,maxChars){
     var result = true;
     if (fieldObj.value.length >= maxChars ) result = false;
	  if (window.event) window.event.returnValue = result;      
     return result;
}

//------------------------------------------------------------------------

function CheckTextLen(fldname,fieldObj,maxChars){
    //alert("fldlen="+fieldObj.value.length+ " maxchars="+maxChars);
    //fieldObj.value = fieldObj.value.substring(0,maxChars);
    if (fieldObj.value.length > maxChars)
    	showError(";;ERR:" + fldname + " length has exceeded limit " + maxChars);
    else
        hideError();
}

//------------------------------------------------------------------------

function getCheckTextLenErr(fldname,fieldObj,maxChars){
    if (fieldObj.value.length > maxChars)
    	return fldname + " length has exceeded limit " + maxChars + "\n"; 
    else
        return ""; 
}

//------------------------------------------------------------------------

function unExpectedErr(e,from){
	if (from == null) from="";
	showError(";;ERR:Error occurred: " + e.name + " - " + e.message + "(" + from + ")");  
}

//------------------------------------------------------------------------

function chkSelectforDup(selectobj,val1){
	var selectobjlen = selectobj.options.length;
	for(i=0;i<selectobjlen;i++){ 
		if(selectobj.options[i].text == val1){	
			return true;
		}
	}
	return false;
}

//------------------------------------------------------------------------
function resetfun(){//common for all, put this js file before other js files
// for ex 1. put this js file 2. keep the other js files, in that u can override this function
//in JS.. the later definition will take place, first def will ignore
	try{
		hideError();
	} catch(e){
		unExpectedErr(e,"resetfun()," );return false;
	}	
}


//------------------------------------------------------------------------

function isValidEmailAddr(emailStr)  {// it checks for email syntax and aa@a.com.. before @ there should be 2 chars

	var emailstring = emailStr;
	var ampIndex = emailstring.indexOf("@");
	var afterAmp = emailstring.substring((ampIndex + 1), emailstring.length);

	// find a dot in the portion of the string after the ampersand only
	var dotIndex = afterAmp.indexOf(".");

	// determine dot position in entire string (not just after amp portion)
	dotIndex = dotIndex + ampIndex + 1;

	// afterAmp will be portion of string from ampersand to dot
	afterAmp = emailstring.substring((ampIndex + 1), dotIndex);

	// afterDot will be portion of string from dot to end of string
	var afterDot = emailstring.substring((dotIndex + 1), emailstring.length);
	var beforeAmp = emailstring.substring(0,(ampIndex));

	//old regex did not allow subdomains and dots in names
	//var email_regex = /^[\w\d\!\#\$\%\&\'\*\+\-\/\=\?\^\_\`\{\|\}\~]+(\.[\w\d\!\#\$\%\&\'\*\+\-\/\=\?\^\_\`\{\|\}\~])*\@(((\w+[\w\d\-]*[\w\d]\.)+(\w+[\w\d\-]*[\w\d]))|((\d{1,3}\.){3}\d{1,3}))$/;
	var email_regex = /^\w(?:\w|-|\.(?!\.|@))*@\w(?:\w|-|\.(?!\.))*\.\w{2,3}/ 

	// index of -1 means "not found"
	if ((emailstring.indexOf("@") != "-1") &&
		(emailstring.length > 5) &&
		(afterAmp.length > 0) &&
		(beforeAmp.length > 1) &&
		(afterDot.length > 1) &&
		(email_regex.test(emailstring)) )
	{
		return true;
	}
	else
	{
		return false;
	}
	
}
//------------------------------------------------------------------------

function chkUrlFormat(url1,onlyfile,user){
	//url1 is urlstring , selectobj1 is list of urls select box
	//onlyfile - if true(1).. only selected file... if false(0)..entire directory.. so add // at the end
	//returns formatted URL or Error:.................
	try {
		//fromloc 0 means clicked from button 1 means called from submit
		var flnm = url1,err=0;
		if (flnm != "") { //if 1 starts
			var starts = flnm.substr(0,4),starts1 = flnm.substr(0,7);
			var cnt =0;
			if (starts1 == "http://" || starts1 == "https:/" || starts1.indexOf("file:") !=-1 ){
				return flnm;
			}else { 
				var filesys = flnm.substr(0,1);
				var winDrive = flnm.substr(1,1);
				if ( filesys == '/' ){ 
					 flnm = "file:\\\\\\" +  flnm; 
				}else if ( filesys == '\\' || winDrive == ':'){
					flnm = "file:\\\\\\" +  flnm; 
				}else{
					flnm = "http://" +  flnm; 
				}
			}
		}
		return flnm;
	} catch(e){
		return "";
	}
}





/*function openCalender() {
	subpop('../common/calendar.jsp?dateField=SettlementDate');
}

function openCalender(fldNm) {
	subpop('../common/calendar.jsp?dateField=' + fldNm);
}*/

function openCalender(fldNm,formNm) {
	subpop('../common/calendar.jsp?dateField=' + fldNm +'&formNm=' + formNm);
}

function subpop(s) {
	addWindow = window.open(s, "cal", "width=300,height=250,resizable=1,status=1,menubar=0,toolbar=0,scrollbars=0,fullscreen=0");
}    

// --------------- checks whether the input string has only numbers Start
function isItIntegerStr(myString) {

    var isInteger = true,myChar="",myInt=0;
    if (myString!="" && typeof(myString)=="string") {
        for (i=0;i < myString.length;i++) {
            myChar=myString.charAt(i);
            myInt=parseInt(myChar);
            if (isNaN(myInt)) {
                isInteger=false;
            }
        }
    } else {
        isInteger=false;
    }
    return isInteger;

}
// --------------- checks whether the input string has only numbers End

	
// ----function usefull for hexa to rgb conversion - start

function HexToR(h) { return parseInt((cutHex(h)).substring(0,2),16) }
function HexToG(h) { return parseInt((cutHex(h)).substring(2,4),16) }
function HexToB(h) { return parseInt((cutHex(h)).substring(4,6),16) }
function cutHex(h) { return (h.charAt(0)=="#") ? h.substring(1,7) : h}// to remove # from string

function convertHtoR(hexaStr){
	//alert(" 1 " + hexaStr);
	hexaStr=cutHex(hexaStr);
	//alert(" 2 " + hexaStr);
	s1 = "rgb(" +HexToR(hexaStr)+", "+ HexToG(hexaStr) + ", " + HexToB(hexaStr)+")";
	//alert(" 3 " + s1);
	return s1;
}
function isSameRgbColor(rgbcol1,hexacol2){
	var hexcol3 = hexacol2;
	var rgbcol2=convertHtoR(hexacol2);
	//alert(" col1=" + rgbcol1 + " col2=" + rgbcol2 );
	if (rgbcol1== hexcol3  || rgbcol1.indexOf(rgbcol2) > -1){
		//alert(" same");
		return true;
	} else {
		//alert(" not same");
		return false;
	}
}

// ---function usefull for hexa to rgb conversion - end

// Checks for the string ending with a given string.
String.prototype.endsWith= endsWith;
function endsWith(txt){		

   	//alert("this =" +  this +"\t param="+txt);

   	if(this.length < txt.length){
   		return false;
   	}

	if( this.substring(this.length - txt.length) == txt) return true;

	return false;
} 

// Checks for the string starting with a given string.
String.prototype.startsWith= startsWith;
function startsWith(txt){		

   	//alert("this =" +  this +"\t param="+txt);

   	if(this.length < txt.length){
   		return false;
   	}

	if( this.substring(0, txt.length) == txt) return true;

	return false;
} 


// Trims the given  text      
function trim(txt){
	txt = ltrim(txt);
	return rtrim(txt);
}

// Trims left of the given  text    
function ltrim(txt){
	if(txt=="") return txt;

	while(true){
		if(txt.charAt(0) != " ") break;
		txt = txt.substring(1);
	}
	return txt;
}

//  Trims right of the given  text  
function rtrim(txt){
	if(txt=="") return txt;

	while(true){
		if(txt.charAt(txt.length-1) != " ") break;
		txt = txt.substring(0, txt.length-1);
	}
	return txt;
}

function check_url(address) {
      if ((address == "")    
        //|| (address.indexOf ('http://') == -1)
        || (address.indexOf ('.') == -1))
          return false;
      return true;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	

	document.cookie = name+"="+value+expires+"; path=/";
}

function collapseTskPan(rpane){
	topFrameset = top.document.getElementById("topframe");	
	//basefrm = window.parent.basefrm;	//document.getElementById("basefrm");
	//taskpane = window.parent.taskpane;	//top.document.getElementById("taskpane");
	if (rpane.src.indexOf("imagesNew/arrowOff.gif") > -1){
		//basefrm.style.display="";
		//taskpane.style.display="";
		topFrameset.cols = "80%,20%";
		rpane.src = "../imagesNew/arrowOn.gif";
		rpane.alt = "Hide Taskpane";
	}
	else{
		//basefrm.style.display="";
		//taskpane.style.display="none";
		topFrameset.cols = "100%,0%";
		rpane.src = "../imagesNew/arrowOff.gif";
		rpane.alt = "Unhide Taskpane";
	}

	createCookie("rpane",rpane.src,0);
}

String.prototype.trim = function(){return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))}
//String.prototype.startsWith = function(str) {return (this.match("^"+str)==str)}
//String.prototype.endsWith = function(str) {return (this.match(str+"$")==str)}
