<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page import="com.eactive.eai.rms.common.login.SessionManager"%>
<%@ include file="/jsp/common/include/localemessage.jsp" %>
<%
	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setHeader("Expires", "0");
%>

<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<jsp:include page="/jsp/common/include/css.jsp"/>
<jsp:include page="/jsp/common/include/script.jsp"/>

<script language="javascript" >
	var url      = '<c:url value="/onl/admin/service/companyMan.json" />';
	var url_view = '<c:url value="/onl/admin/service/companyMan.view" />';
	var isDetail = false;
	
	function getDoc(frame) {
	     var doc = null;
	 
	     // IE8 cascading access check
	     try {
	         if (frame.contentWindow) {
	             doc = frame.contentWindow.document;
	         }
	     } catch(err) {
	     }
	 
	     if (doc) { // successful getting content
	         return doc;
	     }
	 
	     try { // simply checking may throw in ie8 under ssl or mismatched protocol
	         doc = frame.contentDocument ? frame.contentDocument : frame.document;
	     } catch(err) {
	         // last attempt
	         doc = frame.document;
	     }
	     return doc;
	 }  

	function fileupload(e,successcallback,errorcallback){
	    var formObj = $(this);
	    var formURL = formObj.attr("action");
	    if(window.FormData !== undefined)  // for HTML5 browsers
	    {
	        var formData = new FormData(this);
	        
	        $.ajax({
	            url: formURL,
	            type: 'POST',
	            data:  formData,
	            encType:"multipart/form-data",
	            contentType: false,
	            cache: false,
	            processData:false,
	            success: function(json, textStatus, jqXHR)
	            {
	           	 $("input[name=file]").val("");
					var data = json;
					if (!data.rows){
						alert(data.message);
						return ;
					}
					$("#grid").jqGrid('clearGridData');
					var rows = $("#grid")[0].rows;
					var index = Number($(rows[rows.length-1]).attr("id"));
					if (isNaN(index)) index=0;
					for(var i=0;i<data.rows.length;i++){
					    var rowid = index + 1 + i;
						$("#grid").jqGrid('addRow', {
				           rowID : rowid,          
				           initdata : data.rows[i],
				           position :"last",    //first, last
				           useDefValues : false,
				           useFormatter : false,
				           addRowParams : {extraparam:{}}
						});
						if(data.rows[i].RESULT=="X"){
							$("#"+rowid).find("td").css("background-color","#FFCC99");
						}
					}
					
					$("#"+$('#grid').jqGrid('getGridParam','selrow')).focus();
			  		if (typeof callback === 'function') {
						successcallback(data, textStatus, jqXHR);
					}
	            },
	            error: function(jqXHR, textStatus, errorThrown) 
	            {
	           	 $("input[name=file]").val("");
	            	if (typeof callback === 'function') {
						errorcallback(jqXHR, textStatus, errorThrown);
					}
	            }           
	        });
	        e.preventDefault();
	        if (e.unbind)
	        	e.unbind();
	   }
	   else  //for olden browsers
	    {
	    	 formObj.append($("<input type='hidden' name='serviceType' value='"+sessionStorage["serviceType"]+"' />"));
	        //generate a random id
	        var  iframeId = 'unique' + (new Date().getTime());
	        //create an empty iframe
	        var iframe = $('<iframe src="javascript:false;" id="'+iframeId+'" name="'+iframeId+'" />');
	 
	        //hide it
	        iframe.hide();
	 
	        //set form target to iframe
	        formObj.attr('target',iframeId);
	        formObj.attr('action','<c:url value="/onl/admin/service/companyMan.file" />');
	 
	        //Add iframe to body
	        iframe.appendTo('body');
	        iframe.load(function(e)
	        {
	            var doc = getDoc(iframe[0]);
	            var docRoot = doc.body ? doc.body : doc.documentElement;
	            var data = docRoot.innerHTML;
	            var k = JSON.parse(data);
	            $("#grid")[0].addJSONData(k);
	            $("input[name=file]").val("");
	            //data is returned from server.
			  	 if (typeof callback === 'function') {
					//successcallback(data);
				 }
	        });
	 
	    }
	}

	$(document).ready(function() {
		var returnUrl = getReturnUrlForReturn();
		
		var url = '<c:url value="/onl/admin/service/companyMan.json" />';
		$('#grid').jqGrid({
			datatype:"json",
			mtype : 'POST',
			colNames:[
	                  '<%=localeMessage.getString("company.compCd")%>',
	                  '<%=localeMessage.getString("company.compName")%>',
	                  '<%=localeMessage.getString("company.appCode")%>',
	                  '<%=localeMessage.getString("company.bzwkDstcd")%>',
	                  '<%=localeMessage.getString("company.conNetInstName")%>',
	                  '<%=localeMessage.getString("layoutExcelMan.processStus")%>',
	                  '<%=localeMessage.getString("layoutExcelMan.resultMsg")%>'
	                  ],
			colModel:[
					{ name : 'COMPANYCODE'   , align:'left'	,sortable:false  },
					{ name : 'COMPANYNAME' , align:'left'  },
					{ name : 'APPCODE'  , align:'left'  },
					{ name : 'BZWKDSTCODE' , align:'left'  },
					{ name : 'CONNETINSTICODENAME'  , align:'left'  },
					{ name : 'RESULT'  , align:'left'  },
					{ name : 'MESSAGE'  , align:'left'  }
					],
	        jsonReader: {
	             repeatitems:false
	        },	          
		    autoheight: true,
		    height: 300,
			autowidth: true,
			viewrecords: true,
			gridComplete:function (d){
				var colModel = $(this).getGridParam("colModel");
				for(var i = 0 ; i< colModel.length; i++){
					$(this).setColProp(colModel[i].name, {sortable : false});	//그리드 헤더 화살표 삭제(정렬X)		
				}
			
			},				
			ondblClickRow: function(rowId) {
	        },		
			onSelectRow: function(rowId) {
				var data = $(this).getRowData(rowId); 
				$("#ajaxForm input[type!=radio],#ajaxForm select,#ajaxForm textarea").each(function(){
					var name = $(this).attr("name");
					var tag  = $(this).prop("tagName").toLowerCase();
					$(tag+"[name="+name+"]").val(data[name.toUpperCase()]);
				});
	       }
		});
		
		resizeJqGridWidth('grid','content_middle','1000');	
	    $("#multiform").on('submit',fileupload);
		$('#btn_upload').click(function(){
			$("#grid").jqGrid('clearGridData');
			if(window.FormData !== undefined) {
				$("input[name=file]").click();
			}else{
				if ($("input[name=file]").val()==""){
					return;
				}
		        $("#multiform").submit();
			}
	        
		});
		if(window.FormData !== undefined) {
			$("input[name=file]").change(function(ev) {
				var filename = $(this).val().split('\\').pop();
				if (filename == ""){
					return;
				}else{
					$("#multiform").submit();
				}
				
			});
		}
		if(window.FormData !== undefined) {
			$("input[name=file]").hide();
		}else{
			$("input[name=file]").show();
		}
		
		$("#btn_previous").click(function(){
			goNav(returnUrl);//LIST로 이동
		});
		$("#btn_download").click(function(){
			var args = new Object();
			url_view +="?cmd=POPUP2";
		    showModal(url_view,args,400,250);
		});
	});
 
