/*************************************************************************************/
var imgChecked= new Image();
imgChecked.src = "../images/check_box_tick.gif";
var imgUnChecked= new Image();
imgUnChecked.src = "../images/check_box.gif";
var strDateSeparator = "/";


/********************************************************************************
function - DisableLink

linkName - id of anchor to be disabled
disable - boolean - pass true to disable anchor; false otherwise

Assumptions:
To use this function, you must set your forms as follows
(1) You must have a div tag that represents disabled anchor with the following ID pattern - "div"+anchorID.substring(3, anchorID.length) +"Dis"
(2) The function assumes that anchors exist in parent.frames.content.document

*********************************************************************************/


function DisableLink(anchorID, disable)
{
	if(!parent.frames.content)//if null or undefined 
		return;
	
	var objAnchor = parent.frames.content.document.getElementById(anchorID) ;
	var objDisabledDiv = parent.frames.content.document.getElementById("div"+anchorID.substring(3, anchorID.length) +"Dis");
	
	if(objAnchor == 'undefined' || objAnchor == null)
		return;
	
	if(disable)
	{
		objAnchor.style.display = "none";
		objDisabledDiv.style.display = "";
	}
	else
	{
		objAnchor.style.display = "";
		objDisabledDiv.style.display = "none";
	}
}

/**********************************************************************************
 * This function is used to set download facilty when page's unload event is fire
 **********************************************************************************/
function SetDownloadFlag(blnFlag)
    {  
            
        if(navigator.appName != "Netscape" &&  navigator.appVersion.indexOf("MSIE 6.0") != -1)
        {            
            var strLocation=null;                        
            var chk=null;
            var blnGetFrame=false;         
            
            strLocation=window.location.href.split('/');
            if (strLocation.length !=0 && strLocation[strLocation.length -1]=="MainFrame.aspx" && blnGetFrame==false)
            {
                 chk=window.frames[0].document.getElementById("chkDownload");    
                 blnGetFrame=true;
            }           
            
            strLocation=parent.window.location.href.split('/');
            if (strLocation.length !=0 && strLocation[strLocation.length -1]=="MainFrame.aspx" && blnGetFrame==false)
            {
                 chk=parent.window.frames[0].document.getElementById("chkDownload");    
                 blnGetFrame=true;
            }           
            
            strLocation=parent.parent.window.location.href.split('/');
            if (strLocation.length !=0 && strLocation[strLocation.length -1]=="MainFrame.aspx" && blnGetFrame==false)
            {
                 chk=parent.parent.window.frames[0].document.getElementById("chkDownload");    
                 blnGetFrame=true;
            }           
            
            strLocation=parent.parent.parent.window.location.href.split('/');
            if (strLocation.length !=0 && strLocation[strLocation.length -1]=="MainFrame.aspx" && blnGetFrame==false)
            {
                 chk=parent.parent.parent.window.frames[0].document.getElementById("chkDownload");    
                 blnGetFrame=true;
            }            
            
            if (chk !=null)            
            chk.checked=blnFlag;     
                    
        }        
    }

/**********************************************************
 * This function is used to replace contents from the existing string.
 **********************************************************/
function ReplaceAllChar(origString, findString, replaceString)
{
	while(origString.search(findString) >= 0)
		origString = origString.replace(findString, replaceString);
	return origString;
}



/***************************
ValidateBlank(ctrl)
ctrl - control to be validated
returns true if control has some value, false otherwise

******************************/
function ValidateBlank(ctrl)
{
	if(Trim(ctrl.value).length == 0)
		return false;
	else
		return true;
}

/********************
EnableLink() - this function enables/disables an HTML anchor element
linkControl - the HTML anchor element to be enabled/disabled
enable - if true, the element will be enabled
enableCSSClass = class to be applied when link is enabled; set cursor:hand in this class
disableCSSClass = class to be applied when link is disabled; set cursor;default in this class

The function can be extended to include HREF attribute
**********************/
var arrOnClickJS = new Array();
var arrOnMouseoverJS = new Array();
var arrOnMouseoutJS = new Array();
function EnableLink(linkControl, enable, enableCSSClass, disableCSSClass)
{
	
	if(arrOnClickJS[linkControl.id] == null)
	{
		//alert(linkControl.onclick);
		arrOnClickJS[linkControl.id] = linkControl.onclick;//store temporarily before deleting
		//alert(arrOnClickJS[linkControl.id]);
		arrOnMouseoverJS[linkControl.id] = linkControl.onmouseover;//store temporarily before deleting
		arrOnMouseoutJS[linkControl.id] = linkControl.onmouseout;//store temporarily before deleting
	}
	
	if(enable)
	{
		linkControl.onclick = eval(arrOnClickJS[linkControl.id]);//works well in both IE and Mozilla
		linkControl.onmouseover = eval(arrOnMouseoverJS[linkControl.id]);//works well in both IE and Mozilla
		linkControl.onmouseout = eval(arrOnMouseoutJS[linkControl.id]);//works well in both IE and Mozilla
		linkControl.className = enableCSSClass;
	}
	else
	{
		linkControl.onclick = "";//works well in both IE and Mozilla
		linkControl.onmouseover = "";
		linkControl.onmouseout = "";
		linkControl.className = disableCSSClass;
	}
		
}
			
/*********************************************************************************
SingleSelect(clickedImage)

The function allws only single selection of an item at client side.  It works with the image checkboxes (images used along with checkboxes)
The function relates images and checkboxes on the basis of their client side id
For example, to find corresponding checkbox for image 'imgchk56', the function will look for checkbox with id '56'

To reuse this function, the following must be done:
(1)Call this function on click event of image - SingleSelect(this)
(2)Give id to image checkbox in this pattern - 'imgchk' + <id of corresponding checkbox>

*********************************************************************************/
function SingleSelect(sender)
{
	var frm = document.forms[0];
	
	for(i=0; i<= frm.elements.length-1; i++)
	{
		var ctrl = frm.elements[i];
		if(ctrl.type == "checkbox")
		{
			var len = sender.id.length;
			if(ctrl.id != sender.id.substring(6, len))//excepting the checkbox which was clicked, uncheck all other checkboxes
				ctrl.checked = false;
		}
		
	}
	
	for(i=0; i<= document.images.length-1; i++)
	{
		var ctrl = document.images[i];
		if(ctrl.id != sender.id && ctrl.id.substring(0, 6)=="imgchk")//excepting the image which was clicked, uncheck all other checkbox images
			ctrl.src = imgUnChecked.src;
	}
	
}

/***********************************************
GetStringFromDate(dtDate)
returns string representation of date object - format - dd/MM/yy hh:mm


***********************************************/
function GetStringFromDate(dtDate)
{
	if(dtDate == null || dtDate == 'undefined' || dtDate == '')
		return "";
		
	var day = (dtDate.getDate()).toString().length==2?dtDate.getDate():'0'+dtDate.getDate();
	if(isNaN(day))
		return ""; //return false;
	
	var month = (dtDate.getMonth()+1).toString().length==2?(dtDate.getMonth()+1):'0'+(dtDate.getMonth()+1);
	if(isNaN(month))
		return ""; //return false;
	
	var year ;
	if(navigator.appName == "Netscape")
		year = dtDate.getFullYear().toString().substring(1, 3);  //date format change; change 2 to No digits of the year to display. currently showing 'yy'	
	else
		year = dtDate.getFullYear().toString().substring(2, 4);  
	
			
	if(isNaN(year))
		return ""; //return false;
	
	var hours = dtDate.getHours().toString().length==2?dtDate.getHours():"0"+dtDate.getHours();
	if(isNaN(hours))
		return "";
		
	var minutes = dtDate.getMinutes().toString().length==2?dtDate.getMinutes():"0"+dtDate.getMinutes();
	if(isNaN(minutes))
		return "";
	
	val = day + strDateSeparator + month + strDateSeparator + year + " " + hours + ":" + minutes;
	
	return val;
}


