#from Plugins.Extensions.OpenWebif.local import tstrings
<style>
#packagelist {padding:0;}
#packagelist li.installed {font-weight:bold;}
#packagelist li {list-style-type:none;margin:4px 0;}
#packagelist li i {margin:0 10px;}
#packagelist .g {color:green;}
#packagelist .r {color:red;}
#searchpkd {margin:5px 5px; display:inline-block;}
#packagelist li div {display:inline-table;}
#packagelist li div span {font-weight:initial;font-size:smaller;}
</style>
<div id="content_main" class="ui-widget-content" style="min-height: 500px;background-image:none;">
	<div id="info">
		<div style="display:table; width: 100%; zoom: 1;">
			<div style="display:table-cell;width:220px;">
				<h3 class="ui-widget-header">$tstrings['settings']</h3>
				<ol class="sellist" id="slist">
				<li id='themesbtn' data-id="owsettings" class="ui-selected">$tstrings['tstr_ow_settings']</li>
				<li id='pkgbtn' data-id="packages" class="ui-selected">Packages</li>
				#for $sec in $configsections
					<li id='$sec["key"]' data-id='ajax/config?section=$sec["key"]'>$sec["description"]</li>
				#end for
				</ol>
			</div>
			<div class="ui-widget-header" style="display:table-cell;background: none;border-bottom:none;border-top:none;border-left:none;width:1px;"></div>
			<div style="display:table-cell;">
				<div style="width: 100%; zoom: 1;">
					<div id="scontent"></div>
					</div>
		<div id='osettings' style="display:none;">
			<div id="content_main2">
				<h3 class="ui-widget-header">$tstrings['tstr_ow_browser_settings']</h3>
				<table id="configuration">
				<tr><td>$tstrings['tstr_theme']</td><td>
				<select name="selectheme" id="selectheme" style="min-width: 150px;margin: 5px;border:none;font-size: 1em;">
				#for $stheme in $themes
					#if $stheme == $theme
						<option selected="selected">$stheme</option>
					#else
						<option>$stheme</option>
					#end if
				#end for
				</select>
				</td></tr>
				<tr><td>$tstrings['zapbeforestream']</td><td>
				#if $zapstream
				<input type="checkbox" name="zapstream" checked="checked"/>
				#else
				<input type="checkbox" name="zapstream"/>
				#end if
				</td></tr>
				<tr><td>$tstrings['tstr_show_picon_in_channel_list']</td><td>
				#if $showchannelpicon
				<input type="checkbox" name="showchannelpicon" checked="checked"/>
				#else
				<input type="checkbox" name="showchannelpicon"/>
				#end if
				</td></tr>
				<tr><td>$tstrings['tstr_spinner']</td><td>
				<span class="spinner">
				<fieldset style="border:none;" id="fsspinner">
				<label for="fa-spinner"><i class="fa fa-spinner"></i></label>
				<input type="radio" name="Spin" id="fa-spinner">
				<label for="fa-spin1"><i class="fa fa-spin1"></i></label>
				<input type="radio" name="Spin" id="fa-spin1">
				<label for="fa-spin2"><i class="fa fa-spin2"></i></label>
				<input type="radio" name="Spin" id="fa-spin2">
				<label for="fa-spin3"><i class="fa fa-spin3"></i></label>
				<input type="radio" name="Spin" id="fa-spin3">
				<label for="fa-spin4"><i class="fa fa-spin4"></i></label>
				<input type="radio" name="Spin" id="fa-spin4">
				<label for="fa-spin5"><i class="fa fa-spin5"></i></label>
				<input type="radio" name="Spin" id="fa-spin5">
				<label for="fa-spin6"><i class="fa fa-spin6"></i></label>
				<input type="radio" name="Spin" id="fa-spin6">
				</fieldset>
				</span>
				</td></tr>
				</table>
			</div>
		</div>
		
		<div id='packages' style="display:none;">
			<div id="content_main2">
				<h3 class="ui-widget-header">Packages</h3>
				<span id="tb2">
				<input class="pkgbtn" type="radio" id="pkgbtn1" name="tb2" checked="checked" /><label for="pkgbtn1">Update</label>
				<input class="pkgbtn" type="radio" id="pkgbtn2" name="tb2" /><label for="pkgbtn2">Installed</label>
				<input class="pkgbtn" type="radio" id="pkgbtn3" name="tb2" /><label for="pkgbtn3">All</label>
				<input class="pkgbtn" type="radio" id="pkgbtn4" name="tb2" /><label for="pkgbtn4">More..</label>
				<div id="searchpkd"><label for="searchpk">Search:</label><input id="searchpk" value="..." class='ui-widget ui-widget-content ui-corner-all'></div>
				</span>
				<div id="pkgmore">
				<br><br>
				<button id="updatefeed">Update from Feed</button>
				<br><br>
				<button id="upgrade">Upgrade all Packages</button>
				<br><br>
				<div id="pkgupload">
				<button id="selectfile">Select IPK File for Upload</button>
				<br><br>
				Uploaded Files:<br>
				<ul id='tmpfiles'></ul>
				<br><br>
				<form id="uploadpkg" style="display:none" action"uploadpkg"="" method="post" enctype="multipart/form-data" encoding="multipart/form-data">
				<input type="file" name="rfile" id="rfile" maxlength="100000">
				<input type="hidden" name="filename" id="filename">
				</form>
				</div>
				<textarea id="resulttext" style='height:300px;width:100%'>
				</textarea>
				</div>
				<div id="tblpackages">
				<ul id="packagelist"><div id='spinner'><div class='fa fa-spinner fa-spin'></div></div></ul>
				</div>
			</div>
		</div>
		
		</div>
		</div>
	</div>
