/**
 * PURPOSE : Validation and Itemchange for Perl Claim verification
 * AUTHOR : Kunal Mandhre
 * DATE : 03/10/2012
 */

package ibase.webitm.ejb.adm;

import java.rmi.RemoteException;
import java.sql.*;
import java.text.*;
import java.util.*;

import org.w3c.dom.*;

import ibase.system.config.*;
import ibase.webitm.ejb.*;
import ibase.webitm.ejb.adm.AdmCommon;
import ibase.webitm.ejb.dis.DistCommon;
import ibase.webitm.utility.GenericUtility;
import ibase.webitm.utility.ITMException;

@javax.ejb.Stateless
public class PerkClaimIC extends ValidatorEJB implements PerkClaimICLocal, PerkClaimICRemote  
{


	public String wfValData(String currFrmXmlStr, String hdrFrmXmlStr,String allFrmXmlStr, String objContext, String editFlag, String xtraParams) throws RemoteException,ITMException
	{
		Document currDom = null;
		Document hdrDom = null;
		Document allDom = null;
		String errString = "";
		System.out.println("curr xml="+currFrmXmlStr);
		System.out.println("hdr xml="+hdrFrmXmlStr);
		System.out.println("all xml="+allFrmXmlStr);

		try
		{			
			if(currFrmXmlStr != null && currFrmXmlStr.trim().length()!=0)
			{
				currDom = parseString(currFrmXmlStr); 
			}
			if(hdrFrmXmlStr != null && hdrFrmXmlStr.trim().length()!=0)
			{
				hdrDom = parseString(hdrFrmXmlStr); 
			}
			if(allFrmXmlStr != null && allFrmXmlStr.trim().length()!=0)
			{
				allDom = parseString(allFrmXmlStr);
			}
			errString = wfValData(currDom,hdrDom,allDom,objContext,editFlag,xtraParams);
		}//end of try
		catch(Exception e)
		{
			System.out.println("Exception : [PerlClaimIc][wfValData(String currFrmXmlStr)] : ==>\n"+e.getMessage());
			e.printStackTrace();			
			throw new ITMException(e);
		}
		return (errString); 
	}