function GetStringFromDateDMY(date)
{
	var fullDate = GetStringFromDate2(date);
	fullDate = fullDate.substring(0, "dd/mm/yy".length)+fullDate.substring("dd/mm/yy hh:mm".length);
	return fullDate;
}

/***********************************************
GetStringFromDate(dtDate)
returns string representation of date object - format - dd/MM/yy hh:mm ddd
***********************************************/
function GetStringFromDate2(dtDate)
{
	var strDate = GetStringFromDate(dtDate);
	var days = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
	strDate += " " + days[dtDate.getDay()];
	return strDate;
}

/************************************
returns date object from string - format dd/mm/yy hh:mm
*************************************/
function GetDateFromString(strDate)
{
	if(strDate == null || strDate == 'undefined')
		return null;
	
	var day = strDate.substring(0,2);//dd
	var month = strDate.substring(3,5)-1;//mm
	var year = strDate.substring(6,8);//yy
	if((year*1) > 70)//if year > 70, we consider it to be before 2000
		year = "19"+year;
	else
		year = "20"+year;
	var hour = strDate.substring(9,11);//hh
	var minute = strDate.substring(12);//mm
	var dtpDate = new Date(year, month, day, hour, minute);
	
	return dtpDate;
}

/*****************************************************************
Validates that the given date is not a past date - date format - dd/mm/yy hh:mm
*****************************************************************/
function ValidatePastDate(dateString)
{
	var dtToday = new Date();
	return GeneralCompare(dateString, "GreaterEqual", GetStringFromDate(dtToday), "date");
}


/*****************************************************************************
Date Validation function
 
Checks if the date string is valid and returns null if not valid.
If valid, converts it to the appropriate date object, and returns it 
******************************************************************************/
	
function ValidateDate(dateString)
{
	var dateMatchExp = new RegExp("^(\\d{1,2})/(\\d{1,2})/(\\d{4})$");
	var match = dateMatchExp.exec(dateString);
	if (null == match) return null;	//Match failed, invalid date

	if (match[1] < 1 || match[1] > 12) return null;	//validate month
	if (match[2] < 1 || match[2] > 31) return null;	//validate day
	if (match[3] < 1) return null;	//validate year

	// valid day check
	if (match[1] == 2) 		// february check
	{
		if (match[2] > 29) return null;
		//Check for leap year.
		if (((match[3] % 100 == 0 || match[3] % 4 != 0) && (match[3] % 400 != 0))  // non-leap year checked
				&& match[2] > 28) return null;
	}
	else if ((match[1] == 4 || match[1] == 6 || match[1] == 9 || match[1] == 11) && (match[2] > 30))
		return null;

	return new Date(match[3], match[1]-1, match[2]);
}


/******************************************************************************************************
 * This function validates the date in any format
 * @author Ishan
 * @param datestr String representing the Date to be checked
 * @param delim String representing the delimiter that separates, date, month and year
 * date string
 * @param dd Integer value (0 to 2) indicating the position of the date field in the date String
 * @param mm Integer value (0 to 2) indicating the position of the month field in the date String
 * @param yy Integer value (0 to 2) indicating the position of the year field in the date String
 * @return Returns the boolean value true if the date is valid, false otherwise
 *******************************************************************************************************/
function dateCheck(datestr,delim,dd,mm,yy)
{
	if(dd < 0 || dd > 2 || mm < 0 || mm > 2 || yy < 0 || yy > 2 || dd == mm || mm == yy || dd == yy) return false;
	datestr = datestr.trim();
	delim = delim.trim();
	if(datestr.length <= 0 || delim.length <= 0) return false;
	var dt = datestr.split(delim);
	if(dt.length != 3) return false;
	if(isNaN(dt[dd]) || isNaN(dt[mm]) || isNaN(dt[yy])) return false;
	if(Math.floor(dt[dd]) != Math.ceil(dt[dd]) || Math.floor(dt[mm]) != Math.ceil(dt[mm]) || Math.floor(dt[yy]) != Math.ceil(dt[yy])) return false;
	if(dt[mm] < 1 || dt[mm] > 12 || dt[dd] < 1 || dt[dd] > 31 || dt[yy] < 1) return false;

	if(dt[mm] == 2)
	{

		if(dt[dd] > 29) return false;
		//	Check for leap year.
		if(dt[yy] % 100 == 0 && dt[yy] % 400 != 0 && dt[dd] > 28) return false;
		if(dt[yy] % 4 != 0 && dt[dd] > 28) return false;
	}

	if((dt[mm] == 4 || dt[mm] == 6 || dt[mm] == 9 || dt[mm] == 11) && dt[dd] > 30) return false;
	return true;
}

/**
 * This function validates the date in dd/mm/yyyy format
 * @author Ishan
 * @param datestr String representing the Date to be checked
 * @return Returns the boolean value true if the date is valid, false otherwise
 */
function dateCheckMain(datestr)
{
	return dateCheck(datestr,strDateSeparator,2,1,0);
}

/*******************************************************************************
GeneralCompare - compares between all kinds of datatypes and operators

value1 - first value
operator - greater/lessthan/greaterequal etc
value2 - second value
type - datatype like number/date/string etc

*******************************************************************************/
function GeneralCompare(value1, operator, value2, type)
{
	if(operator == "GreaterEqual" && type == "number")
		return (value1 >= value2);
	if(operator == "Greater" && type == "number")
		return (value1 > value2);
	if(operator == "GreaterEqual" && type == "date")//expects dates to be in string dd/mm/yy hh:mm format
		return (GetDateFromString(value1) >= GetDateFromString(value2));
}


/************************************************************
Validation functions for numeric an numeric fraction keypress 
************************************************************/
function NumericKeyPressFraction(passedEvent)
{ 
	var objEvent = (passedEvent==null)? window.event: passedEvent;//for mozilla compatibility
	var keyCode = (navigator.appName == "Netscape")? objEvent.which: objEvent.keyCode;
	if(keyCode < 30)
		return;
	if((keyCode>=48 && keyCode<=59) || (keyCode==46)|| (keyCode==13))
		return true;
	else 
		return false;
}

function NumericKeyPress(passedEvent)
{ 
	var objEvent = (passedEvent==null)? window.event: passedEvent;//for mozilla compatibility
	var keyCode = (navigator.appName == "Netscape")? objEvent.which: objEvent.keyCode;
	if(keyCode < 30)
		return true;
	if((keyCode>=48 && keyCode<=59) || (keyCode==13))
		return true;
	else 
		return false;
}

/*Added By: Nishant Dave...8th May,07*/
function NumericKeyPressForOrder(passedEvent)
{ 
	var objEvent = (passedEvent==null)? window.event: passedEvent;//for mozilla compatibility
	var keyCode = (navigator.appName == "Netscape")? objEvent.which: objEvent.keyCode;	
	if(keyCode < 30)
		return true;
	if((keyCode>=48 && keyCode<=59) || (keyCode==13) || (keyCode==45))
		return true;
	else 
		return false;
}
/*Added Completed*/

function NumericKeyPressAllowNegative(passedEvent)
{ 
	var objEvent = (passedEvent==null)? window.event: passedEvent;//for mozilla compatibility
	var keyCode = (navigator.appName == "Netscape")? objEvent.which: objEvent.keyCode;
	if(keyCode < 30)
		return;
	if((keyCode>=48 && keyCode<=59) || (keyCode==13) || (keyCode==45))
		return true;
	else 
		return false;
}

        function KeyPressWithDashSpace(passedEvent)
		{ 		    
			var objEvent = (passedEvent==null)? window.event: passedEvent;//for mozilla compatibility
			var keyCode = (navigator.appName == "Netscape")? objEvent.which: objEvent.keyCode;			
					
		    if (keyCode  == 0 ) // this is added for navigation keys
				return true;			
			if (keyCode  == 45 ) // this is added for "-"
				return true;			
			if (keyCode  == 32 ) // this is added for " "
				return false;			
			if(keyCode < 30)
				return false;
			if((keyCode>=48 && keyCode<=59) || (keyCode==13))
				return true;						
			
				return false;
		}
		