</div>
<script type="text/javascript">
#raw
// TODO minimize js

var filteredpkg;
var filterval='';

function prepareUpload() {
	var fn = $(this).val();
	fn = fn.replace('C:\\fakepath\\','');
	if (confirm('Upload Package' + ' ( ' + fn + ') ?') === false) {
		return;
	}

	var frm = document.forms["uploadpkg"];
	frm.filename.value = fn;	

	$('form#uploadpkg')
		.unbind('submit')
		.submit(function (e) 
	{
		var formData = new FormData(this);
		$.ajax({
			url: '/ipkg/upload',
			type: 'POST',
			data: formData,
			mimeType:"multipart/form-data",
			contentType: false,
			cache: false,
			processData:false,
			dataType: 'json',
			success: function (data, textStatus, jqXHR) {
				var r = data.Result;
				if (r[0]==true) {
					alert("DONE");
				} else {
					alert("Upload File Error: " + r[1]);
				}
			},
			error: function (jqXHR, textStatus, errorThrown) {
				alert("Upload File Error: " + errorThrown);
			}
		});
		e.preventDefault();
		try {
			e.unbind();
		} catch(e){}
	});
	$('form#uploadpkg').submit();
}
function getPkgFilename(){
	var frm = document.forms["form_uploadpkg"];
	frm.filename.value = frm.file.value;
}

function ShowFilterPackages()
{
	var row='';
	$.each( filteredpkg, function( key, val ) {
		var name = val['name'];
		var desc = val['d'];
		if(filterval=== '' || name.toLowerCase().search(filterval.toLowerCase()) !== -1 || desc.toLowerCase().search(filterval.toLowerCase()) !== -1) {
			var upd = (val['u'] == '0') ? "":val['u'];
			var i = val['i'];
			var sel = (i == '1') ? "class='installed' ":"";
			if(i == '1' && val['u'] != '0')
				i = '2';
			var ico = (i == '1') ? "fa-trash-o r":"fa-save g";
			if(upd!='') {
				upd = " -> " + upd;
			}
			row += "<li "+sel+"data-i='"+i+"' data-n='"+name+"'>"+ "<i class='fa "+ico+"'></i><div>" + name +" (" + val['v'] + upd +")<br><span>" + desc + "</span></div></li>";
		}
	});
	$("#packagelist").html(row);

}

function FillPackages(pkgs,mode)
{
	var _update = $.grep(pkgs, function(v) {
		return (v.u != '0');
	});
	var _installed = $.grep(pkgs, function(v) {
		return (v.i == '1');
	});

	if (mode == 'pkgbtn1')
		filteredpkg = _update.slice();
	else if (mode == 'pkgbtn2') {
		filteredpkg = _installed.slice();
	} else
		filteredpkg = pkgs.slice();

	$("#packagelist").html('');

	ShowFilterPackages();

	$('#packagelist > li').click( function () {
		ask($(this),false);
	});


}

function ask(obj,man)
{
	var pk = $(obj).html();
	var i = $(obj).data('i');
	if(!man) {
		pk = $(obj).data('n');
	}
	
	var cmd = '';
	
	if(i=='1') {
		if (confirm('Remove Package' + ' ( ' + pk + ') ?') === true) {
			cmd = 'remove&' + pk;
		}
	} else if (i=='2') {
		if (confirm('Update Package' + ' ( ' + pk + ') ?') === true) {
			cmd = 'install&package=' + pk;
		}
	} else {
		if (confirm('Install Package' + ' ( ' + pk + ') ?') === true) {
			cmd = 'install&package=' + pk;
		}
	}
	
	if(cmd != '')
	{
		Action('/ipkg?command='+cmd,'true');
		$("#tblpackages").hide();
		$("#pkgmore").show();
		$('#pkgbtn4').prop('checked', true); 
	}
	
}

