package itn.let.mjo.payva.web;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import egovframework.rte.fdl.idgnr.EgovIdGnrService;
import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper;
import itn.com.cmm.EgovMessageSource;
import itn.com.cmm.LoginVO;
import itn.com.cmm.service.EgovFileMngService;
import itn.com.cmm.service.EgovFileMngUtil;
import itn.com.cmm.util.StringUtil;
import itn.com.utl.fcc.service.EgovStringUtil;
import itn.let.cop.bbs.service.EgovBBSAttributeManageService;
import itn.let.mjo.addragency.service.AddrAgencyService;
import itn.let.mjo.msg.service.MjonMsgService;
import itn.let.mjo.msg.service.MjonMsgVO;
import itn.let.mjo.msgdata.service.MjonMsgDataService;
import itn.let.mjo.msgdata.service.MjonMsgReturnVO;
import itn.let.mjo.pay.service.MjonPayService;
import itn.let.mjo.pay.service.MjonPayVO;
import itn.let.mjo.pay.service.MjonVaMsgLogVO;
import itn.let.mjo.payva.service.VacsVactService;
import itn.let.mjo.payva.service.VacsVactVO;
import itn.let.mjo.temp.service.TempVO;
import itn.let.sym.site.service.JoinSettingVO;
import itn.let.uss.umt.service.EgovUserManageService;
import itn.let.uss.umt.service.MberManageVO;
import itn.let.utl.user.service.CheckBoardUtil;
import itn.let.utl.user.service.CheckFileUtil;
//import itn.let.utl.user.service.CheckLoginUtil;il;il;il;il;il;il;
import itn.let.utl.user.service.CheckLoginUtil;

@Controller
public class VacsController {
	
/*
	@Resource(name = "MjonMsgSentService")
    private MjonMsgSentService mjonMsgSentService;

	@Resource(name = "EgovCmmUseService")
	private EgovCmmUseService cmmUseService;
	
	*/

    @Resource(name="addrAgencyService")
    private AddrAgencyService addrAgencyService;
    
    @Resource(name = "egovMjonMsgGroupIdGnrService")
    private EgovIdGnrService idgenMjonMsgGroupId;
    
	@Resource(name = "egovMjonCashIdGnrService")
    private EgovIdGnrService idgenMjonCashId;
    
    @Resource(name = "checkBoardUtil")
	private CheckBoardUtil checkBoardUtil;

	@Resource(name = "checkFileUtil")
	private CheckFileUtil checkFileUtil;
	
	@Resource(name = "checkLoginUtil")
	private CheckLoginUtil checkLoginUtil;
	
	@Resource(name = "EgovBBSAttributeManageService")
	private EgovBBSAttributeManageService bbsAttrbService;
	
    @Resource(name="egovMessageSource")
    EgovMessageSource egovMessageSource;
    
    @Resource(name="EgovFileMngUtil")
	private EgovFileMngUtil egovFileMngUtil;

    @Resource(name="EgovFileMngService")
    private EgovFileMngService fileMngService;

    //전용계좌 서비스
    @Resource(name="vacsVactService")
    private VacsVactService vacsVactService;
    
    //결제 서비스
    @Resource(name="mjonPayService")
    private MjonPayService mjonPayService;
    
    //문자발송 서비스
	@Resource(name = "MjonMsgDataService")
    private MjonMsgDataService mjonMsgDataService;
	
	@Resource(name = "mjonMsgService")
    private MjonMsgService mjonMsgService;
    
	/** userManageService */
	@Resource(name = "userManageService")
	private EgovUserManageService userManageService;
	
    
    private static final Logger logger = LoggerFactory.getLogger(VacsController.class);
 
    /////////////////////////////////////////////////////////////////////////////////////////
    //
    //
    //	USER
    //
    //
    //	1.전용계좌 ajax 페이지

    /**
     * 
     * 전용 계좌 정보 가져오기 
     * 1.신규 계좌 정보
     * 2.보유 하고 있는 전용계좌
     *  
     * @param addrVO
     * @param model
     * @return
     * @throws Exception
     */
    