/***************************************************************
Limits the length of text area HTML object
Use this function on onkeypress event of text area object
***************************************************************/
function LimitLength(passedEvent, maxLength)
{
	var objEvent = (passedEvent==null)? window.event: passedEvent;//for mozilla compatibility
	var keyCode = (navigator.appName == "Netscape")? objEvent.which: objEvent.keyCode;
	if(keyCode < 30)
		return;
	if(navigator.appName == "Netscape")//mozilla compatibility
		return (passedEvent.target.value.length < maxLength)
	else
		return (passedEvent.srcElement.value.length < maxLength)
}


/*************************************************
Validates that only alpha-numeric characters are entered
**************************************************/
function AlphaNumericKeypress(passedEvent)
{
	//only alpha-numeric characters are allowed - first character must not be a number
	
	var objEvent = (passedEvent==null)? window.event: passedEvent;//for mozilla compatibility
	var keyCode = (navigator.appName == "Netscape")? objEvent.which: objEvent.keyCode;
	if(keyCode < 30)
		return;
	if((keyCode>=48 && keyCode<=59) || (keyCode >= 65 && keyCode <=90) || (keyCode >= 97 && keyCode <=122) || (keyCode==13))
		return true;
	else 
		return false;
	
}

/*************************************************
Validates that only alpha-numeric characters and spaces are entered
**************************************************/
function AlphaNumericSpaceKeypress(passedEvent)
{
	//only alpha-numeric characters are allowed - first character must not be a number
	var objEvent = (passedEvent==null)? window.event: passedEvent;//for mozilla compatibility
	var keyCode = (navigator.appName == "Netscape")? objEvent.which: objEvent.keyCode;
	
	if(keyCode < 30)
		return;
	if((keyCode>=48 && keyCode<=59) || (keyCode >= 65 && keyCode <=90) || (keyCode >= 97 && keyCode <=122) || 
		(keyCode==13) || (keyCode == 32))
		return true;
	else 
		return false;
	
}


/*************************************************
Validates that no textbox no the given form is blank
**************************************************/
function ValidateTextboxes()
{
	var frm = document.forms[0];
	
	for(i=0; i<frm.elements.length; i++)
		if(frm.elements[i].type == "text")
			if(Trim(frm.elements[i].value) == "")//some textbox is blank
				return false;

	return true;//if we reach here, it means no textbox is blank
}

/*************************************************
Changes location of parent
**************************************************/
function ChangeParentLocation(url)
{
	window.parent.location = url;
}

/**********************************************************
* The function changes source of images of a given list of images
Used to set uncheck images to other images when an image has checked image

Before using this function, you must have a function in your caller page which returns CSV of control IDs that you want to loop through
for toggling the image.  The function name must be GetCSVControlID(). This has been done to improve performance.  This function (UncheckAllImagesExceptThis)
will generally be called on click event of items in a grid.  So, it will not be optimum to render such function with a huge list of CSV in the
click event of each item in grid.  Instead caller page should render GetCSVControlID() on page just once and then let UncheckAllImagesExceptThis
call GetCSVControlID() for getting the CSV.
**********************************************************/
function UncheckAllImagesExceptThis(checkedImageID)
{	
	var csvAllImageIDs = GetCSVControlID();
	if(csvAllImageIDs.length == 0)
		return;
	var arrControls = csvAllImageIDs.split(',');
	for(i=0; i<=arrControls.length-1; i++)
		if(arrControls[i] != checkedImageID)
			document.getElementById(arrControls[i]).src = imgUnChecked.src;
}


/**********************************************************
* The function changes source of images of a given list of images
Used to set uncheck images to other images when an image has checked image

Before using this function, you must have a function in your caller page which returns CSV of control IDs that you want to loop through
for toggling the image.  The function name must be GetCSVCheckedBoxesID(). This has been done to improve performance.  This function (UncheckAllCheckboxesExceptThis)
will generally be called on click event of items in a grid.  So, it will not be optimum to render such function with a huge list of CSV in the
click event of each item in grid.  Instead caller page should render GetCSVCheckedBoxesID() on page just once and then let UncheckAllCheckboxesExceptThis
call GetCSVCheckedBoxesID() for getting the CSV.
**********************************************************/
function UncheckAllCheckboxesExceptThis(checkedOneID)
{	
	var csvAllCheckboxes = GetCSVCheckedBoxesID();
	if(csvAllCheckboxes.length == 0)
		return;
	var arrControls = csvAllCheckboxes.split(',');
	for(i=0; i<=arrControls.length-1; i++)
		if(arrControls[i] != checkedOneID)
			document.getElementById(arrControls[i]).checked = false;
}



/**********************************************************
* This function is used for Toggling checkbox images
**********************************************************/
function ChangeImageSrcSpecial(objInput,strCheckBoxName){	
	try{
		
		if(objInput.src.toLowerCase() != imgChecked.src.toLowerCase()){	
			objInput.src = imgChecked.src;			
			if(typeof(strCheckBoxName)!= 'undefined' && strCheckBoxName != null)
				SetCheckStatusSpecial(true,strCheckBoxName);					
		}else{		
			objInput.src = imgUnChecked.src;
			if(typeof(strCheckBoxName)!= 'undefined' && strCheckBoxName != null)
				SetCheckStatusSpecial(false,strCheckBoxName);
		}
	}catch(Exc){
		alert('Error in ChangeImage.\r\n' + Exc.message);
	}	
}
/**********************************************************
* This function is used for checking or unchecking checkbox
**********************************************************/
function SetCheckStatusSpecial(blnStatus,strCheckBoxName){
	try{
		var objCheckBox = document.getElementById(strCheckBoxName);
		if(typeof(objCheckBox) != 'undefined' && objCheckBox!=null){
			objCheckBox.checked = blnStatus;									
		}else{
			//alert('Unable to set check box status');
		}
	}catch(Exc){
		//alert('Error in SetCheckStatus.\r\n' + Exc.message);
	}
}

/**********************************************************
* This function is used for Toggling checkbox images
 **********************************************************/
function ChangeImageSrc(objInput,strCheckBoxName){	
	try{
		
		if(objInput.src.toLowerCase() != imgChecked.src.toLowerCase()){	
			objInput.src = imgChecked.src;												
			SetCheckStatus(true,strCheckBoxName);
		}else{
			objInput.src = imgUnChecked.src;
			SetCheckStatus(false,strCheckBoxName);
		}
	}catch(Exc){
		//alert('Error in ChangeImage.\r\n' + Exc.message);
	}	
}


/**********************************************************
* This function is used for Toggling checkbox images overload 1
 **********************************************************/
function ChangeImageSrc2(objImage, objCheckbox)
{	
	
	try
	{
		//first check the state of image and then toggle it
		if(objImage.src.toLowerCase() != imgChecked.src.toLowerCase())
		{	
			objImage.src = imgChecked.src;												
			objCheckbox.checked = true;
		}
		else
		{
			objImage.src = imgUnChecked.src;
			objCheckbox.checked = false;
		}
	}
	catch(Exc)
	{
		//alert('Error in ChangeImage.\r\n' + Exc.message);
	}	
}

/**********************************************************
* This function is used for checking or unchecking checkbox
 **********************************************************/
function SetCheckStatus(blnStatus,strCheckBoxName){
	try{
		var objCheckBox = document.getElementById(strCheckBoxName);
		if(typeof(objCheckBox) != 'undefined' && objCheckBox!=null){
			objCheckBox.checked = blnStatus;						
			objCheckBox.onclick();		
		}else{
			//alert('Unable to set check box status');
		}
	}catch(Exc){
		//alert('Error in SetCheckStatus.\r\n' + Exc.message);
	}
}
function ChangeImage(objInput)
{
	var strName = objInput.id;			
	objInput.src="../images/check_box_tick.gif";
	//alert(strName);
}
/**********************************************************
* This function is used for opening new window
 **********************************************************/
