<html>
<head>
<style type="text/css">
body{
	font:12px/1.231 arial,helvetica,clean,sans-serif;
	background-color:#F8FBFC;
	color:#333333;
}
table.dataTable {
	font-family:verdana,arial,helvetica,sans-serif;
	font-size:11px;
	border-collapse: collapse;
	background-color: white;
}
table.dataTable, table.dataTable th, table.dataTable td {
	border: 1px #CDCED0 solid;
}
table.dataTable td {
	line-height:10px;
}
.divStyle{
	float:right;
	height:100px;
	position:relative;
	right:300px;
	top:50px;
	width:300px;
}

.buttonStyle{
	background-color:#dbc7db;
	-webkit-border-radius: 20px;
	-moz-border-radius: 20px;
	border-radius: 20px;
	-webkit-box-shadow: 10px 10px 10px #d1cfe8;
	-moz-box-shadow: 10px 10px 10px #d1cfe8;
	box-shadow: 10px 10px 10px #d1cfe8;
	cursor:pointer;
}
</style>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<!-- script type="text/javascript" src="http://code.google.com/apis/gears/gears_init.js"></script -->
<script src="${common_static_path}/common/scripts/jquery.ajaxqueue.js"></script>
<script>
var size = 10;
var requestPool;
var req_contents = {};
/*
if (!window.google || !google.gears)
{
	location.href = "http://gears.google.com/?action=install&name=OrangeScape Batch Import" +
		"&icon_src=http://www.google.com/a/orangescape.com/images/logo.gif"+
		"&message=Install Google Gears for OrangeScape batch import to work&return="+location.href;
}
*/
function showAdvOptions()
{
	document.getElementById("advancedOptions").style.display = 'block';
	document.getElementById("showOptions").style.display = 'none';
}

function hideAdvOptions()
{
	document.getElementById("advancedOptions").style.display = 'none';
	document.getElementById("showOptions").style.display = 'block';
}
function onlyNumbers(evt)
{
	var charCode = (evt.which) ? evt.which : evt.keyCod
	if (charCode > 31 && (charCode < 48 || charCode > 57))
		return false;
	return true;

}

function browse()
{
	var size = document.getElementById("no_of_rec").value;
	if (! size)
		size = 10;
	var no_of_batch = document.getElementById("no_of_batch").value;
	if (! no_of_batch)
		no_of_batch = 2;

	requestPool = $.manageAjax.create('queue', {queue: true, preventDoubbleRequests:true, maxRequests:no_of_batch});
	var desktop = google.gears.factory.create('beta.desktop');
	desktop.openFiles(function(files) {
      jQuery("#progress").html("");
      var progstr = "<table>";
      for (var i = 0; i < files.length; i++)
      {
        var f = files[i];
        var fname = f.name.split('.')[0];
      	progstr += "<tr><td>" + fname + "</td>";
      	progstr += "<td id='" + fname + "'></td></tr>";
      }
      progstr += "</table>";
      jQuery("#progress").html(progstr);
      for (var i = 0; i < files.length; i++) {
        var f = files[i];
		var fname  = f.name.split('.')[0];
        var content = new Array();
        var bytecount = 0;
        while(bytecount < f.blob.length)
        {
        	var nextcount = bytecount+1024;
        	var actualcount = nextcount < f.blob.length ? 1024 : (f.blob.length-bytecount);
        	var blockbytes = f.blob.getBytes(bytecount, actualcount);
        	content = content.concat(blockbytes);
        	bytecount = nextcount;
        }
        var lines = new Array();
        var linestr = "";
        var lineCount = 0;
        var prevChar = 0;
        for(var c = 0; c < content.length; c++)
        {
        	var num = content[c];
        	linestr += String.fromCharCode(num);
        	if((num == 13 || num==10) && prevChar!=13)
        	{
    			lines[lineCount] = linestr;
        		linestr = "";
        		lineCount++;
        	}
            prevChar = num
        }
        var reqno = 0;
        var contentstr = lines[0];
        for(var l = 1; l < lines.length; l++)
        {
        	var lin = lines[l];
        	contentstr += lin;
        	if(l % size == 0)
        	{
        		upload(reqno, fname, contentstr, 1);
        		contentstr = lines[0];
        		reqno++;
        	}
        }
		if (contentstr != lines[0]){
			upload(reqno, fname, contentstr, 1);
		}
    }

	},{ filter: ['text/plain', '.csv'] });
}