	/**
	 * The public overloaded method takes a document as input and is used for the validation of specified fields 
	 * Returns validation string if exist otherwise returns null in XML format
	 * @param currDom contains the current form data as a document object model
	 * @param hdrDom contains all the header information
	 * @param allDom contains the field data of all the forms 
	 * @param objContext represents form number
	 * @param editFlag represents the mode of transaction(A-Add or E-Edit)
	 * @param xtraParams contains additional information such as loginEmpCode,loginCode,chgTerm etc
	 */	
	public String wfValData(Document currDom, Document hdrDom, Document allDom, String objContext, String editFlag, String xtraParams) throws RemoteException, ITMException 	
	{
		String errString = "";
		String columnValue = "";
		String sql = "";	
		String adCode = "" , balOpt = "" ,payable = "" , varValue = "" , empCode = "", bankCode = "";
		String adjLoan = "", fullAmt = "" , paySite = "" ,cadre = "" ,grade = "";
		String payrollVoucher = "",payrollPrd = "";
		String childNodeName = "";
		//String invStat = "";
		int noOfChilds = 0;
		int noOfParent = 0;                            
		int count = 0;    

		//double balanceAmt = 0;
		java.util.Date claimDate = null; 
		Timestamp relieveDate = null;

		ResultSet rs = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		GenericUtility genericUtility = GenericUtility.getInstance();
		StringBuffer errStringXml = new StringBuffer("<?xml version=\"1.0\"?>\r\n<Root><Errors>");
		String errorType = "", errCode = "";
		ArrayList errList = new ArrayList();
		ArrayList errFields = new ArrayList();
		AdmCommon admCommon = new AdmCommon(); 
		SimpleDateFormat simpleDateFormat = null;

		try
		{

			int currentFormNo = 0, cnt = 0;		

			ConnDriver connDriver = null;
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			simpleDateFormat = new SimpleDateFormat("dd/MM/yy");

			Node childNode =null;

			String userId = genericUtility.getValueFromXTRA_PARAMS( xtraParams, "loginCode" );
			if ( objContext != null && objContext.trim().length() > 0 )
			{
				currentFormNo = Integer.parseInt( objContext );
			}

			NodeList parentList = currDom.getElementsByTagName( "Detail" + currentFormNo );
			NodeList childList = null;	
			noOfParent = parentList.getLength();

			switch(currentFormNo)
			{
			case 1 :
			{
				System.out.println("Case 1 Validation");
				childList = parentList.item( 0 ).getChildNodes();
				noOfChilds = childList.getLength();
				for (int ctr = 0; ctr < noOfChilds; ctr++)
				{	
					childNode = childList.item( ctr );
					if( childNode.getNodeType() != Node.ELEMENT_NODE )
					{
						continue;
					}
					childNodeName = childNode.getNodeName();						
					if ( childNode != null && childNode.getFirstChild() != null )
					{
						columnValue = childNode.getFirstChild().getNodeValue();
					}
					System.out.println(" columnName [" + childNodeName + "] columnValue [" + columnValue + "]");
					if ( "ad_code".equalsIgnoreCase( childNodeName ) )
					{
						adCode = checkNull(genericUtility.getColumnValue( "ad_code", currDom ));
						System.out.println("adCode="+adCode);
						//ls_var_val = gf_getenv("999999" , "CLAIMAD_WO_LOANADJ")
						varValue =  admCommon.getEnv("999999", "CLAIMAD_WO_LOANADJ", conn);
						System.out.println("varValue="+varValue);
						if(varValue != null && varValue.trim().length() > 0 && "NULLFOUND".equalsIgnoreCase(varValue))
						{
							varValue = varValue.trim()+",";
							if(varValue.indexOf(adCode.trim()+",") > 0 )
							{
								//errcode = "VPPERKAD1~tThis type of perk can not be claimed using this option, use claim without loan adjustment option"
								errList.add( "VPPERKAD1" );
								errFields.add( childNodeName.toLowerCase() );
							}
						}

						sql = " select count(*) from allwdedn where ad_code = ? ";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, adCode);
						rs = pstmt.executeQuery();
						if (rs.next())
						{
							cnt = rs.getInt(1);
						}							
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

						if(cnt == 0)
						{
							errList.add( "VMADC1" );
							errFields.add( childNodeName.toLowerCase() );
						}
						else
						{
							sql = " select bal_opt,payable from allwdedn where ad_code = ? ";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1, adCode);
							rs = pstmt.executeQuery();
							if (rs.next())
							{
								balOpt = checkNull(rs.getString("bal_opt"));
								payable = checkNull(rs.getString("payable"));
							}							
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
							if("D".equalsIgnoreCase(payable))
							{
								errList.add( "VTADTYPE" );
								errFields.add( childNodeName.toLowerCase() );
							}
						}
					}
					else if ( "claim_date".equalsIgnoreCase( childNodeName ) )
					{
						System.out.println("claim date = "+genericUtility.getColumnValue( "claim_date", currDom ) == null);
						if(genericUtility.getColumnValue( "claim_date", currDom ) == null)
						{
							errList.add( "VMDATENULL" );
							errFields.add( childNodeName.toLowerCase() );
						}
					}
					else if ( "bank_code".equalsIgnoreCase( childNodeName ) )
					{
						bankCode = checkNull(genericUtility.getColumnValue( "bank_code", currDom ));
						System.out.println("bankCode="+bankCode);

						if(bankCode != null && bankCode.trim().length() > 0)
						{
						sql = " select count(*) from bank where bank_code = ? ";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, bankCode);
						rs = pstmt.executeQuery();
						if (rs.next())
						{
							cnt = rs.getInt(1);
						}							
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;
						if(cnt == 0)
						{
							errList.add( "VMBANK1" );
							errFields.add( childNodeName.toLowerCase() );
						}
						}
					}
					else if ( "emp_code".equalsIgnoreCase( childNodeName ) )
					{
						empCode = checkNull(genericUtility.getColumnValue( "emp_code", currDom ));
						System.out.println("empCode="+empCode);

						sql = " select count(*) from employee where emp_code = ? ";
						pstmt = conn.prepareStatement(sql);
						pstmt.setString(1, empCode);
						rs = pstmt.executeQuery();
						if (rs.next())
						{
							cnt = rs.getInt(1);
						}							
						rs.close();
						rs = null;
						pstmt.close();
						pstmt = null;

						if(cnt == 0)
						{
							errList.add( "VMEMP1" );
							errFields.add( childNodeName.toLowerCase() );
						}
						else
						{
							sql = " Select count(*)  from loans   Where emp_code = ?  "
									+"	and (status = 'U' or (status = 'A' and start_dedn <> 'Y')) 	and accrual_amt > 0 ";
							pstmt = conn.prepareStatement(sql);
							pstmt.setString(1,empCode);
							rs = pstmt.executeQuery();
							if (rs.next())
							{
								cnt = rs.getInt(1);
							}							
							rs.close();
							rs = null;
							pstmt.close();
							pstmt = null;
							if(cnt > 0)
							{
								errList.add( "VTLOAN7" );
								errFields.add( childNodeName.toLowerCase() );
							}
						}
						System.out.println("case 1 val for process tab");
						empCode = checkNull(genericUtility.getColumnValue("emp_code",currDom));
						adCode = checkNull(genericUtility.getColumnValue("ad_code",currDom));
						fullAmt = checkNull(genericUtility.getColumnValue("full_amt",currDom)) ; 
						adjLoan = checkNull(genericUtility.getColumnValue("adjust_loan",currDom));
						System.out.println("empCode="+empCode);
						System.out.println("adCode="+adCode);
						System.out.println("fullAmt="+fullAmt);
						System.out.println("adjLoan="+adjLoan);
						if(genericUtility.getColumnValue("claim_date", currDom) == null)
						{
							claimDate = null;
						}
						else
						{
							claimDate =  simpleDateFormat.parse(genericUtility.getColumnValue("claim_date", currDom));
						}
						System.out.println("claimDate="+claimDate);
						/*
						if("Y".equalsIgnoreCase(adjLoan))
						{
							//loan tab enable
							sql = "select sum(balance_amt) 	from allowdedn_bal,loans where ref_no = loan_no "
									+" and allowdedn_bal.emp_code = ?  and ad_code between '0' and 'z' and amt_bal > 0 	and ref_type = 'L' 	and adjustable = 'Y'";
							pstmt = conn.prepareStatement( sql );
							pstmt.setString( 1, empCode );						
							rs = pstmt.executeQuery();	
							if( rs.next() )
							{
								balanceAmt = rs.getDouble(1);
							}
							rs.close();rs = null;
							pstmt.close();pstmt = null;
						}
						else
						{
							//loan tab disable
						}
						*/

						sql = "select relieve_date,pay_site,cadre,grade " 
								+" from employee where emp_code = ? ";
						pstmt = conn.prepareStatement( sql );
						pstmt.setString( 1, empCode );						
						rs = pstmt.executeQuery();	
						if( rs.next() )
						{
							relieveDate = rs.getTimestamp("relieve_date");
							paySite = checkNull(rs.getString("pay_site"));
							cadre = checkNull(rs.getString("cadre"));
							grade = checkNull(rs.getString("grade"));
						}
						rs.close();rs = null;
						pstmt.close();pstmt = null;

						String envName = adCode.trim().toUpperCase()+"_CLAIMCURRPRD";
						System.out.println("envName="+envName);
						//ls_can_claim_in_sameyear = gf_get_admenv(ls_site , ls_cadre , ls_grade , & 
						//	ls_env_name , ld_claim)
						String canClaimInsameYear = admCommon.getAdmEnv(paySite, cadre, grade, envName, relieveDate, conn);
						System.out.println("canClaimInsameYear="+canClaimInsameYear);

						if("NULLFOUND".equalsIgnoreCase(canClaimInsameYear))
						{
							canClaimInsameYear = admCommon.getEnv("999999", envName, conn);
							System.out.println("canClaimInsameYear="+canClaimInsameYear);
							if("NULLFOUND".equalsIgnoreCase(canClaimInsameYear))
							{
								errList.add( "VSENVAR1" );
								errFields.add( childNodeName.toLowerCase() );
								//ls_errcode = 'VSENVAR1~t Variable (" + ls_env_name + ") is not defined properly'
							}
						}
						/*else if() elseif left(ls_can_claim_in_sameyear , 4) = "ERR~t" then
						{
							ls_errcode = mid(ls_can_claim_in_sameyear , 5) + &
									'Could not fetch environment (' + ls_env_name + ') from site_env table'
						}*/

					}
					else if ( "payroll_voucher".equalsIgnoreCase( childNodeName ) )
					{
						payrollVoucher = checkNull(genericUtility.getColumnValue( "payroll_voucher", currDom ));
						payrollPrd = checkNull(genericUtility.getColumnValue( "payroll_prd", currDom ));
						if("P".equalsIgnoreCase(payrollVoucher))
						{
							if(payrollPrd == null || payrollPrd.trim().length() == 0 )
							{
								errList.add( "VMPRDCD" );
								errFields.add( childNodeName.toLowerCase() );
							}
						}
						
					}
					/*else
					{
						System.out.println("case 1 val else");
						empCode = checkNull(genericUtility.getColumnValue("emp_code",currDom));
						adCode = checkNull(genericUtility.getColumnValue("ad_code",currDom));
						fullAmt = checkNull(genericUtility.getColumnValue("full_amt",currDom)) ; 
						adjLoan = checkNull(genericUtility.getColumnValue("adjust_loan",currDom));
						System.out.println("empCode="+empCode);
						System.out.println("adCode="+adCode);
						System.out.println("fullAmt="+fullAmt);
						System.out.println("adjLoan="+adjLoan);
						if(genericUtility.getColumnValue("claim_date", currDom) == null)
						{
							claimDate = null;
						}
						else
						{
							claimDate =  simpleDateFormat.parse(genericUtility.getColumnValue("claim_date", currDom));
						}
						System.out.println("claimDate="+claimDate);
						if("Y".equalsIgnoreCase(adjLoan))
						{
							//loan tab enable
							sql = "select sum(balance_amt) 	from allowdedn_bal,loans where ref_no = loan_no "
									+" and allowdedn_bal.emp_code = ?  and ad_code between '0' and 'z' and amt_bal > 0 	and ref_type = 'L' 	and adjustable = 'Y'";
							pstmt = conn.prepareStatement( sql );
							pstmt.setString( 1, empCode );						
							rs = pstmt.executeQuery();	
							if( rs.next() )
							{
								balanceAmt = rs.getDouble(1);
							}
							rs.close();rs = null;
							pstmt.close();pstmt = null;
						}
						else
						{
							//loan tab disable
						}

						sql = "select relieve_date,pay_site,cadre,grade " 
								+" from employee where emp_code = ? ";
						pstmt = conn.prepareStatement( sql );
						pstmt.setString( 1, empCode );						
						rs = pstmt.executeQuery();	
						if( rs.next() )
						{
							relieveDate = rs.getTimestamp("relieve_date");
							paySite = checkNull(rs.getString("pay_site"));
							cadre = checkNull(rs.getString("cadre"));
							grade = checkNull(rs.getString("grade"));
						}
						rs.close();rs = null;
						pstmt.close();pstmt = null;

						String envName = adCode.trim().toUpperCase()+"_CLAIMCURRPRD";
						System.out.println("envName="+envName);
						//ls_can_claim_in_sameyear = gf_get_admenv(ls_site , ls_cadre , ls_grade , & 
						//	ls_env_name , ld_claim)
						String canClaimInsameYear = admCommon.getAdmEnv(paySite, cadre, grade, envName, relieveDate, conn);
						System.out.println("canClaimInsameYear="+canClaimInsameYear);

						if("NULLFOUND".equalsIgnoreCase(canClaimInsameYear))
						{
							canClaimInsameYear = admCommon.getEnv("999999", envName, conn);
							System.out.println("canClaimInsameYear="+canClaimInsameYear);
							if("NULLFOUND".equalsIgnoreCase(canClaimInsameYear))
							{
								errList.add( "VSENVAR1" );
								errFields.add( childNodeName.toLowerCase() );
								//ls_errcode = 'VSENVAR1~t Variable (" + ls_env_name + ") is not defined properly'
							}
						}
						//else if() elseif left(ls_can_claim_in_sameyear , 4) = "ERR~t" then
						//{
							//ls_errcode = mid(ls_can_claim_in_sameyear , 5) + &
								//	'Could not fetch environment (' + ls_env_name + ') from site_env table'
						//}
					}*/


				}// for loop end
			}//case 1 end
			break;
			case 2 :
			{
				System.out.println("Case 2 Validation");
				NodeList parentNodeList = null;
				Node parentNode = null;
				int parentNodeListLength = 0;
				double claimAmount = 0,balAmount = 0;
				parentNodeList = allDom.getElementsByTagName("Detail2");
				parentNodeListLength = parentNodeList.getLength();
				System.out.println("Detail2 length = "+parentNodeListLength);
				if(parentNodeListLength < 1)
				{
					errList.add( "VTNOSEL" );
					errFields.add( " " );
				}
				else
				{
					fullAmt =  checkNull(genericUtility.getColumnValue("full_amt", hdrDom));
					for(int ctr = 0; ctr < parentNodeListLength ; ctr++ )
					{
						System.out.println("TEST LENGTH="+parentNodeListLength);
						parentNode = parentNodeList.item(ctr);
						//Element  parentNode1 = (Element)parentNodeList.item(ctr);
						//claimAmount = Double.parseDouble(genericUtility.getColumnValue("claim_amt", dom, "2")== null?"0":genericUtility.getColumnValue("claim_amt", dom, "2"));
						claimAmount = Double.parseDouble(genericUtility.getColumnValueFromNode( "claim_amt", parentNodeList.item(ctr) )== null?"0":genericUtility.getColumnValueFromNode( "claim_amt", parentNodeList.item(ctr) ));
						balAmount = Double.parseDouble(genericUtility.getColumnValueFromNode( "amt_bal", parentNodeList.item(ctr) )== null?"0":genericUtility.getColumnValueFromNode( "amt_bal", parentNodeList.item(ctr) ));
						//balAmount = Double.parseDouble(genericUtility.getColumnValue("amt_bal", dom, "2")== null?"0":genericUtility.getColumnValue("amt_bal", dom, "2"));
						System.out.println("Full amy=="+fullAmt+"   "+balAmount+"   "+claimAmount);
						if("Y".equalsIgnoreCase(fullAmt))
						{
							if(balAmount != claimAmount)
							{
								errList.add( "VTPERK1" );
								errFields.add( "claim_amt" );
							}
						}
						else
						{
							if(claimAmount > balAmount)
							{
								errList.add( "VMADJAMT2" );
								errFields.add( "claim_amt" );
							}
						}

					}
				}

			// for loop end
			}//case 2 end
			break;
			case 3:
			{
				System.out.println("Case 3 Validation");
				childList = parentList.item( 0 ).getChildNodes();
				noOfChilds = childList.getLength();
				for ( int ctr = 0; ctr < noOfChilds; ctr++ )  //Loop for each node of current detail
				{	
					childNode = childList.item( ctr );
					if( childNode.getNodeType() != Node.ELEMENT_NODE )
					{
						continue;
					}
					childNodeName = childNode.getNodeName();
					if ( childNode != null && childNode.getFirstChild() != null )
					{
						columnValue = childNode.getFirstChild().getNodeValue();
					}
					System.out.println(" columnName [" + childNodeName + "] columnValue [" + columnValue + "]");
					if( "xyz".equalsIgnoreCase( childNodeName ) )
					{


					}//End of case "loc_code__to"

				}//End of inner for loop

			}//case3 end
			} //switch end
			int errListSize = errList.size();
			cnt =0;
			String errFldName = null;
			if ( errList != null && errListSize > 0 )
			{
				for (cnt = 0; cnt < errListSize; cnt++ )
				{
					errCode = (String)errList.get(cnt);
					errFldName = (String)errFields.get(cnt);
					System.out.println("errCode .........."+errCode);
					//String errMsg = hashMap.get(errCode)!=null ? hashMap.get(errCode).toString():"";
					//System.out.println("errMsg .........."+errMsg);
					errString = getErrorString( errFldName, errCode, userId );
					errorType =  errorType( conn , errCode );
					if ( errString.length() > 0)
					{
						String bifurErrString = errString.substring( errString.indexOf("<Errors>") + 8,errString.indexOf("<trace>"));
						bifurErrString =bifurErrString;//+"<trace>"+errMsg+"</trace>";
						bifurErrString =bifurErrString+errString.substring( errString.indexOf("</trace>") + 8,errString.indexOf("</Errors>"));
						errStringXml.append(bifurErrString);
						System.out.println("errStringXml .........."+errStringXml);
						errString = "";
					}
					if ( errorType.equalsIgnoreCase("E"))
					{
						break;
					}
				}
				errList.clear();
				errList = null;
				errFields.clear();
				errFields = null;

				errStringXml.append("</Errors></Root>\r\n");
			}
			else
			{
				errStringXml = new StringBuffer( "" );
			}
			errString = errStringXml.toString();
		}//try block end
		catch(Exception e)
		{
			System.out.println("Exception in PerlClaimIc  == >");
			e.printStackTrace();
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if( conn != null && ! conn.isClosed() )
				{
					conn.close();
				}
			}
			catch(Exception e)
			{
				System.out.println( "Exception :PerlClaimIc:wfValData :==>\n"+e.getMessage());
				throw new ITMException(e);
			}
		}
		return errString;
	}
	private String errorType( Connection conn , String errorCode )
	{
		String msgType = "";
		PreparedStatement pstmt = null ; 
		ResultSet rs = null;
		try
		{			
			String  sql = " SELECT MSG_TYPE FROM MESSAGES WHERE MSG_NO =   ? ";

			pstmt = conn.prepareStatement( sql );			
			pstmt.setString(1, errorCode);			
			rs = pstmt.executeQuery();
			while( rs.next() )
			{
				msgType = rs.getString("MSG_TYPE");
			}			
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}		
		finally
		{
			try
			{
				if ( rs != null )
				{
					rs.close();
					rs = null;
				}
				if ( pstmt != null )
				{
					pstmt.close();
					pstmt = null;
				}
			}
			catch ( Exception e )
			{
				e.printStackTrace();
			}
		}		
		return msgType;
	}


	/**
	 * The public method is used for converting the current form data into a document(dom)
	 * The currDom is then given as argument to the overloaded function wfValData to perform validation
	 * Returns validation string if exists else returns null in XML format
	 * @param currFrmXmlStr contains the current form data in XML format
	 * @param hdrFrmXmlStr contains all the header information in the XML format
	 * @param allFrmXmlStr contains the data of all the forms in XML format
	 * @param objContext represents the form number
	 * @param currentColumn represents the value of current field.
	 * @param editFlag represents the mode of transaction(A-Add or E-Edit)
	 * @param xtraParams contains additional information such as loginEmpCode,loginCode,chgTerm etc
	 */
	public String itemChanged(String currFrmXmlStr, String hdrFrmXmlStr, String allFrmXmlStr, String objContext, String currentColumn, String editFlag, String xtraParams) throws RemoteException, ITMException
	{
		Document currDom = null;
		Document hdrDom = null;
		Document allDom = null;

		String errString = null;
		System.out.println("currFrmXmlStr::"+currFrmXmlStr);
		System.out.println("hdrFrmXmlStr::"+hdrFrmXmlStr);
		System.out.println("allFrmXmlStr::"+allFrmXmlStr);

		GenericUtility genericUtility = GenericUtility.getInstance();

		try
		{
			if (currFrmXmlStr != null && currFrmXmlStr.trim().length()!=0)
			{
				currDom = genericUtility.parseString(currFrmXmlStr); 
			}
			if (hdrFrmXmlStr != null && hdrFrmXmlStr.trim().length()!=0)
			{
				hdrDom = genericUtility.parseString(hdrFrmXmlStr); 
			}
			if (allFrmXmlStr != null && allFrmXmlStr.trim().length()!=0)
			{
				allDom = genericUtility.parseString(allFrmXmlStr); 
			}
			errString = itemChanged( currDom, hdrDom, allDom, objContext, currentColumn, editFlag, xtraParams );
			System.out.println ( "ErrString :" + errString);
		}
		catch (Exception e)
		{
			System.out.println ( "Exception : PerlClaimIc:defaul_ItemChanged(String,String):" + e.getMessage() + ":" );
			errString = genericUtility.createErrorString(e);
			throw new ITMException(e);
		}
		System.out.println ( "returning from PerlClaimIc default_Itemchanged" );
		return errString;
	}	

	/**
	 * The public overloaded method takes a document as input and is used for the validation of required fields 
	 * Returns validation string if exist otherwise returns null in XML format
	 * @param currDom contains the current form data as a document object model
	 * @param hdrDom contains all the header information
	 * @param allDom contains the field data of all the forms 
	 * @param objContext represents form number
	 * @param currentColumn represents the current field 
	 * @param editFlag represents the mode of transaction(A-Add or E-Edit)
	 * @param xtraParams contains additional information
	 * 
	 */
	public String itemChanged( Document currDom, Document hdrDom, Document allDom, String objContext, String currentColumn, String editFlag, String xtraParams ) throws RemoteException,ITMException
	{
		String retValue = "";
		try
		{
			retValue = default_ItemChanged( currDom, hdrDom, allDom,  objContext, currentColumn, editFlag, xtraParams );
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
			throw new ITMException(e);
		}
		return retValue;

	}
	public String default_ItemChanged( Document currDom, Document hdrDom, Document allDom, String objContext, String currentColumn, String editFlag, String xtraParams ) throws RemoteException,ITMException
	{
		String sql = "";
		String empCode = "", adCode = "" , adjLoan = "" ,paySite = "" ,cadre = "" ,grade = "",descr = "";
		String adDescr = "", payMode = "", bankCode = "", payrollVoucher = "", payrollPrd = "";
		String fullAmt = "" ,fName = "",lName = "";
		String loanRefNo = "", loanAdCode = "", schemeNo = "";
		String loanNo = "";
		int currentFormNo = 0;
		int domID = 0;	
		int count = 0;
		double  balanceAmt = 0 , claimAmount = 0,amount = 0 ,balAmount = 0;
		double loanAdjPerc = 0,loanBalAmt = 0, loanMonInst = 0, loanInterest = 0, loanAmt = 0;
		java.util.Date claimDate = null,startDate = null , endDate = null ;
		Timestamp  relieveDate = null;
		NodeList parentNodeList = null;
		Node parentNode = null;
		int parentNodeListLength = 0;
		ResultSet rs = null,rs1 = null;
		Connection conn = null;
		PreparedStatement pstmt = null,pstmt1 = null;
		StringBuffer valueXmlString = new StringBuffer();		

		GenericUtility genericUtility = GenericUtility.getInstance();
		AdmCommon admCommon = new AdmCommon();
		try
		{
			//String dbDateFormat = genericUtility.getDBDateFormat();
			String applDateFormat = genericUtility.getApplDateFormat();
			SimpleDateFormat sdf = new SimpleDateFormat(applDateFormat);

			ConnDriver connDriver = null;
			connDriver = new ConnDriver();
			conn = connDriver.getConnectDB("DriverITM");
			if( objContext != null && objContext.trim().length() > 0 )
			{
				currentFormNo = Integer.parseInt( objContext );
			}
			valueXmlString = new StringBuffer( "<?xml version=\"1.0\"?>\r\n<Root>\r\n<Header>\r\n<editFlag>" );
			valueXmlString.append( editFlag ).append( "</editFlag>\r\n</Header>\r\n" );

			switch ( currentFormNo )
			{
			case 1:
			{
				System.out.println("case 1 IC...");
				//valueXmlString.append( "<Detail1 domID='1'>\r\n" );
				valueXmlString.append( "<Detail1 domID='1' selected=\"Y\">\r\n" );
				valueXmlString.append("<attribute selected=\"Y\" updateFlag=\"E\" status=\"O\" pkNames=\"\" />\r\n");
				if( currentColumn.trim().equalsIgnoreCase( "itm_default" ) )							
				{	
					valueXmlString.append("<claim_date><![CDATA["+ sdf.format(new java.util.Date()).toString() +"]]></claim_date>");
				}
				else if( currentColumn.trim().equalsIgnoreCase( "emp_code" ) )
				{
					empCode = checkNull(genericUtility.getColumnValue("emp_code",currDom));
					valueXmlString.append( "<emp_code><![CDATA[" ).append( empCode ).append( "]]></emp_code>\r\n" );
					empCode = checkNull(genericUtility.getColumnValue("claim_date",currDom));
					valueXmlString.append( "<claim_date><![CDATA[" ).append( empCode ).append( "]]></claim_date>\r\n" );
					adCode = checkNull(genericUtility.getColumnValue("ad_code",currDom));
					valueXmlString.append( "<ad_code><![CDATA[" ).append( adCode ).append( "]]></ad_code>\r\n" );
					adjLoan= checkNull(genericUtility.getColumnValue("adjust_loan",currDom));
					valueXmlString.append( "<adjust_loan><![CDATA[" ).append( adjLoan ).append( "]]></adjust_loan>\r\n" );
					fullAmt = checkNull(genericUtility.getColumnValue("full_amt",currDom));
					valueXmlString.append( "<full_amt><![CDATA[" ).append( fullAmt ).append( "]]></full_amt>\r\n" );
					payrollVoucher = checkNull(genericUtility.getColumnValue("payroll_voucher",currDom));
					valueXmlString.append( "<payroll_voucher><![CDATA[" ).append( payrollVoucher ).append( "]]></payroll_voucher>\r\n" );
					payrollPrd = checkNull(genericUtility.getColumnValue("payroll_prd",currDom));
					valueXmlString.append( "<payroll_prd><![CDATA[" ).append( payrollPrd ).append( "]]></payroll_prd>\r\n" );
					bankCode = checkNull(genericUtility.getColumnValue("bank_code",currDom));
					valueXmlString.append( "<bank_code><![CDATA[" ).append( bankCode ).append( "]]></bank_code>\r\n" );
					payMode = checkNull(genericUtility.getColumnValue("pay_mode",currDom));
					valueXmlString.append( "<pay_mode><![CDATA[" ).append( payMode ).append( "]]></pay_mode>\r\n" );
					adDescr = checkNull(genericUtility.getColumnValue("ad_descr",currDom));
					valueXmlString.append( "<ad_descr><![CDATA[" ).append( adDescr ).append( "]]></ad_descr>\r\n" );
					
					descr = "";
					empCode = genericUtility.getColumnValue("emp_code",currDom);
					sql = " select emp_fname from employee where emp_code = ? ";
					System.out.println("empCode ="+empCode);
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, empCode);
					rs = pstmt.executeQuery();
					if( rs.next() )
					{
						descr = checkNull(rs.getString("emp_fname"));
					}
					rs.close();rs = null;
					pstmt.close();pstmt = null;
					
					valueXmlString.append( "<emp_name><![CDATA[" ).append( descr ).append( "]]></emp_name>\r\n" );
				}
				else if( currentColumn.trim().equalsIgnoreCase( "ad_code" ) )
				{
					empCode = checkNull(genericUtility.getColumnValue("emp_code",currDom));
					valueXmlString.append( "<emp_code><![CDATA[" ).append( empCode ).append( "]]></emp_code>\r\n" );
					empCode = checkNull(genericUtility.getColumnValue("claim_date",currDom));
					valueXmlString.append( "<claim_date><![CDATA[" ).append( empCode ).append( "]]></claim_date>\r\n" );
					adCode = checkNull(genericUtility.getColumnValue("ad_code",currDom));
					valueXmlString.append( "<ad_code><![CDATA[" ).append( adCode ).append( "]]></ad_code>\r\n" );
					adjLoan= checkNull(genericUtility.getColumnValue("adjust_loan",currDom));
					valueXmlString.append( "<adjust_loan><![CDATA[" ).append( adjLoan ).append( "]]></adjust_loan>\r\n" );
					fullAmt = checkNull(genericUtility.getColumnValue("full_amt",currDom));
					valueXmlString.append( "<full_amt><![CDATA[" ).append( fullAmt ).append( "]]></full_amt>\r\n" );
					payrollVoucher = checkNull(genericUtility.getColumnValue("payroll_voucher",currDom));
					valueXmlString.append( "<payroll_voucher><![CDATA[" ).append( payrollVoucher ).append( "]]></payroll_voucher>\r\n" );
					payrollPrd = checkNull(genericUtility.getColumnValue("payroll_prd",currDom));
					valueXmlString.append( "<payroll_prd><![CDATA[" ).append( payrollPrd ).append( "]]></payroll_prd>\r\n" );
					bankCode = checkNull(genericUtility.getColumnValue("bank_code",currDom));
					valueXmlString.append( "<bank_code><![CDATA[" ).append( bankCode ).append( "]]></bank_code>\r\n" );
					payMode = checkNull(genericUtility.getColumnValue("pay_mode",currDom));
					valueXmlString.append( "<pay_mode><![CDATA[" ).append( payMode ).append( "]]></pay_mode>\r\n" );
					descr = checkNull(genericUtility.getColumnValue("emp_name",currDom));
					valueXmlString.append( "<emp_name><![CDATA[" ).append( descr ).append( "]]></emp_name>\r\n" );
					
					adDescr = "";
					adCode = genericUtility.getColumnValue("ad_code",currDom);
					sql = " select descr from allwdedn where ad_code = ? ";
					System.out.println("adCode ="+adCode);
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, adCode);
					rs = pstmt.executeQuery();
					if( rs.next() )
					{
						adDescr = checkNull(rs.getString("descr"));
					}
					rs.close();rs = null;
					pstmt.close();pstmt = null;
					valueXmlString.append( "<ad_descr><![CDATA[" ).append( adDescr ).append( "]]></ad_descr>\r\n" );
				}//end ad_code
				else if( currentColumn.trim().equalsIgnoreCase( "payroll_voucher" ) )
				{
					empCode = checkNull(genericUtility.getColumnValue("emp_code",currDom));
					valueXmlString.append( "<emp_code><![CDATA[" ).append( empCode ).append( "]]></emp_code>\r\n" );
					empCode = checkNull(genericUtility.getColumnValue("claim_date",currDom));
					valueXmlString.append( "<claim_date><![CDATA[" ).append( empCode ).append( "]]></claim_date>\r\n" );
					adCode = checkNull(genericUtility.getColumnValue("ad_code",currDom));
					valueXmlString.append( "<ad_code><![CDATA[" ).append( adCode ).append( "]]></ad_code>\r\n" );
					adjLoan= checkNull(genericUtility.getColumnValue("adjust_loan",currDom));
					valueXmlString.append( "<adjust_loan><![CDATA[" ).append( adjLoan ).append( "]]></adjust_loan>\r\n" );
					fullAmt = checkNull(genericUtility.getColumnValue("full_amt",currDom));
					valueXmlString.append( "<full_amt><![CDATA[" ).append( fullAmt ).append( "]]></full_amt>\r\n" );
					
					
					bankCode = checkNull(genericUtility.getColumnValue("bank_code",currDom));
					valueXmlString.append( "<bank_code><![CDATA[" ).append( bankCode ).append( "]]></bank_code>\r\n" );
					payMode = checkNull(genericUtility.getColumnValue("pay_mode",currDom));
					valueXmlString.append( "<pay_mode><![CDATA[" ).append( payMode ).append( "]]></pay_mode>\r\n" );
					descr = checkNull(genericUtility.getColumnValue("emp_name",currDom));
					valueXmlString.append( "<emp_name><![CDATA[" ).append( descr ).append( "]]></emp_name>\r\n" );
					
					adDescr = "";
					adCode = genericUtility.getColumnValue("ad_code",currDom);
					sql = " select descr from allwdedn where ad_code = ? ";
					System.out.println("adCode ="+adCode);
					pstmt = conn.prepareStatement(sql);
					pstmt.setString(1, adCode);
					rs = pstmt.executeQuery();
					if( rs.next() )
					{
						adDescr = checkNull(rs.getString("descr"));
					}
					rs.close();rs = null;
					pstmt.close();pstmt = null;
					valueXmlString.append( "<ad_descr><![CDATA[" ).append( adDescr ).append( "]]></ad_descr>\r\n" );
					
					payrollVoucher = checkNull(genericUtility.getColumnValue("payroll_voucher",currDom));
					payrollPrd = checkNull(genericUtility.getColumnValue("payroll_prd",currDom));
					
					if("V".equalsIgnoreCase(payrollVoucher))
					{
						valueXmlString.append( "<payroll_prd protect = '1'><![CDATA[" ).append( "" ).append( "]]></payroll_prd>\r\n" );
					}
					else
					{
						valueXmlString.append( "<payroll_prd protect = '0'><![CDATA[" ).append( payrollPrd ).append( "]]></payroll_prd>\r\n" );
					}
					valueXmlString.append( "<payroll_voucher><![CDATA[" ).append( payrollVoucher ).append( "]]></payroll_voucher>\r\n" );
					
				}//end payroll_voucher
				valueXmlString.append("</Detail1>\r\n");
			}//case 1 end here
			break;
			case 2:
			{
				System.out.println("case 2 IC...");
				//valueXmlString.append( "<Detail2 domID='1'>\r\n" );
				if( currentColumn.trim().equalsIgnoreCase( "itm_default" ) )							
				{	
					empCode = checkNull(genericUtility.getColumnValue("emp_code",hdrDom));
					adCode = checkNull(genericUtility.getColumnValue("ad_code",hdrDom));
					fullAmt = checkNull(genericUtility.getColumnValue("full_amt",hdrDom)) ; 
					adjLoan = checkNull(genericUtility.getColumnValue("adjust_loan",hdrDom));
					System.out.println("empCode="+empCode);
					System.out.println("adCode="+adCode);
					System.out.println("fullAmt="+fullAmt);
					System.out.println("adjLoan="+adjLoan);
					if(genericUtility.getColumnValue("claim_date", hdrDom) == null)
					{
						claimDate = null;
					}
					else
					{
						claimDate =  sdf.parse(genericUtility.getColumnValue("claim_date", hdrDom));
					}
					System.out.println("claimDate="+claimDate);
					if("Y".equalsIgnoreCase(adjLoan))
					{
						//loan tab enable
						sql = "select sum(balance_amt) 	from allowdedn_bal,loans where ref_no = loan_no "
								+" and allowdedn_bal.emp_code = ?  and ad_code between '0' and 'z' and amt_bal > 0 	and ref_type = 'L' 	and adjustable = 'Y'";
						pstmt = conn.prepareStatement( sql );
						pstmt.setString( 1, empCode );						
						rs = pstmt.executeQuery();	
						if( rs.next() )
						{
							balanceAmt = rs.getDouble(1);
						}
						rs.close();rs = null;
						pstmt.close();pstmt = null;
					}
					else
					{
						//loan tab diable
						System.out.println("loan tab diable");
					}

					sql = "select relieve_date,pay_site,cadre,grade " 
							+" from employee where emp_code = ? ";
					pstmt = conn.prepareStatement( sql );
					pstmt.setString( 1, empCode );						
					rs = pstmt.executeQuery();	
					if( rs.next() )
					{
						relieveDate = rs.getTimestamp("relieve_date");
						paySite = checkNull(rs.getString("pay_site"));
						cadre = checkNull(rs.getString("cadre"));
						grade = checkNull(rs.getString("grade"));
					}
					rs.close();rs = null;
					pstmt.close();pstmt = null;

					String envName = adCode.trim().toUpperCase()+"_CLAIMCURRPRD";
					//ls_can_claim_in_sameyear = gf_get_admenv(ls_site , ls_cadre , ls_grade , & 
					//	ls_env_name , ld_claim)
					String canClaimInsameYear = admCommon.getAdmEnv(paySite, cadre, grade, envName, relieveDate, conn);
					/*
					if ls_can_claim_in_sameyear = "ERR~t<NULLFOUND>" then
							ls_can_claim_in_sameyear = gf_getenv('999999', ls_env_name) 
							if ls_can_claim_in_sameyear = "NULLFOUND" then
								ls_errcode = 'VSENVAR1~t Variable (" + ls_env_name + ") is not defined properly'
								exit
							end if
						elseif left(ls_can_claim_in_sameyear , 4) = "ERR~t" then
							ls_errcode = mid(ls_can_claim_in_sameyear , 5) + &
								'Could not fetch environment (' + ls_env_name + ') from site_env table' 
							exit
						end if
					 */
					if("NULLFOUND".equalsIgnoreCase(canClaimInsameYear))
					{
						canClaimInsameYear = admCommon.getEnv("999999", envName, conn);
						if("NULLFOUND".equalsIgnoreCase(canClaimInsameYear))
						{
							//ls_errcode = 'VSENVAR1~t Variable (" + ls_env_name + ") is not defined properly'
						}
					}
					/*else if() elseif left(ls_can_claim_in_sameyear , 4) = "ERR~t" then
					{
						ls_errcode = mid(ls_can_claim_in_sameyear , 5) + &
								'Could not fetch environment (' + ls_env_name + ') from site_env table'
					}*/
					/*
					if("Y".equalsIgnoreCase(fullAmt))
					{
						valueXmlString.append( "<claim_amt protect ='1'><![CDATA[" ).append( checkNull( "" )).append( "]]></claim_amt>\r\n" );
					}
					else
					{
						valueXmlString.append( "<claim_amt protect ='0'><![CDATA[" ).append( checkNull( "" )).append( "]]></claim_amt>\r\n" );
					}
					*/
					/*
					ls_can_claim_in_sameyear = upper(trim(ls_can_claim_in_sameyear))
							if ls_can_claim_in_sameyear <> 'Y' then ls_can_claim_in_sameyear = 'N'
							if not isnull(ld_relieve) then ls_can_claim_in_sameyear = 'Y'
							ll_rows = dw_claim.retrieve(ls_emp, ls_ad_code, ld_claim , ls_can_claim_in_sameyear )

							if ll_rows = 1 then
								dw_claim.selectrow(1, true)
							end if
					 */
					canClaimInsameYear = canClaimInsameYear.trim().toUpperCase();
					if(!"Y".equals(canClaimInsameYear))
					{
						canClaimInsameYear = "N";
					}
					if(relieveDate != null)
					{
						canClaimInsameYear = "Y";
					}

					sql =  " SELECT allowdedn_bal.emp_code, employee.emp_fname, employee.emp_lname, allowdedn_bal.ad_code, allowdedn_bal.start_date, allowdedn_bal.end_date, "    
							+" allowdedn_bal.amount, allowdedn_bal.amt_bal, amt_bal claim_amt   FROM allowdedn_bal, employee "  
							+" WHERE ( allowdedn_bal.emp_code = employee.emp_code ) and   ( allowdedn_bal.emp_code = ? ) AND  ( allowdedn_bal.ad_code = ? ) AND "
							+" ( allowdedn_bal.amt_bal <> 0 ) AND  ( allowdedn_bal.ref_type = 'K' ) AND    ( decode(?,'Y',allowdedn_bal.start_date,allowdedn_bal.end_date)  < ? ) AND "
							+" (allowdedn_bal.exp_date is null OR   allowdedn_bal.exp_date >= ? )   ORDER BY allowdedn_bal.start_date ASC   ";
					pstmt = conn.prepareStatement( sql );
					pstmt.setString( 1, empCode );
					pstmt.setString( 2, adCode );
					pstmt.setString( 3, canClaimInsameYear );
					pstmt.setDate( 4,new java.sql.Date(claimDate.getTime()));
					pstmt.setDate( 5, new java.sql.Date(claimDate.getTime()));
					rs = pstmt.executeQuery();	
					while( rs.next() )
					{
						empCode = checkNull(rs.getString("emp_code"));
						fName = checkNull(rs.getString("emp_fname"));
						lName = checkNull(rs.getString("emp_lname"));
						adCode = checkNull(rs.getString("ad_code"));
						startDate = rs.getDate("start_date");
						endDate = rs.getDate("end_date");
						amount = rs.getDouble("amount");
						balAmount = rs.getDouble("amt_bal");
						claimAmount = rs.getDouble("claim_amt");

						//relieveDate = rs.getTimestamp("relieve_date");

						domID++;

						valueXmlString.append( "<Detail2 domID='"+ domID +"'  selected=\"N\">\r\n" );
						valueXmlString.append("<attribute selected=\"N\" updateFlag=\"A\"  status=\"N\" pkNames=\"\" />\r\n");
						valueXmlString.append( "<emp_code><![CDATA[" ).append(  empCode ).append( "]]></emp_code>\r\n" );
						valueXmlString.append( "<emp_fname><![CDATA[" ).append( fName).append( "]]></emp_fname>\r\n" );
						valueXmlString.append( "<emp_lname><![CDATA[" ).append(  lName).append( "]]></emp_lname>\r\n" );
						valueXmlString.append( "<amount><![CDATA[" ).append( amount).append( "]]></amount>\r\n" );
						valueXmlString.append( "<amt_bal><![CDATA[" ).append( balAmount).append( "]]></amt_bal>\r\n" );
						if("Y".equalsIgnoreCase(fullAmt))
						{
							valueXmlString.append( "<claim_amt protect ='1'><![CDATA[" ).append( claimAmount).append( "]]></claim_amt>\r\n" );
						}
						else
						{
							valueXmlString.append( "<claim_amt protect ='0'><![CDATA[" ).append( claimAmount).append( "]]></claim_amt>\r\n" );
						}
						valueXmlString.append( "<start_date><![CDATA[" ).append( sdf.format(startDate)).append( "]]></start_date>\r\n" );
						valueXmlString.append( "<end_date><![CDATA[" ).append( sdf.format(endDate)).append( "]]></end_date>\r\n" );
						valueXmlString.append("</Detail2>\r\n");
					}
					rs.close();rs = null;
					pstmt.close();pstmt = null;


				}

			}//case 1 end here
			break;
			case 3:
			{
				System.out.println("case 3 IC...");
				domID = 0;
				if( currentColumn.trim().equalsIgnoreCase( "itm_default" ) )							
				{
					//lpnNo = checkNull(genericUtility.getColumnValue("lpn_no", allDom, "2"));
					adjLoan = checkNull(genericUtility.getColumnValue("adjust_loan",hdrDom));
					System.out.println("adjLoan"+adjLoan);
					if("Y".equalsIgnoreCase(adjLoan))
					{
						empCode = checkNull(genericUtility.getColumnValue("emp_code",hdrDom));
						adCode = checkNull(genericUtility.getColumnValue("ad_code",hdrDom));
						if(genericUtility.getColumnValue("claim_date", hdrDom) == null)
						{
							claimDate = null;
						}
						else
						{
							claimDate =  sdf.parse(genericUtility.getColumnValue("claim_date", hdrDom));
						}
						parentNodeList = allDom.getElementsByTagName("Detail2");
						parentNodeListLength = parentNodeList.getLength();
						double claimTotalAmt = 0.0; 
						int case1 = 0;
						int case2 = 0;
						System.out.println("DETAIL2 TEST LENGTH="+parentNodeListLength);
						for(int ctr = 0; ctr < parentNodeListLength ; ctr++ )
						{
							
							parentNode = parentNodeList.item(ctr);
							Element  parentNode1 = (Element)parentNodeList.item(ctr);
							//String selected = parentNode1.getAttribute("selected");//change by Kunal on 31/08/12


							System.out.println("Claim amt="+genericUtility.getColumnValue("claim_amt", allDom, "2"));
							claimAmount = Double.parseDouble(genericUtility.getColumnValue("claim_amt", allDom, "2")== null?"0":genericUtility.getColumnValue("claim_amt", allDom, "2"));
							System.out.println("claimAmount="+claimAmount);
							claimTotalAmt = claimTotalAmt + claimAmount;


						}
						System.out.println("claimTotalAmount="+claimTotalAmt);
						balanceAmt = claimTotalAmt ;
						
						sql = "select loan_no from 	loans where emp_code = ? and "
								+" loans.balance_amt > 0  and loans.adjustable = 'Y' and status ='A' ";
						pstmt = conn.prepareStatement( sql );
						pstmt.setString( 1, empCode );						
						rs = pstmt.executeQuery();	
						if(rs == null)
						{
							valueXmlString.append( "<Detail3 domID='1' selected=\"N\">n</Detail3>" );
						}
						while( rs.next() )
						{
							loanNo = checkNull(rs.getString("loan_no"));

							sql = "select count(*)   from loan_adj 	where loan_no = ? ";
							pstmt1 = conn.prepareStatement( sql );
							pstmt1.setString( 1,loanNo );						
							rs1 = pstmt1.executeQuery();	
							if( rs1.next() )
							{
								count = rs1.getInt(1);
							}
							rs1.close();rs1 = null;
							pstmt1.close();pstmt1 = null;

							if(count > 0)
							{
								sql = " Select allowdedn_bal.ad_code, loan_adj.adj_perc, allowdedn_bal.ref_no,	allowdedn_bal.start_date, allowdedn_bal.end_date, " 
										+" loans.scheme_no, loans.loan_amt, loans.balance_amt,		loans.mon_inst,loans.interest "
										+" from allowdedn_bal,loans,loan_adj			where (allowdedn_bal.ref_no = loans.loan_no) "
										+" and (loans.loan_no = loan_adj.loan_no)		and (allowdedn_bal.ref_no = ? ) "
										+" and (loan_adj.ad_code = ? )  	and (allowdedn_bal.ad_code between '0' and 'Z') "
										+" and  ( ?  between loan_adj.eff_date and loan_adj.exp_date) 		and (allowdedn_bal.amt_bal > 0) "
										+" and (allowdedn_bal.ref_type = 'L') 	and (loans.adjustable = 'Y') 	Order by end_date ";
								pstmt1 = conn.prepareStatement( sql );
								pstmt1.setString( 1,loanNo );						
								pstmt1.setString( 2,adCode );
								pstmt1.setDate( 3,new java.sql.Date(claimDate.getTime()) );
								case1++;
							}
							else
							{
								sql = " Select ad_code, adj_perc, ref_no, start_date, end_date, "
										+" scheme_no, loan_amt, balance_amt, mon_inst, interest "
										+" from allowdedn_bal,loans Where ref_no = loan_no and allowdedn_bal.ref_no = ? and ad_code between '0' and 'z' "
										+" and amt_bal > 0 	and ref_type = 'L' 		and adjustable = 'Y' 		Order by start_date ";
								pstmt1 = conn.prepareStatement( sql );
								pstmt1.setString( 1,loanNo );						
								case2++;
							}
							rs1 = pstmt1.executeQuery();	
							/*li_xx = 0
								lc_adj = 0*/
							//double adjAmt = 0;
							//double adjAmtTemp = 0;
							while( rs1.next() )
							{
								domID++;
								loanAdCode = rs1.getString("ad_code");
								loanAdjPerc = rs1.getDouble("adj_perc");
								loanRefNo = rs1.getString("ref_no");
								startDate = rs1.getDate("start_date");
								endDate = rs1.getDate("end_date");
								schemeNo = rs1.getString("scheme_no");
								loanAmt = rs1.getDouble("loan_amt");
								loanBalAmt = rs1.getDouble("balance_amt");
								loanMonInst = rs1.getDouble("mon_inst");
								loanInterest = rs1.getDouble("interest");
								valueXmlString.append( "<Detail3 domID='"+domID+"' selected=\"Y\">\r\n" );  
								valueXmlString.append("<attribute selected=\"Y\" updateFlag=\"E\" status=\"O\" pkNames=\"\" />\r\n"); 
								valueXmlString.append( "<tran_id/>" );
								valueXmlString.append( "<ref_no><![CDATA[" ).append( loanRefNo).append( "]]></ref_no>\r\n" );
								valueXmlString.append( "<ad_code><![CDATA[" ).append( loanAdCode).append( "]]></ad_code>\r\n" );
								valueXmlString.append( "<eff_date><![CDATA[" ).append( sdf.format(startDate)).append( "]]></eff_date>\r\n" );
								valueXmlString.append( "<bal_amt><![CDATA[" ).append(  loanBalAmt).append( "]]></bal_amt>\r\n" );
								double temp;
								if(balanceAmt > 0)
								{
									temp = (claimTotalAmt * loanAdjPerc) / 100;
									if(temp > loanBalAmt)
										temp = loanBalAmt ;
									if(temp >= balanceAmt)
									{
										valueXmlString.append( "<adj_amt><![CDATA[" ).append(  balanceAmt).append( "]]></adj_amt>\r\n" );
										//adjAmtTemp = balanceAmt;
									}
									else
									{
										valueXmlString.append( "<adj_amt><![CDATA[" ).append(  temp).append( "]]></adj_amt>\r\n" );
										//adjAmtTemp = temp;
									}
									balanceAmt = balanceAmt - temp ;
								}
								else
								{
									valueXmlString.append( "<adj_amt><![CDATA[0]]></adj_amt>\r\n" );
									//adjAmtTemp = 0;
								}
								
								valueXmlString.append( "<line_no><![CDATA[" ).append(  domID ).append( "]]></line_no>\r\n" );
								
								valueXmlString.append( "<ref_type><![CDATA[" ).append( "L").append( "]]></ref_type>\r\n" );
								valueXmlString.append( "<scheme_no><![CDATA[" ).append( schemeNo).append( "]]></scheme_no>\r\n" );
								
								valueXmlString.append( "<start_date><![CDATA[" ).append( sdf.format(startDate)).append( "]]></start_date>\r\n" );
								valueXmlString.append( "<end_date><![CDATA[" ).append( sdf.format(endDate)).append( "]]></end_date>\r\n" );
								valueXmlString.append( "<loan_amt><![CDATA[" ).append(  loanAmt).append( "]]></loan_amt>\r\n" );
								valueXmlString.append( "<adj_perc><![CDATA[" ).append(  loanAdjPerc).append( "]]></adj_perc>\r\n" );
								valueXmlString.append( "<mon_inst><![CDATA[" ).append(  loanMonInst).append( "]]></mon_inst>\r\n" );
								valueXmlString.append( "<interest><![CDATA[" ).append(  loanInterest).append( "]]></interest>\r\n" );

								
								//							adjAmt = adjAmt + adjAmtTemp;
								//							lc_adj = lc_adj + dw_1.getitemdecimal(ll_row,"adj_amt")
								valueXmlString.append("</Detail3>\r\n");	

							}
							rs1.close();rs1 = null;
							pstmt1.close();pstmt1 = null;

						}
						rs.close();rs = null;
						pstmt.close();pstmt = null;

					}
					else //loan tab disable
					{
						System.out.println("loan tab diable");
						valueXmlString.append( "<Detail3 domID='1' selected=\"N\">n</Detail3>" );
					}
				}
				break;				  		
			}// case 3
			}//switch  end
		}//try block end
		catch(Exception e)
		{
			System.out.println( "Exception :PerlClaimIc :default_ItemChanged(Document,String):" + e.getMessage() + ":" );
			valueXmlString = valueXmlString.append( genericUtility.createErrorString( e ) );
			throw new ITMException(e);
		}
		finally
		{
			try
			{
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
				if (pstmt != null)
				{
					pstmt.close();
					pstmt = null;
				}
				if( conn != null && ! conn.isClosed() )
				{
					conn.close();
					conn = null;
				}
			}
			catch(Exception e)
			{
				System.out.println( "Exception :PerlClaimIc:default_ItemChanged :==>\n"+e.getMessage());
				throw new ITMException(e);
			}
		}
		valueXmlString.append( "</Root>\r\n" );	
		System.out.println( "\n****ValueXmlString :" + valueXmlString.toString() + ":********" );
		return valueXmlString.toString();
	}

	private String checkNull( String inputVal )
	{
		if ( inputVal == null )
		{
			inputVal = "";
		}
		return inputVal;
	}
	private String getAttribValue(Node detailNode, String nodeName, String attribStr)
	{
		String attribValue = "";
		try
		{
			String domStr = GenericUtility.getInstance().serializeDom(detailNode);
			Document dom = GenericUtility.getInstance().parseString(domStr);
			if( dom != null /*&& dom.getAttributes() != null*/)
			{
				Node attributeNode = dom.getElementsByTagName( nodeName ).item(0);
				attribValue = getAttribValue(attributeNode, attribStr);
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception : getAttribValue :" + e.getMessage());
		}
		return attribValue;
	}

	private String getAttribValue(Node detailNode, String attribStr)
	{
		String attribValue = "";
		try
		{
			if( detailNode != null && detailNode.getAttributes() != null)
			{
				Node attribNode = detailNode.getAttributes().getNamedItem( attribStr );
				if( attribNode != null )
				{
					attribValue = checkNull( attribNode.getNodeValue() );
				}
			}
		}
		catch(Exception e)
		{
			System.out.println("Exception : getAttribValue :" + e.getMessage());
		}
		return attribValue;
	}
}