function showPopupWindow(pageName, pageTitle, winHeight, winWidth)
{
	var winTopPos = eval(screen.height - winHeight) / 2;
	var winLeftPos = eval(screen.width - winWidth) / 2;

	window.open(pageName,"","top=" + winTopPos + ",left=" + winLeftPos + ",height=" + winHeight + ",width=" + winWidth + ",toolbar=none,scrollbars=1");
}
function showPopupWindowPDF(pageName, pageTitle, winHeight, winWidth)
{
	var winTopPos = 3;
	var winLeftPos = eval(screen.width - winWidth) / 2;

	window.open(pageName,"","top=" + winTopPos + ",left=" + winLeftPos + ",height=" + winHeight + ",width=" + winWidth + ",toolbar=none,scrollbars=1,resizable=yes,fullscreen");
}

/**********************************************************
 * This function is used for opening new window
 **********************************************************/
function openPopWin(winURL, winWidth, winHeight, moveX, moveY, winFeatures,winName){
	var winDefaultFeatures;
	var popWin;
	if(openPopWin.arguments.length != 7)		
 		winName = "popUnder" + winCount++ //unique name for each pop-up window
	//winName = "popUnder"
	try{
 		if(moveX == '' || moveY=='' && (isNan(winWidth) && isNaN(winHeight))){
 			moveX = (screen.width-winWidth)/2 ; 
 			moveY = (screen.height-winHeight)/2;
 		}
 	}catch(exc){
 		moveX = 0;
 		moveY = 0;
 	} 	
 	winDefaultFeatures ="width=" + winWidth + ",height=" + winHeight + ",Top=" + moveY + ",Left=" + moveX+ ",dependent=1,alwaysRasised=1";
 	if (openPopWin.arguments.length == 6) //any additional features? 
   		winFeatures =  winDefaultFeatures + "," + winFeatures ;
   	else
   		winFeatures = winDefaultFeatures;
 	// open the new browser window
 	popWin = window.open(winURL, winName,winFeatures,true)	
	popWin.focus();	
	return(popWin);
}
/****************************************************************************************
 * This function is used trimming the input string.
 ****************************************************************************************/
 
function Trim(strInput)
{
	var ltrim = /^\s+/;
	var rtrim = /\s+$/;
	strInput = strInput.replace(ltrim,'');
	strInput = strInput.replace(rtrim,'');
	return strInput;
}

/****************************************************************************************
 * This function is used to enforce that atleast one checkbox should be checked in grid
 * when none of the checkboxes are selected in grid, it will return false
 ****************************************************************************************/
function validateGridSelection(oSource, oArgs)
{
	//var checkedFlag = false;
	oArgs.IsValid = false;
	var argValid=false;
	var frm = document.forms[0];
	
	for(i=0; i<frm.elements.length; i++)
	{
		if(frm.elements[i].type == "checkbox")
		{
			if(frm.elements[i].checked == true)
			{
				//checkedFlag = true;
				//break;
				oArgs.IsValid = true;
				argValid=true;
				break;
			}
		}
	}
	return argValid;
/*	if(!checkedFlag)
	{
		alert('Please select atleast one checkbox');
	}*/
}

/*********************************************************************************
Validates that atleast one checkbox is selected on the given form

*********************************************************************************/
function ValidateSelectionInForm(targetForm)
{
	var frm = targetForm;
	
	for(i=0; i<frm.elements.length; i++)
		if(frm.elements[i].type == "checkbox")
			if(frm.elements[i].checked)
				return true;

	return false;

}

/*********************************************************************************
Validates that atleast one item is there in the given grid table and the grid is not blank
*********************************************************************************/
function ValidateRecordsInGrid(targetGridTable)
{
	if(targetGridTable.rows.length > 1)//first row in data grid is header
		return true;
	else
		return false;
		
}



 /*********************************************************************************
 * Function Name	: setStatusScript
 * Parameters		: strStatusbarHeading - Left Heading of Status Bar
					  strNoOfPages - No of links to be displayed (Excluding sublinks)
					  strCurrentPage - Current Page No
					  strPageHeading - Right Heading of Status Bar
					  blnIsFrame - true: frame; false: no frame
					  strNoOfSubPages - No of sublinks to be displayed
 * Description		: Used to set status bar values
 * Revision History	: Initial Revision by Paras Shah on 20/jul/2004
					  Modified by Parthiv for adding strNoOfSubPages on 
 *********************************************************************************/
function setStatusScript(strStatusbarHeading, strNoOfPages, strCurrentPage, strPageHeading, blnIsFrame,strNoOfSubPages)
{
	try{
		if (blnIsFrame == 'true')
			parent.parent.setStatusData(strStatusbarHeading, strNoOfPages, strCurrentPage, strPageHeading, blnIsFrame,strNoOfSubPages);
		else if(blnIsFrame == 'FrameParent')
			parent.parent.parent.setStatusData(strStatusbarHeading, strNoOfPages, strCurrentPage, strPageHeading, blnIsFrame,strNoOfSubPages);
		else
			parent.setStatusData(strStatusbarHeading, strNoOfPages, strCurrentPage, strPageHeading, blnIsFrame);
	}catch(Exc){
		//Do Nothing
	}	
}
/**********************************************************
 * This function is used to replace contents from the existing string.
 **********************************************************/
function Replace(strValue,strFind,strReplace){
	if(trim(strValue)=="") return strValue;
	if(strValue.indexOf(strFind)==-1) return strValue;
	var reg = new RegExp(strFind,"g");//g stands for Global replcement.i can be used for ignoring case.
	var strReturn;		
	try{
		strReturn = strValue;
		strReturn = strReturn.replace(reg,strReplace);
	}catch(exc){
		strReturn = strValue;
		alert("Unable to replace string '" + strFind + "' with '"+ strReplace +"' in\n" + strValue+"\n\nError Information: " + exc.name + " \nError Details: " + exc.message);
	}	
	return strReturn;		
}


/**********************************************************
 * This function is used to replace contents from the existing string.
 **********************************************************/
function ReplaceAll(origString, findString, replaceString)
{
	while(origString.search(findString) > 0)
		origString = origString.replace(findString, replaceString);
	return origString;
}


/**********************************************************
 * This function is used for debugging purpose
 **********************************************************/
function displayProperties(obj) 
{
	var str = ""; 	var arrProp = new Array();
	var prop;
	var arrIndex = 0;

	if(typeof(obj) == "undefined")
	{
		alert('displayProperties: Parameter is not an object!');
		return false; 	
	}
	
	if(typeof(obj[0]) != "undefined") 
	{
		for(prop = 0;prop < obj.length;prop++) 
		{
			str += "\n" + prop + "=" + obj[prop];
			arrProp[arrIndex++] = "\n" + prop + "=" + obj[prop];
		}
	}
	else
	{
		for(prop in obj)
		{
			str += "\n" + prop + "=" + eval("obj." + prop);
			arrProp[arrIndex++] = "\n" + prop + "=" + obj[prop];
		}
	}
	alert(arrProp.sort()); 
}

 /*********************************************************************************
 * Function Name	: showUploadProgress
 * Parameters		: -
 * Description		: Used to show upload progress bar
 * Revision History	: Initial Revision by Paras Shah on 06/sep/2004
 *********************************************************************************/
function showUploadProgress()
{	
	if(Page_ClientValidate())
	{		
		
		document.getElementById("lblMessage").style.display ='none';					
		document.getElementById("divUploadProgress").style.display = '';				
		return true;
	}
	
	return false;	
}
 /*********************************************************************************
 * Function Name	: RedirectUser
 * Parameters		: -
 * Description		: Authorize Page Level Access
 * Revision History	: Initial Revision by Nimesh Dhruve on 04/Oct/2004
 *********************************************************************************/