function upload(reqno, metadata, content, attempt)
{
	var requestid =  metadata+"-"+reqno;
    /* if (console){
        console.info(new Date()+': '+reqno+' - '+metadata+' - '+requestid+' - '+attempt)
    } */
    req_contents[requestid] = content
    if(attempt==1)
        jQuery("#"+metadata).append("<img id='" + requestid + "' src='/runtime/images/arrowup.png'/>");
	content += String.fromCharCode(10);
	 requestPool.add({
      url: "/${applicationId}/1/flatcsvimport",
      global: false,
      type: "POST",
      data: {requestid: requestid, update: "true", sheetMetadataName: metadata, attempt:attempt, csvfile: content},
      dataType: "html",
      success: function(msg){
      	var startstr = "requestid=";
      	var start = this.data.indexOf(startstr) + startstr.length;
        var reqid = this.data.substring(start, this.data.indexOf("&update"));
        jQuery("#"+reqid).attr("src", "/runtime/images/arrowdown.png");
        /*if(console){
            console.info(new Date()+': '+reqid+' finished')
        } */
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
      	var startstr = "requestid=";
      	var start = this.data.indexOf(startstr) + startstr.length;
        var reqid = this.data.substring(start, this.data.indexOf("&update"));

        var metadata = this.data.substring(this.data.indexOf('sheetMetadataName=') + 18, this.data.indexOf("&attempt="));
        var reqno = parseInt(reqid.substring(reqid.indexOf(metadata)+metadata.length+1))
        var attempt = parseInt(this.data.substring(this.data.indexOf('&attempt=') + 9, this.data.indexOf("&csvfile=")));
        var content = req_contents[reqid]
        if(attempt < 25){
            if(console){
                console.warn('Re-request '+reqno)
            }
            upload(reqno, metadata, decodeURI(content), attempt+1);
        }else{
            if(console){
                console.info(new Date()+': reqid '+reqid+' failed.')
            }
            alert("Error while uploading data : "+this.data);
             alert("Response : "+XMLHttpRequest.responseText
             +"\n Status : "+textStatus
             +"\n Description : "+errorThrown);
        }
	  }
   });

}

</script>

</head>
<body>

<div id="advancedOptions" colspan="2" class="divStyle" style="display:none;">
	<table  class="dataTable">
		<tr>
			<td>Enter Number of Records:</td><td><input	type="text" id="no_of_rec" value = "" maxlength = "3" size = "3" onkeypress="return onlyNumbers(event);"></td>
		</tr>
		<tr>
			<td>Enter Number of Threads:</td><td><input	type="text" id="no_of_batch" value = "" maxlength = "3" size = "3" onkeypress="return onlyNumbers(event);"></td>
		</tr>
		<tr>
			<td colspan="2" style="padding-left:2px;padding-top:2px;padding-bottom:2px;"> <b> <span style="font-size:10px; color:#808080;"><em>(Note: Here you can specify size of a batch and number of threads to be uploaded at a time.)</em></span> <b> </td>
		</tr>
		<tr height="30px">
			<td colspan="2" align="right"> <span class="buttonStyle" onclick="hideAdvOptions()">Hide Options </span></td>
		</tr>
	</table>
</div>

<!-- div id="showOptions"class="divStyle">
	<span class="buttonStyle" onclick="showAdvOptions()">Click Here to Show Advanced Options</span>
</div -->

<div style="float:left">
	<table class="dataTable">
	<tr style="background-color:#F5F5F5;">
		<th><b>Sheet Details</b></th>
		<th colspan="2"> <span style="font-size:10px; color:#808080;"><em>Click on Browse & Upload to Uplodad csv data.</em></span>
			<!-- Click <a href="javascript:browse()">here<a> to upload multiple csv files <br>
			<span style="font-size:10px; color:#808080;"><em>(Note: File name should be same as metadata name)</em></span> -->
		</th>
	</tr>
	<tr>
		<td></td>
		<td colspan="2" id="progress">
		</td>
	</tr>
	#for sheetName in $sheetNameList:
		<tr>
			<td><span style="display:block;padding-left:3px; padding-right:3px;"><a href="/${applicationId}/1/administrator/${sheetName}">${sheetName}</a></span></td>
			<form id="mainform" action="/${applicationId}/1/flatcsvimport?update=true&sheetMetadataName=${sheetName}&redirectUrl=/${applicationId}/1/administrator" enctype="multipart/form-data" method="post">
			<td><input type="file" name="csvfile"/></td>
			<td><input type="submit" value="Upload"></td>
			</form>
		</tr>
	#end for
	<table>
</div>





</body>
</html>