    @RequestMapping(value= {
    					"/web/member/pay/selectPayVAViewAjax.do"
    					})
    public String selectVAListAjax(
    		HttpServletRequest request
    		, @ModelAttribute("searchVO") TempVO tempVO
    		, ModelMap model
    		, RedirectAttributes redirectAttributes
    		) throws Exception {

    	logger.debug("VacsController-selectVAListAjax");
    	
    	//사용자 로그인 여부 체크
    	String isLogin = checkLoginUtil.isLoginCheck4JsonPage(redirectAttributes);
    	if (!"Y".equals(isLogin)) return "/web/member/pay/PayView";
    	

    	//로그인 정보 획득
    	LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
    	   	
    	 
		//대상 리스트 가져오기    	    	
    	VacsVactVO vacsVactVO = new VacsVactVO();
    			
    	vacsVactVO.setMberId(loginVO.getId());
    	List<?> bankList = vacsVactService.selectBankAcctList(vacsVactVO);		//할당 가능한 계좌 수량  리스트 받아오기
    	List<?> myBankList = vacsVactService.selectMyBankAcctList(vacsVactVO);	//내가 할당받은 전용계좌 리스트 받아오기
    	
    	MjonVaMsgLogVO vaMsgLogVO = new MjonVaMsgLogVO();
    	vaMsgLogVO.setMberId(loginVO.getId());
    	
    	Date now = new Date();
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String date = sdf.format(now);
		vaMsgLogVO.setSendDate(date);
		
    	MjonVaMsgLogVO resultMsgInfo = mjonPayService.selectMyAcctSendCnt(vaMsgLogVO);
    	
    	//대상 리스트, 페이징 정보 전달
    	model.addAttribute("resultList", bankList);
    	model.addAttribute("resultMyList", myBankList);
    	model.addAttribute("resultMsgInfo", resultMsgInfo);
    	
    	return "/web/pay/PayVAViewAjax";
    	
    }
    
    /**
   	 * 전용계좌 할당해주기
   	 * @param commandMap 파라메터전달용 commandMap
   	 * @param model 화면모델
   	 * @return uss/umt/EgovIdDplctCnfirm
   	 * @throws Exception
   	 */
   	@RequestMapping(value = "/web/member/pay/updateVacsAccountUsrIdAjax.do")
   	public ModelAndView updateVacsAccountUsrIdAjax(@RequestParam Map<String, Object> commandMap, HttpServletRequest request) throws Exception {

       	ModelAndView modelAndView = new ModelAndView();
       	modelAndView.setViewName("jsonView");
       	
    	//로그인 정보 획득
    	LoginVO loginVO = (LoginVO) EgovUserDetailsHelper.getAuthenticatedUser();
       	
    	try {
    		
    		//대상 리스트 가져오기    
    		VacsVactVO vacsVactVO = new VacsVactVO();
    		//사용자 아이디 셋팅
    		vacsVactVO.setMberId(loginVO.getId());
    		
    		/**
    		 * 회원 정지된 상태이면 문자 발송이 안되도록 처리함
    		 * 현재 로그인 세션도 만료 처리함
    		 * */
    		boolean mberSttus = userManageService.selectUserStatusInfo(loginVO.getId());
    		
    		if(!mberSttus) {
    			
    			modelAndView.addObject("message", "현재 고객님께서는 문자온 서비스 이용이 정지된 상태로 전용계좌를 발급하실 수 없습니다. 이용정지 해제를 원하시면 고객센터로 연락주시기 바랍니다.");
    			modelAndView.addObject("result", "statusFail");
    			
    			// 세션 로그아웃
    			request.getSession().invalidate();
    			
    			return modelAndView;
    			
    		}
    		
    		
        	List<?> bankList = vacsVactService.selectBankAcctList(vacsVactVO);		//할당 가능한 계좌 수량  리스트 받아오기
        	List<?> myBankList = vacsVactService.selectMyBankAcctList(vacsVactVO);	//내가 할당받은 전용계좌 리스트 받아오기

       		int myBankCnt = myBankList.size();
       		
       		if(myBankCnt > 0) {	//할당받은 전용계좌가 1개 이상이면 할당 불가 처리
       			
       			modelAndView.addObject("message", "전용계좌를 보유하고 있어 추가 할 수 없습니다.");
    			modelAndView.addObject("result", "fail");
       			
       		}else {
       			
       			//은행코드 셋팅
       			vacsVactVO.setBankCd(commandMap.get("bankCd").toString());
       			
       			//계좌 할당일자 생성
       			Date now = new Date();
       			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
       			String openDate = sdf.format(now);
       			vacsVactVO.setOpenIl(openDate);
       			
       			//계좌 상태 셋팅  0: 미할당, 1:할당
       			vacsVactVO.setAcctSt("1");
       			
       			String cmfNm = "문자온_" + loginVO.getName(); 		//예금주명 셋팅 - 문자온_예금주명 으로 입력하되 최대 20바이트를 넘을 수 없다.
       	    	//String cmfNm = "itn_예금주명 으로 입력하되 최대 20바이트를 넘을 수 없다."; 		//예금주명 셋팅 - itn_예금주명 으로 입력하되 최대 20바이트를 넘을 수 없다.
       			String charset = "euc-kr"; 						//문자 바이트 계산에 필요한 캐릭터 셋 : 한글 2Byte로 계산
       			int bytes = cmfNm.getBytes(charset).length;
       			
       			if(bytes > 20) {
       				
       				cmfNm = cmfNm.substring(0,10);
       				
       			}
       			
       			vacsVactVO.setCmfNm(cmfNm);
       			
       			//할당 된 계좌 return 받기로 변경
       			String myBankAccount = vacsVactService.updateVacsAccountUsrId(vacsVactVO);	//내가 할당받은 전용계좌 리스트 받아오기
       			
       			if(StringUtil.isNotEmpty(myBankAccount)){
       				modelAndView.addObject("result", "success");
       				
       				
       				vacsVactService.insertVacsHistory(vacsVactVO);
       				
       			}
       			else {
       				
       				modelAndView.addObject("message", "해당 은행은 전용계좌를 받을 수 없습니다.");
       				modelAndView.addObject("result", "fail");
       				
       			}
       			
       		}
			
		} catch (Exception e) {
			throw new Exception("전용계좌 신규 신청 오류 ::: " + e);
		}
    	
		

    		return modelAndView;
   	}
   	