function Action(action,rl)
{
	$('#resulttext').val('');
	$.ajax({
		url: action,
		success: function ( data ) {
			var txt = data.replace('<html><body>','').replace('</body></html>','').replace(/<br>/g,'');
			$('#resulttext').val(txt);
			if(rl !== undefined) {
				SetLSValue('pkg-date','');
			}
		}
	});
}

function ShowPackages(mode)
{
	$("#tblpackages").hide();
	if (mode == 'pkgbtn4') {
		$("#pkgmore").show();
		if(noupload)
			return;
		$('#tmpfiles').empty();
		$.ajax({
			url: '/ipkg?command=tmp',
			dataType: 'json',
			success: function (data) {
				var files = '';
				$.each( data.ipkfiles, function( key, val ) {
					files+='<li>' + val['name'] + '</li>'
				});
				$('#tmpfiles').html(files);
				$('#tmpfiles > li').click( function () {
					ask($(this),true);
				});
			}
		});
		return;
	}

	$("#pkgmore").hide();
	$("#tblpackages").show();

	var date = new Date();
	date = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+date.getHours();

	var cache = GetLSValue('pkg-date','')
	if(cache === date) {
		cache = GetLSValue('pkg-data',null);
		if(cache != null) {
			var pkgs = JSON.parse(cache);
			FillPackages(pkgs,mode);
			return;
		}
	}

	$.ajax({
		url: '/ipkg?command=listall',
		success: function ( data ) {
			SetLSValue('pkg-date',date);
			SetLSValue('pkg-data',data);
			var pkgs = JSON.parse(data);
			FillPackages(pkgs,mode);
		}
	});
}

function load_scontent(url) {
	$("#scontent").html('');
	$("#osettings").hide();
	$("#packages").hide();
	if(url=='owsettings')
	{
		$("#osettings").show();
		$("#selectheme").change(function() {
			ChangeTheme($(this).val());
		});
		return;
	}
	if(url=='packages')
	{
		$("#packages").show();
		ShowPackages('pkgbtn1');
		return;
	}
	$("#scontent").load(url , function () {
		$("#scontent").find("#content_main").attr("id","content_main1");
	});
	return false;
}
$(function() { 
	$( "#slist" ).selectable({
		selected: function( event, ui ) {
			var ids = $('#slist .ui-selected').map(function() {
				if($(this).data('id') !== undefined) {
					load_scontent($(this).data('id'));
				}
			});
		},
		classes: {
			"ui-selected": getActiveCls()
		}
	});
	load_scontent('owsettings');
	
	$(".spinner input[type='radio']").checkboxradio({ icon: false });
	$(".spinner fieldset").controlgroup();
	var spin = GetLSValue('spinner','fa-spinner');
	$('#'+spin).attr('checked', true).checkboxradio("refresh");
	$(".spinner input:radio").change(function() {
		SetLSValue('spinner',$(this).attr('id'));
		SetSpinner();
	});

	setHover('#slist li');
	$('#fsspinner > label').css('padding-left','10px');
	$('#fsspinner > label').css('padding-right','10px');
	$("#themesbtn").addClass(getActiveCls());

	$("input[name=zapstream]").click(function(evt) {
		$('input[name=zapstream]').attr('checked', evt.currentTarget.checked);
		webapi_execute("/api/zapstream?checked=" + evt.currentTarget.checked);
	});

	$("input[name=showchannelpicon]").click(function(evt) {
		$('input[name=showchannelpicon]').attr('checked', evt.currentTarget.checked);
		webapi_execute("/api/showchannelpicon?checked=" + evt.currentTarget.checked);
	});
	
	$('#tb2').buttonset();
	$('#tb3').buttonset();
	$('.pkgbtn').click(function () { ShowPackages($(this).attr('id')); });
	$('#selectfile').click(function () {$("#rfile").trigger('click'); });
	$('#rfile').change(prepareUpload);
	$('#updatefeed').click(function () {Action('/ipkg?command=update',true); });
	$('#upgrade').click(function () {Action('/ipkg?command=upgrade','true'); });
	
	$('#searchpk').focus(function () { 
		if ($(this).val() === '...') {
			$(this).val('');
		}
	}).keyup(function (){
		if ($(this).data('val') !== this.value) {
			filterval=this.value;
			ShowFilterPackages();
		}
		$(this).data('val', this.value);
	}); /*.blur(function (){
		filterval='';
		$(this).data('val', '');
		if ($(this).val() === '') {
			$(this).val('...');
		}
	});
	*/
});
#end raw
#if $allowipkupload
var noupload=true;
#else
\$(function() { 
	\$("#pkgupload").remove();
});
var noupload=false;
#end if
</script>