function RedirectUser(){
	try{
		//alert('ok');
		var blnValidUser = false;	
		
		//Remove below 2 lines after implementing the security server side
		if(typeof(strAuthorizedUser) == 'undefined')
			blnValidUser = false;
			
		if(typeof(strAuthorizedUser)!='undefined' && strAuthorizedUser == true)
			blnValidUser = true;
		if(typeof(parent.strAuthorizedUser) !='undefined' && parent.strAuthorizedUser==true)
			blnValidUser = true;
		if(typeof(parent.parent.strAuthorizedUser) !='undefined' && parent.parent.strAuthorizedUser==true)
			blnValidUser = true;
		//	--	http://localhost/Yemo/UM/USR_UserFrameSet.aspx	
		//alert(blnValidUser);
		if(!blnValidUser){			
			//window.location = "/Yemo/UnAuthorizedRequest.aspx";
		}
	}catch(Exc){
		alert("An error occured while validating user.\nAdditional Details: -\nFunction Name RedirectUser()\nError Message: " + Exc.message);
	}
}

 /*********************************************************************************
 * Function Name	: checkLength
 * Parameters		: oSrc - source control; donot pass; automatically passed by validator
						args - arguments passed by validator control
 * Description		: Custom JS function to check the length of characters in a control; returns false if control
						contains more characters, otherwise true.  Used when setting property ClientValidationFunction
						length 1000 hardcoded
 * Revision History	: Initial Revision by Murtaza Tinwala on 5-10-04
 *********************************************************************************/
function checkLength(oSrc, args)
{
	var ctrlObject = document.getElementById(oSrc.getAttribute("controltovalidate"));
	try{
		args.IsValid = false;
		if(typeof(ctrlObject) != 'undefined'){ 
			var desclength = ctrlObject.value.length;
			
			if(desclength<1000)
			{
				args.IsValid = true;
				return true;
			}
			else
			{	
				args.IsValid = false;
				return false;
			}	
		}
		else{
			alert("Unable to find control");
			args.IsValid = false;
			return false;
			
		}
	}catch(Exc){
		alert(Exc.message);
	}
}
 /*********************************************************************************
 * Function Name	: GenerateThumbNail
 * Parameters		: strFrameId   - Id of the Iframe in which we want to load thumb nail image.
					  strImagePath - File Path. 
 * Revision History	: Initial Revision by Rizwan Mirza on 08-Oct-04
 *********************************************************************************/
function GenerateThumbNail(strFrameId,objImageText){
	try{
		var objFrame = document.getElementById(strFrameId);
		var objFile = document.getElementById(objImageText);		
		//parse querystring and pass it to thumbnail generator; is there a better method to retrieve querystring?
		objFrame.src = "../bal/ThumbGenerator.aspx?filename="+ objFile.value;		
	}catch(Exc){
		alert("Unable to generate Thumbnail");
	}
}



function DisableCheckbox(nameOfControl)
{
	var ctrl = document.getElementById(nameOfControl);
	if(ctrl != null && ctrl != 'undefined')
		ctrl.checked= false;	
}
/***************************************************************************
ChangeSequenceListbox: changes sequence of selected items in the given listbox one place up or down
parameters: 
ctrlName - the name of the listbox control
down - pass true for moving items down, false to up
selectErrorMessage - error message to be shown if no item is selected
***************************************************************************/
function ChangeSequenceListbox(ctrlName, down, selectErrorMessage) 
{
	ctrl = document.getElementById(ctrlName);
	sl = ctrl.selectedIndex;
	if (sl != -1 && ctrl.options[sl].value > "") 
	{
		if (!down)//move items up
		{
			var oTo = ctrl;
			if(!ctrl.options[0].selected)
			{
				for (var j = 0; j < ctrl.length; j++)
				{
					if (ctrl.options[j].selected && j)
					{
						var currText	= ctrl.options[j].text;
						var currValue	= ctrl.options[j].value;

						ctrl.options[j].text		= ctrl.options[j-1].text
						ctrl.options[j].value		= ctrl.options[j-1].value
						ctrl.options[j-1].text	= currText;
						ctrl.options[j-1].value	= currValue;

						ctrl.options[j-1].selected= true;
						ctrl.options[j].selected	= false;
					}
				}
			}
		}
		else //move items down
		{
			var tot	= ctrl.options.length;
			if(!tot) return

			for (var j=ctrl.options.length-1; j >0 ; j--)
			{
				if (ctrl.options[j-1].selected)
				{
					var currText	= ctrl.options[j].text;
					var currValue	= ctrl.options[j].value;

					ctrl.options[j].text		= ctrl.options[j-1].text;
					ctrl.options[j].value		= ctrl.options[j-1].value;
					ctrl.options[j-1].text		= currText;
					ctrl.options[j-1].value	= currValue;

					ctrl.options[j].selected	=true;
					ctrl.options[j-1].selected	=false;
				}
			}
		}
	} 
	else
	{ 
		alert(selectErrorMessage);
	}
}

/************************************************************************
Selects all items in a listbox
ctrlName - name of listbox
************************************************************************/
function ListboxSelectAll(ctrlName)
{
	var lst = document.getElementById(ctrlName);
	for (var i = 0; i <=lst.length-1; i++)
		lst.options[i].selected = true;
}
/*********************************************************************************
 * Function Name	: startHighlight
 * Parameters		: GridName   - Id of the datagrid on which we want to apply row highlighting					  
 * Revision History	: Initial Revision by Kiran Mistry on 23-August-05
 *********************************************************************************/
function startHighlight(GridName)
{
	if (document.all && document.getElementById)
	{  
		navRoot = document.getElementById(GridName);
			
		// Get a reference to the TBODY element 
		tbody = navRoot.childNodes[0];
			
		for (i = 1; i < tbody.childNodes.length; i++)
		{
			node = tbody.childNodes[i];
			if (node.nodeName == "TR")
			{
				node.onmouseover=function()
				{
					this.className = "over";                
				}
					
				node.onmouseout=function()
				{
					this.className = this.className.replace("over", "");
				}
			}
		}
	}
}