</script>
</head>
	<body>
		<div class="right_box">
			<div class="content_top">
				<ul class="path">
					<li><a href="#">${rmsMenuPath}</a></li>					
				</ul>					
			</div><!-- end content_top -->
			<div class="content_middle" id="content_middle">
				<form id="multiform" method="POST" enctype="multipart/form-data" action="<c:url value="/onl/admin/service/companyMan.file"/>">
					<div class="search_wrap">
						<div style="display:inline-block;">
							<input type="file" name="file" style="display:inline-block"/>
							<input type="text" name="cmd" style="display:none" value="UPLOAD"/>
						</div>
					<img src="<c:url value="/img/btn_upload.png"/>" alt="" id="btn_upload" level="W" />
					<img src="<c:url value="/img/btn_previous.png"/>" alt="" id="btn_previous" level="R" status="DETAIL,NEW"/>
					</div>
				</form>
				<div class="title"><%=localeMessage.getString("company.uploadTitle")%> </div>				
				<table class="table_row" cellspacing="0" style="margin-top:15px;">
					<tr>
						<th style="width:20%;"><%=localeMessage.getString("company.excelDown")%> </th>
						<td style="width:80%;"><img src="<c:url value="/img/btn_download.png"/>" alt="" id="btn_download" level="W" /></td>
					</tr>
				</table>
				<table id="grid" ></table>
				<div id="pager"></div>
				
				<form id="ajaxForm">
					<table class="table_row" cellspacing="0" style="margin-top:15px;">
						<tr>
							<th style="width:20%;"><%=localeMessage.getString("company.compCd")%></th>
							<td style="width:80%;"><input type="text" name="COMPANYCODE"/></td>
						</tr>
						<tr>
							<th><%=localeMessage.getString("layoutExcelMan.processStus")%></th>
							<td ><input type="text" name="RESULT" /></td>
						</tr>
						<tr height="50px">
							<th><%=localeMessage.getString("layoutExcelMan.resultMsg")%></th>
							<td><textarea  name="MESSAGE" style="width:100%; height:200px;"></textarea></td>
						</tr>
					</table>
				</form>	
				
			</div><!-- end content_middle -->
		</div><!-- end right_box -->	
	</body>
</html>

