<%-
	require "luci.sys"
	require "nixio.fs"
	local url=luci.sys.exec("uci get sierraupdate.@sierraupdate[0].url | xargs echo -n") or ""
	local filename=luci.sys.exec("uci get sierraupdate.@sierraupdate[0].filename | xargs echo -n") or ""
-%>


<script type="text/javascript">//<![CDATA[

function init_page()
{
	var table = document.getElementById('dot');
	for ( i=0;i<table.rows.length;i++){
		for(j=0;j<table.rows[i].cells.length;j++){
			table.rows[i].deleteCell(0);
		}
	}

	var updatebtn = document.getElementById('updatebtn');
	var stxhr = new XHR();
	stxhr.get('<%=luci.dispatcher.build_url("admin", "services", "sierraupdate")%>/sierraupdate_init' , null,
		function(x, mArray)
		{
		}
		);
	<% if url ~= ""  and filename ~= "" then %>
		updatebtn.disabled = false;
	<%end%>
} 

function update_firmware()
{
	var stxhr = new XHR();
	stxhr.get('<%=luci.dispatcher.build_url("admin", "services", "sierraupdate")%>/sierraupdate_update' + '/' + "C" + '/' + "update" + '/' + "custom" + '/' + "<%=filename%>" , null,
		function(x, mArray)
		{
			if (mArray && mArray.length && mArray.length > 0)
			{
				var min = 0;
				var data="";
				var max=mArray.length;
				for (i = min; i < max; i++) {
					data = data + mArray.firmwares[i] + ".";
				}
				alert(data);
			}else if (mArray && mArray.length){
				alert("Could not finish updating.");
			}  
		}
		);
}

XHR.poll(10, '<%=luci.dispatcher.build_url("admin", "services", "sierraupdate","sierraupdate_status" )%>', { status: 1 },
	function(x, mArray)
	{
		var data="";
		if (mArray && mArray.length && mArray.length > 0)
		{
			var min = 0;
			var max=mArray.length;
			var max_p=0;
			var table = document.getElementById('dot');
			for(var i=0;i<table.rows.length;i++) {
				max_p += table.rows[i].cells.length;
			}
			for (i = max_p; i < max ; i++) {
				var row = table.insertRow(0);
				var cell = row.insertCell(0);
				cell.innerHTML = mArray.data[i];
			}
		}
	}
	); 
	//]]></script> 
	<body onload="init_page()">
		<!-- <h2><a>Download Over The Air</a></h2> -->
		<!-- <div >From Custom Server</div> -->
		<div id="buttoncss" align="center">
			<table class="cbi-section-table" style="width:940px; margin-left:5px">
				<input id="updatebtn" onclick="update_firmware()" type="button" disabled="false" value="<%:Update now%>" class="cbi-button cbi-button-apply"/>
			</table>
		</div>

		<fieldset class="cbi-section">
			<table width="100%" cellspacing="10" id="dot">
				<tr></tr>
			</table>
		</fieldset>
	</body>