/***************************************************
function PageQuery(q) 
internal function used to process querystring
***************************************************/
function PageQuery(q) 
{
	if(q.length > 1) 
		this.q = q.substring(1, q.length);
	else 
		this.q = null;
	
	this.keyValuePairs = new Array();
	
	if(q) 
	{
		for(var i=0; i < this.q.split("&").length; i++) 
		{
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	
	this.getKeyValuePairs = function() 
	{ 
		return this.keyValuePairs; 
	}
	
	this.getValue = function(s) 
	{
		for(var j=0; j < this.keyValuePairs.length; j++) 
		{
			if(this.keyValuePairs[j].split("=")[0] == s)
				return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}
	
	this.getParameters = function() 
	{
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++) 
		{
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}
	
	this.getLength = function() 
	{ 
		return this.keyValuePairs.length; 
	}	
}


/************************************************************************
function - queryString(key)
processes querystring and returns the given value at client side
************************************************************************/
function queryString(key)
{
	var page = new PageQuery(window.location.search); 
	return unescape(page.getValue(key)); 
}



/***************************************************************************
function GetQueryString(varParamNameToGet)
varParamNameToGet - query string variable whose value is sought

This function returns the value of the given querystring variable
****************************************************************************/
function GetQueryString(varParamNameToGet)
{
	var strQueryParams = window.location.search;
	
	if(strQueryParams != "")
		strQueryParams = strQueryParams.substring(1, strQueryParams.length);//remove ?
		
	strQueryParams = strQueryParams.split('&');
	
	for(i=0; i<=strQueryParams.length-1; i++)
	{
		var strParamName = strQueryParams[i].split('=')[0];
		var strParamValue = strQueryParams[i].split('=')[1];
		
		if(strParamName == varParamNameToGet)
			return strParamValue;
	}
}


function removeitem(obj, index) { /* NEW added from version 1.1 */
	obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
	if (obj.tagName.toLowerCase() != "select" || obj.length == 0)
		return;
	if (index === true) {
		for (index=obj.length-1; index>=0; index--) {
			if (obj[index].selected) {
				obj[index] = null;
			}
		}
	} else {
		obj[((typeof index != "number") || index > (obj.length - 1) || index < 0 ? obj.length - 1 : index)] = null;
	}
}


/****************************************************************************************************************
// XmlDocument factory function
This JS function produces XmlDocument object; The following example teaches how to use this function.

var doc = XmlDocument.create();
doc.loadXML( "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
   "<root>" +
      "<test attr=\"234\" name=\"Test 1\"/>" +
      "<test attr=\"25534\" name=\"Test 2\"/>" +
   "</root>");
   
if(navigator.appName == "Netscape")
	some_bar_node = doc.evaluate('//test[@attr="234"]', doc, null, 9, null).singleNodeValue;
else
	some_bar_node = doc.selectSingleNode('//test[@attr="25534"]');
	
var idval = some_bar_node.getAttribute("attr"); // idval should now be == 'id17'
alert("xpath="+idval);

****************************************************************************************************************/

//<script>
//////////////////
// Helper Stuff //
//////////////////

// used to find the Automation server name
function getDomDocumentPrefix() 
{
	if (getDomDocumentPrefix.prefix)
		return getDomDocumentPrefix.prefix;
	
	var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
	var o;
	for (var i = 0; i < prefixes.length; i++) {
		try {
			// try to create the objects
			o = new ActiveXObject(prefixes[i] + ".DomDocument");
			return getDomDocumentPrefix.prefix = prefixes[i];
		}
		catch (ex) {};
	}
	
	throw new Error("Could not find an installed XML parser");
}

function getXmlHttpPrefix() 
{
	if (getXmlHttpPrefix.prefix)
		return getXmlHttpPrefix.prefix;
	
	var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
	var o;
	for (var i = 0; i < prefixes.length; i++) {
		try {
			// try to create the objects
			o = new ActiveXObject(prefixes[i] + ".XmlHttp");
			return getXmlHttpPrefix.prefix = prefixes[i];
		}
		catch (ex) {};
	}
	
	throw new Error("Could not find an installed XML parser");
}

//////////////////////////
// Start the Real stuff //
//////////////////////////


// XmlHttp factory
function XmlHttp() {}

XmlHttp.create = function () 
{
	try {
		if (window.XMLHttpRequest) {
			var req = new XMLHttpRequest();
			
			// some versions of Moz do not support the readyState property
			// and the onreadystate event so we patch it!
			if (req.readyState == null) {
				req.readyState = 1;
				req.addEventListener("load", function () {
					req.readyState = 4;
					if (typeof req.onreadystatechange == "function")
						req.onreadystatechange();
				}, false);
			}
			
			return req;
		}
		if (window.ActiveXObject) {
			return new ActiveXObject(getXmlHttpPrefix() + ".XmlHttp");
		}
	}
	catch (ex) {}
	// fell through
	throw new Error("Your browser does not support XmlHttp objects");
};

// XmlDocument factory
function XmlDocument() {}

XmlDocument.create = function () 
{
	try {
		// DOM2
		if (document.implementation && document.implementation.createDocument) {
			var doc = document.implementation.createDocument("", "", null);
			
			// some versions of Moz do not support the readyState property
			// and the onreadystate event so we patch it!
			if (doc.readyState == null) {
				doc.readyState = 1;
				doc.addEventListener("load", function () {
					doc.readyState = 4;
					if (typeof doc.onreadystatechange == "function")
						doc.onreadystatechange();
				}, false);
			}
			
			return doc;
		}
		if (window.ActiveXObject)
			return new ActiveXObject(getDomDocumentPrefix() + ".DomDocument");
	}
	catch (ex) {}
	throw new Error("Your browser does not support XmlDocument objects");
};

// Create the loadXML method and xml getter for Mozilla
if (window.DOMParser &&
	window.XMLSerializer &&
	window.Node && Node.prototype && Node.prototype.__defineGetter__) 
	{

		// XMLDocument did not extend the Document interface in some versions
		// of Mozilla. Extend both!
		//XMLDocument.prototype.loadXML = 
		Document.prototype.loadXML = function (s) {
			
		// parse the string to a new doc	
		var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
		
		// remove all initial children
		while (this.hasChildNodes())
			this.removeChild(this.lastChild);
			
		// insert and import nodes
		for (var i = 0; i < doc2.childNodes.length; i++) {
			this.appendChild(this.importNode(doc2.childNodes[i], true));
		}
	};
	
	
	/*
	 * xml getter
	 *
	 * This serializes the DOM tree to an XML String
	 *
	 * Usage: var sXml = oNode.xml
	 *
	 */
	// XMLDocument did not extend the Document interface in some versions
	// of Mozilla. Extend both!
	/*
	XMLDocument.prototype.__defineGetter__("xml", function () {
		return (new XMLSerializer()).serializeToString(this);
	});
	*/
	Document.prototype.__defineGetter__("xml", function () {
		return (new XMLSerializer()).serializeToString(this);
	});
}



/*************************************************************************************
GetNodeInnerText - retrieves the inner text of the SINGLE XML node which is returned by the given XPath query
xmlString - XmlDocument object in string form
xpathExpression - XPath expression
*************************************************************************************/
function GetNodeInnerText(xmlString, xpathExpression)
{
	
	var doc = XmlDocument.create();
	doc.loadXML(xmlString);

	if(navigator.appName == "Netscape")
	{
		objXMLNodeList = doc.evaluate(xpathExpression, doc, null, 6, null);
		return objXMLNodeList.snapshotItem(0).textContent;
	}
	else
	{
		objXMLNodeList = doc.selectNodes(xpathExpression);
		return objXMLNodeList[0].text;
	}
}

/*************************************************************************************
GetXMLNode - retrieves the SINGLE XML node which is returned by the given XPath query
xmlString - XmlDocument object in string form
xpathExpression - XPath expression

This function is useful to retrieve a child node inside an XML node.  As both IE and Mozilla support getElementsByTagName(name),
we can easily retrieve the content of an XML node later
*************************************************************************************/
function GetXMLNode(xmlString, xpathExpression)
{
	
	var doc = XmlDocument.create();
	doc.loadXML(xmlString);

	if(navigator.appName == "Netscape")
	{
		objXMLNodeList = doc.evaluate(xpathExpression, doc, null, 6, null);
		return objXMLNodeList.snapshotItem(0);
	}
	else
	{
		objXMLNodeList = doc.selectNodes(xpathExpression);
		return objXMLNodeList[0];
	}
}

/*************************************************************************************
GetXMLNodeContent - retrieves the content of the given XML node 
*************************************************************************************/
function GetXMLNodeContent(xmlNode)
{
	if(navigator.appName == "Netscape")
		return xmlNode.textContent;
	else
		return xmlNode.text;
}


/*********************************************************************************************
FilterCSV(csv)
Removes specific values in the given CSV
Removes duplicate values in the given CSV
*********************************************************************************************/
function FilterCSV(csvInSession, csvAllOnPage, csvSelectedOnPage)
{
	var htSession = new Hashtable();
	var htAllOnPage = new Hashtable();
	var htSelectedOnPage = new Hashtable();
		
	htSession.initialize(csvInSession);
	htAllOnPage.initialize(csvAllOnPage);
	htSelectedOnPage.initialize(csvSelectedOnPage);
	
	//remove all items of this page from session
	for(var key in htAllOnPage.hashtable)
		htSession.remove(htAllOnPage.hashtable[key]);//the item will be removed if it exists in session
	
	//now add selected items to session
	for(var key in htSelectedOnPage.hashtable)
		htSession.hashtable.push(htSelectedOnPage.hashtable[key]);
	
	return htSession.toCSV();
}

function RemoveDuplicates(csv)
{
	var ht = new Hashtable();
	ht.initialize(csv);
	ht.removeDuplicates();
	return ht.toCSV();
}


/********************** HASHTABLE START**********************************************/

/**
    Created by: Michael Synovic
    on: 01/12/2003
    
    This is a Javascript implementation of the Java Hashtable object.
    
    Contructor(s):
     Hashtable()
              Creates a new, empty hashtable
    
    Method(s):
     void clear() 
              Clears this hashtable so that it contains no keys. 
     boolean containsKey(String key) 
              Tests if the specified object is a key in this hashtable. 
     boolean containsValue(Object value) 
              Returns true if this Hashtable maps one or more keys to this value. 
     Object get(String key) 
              Returns the value to which the specified key is mapped in this hashtable. 
     boolean isEmpty() 
              Tests if this hashtable maps no keys to values. 
     Array keys() 
              Returns an array of the keys in this hashtable. 
     void put(String key, Object value) 
              Maps the specified key to the specified value in this hashtable. A NullPointerException is thrown is the key or value is null.
     Object remove(String key) 
              Removes the key (and its corresponding value) from this hashtable. Returns the value of the key that was removed
     int size() 
              Returns the number of keys in this hashtable. 
     String toString() 
              Returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters ", " (comma and space). 
     Array values() 
              Returns a array view of the values contained in this Hashtable. 
            
*/
function Hashtable()
{
    this.clear = hashtable_clear;
    this.containsKey = hashtable_containsKey;
    this.containsValue = hashtable_containsValue;
    this.get = hashtable_get;
    this.isEmpty = hashtable_isEmpty;
    this.keys = hashtable_keys;
    this.put = hashtable_put;
    this.remove = hashtable_remove;
    this.size = hashtable_size;
    this.toString = hashtable_toString;
    this.values = hashtable_values;
    this.initialize = hashtable_initialize;
    this.hashtable = new Array();
    this.toCSV = hashtable_toCSV;
    this.removeDuplicates = hashtable_removeDuplicates;
}

/*=======Private methods for internal use only========*/
function hashtable_removeDuplicates()
{
	for(var i in this.hashtable)//loop through each item 
		for(var j in this.hashtable)//compare this item with every other item
			if(i!=j && this.hashtable[i] == this.hashtable[j])//don't compare with itself and if you find a duplicate
				this.hashtable[i] = "removethis#";//mark for deletion
				
	var uniqueArr = new Array();
	for(var i in this.hashtable)//loop through all items
		if(this.hashtable[i] != "removethis#")//exclude items marked for deletion
			uniqueArr[i] = this.hashtable[i] ;//build new array
			
	this.hashtable = uniqueArr;
}				


function hashtable_toCSV()
{
    var strCSV = "";
    
    for(var key in this.hashtable)
		strCSV += this.hashtable[key] + ",";
	
	if(strCSV != "")
		strCSV = strCSV.substring(0, strCSV.length-1);
	
	return strCSV;
}


function hashtable_clear()
{
    this.hashtable = new Array();
}

function hashtable_containsKey(key)
{
    var exists = false;
    for (var i in this.hashtable) {
        if (i == key && this.hashtable[i] != null) {
            exists = true;
            break;
        }
    }
    return exists;
}

function hashtable_containsValue(value)
{
    var contains = false;
    if (value != null) {
        for (var i in this.hashtable) {
            if (this.hashtable[i] == value) {
                contains = true;
                break;
            }
        }
    }
    return contains;
}

function hashtable_get(key)
{
    return this.hashtable[key];
}

function hashtable_isEmpty()
{
    return (parseInt(this.size()) == 0) ? true : false;
}

function hashtable_keys()
{
    var keys = new Array();
    for (var i in this.hashtable) //loop through all the keys - i will contain a reference of key
    {
        if (this.hashtable[i] != null) 
            keys.push(i);//when you use push method; the keys in the new array are 0-based and are incremented automatically
    }
    return keys;
}

function hashtable_values()
{
    var values = new Array();
    for (var i in this.hashtable)//loop through all the keys - i will contain a reference of key
    {
        if (this.hashtable[i] != null) 
            values.push(this.hashtable[i]);//get value of this key
    }
    return values;
}

function hashtable_put(key, value)
{
    if (key == null || value == null) {
        throw "NullPointerException {" + key + "},{" + value + "}";
    }else{
        this.hashtable[key] = value;
    }
}

function hashtable_remove(value)
{
    if(this.containsValue(value))
    {
		var tmp = this.hashtable;
		this.clear();
		for(var i in tmp)
			if(tmp[i] != value)//exclude item to delete
				this.hashtable[i] = tmp[i];
    }
}

function hashtable_size()
{
    var size = 0;
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null) 
            size ++;
    }
    return size;
}

function hashtable_toString()
{
    var result = "";
    for (var i in this.hashtable)
    {      
        if (this.hashtable[i] != null) 
            result += "{" + i + "},{" + this.hashtable[i] + "}\n";   
    }
    return result;
}


function hashtable_initialize(csv)
{
	if(csv != "")
	{
		var arr = csv.split(',');
		for(i=0; i<=arr.length-1; i++)
			this.put(i, arr[i]);		
	}
}

/********************** HASHTABLE OVER**********************************************/

function RemoveLastComma(str)
{
	if(str != "")
		if(str.charAt(str.length-1) == ",")
			str = str.substring(0, str.length-1);
	
	return str;
}

function RemoveLastChar(str)
{
	if(str != "")
		str = str.substring(0, str.length-1);
	
	return str;
}


/************************************************************
Returns mouse position
************************************************************/
function GetMousePosition(passedEvent)
{ 
	var objEvent = (passedEvent==null)? window.event: passedEvent;//for mozilla compatibility
	return objEvent.x+","+objEvent.y;
}

function htmlEncode(s) 
{
    var str = new String(s);
    str = str.replace(/&/g, "&amp;");
    str = str.replace(/</g, "&lt;");
    str = str.replace(/>/g, "&gt;");
    str = str.replace(/"/g, "&quot;");
    return str;
} 


/**************************************************************************************************
getOffsetLeft (el)
getOffsetTop (el)

Retrieves the page coordinates of an HTML element
***************************************************************************************************/

var _tpNS = (document.all)?false:true;

function getOffsetLeft (el) {
  var sl = el;
  var ol = el.offsetLeft;
  var sh = 0;
  while ((el = el.offsetParent) != null){
    ol += el.offsetLeft;
     if(el.offsetParent && el.offsetParent.offsetParent){
     var scrollLeft = el.offsetParent.scrollLeft;
       if(!isNaN(scrollLeft)){
         sh -= scrollLeft;
       }
    }
  }

   el = sl;
   if(_tpNS){
        while((el = el.parentNode) != null){
             if(el.parentNode && el.parentNode.parentNode
                && !(el.parentNode.tagName && 
el.parentNode.tagName.toUpperCase() == "BODY")){
      	        var scrollLeft = el.parentNode.scrollLeft;
                if(!isNaN(scrollLeft) && scrollLeft > 0 ){
                   sh -= scrollLeft;
                }
            }
        }
   }
  return ol+sh;
}

function getOffsetTop (el) {
  var ot = el.offsetTop;
  var sl = el;
  var sh = 0;
  while((el = el.offsetParent) != null){
       ot += el.offsetTop;
       if(el.offsetParent && el.offsetParent.offsetParent){
	     var scrollTop = el.offsetParent.scrollTop;
         if(!isNaN(scrollTop)) sh -= scrollTop;
      }
   }
   el = sl;
   if(_tpNS){
        while((el = el.parentNode) != null){
             if(el.parentNode && el.parentNode.parentNode
                && !(el.parentNode.tagName && 
el.parentNode.tagName.toUpperCase() == "BODY")){
      	        var scrollTop = el.parentNode.scrollTop;
                if(!isNaN(scrollTop) && scrollTop > 0 ){
                   sh -= scrollTop;
                }
            }
        }
   }
  return ot + sh;
}

/**************************************************************************************************
getOffsetLeft (el)
getOffsetTop (el)

Retrieves the page coordinates of an HTML element
***************************************************************************************************/


/***************************************************************************************************
setTooltip(elm, tooltipWidth, delay, tooltipHTML)
elm - name of element to be set tooltip on
tooltipWidth - width of tooltip
delay - delay time for tooltip
tooltipHTML - content of tooltip

sets tooltip on the given HTML element - pass nulls in paramters if you want to use defaults

include overlib.js in your page to use this function 
***************************************************************************************************/
function setTooltip(elementName, tooltipWidth, delay, timeout, tooltipHTML)
{
	//alert(elementName+' '+tooltipWidth+' '+delay+' '+timeout+' '+tooltipHTML);
	
	var ctrl = document.getElementById(elementName);
	
	ctrl.onmouseover = function tooltip()
		{	
			
			overlib(tooltipHTML, FOLLOWMOUSE, WIDTH, tooltipWidth);
			//document.getElementById("divInfo").innerHTML += "mouseover="+event.srcElement.id+"<BR>"+" rendered";
			//return escape(tooltipHTML);
		};
	ctrl.onmouseout = function clear()
		{
			document.getElementById("overDiv").style.visibility = "hidden"; 
			document.getElementById("overDiv").innerHTML = "";
			document.getElementById("overDiv").width = 0;
			document.getElementById("overDiv").height = 0;
			document.getElementById("overDiv").style.left = 0;
			document.getElementById("overDiv").style.top = 0;
			//document.getElementById("divInfo").innerHTML += "mouseout="+event.srcElement.id+"<BR>"+document.getElementById("overDiv").width;
		};
	
}

/***************************************************************************************************
clearTooltip(elm, tooltipWidth, delay, tooltipHTML)
elm - name of element whose tooltip is to be cleared

clears tooltip on the given HTML element - call this function when you find a tooltip is stuck
include overlib.js in your page to use this function 
***************************************************************************************************/
function clearTooltip(elementName, tooltipWidth, delay, tooltipHTML)
{
	var ctrl = document.getElementById(elementName);
	ctrl.onmouseover = function clear(){return false;};
	ctrl.onmouseout = function clear(){return false;};
}



/***************************************************************************************************
SendAJAXRequest:  Use this function to send AJAX requests to a predefined server side ASHX handler
functionName - The name of server side function to be called - this function is actually some server side code block that returns data
queryString - querystring to be sent to server side function 
callBackFunction - 
	the client side function that will be called when data comes from server side;  Get data in XML format from http.responseXML or in text 
	format from http.responseText, depending upon the way you are returning data from your server side block

	Put the following status check in your client side function
			if (http.readyState != 4 || http.status != 200 )
				return;


***************************************************************************************************/
var http = null;//HTTP object
function SendAJAXRequest(functionName, queryString, callBackFunction)
{
	if(navigator.appName != "Netscape")
		http = new ActiveXObject("Microsoft.xmlhttp");
	else
		http = new XMLHttpRequest();
	
	var root = window.location.pathname.split("/")[1];	
	
	http.open("GET", "/"+root+"/AJAXFunctions.ashx?Function="+functionName+"&"+queryString, true); 
	http.onreadystatechange = callBackFunction;
	http.send(null);
}

var http = null;//HTTP object
function PostThroughAJAX(actionPage, queryString, callBackFunction)
{
	if(navigator.appName != "Netscape")
		http = new ActiveXObject("Microsoft.xmlhttp");
	else
		http = new XMLHttpRequest();
	
	var root = window.location.pathname.split("/")[1];	
	
	http.open("GET", actionPage+"?"+queryString, true); 
	http.onreadystatechange = callBackFunction;
	http.send(null);
}

function SerializeForm()
{
	var ctrls = document.forms[0].elements;
	var namevalue = "";
	for(var i=0; i<=ctrls.length-1; i++)
		namevalue += ctrls[i].id+"="+ctrls[i].value+"&";
	
	namevalue = namevalue.substring(0, namevalue.length-1);
	return namevalue;	
}

function getKeyCode(passedEvent)
{
	var objEvent;
	var keyCode;
	
	if(navigator.appName == "Netscape")
	{
		objEvent = passedEvent;
		keyCode = objEvent.which;
	}
	else
	{
		objEvent = window.event;
		keyCode = objEvent.keyCode;
	}
	
	return keyCode;
}

function getEventSource(passedEvent)
{
	var objEvent;
	var src;
	
	if(navigator.appName == "Netscape")
	{
		objEvent = passedEvent;
		src = objEvent.target;
	}
	else
	{
		objEvent = window.event;
		src = objEvent.srcElement;
	}
	
	return src;
	
}


function copyAttributes(source, target)
{
	for(i=0; i<=source.attributes.length-1; i++)
	{
		if(source.attributes[i].nodeName.toLowerCase() == "innerhtml")
			alert(source.attributes[i].nodeName+"="+source.attributes[i].nodeValue);
		target.setAttribute(source.attributes[i].nodeName, source.attributes[i].nodeValue);
	}
}

/***************************************************************************************************
eraseTooltip()
clears tooltip from the entire HTML page  
***************************************************************************************************/
function eraseTooltip()
{
	if(document.getElementById("overDiv"))
	{
		document.getElementById("overDiv").style.visibility = "hidden"; 
		document.getElementById("overDiv").innerHTML = "";
		document.getElementById("overDiv").width = 0;
		document.getElementById("overDiv").height = 0;
		document.getElementById("overDiv").style.left = 0;
		document.getElementById("overDiv").style.top = 0;
	}
}

function addToSelectControl(controlID, itemText, itemValue)
{
	var ctrl = document.getElementById(controlID);
	var oOption = document.createElement("OPTION");
	oOption.id = itemValue;
	oOption.text = itemText;
	oOption.value = itemValue;
	ctrl.options.add(oOption);
	setTooltip(oOption.id, (oOption.text.length)*6, 0, 0, oOption.text);
}

function clearSelectControl(controlID)
{
	var ctrl = document.getElementById(controlID);
	for(m=ctrl.options.length-1; m>=0; m--)
		ctrl.remove(m);
}

function isFirefox()
{
	return navigator.appName == "Netscape";
}

function IsValidNumber(str)
{
	var regExp = new RegExp('[^0-9]');
	return !regExp.test(str);
}

function IsAlphaNumeric(str)
{
	var regExp = new RegExp('[^0-9a-zA-Z ]');
	return !regExp.test(str);
}


/**************************
findDuplicateRow(jsTable)

jsTable: array of records; columns within a record should be delimited by #

Description:
Finds duplicate rows in the given JS table
The table must be in the following format:

Returns:
"" if no duplicate found
The entry which has a duplicate if duplicate exists

The JS table like the following

Murtaza#Tinwala#Male#Rajkot
Kandarp#Nirmal#Male#Junagadh
Rinku#Bhatt#Female#Ahmedabad


***************************/
function findDuplicateRow(jsTable)
{
	var rows = jsTable;
	for(r1=0; r1<=rows.length-1; r1++)
		for(r2=r1+1; r2<=rows.length-1; r2++)
			if(rows[r1].toLowerCase() == rows[r2].toLowerCase())
				return rows[r1];		
	return "";
}

/* ========================== */

function showPopupResizableWindow(pageName, pageTitle, winHeight, winWidth)
{
	var winTopPos = eval(screen.height - winHeight) / 2;
	var winLeftPos = eval(screen.width - winWidth) / 2;

	testwindow = window.open(pageName,pageTitle, "'fullscreen=no,scrollbars=yes,status=yes,menubar=no,resizable=yes,width="+winWidth+",height="+winHeight+"'");
	testwindow.moveTo(winLeftPos,winTopPos);
}

/* ========================== */