    /**
   	 * 전용계좌 계좌번호 문자 전송해주기
   	 * @param commandMap 파라메터전달용 commandMap
   	 * @param model 화면모델
   	 * @return uss/umt/EgovIdDplctCnfirm
   	 * @throws Exception
   	 */
   	@RequestMapping(value = "/web/member/pay/insertVacsAccountSendMsgLogAjax.do")
   	public ModelAndView insertVacsAccountSendMsgLogAjax(MjonVaMsgLogVO vaMsgLogVO) throws Exception {

       	ModelAndView modelAndView = new ModelAndView();
       	modelAndView.setViewName("jsonView");
       	
    	//로그인 정보 획득
       	LoginVO	loginVO = (LoginVO)EgovUserDetailsHelper.getAuthenticatedUser();
    	String	userId = loginVO == null ? "" : EgovStringUtil.isNullToString(loginVO.getId());
       	
    	String resultSts = "0";
		String resultBlockSts = "0";
    	
    	if(userId.equals("")) {
    		
    		modelAndView.addObject("message", "로그인이 필요합니다.");
			modelAndView.addObject("result", "LoginFail");
			return modelAndView;	
    		
    	}
    	
    	try {
    		
    		String accMsg = vaMsgLogVO.getAccMsg();
    		String[] tempMsg = accMsg.split("/");
    		String msg = "회원님의 계좌번호는 {{0}} 입니다.";
    		String replaceMsg = "";
    		int i = 0;
    		for(String temp : tempMsg) {
    			
    			String[] arrStr = temp.split("_");	//은행코드_은행명_전용계좌번호 형태의 텍스트로 넘어온다.
    			
    			if(arrStr.length < 1) {
    				modelAndView.addObject("message", "올바른 계좌정보가 아닙니다.");
    				modelAndView.addObject("result", "fail");
    				return modelAndView;
    			}else {
    				
    				if(i == 0) { //은행명 + 전용계좌번호 문장 만들기
    					
    					replaceMsg = "[" + arrStr[1] + "] " + arrStr[2];
    					
    				}else {
    					
    					replaceMsg = replaceMsg + ", " +"[" + arrStr[1] + "] " + arrStr[2];
    					
    				}
    				
    				vaMsgLogVO.setBankCd(arrStr[0]); //은행 코드번호
    				vaMsgLogVO.setAcctNo(arrStr[2]); //전용계좌번호
    				
    			}
    			
    			i++; 
    			
    		}
    		
    		//전송 문자 내용 만들기
    		String repMsg = msg.replace("{{0}}", replaceMsg);
    		vaMsgLogVO.setMsg(repMsg);
    		vaMsgLogVO.setMberId(userId);
    		
    		MjonMsgVO mjonMsgVO = new MjonMsgVO();

    		//문자 종류 체크
    		int bytes = repMsg.getBytes("euc-kr").length;
    		if(bytes < 90) { //단문 
    			mjonMsgVO.setMsgType("4");
    		}else {	//장문
    			mjonMsgVO.setMsgType("6");
    		}
    		
    		//회원 발신번호 받아오기
    		List<String> resultSendPhonList = mjonMsgDataService.selectSendPhonNumList(userId);
    		
    		//회원 발신번호 등록이 되어있지 않으면 발송 중지처리.
    		if(resultSendPhonList.size() == 0 || resultSendPhonList == null) {
    			
    			modelAndView.addObject("message", "문자 발송에 필요한 발신번호가 등록되어 있지 않습니다. 마이페이지에서 발신번호를 등록해 주세요.");
    			modelAndView.addObject("result", "fail");
    			
    			return modelAndView;
    			
    		}
    		
    		String callFrom = resultSendPhonList.get(0);	//임의로 리스트 첫번째 발신번호로 지정
    		String callTo = vaMsgLogVO.getCallTo();
    		mjonMsgVO.setCallFrom(callFrom);				//발신자번호
    		mjonMsgVO.setSmsTxt(repMsg);					//전송 메세지
    		//mjonMsgVO.setCallTo(vaMsgLogVO.getCallTo());	//수신자 번호
    		mjonMsgVO.setUserId(userId);					//회원아이디 
    		mjonMsgVO.setReserveYn("N"); 					//즉시전송
    		mjonMsgVO.setFileCnt("0"); 						//첨부이미지 갯수
    		
    		//수신번호가 배열로 되어있어서 배열에 담아준다.
    		String[] phone = new String[1];
    		for(int j=0; j< 1; j++) {
    			
    			phone[j] = callTo;
    			
    		}
    		
    		mjonMsgVO.setCallToList(phone);
    		int callToListCnt = mjonMsgVO.getCallToList().length;
    		mjonMsgVO.setTotalCallCnt(callToListCnt);
    		
    		//전송사 선택하기
        	/*MjonMsgVO pramVO = new MjonMsgVO();
        	List<MjonMsgVO> sendRateList = mjonMsgService.selectTodayAgentSendCntList(pramVO); // 전송사 전송 배분률 및 현재 전송건수 조회
        	for (MjonMsgVO tmpVO : sendRateList) {
        		float cnt = Float.parseFloat(tmpVO.getMsgGroupCnt());
        		float totCnt = tmpVO.getTotCnt();
        		tmpVO.setSendRateInfo(Float.parseFloat(tmpVO.getSendRate()) - (cnt / totCnt * 100)); // 배분률 - 현재전송 비율
        	}
        	
        	String sendAgent = sendRateList.get(0).getAgentCode();
        	float maxRate = sendRateList.get(0).getSendRateInfo();
        	for (MjonMsgVO tmpVO : sendRateList) { // 배분률 대비 현재전송 비율이 가장 적은거 찾기
        		if (maxRate < tmpVO.getSendRateInfo()) {
        			maxRate = tmpVO.getSendRateInfo();
        			sendAgent = tmpVO.getAgentCode();
        		}
        	}*/
    		
        	mjonMsgVO.setAgentCode("04"); //전송사 선택
        	//mjonMsgVO.setAgentCode(sendAgent); //전송사 선택
        	
        	if(mjonMsgVO.getAgentCode().equals("03")) {	//아이엠오 전송사 문자 타입 설정해 주기
        		
        		// 단순 장문 문자는 neoType : 2, 그림 포함 : 4
        		if(mjonMsgVO.getFileCnt().equals("0")) { // 단순 장문 문자
        			
        			mjonMsgVO.setNeoType("2");
        			
        		}else{ // 그림포함 문자인경우
        			
        			mjonMsgVO.setNeoType("4");
        			
        		}
        		
        	}
        	
        	//현재 고객의 보유 캐시가 문자 발송이 가능한 금액인지 체크
        	String userMoney = mjonMsgDataService.selectBeforeCashData(mjonMsgVO);
         	String userPoint = mjonMsgDataService.selectBeforePointData(mjonMsgVO);
        	mjonMsgVO.setBefPoint(userPoint); //현재 보유 포인트 정보 저장
//        	mjonMsgVO.setBefCash(userMoney); //현재 보유 포인트 정보 저장
        	
        	//문자발송 금액 계산하기
    		//문자 전송 개인 단가 불러오기
    		//1.시스템 기본 단가 정보 불러오기
    		JoinSettingVO sysJoinSetVO = mjonMsgDataService.selectJoinSettingInfo();
    		
    		//2.사용자 개인 단가 정보 불러오기
    		MberManageVO mberManageVO = new MberManageVO(); 
    		
    		if(!userId.equals("")) {
    			
    			mberManageVO = mjonMsgDataService.selectMberManageInfo(userId);
    			
    		}
    		
    		//3.사용자 개인단가 정보가 0이 아니면 개인단가 사용, 없으면 시스템 기본 단가 사용
    		Float shortPrice = mberManageVO.getShortPrice();
    		Float longPrice = mberManageVO.getLongPrice();

    		if(shortPrice == 0 || longPrice == 0) {
    			
    			shortPrice = sysJoinSetVO.getShortPrice();
    			longPrice = sysJoinSetVO.getLongPrice();
    			
    		}
        	
    		if(mjonMsgVO.getMsgType().equals("4")) {	//단문 금액 
				mjonMsgVO.setTotPrice(shortPrice.toString());	//총금액
				mjonMsgVO.setEachPrice(shortPrice.toString());	//한건 금액
			}else {	//장문 금액
				mjonMsgVO.setTotPrice(longPrice.toString());
				mjonMsgVO.setEachPrice(longPrice.toString());
			}
    		
        	String totPrice = mjonMsgVO.getTotPrice();
        	//String eachPrice = mjonMsgVO.getEachPrice();
        	
        	BigDecimal befCash = new BigDecimal(userMoney).setScale(2, RoundingMode.HALF_EVEN);
        	BigDecimal totMsgPrice = new BigDecimal(totPrice).setScale(2, RoundingMode.HALF_EVEN);
        	
    		
    		
        	//현재 보유 금액이 발송 문자 총 금액보다 클 경우만 문자 발송
        	//BigDecimal 비교 연산
        	// befCash(현재 보유금액) 값이 totMsgPrice(문자전송 금액) 보다 많으면 문자 전송	
        	if(befCash.compareTo(totMsgPrice) == 1) { // -1 : befCash > totMsgPrice, 0 : befCash = totMsgPrice, 1 : befCash < totMsgPrice,
        		
        		//문자 발송 처리
            	//resultSts = mjonMsgDataService.insertMsgDataInfo(mjonMsgVO);
        		
        		mjonMsgVO.setBefCash(befCash.toString());
	    		
	    		//문자 전송 그룹아이디 생성
	    		mjonMsgVO.setMsgGroupId(idgenMjonMsgGroupId.getNextStringId());
        		
        		MjonMsgReturnVO returnVO = mjonMsgDataService.insertMsgDataInfo(mjonMsgVO); 
        		
        		resultSts = returnVO.getSendMsgCnt();
        		resultBlockSts = returnVO.getSendMsgBlockCnt();
        		
        		//문자 발송 캐시 차감 해주기
	    		MjonPayVO mjonPayVO = new MjonPayVO(); 
        		
        		//문자 발송 테이블에 입력 데이터가 있는 경우 그룹 테이블에도 입력 해 준다.
	    		/*if(Integer.parseInt(resultSts) > 0 && Integer.parseInt(mjonMsgVO.getMsgGroupCnt()) > 0) {
	    			
	    			// 문자 전송 그룹 테이블에 정보 입력
	    			mjonMsgService.insertGroupMsgData(mjonMsgVO);
	    			
	    		}*/
	    		
	    		//1건 이상 발송이 있는 경우만 캐쉬를 차감 시킨다.
	    		/*if(Integer.parseInt(resultSts) > 0) {
	    			mjonPayVO.setCashId(idgenMjonCashId.getNextStringId());
	    			mjonPayVO.setUserId(mjonMsgVO.getUserId());
	    			mjonPayVO.setCash(-Float.parseFloat(mjonMsgVO.getTotPrice()));
	    			mjonPayVO.setFrstRegisterId(mjonMsgVO.getUserId());
	    			mjonPayVO.setMemo("SMS 문자 " + resultSts + "건 발송");
	    			mjonPayVO.setMsgGroupId(mjonMsgVO.getMsgGroupId());
	    			
	    			mjonPayService.insertCash(mjonPayVO); //캐시차감 
	    			mjonPayService.updateMemberCash(mjonPayVO); //회원정보 업데이트
	    		}*/
        		
        	}else {
        		
        		modelAndView.addObject("message", "문자 발송에 필요한 보유 잔액이 부족 합니다.");
    			modelAndView.addObject("result", "fail");
    			
    			return modelAndView;
        		
        	}
        	
    		//문자 발송하기

    		//발송일자 생성 - 하루에 세번만 보낼수 있어서 날짜를 입력하는 것임
    		Date now = new Date();
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    		String date = sdf.format(now);
    		vaMsgLogVO.setSendDate(date);
    		
    		//전송문자 로그 입력하기
    		int logCnt = mjonPayService.insertVaMsgLogInfo(vaMsgLogVO);
    		
    		if(logCnt > 0 && Integer.parseInt(resultSts) > 0) {
    			
   				modelAndView.addObject("result", "success");
    			
    		}else {
    			
    			modelAndView.addObject("message", "문자 발송에 실패 하였습니다.");
   				modelAndView.addObject("result", "fail");
    			
    		}
    		
		} catch (Exception e) {
			System.out.println(" insertVacsAccountSendMsgLogAjax Controller 전용계좌  문자 발송 오류  ::: " + e);
			throw new Exception("전용계좌  문자 발송 오류 ::: " + e);
			
		}

    		return modelAndView;
   	}
    
    
	/*
	 * 1.url 이동
	 * 2.ajax
	 * 	2-1.page call return htem
	 *  2-2.action call return success or fail
	 *  
	 * 1.
	 * 	a call b redirect c
	 * 
	 * 2-1.ajax call
	 * 	blank html
	 * 
	 * 2-2.
	 *  return fail 
	 *  
	 * */
    /////////////////////////////////////////////////////////////////////////////////////////
    //
    //
    //	ADMIN
    //
    //
    
    
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //
    //
    //	private function
    //
    //
    
    
	/**
	 * XSS 방지 처리.
	 *
	 * @param data
	 * @return
	 */
	protected String unscript(String data) {
		if (data == null || data.trim().equals("")) {
			return "";
		}

		String ret = data;

		ret = ret.replaceAll("<(S|s)(C|c)(R|r)(I|i)(P|p)(T|t)", "&lt;script");
		ret = ret.replaceAll("</(S|s)(C|c)(R|r)(I|i)(P|p)(T|t)", "&lt;/script");

		ret = ret.replaceAll("<(O|o)(B|b)(J|j)(E|e)(C|c)(T|t)", "&lt;object");
		ret = ret.replaceAll("</(O|o)(B|b)(J|j)(E|e)(C|c)(T|t)", "&lt;/object");

		ret = ret.replaceAll("<(A|a)(P|p)(P|p)(L|l)(E|e)(T|t)", "&lt;applet");
		ret = ret.replaceAll("</(A|a)(P|p)(P|p)(L|l)(E|e)(T|t)", "&lt;/applet");

		ret = ret.replaceAll("<(E|e)(M|m)(B|b)(E|e)(D|d)", "&lt;embed");
		ret = ret.replaceAll("</(E|e)(M|m)(B|b)(E|e)(D|d)", "&lt;embed");

		ret = ret.replaceAll("<(F|f)(O|o)(R|r)(M|m)", "&lt;form");
		ret = ret.replaceAll("</(F|f)(O|o)(R|r)(M|m)", "&lt;form");

		//ret = ret.replaceAll("<", "&lt;");
		ret = ret.replaceAll("alert", "");
		//ret = ret.replaceAll("iframe", "");
		
		return ret;
	}
}
