<!DOCTYPE HTML>
<html>
	<head>
		<script> 
			var version = '1.0.7';
			
			var ncommand = false;
			var standalone = false;
			var wallcon = true;
		</script>
		<script src="js/libs/jquery.js"></script>
		<script>
			document.write('<script src="js/utils.js?v='+version+'"\><\/script>');
			document.write('<script src="js/tween.js?v='+version+'"\><\/script>');
			document.write('<script src="js/storage.js?v='+version+'"\><\/script>');
			document.write('<script src="js/libs/socketio.js?v='+version+'"\><\/script>');
			document.write('<script src="js/libs/binary.js?v='+version+'"\><\/script>');
			document.write('<script src="js/websocket.js?v='+version+'"\><\/script>');
			document.write('<script src="js/libs/ace/ace.js?v='+version+'"\><\/script>');
			document.write('<script src="js/libs/ace/ext-language_tools.js?v='+version+'"\><\/script>');
		</script>
		<script>
			var str = '';
			var cmirror, editor;
			var modulelist = [];
			var manufacturerlist = [];
			
			$(document).ready(function(){
			
				editor = ace.edit("modulecode");
				editor.setTheme("ace/theme/vibrant_ink");
				editor.getSession().setMode("ace/mode/javascript");
				editor.setDisplayIndentGuides(true);
				editor.getSession().setUseWrapMode(true);
				var langTools = ace.require("ace/ext/language_tools");
				editor.setOptions({enableBasicAutocompletion: true});
				editor.setOptions({enableLiveAutocompletion: true});
				editor.setOptions({enableSnippets: true});
				editor.setShowPrintMargin(false);
				editor.$blockScrolling = Infinity;
				var autoCompleter = {
					getCompletions: function(editor, session, pos, prefix, callback) {
						if (prefix.length === 0) { callback(null, []); return }
						var completerList = [
						   {name: 'tcpclient', meta: '(ip, port, message, callback)'},
						   {name: 'udpclient', meta: '(ip, port, message, callback)'},
						];
						callback(null, completerList.map(function(ea){           
							return {name: ea.name, value: ea.name, meta: ea.meta}
						}));
					}
				}
				//langTools.addCompleter(autoCompleter);
				if (standalone){
					var os = require('os'), fs = require('fs');
					var gui = require('nw.gui');
					var win = gui.Window.get();
					//win.showDevTools();
				}
				
				if (1) startWebsocket(function(){
					//if (standalone) websocket.emit('message', {command: 'discover', timeout: 10}, noop);
					server({
						opts: {command: 'read_allmodules'},
						callback: function(data){
							modulelist = json_decode(data);
							if (standalone){
								for (var i=0; i<modulelist.length; i++){
									modulelist[i].file = modulelist[i].path+modulelist[i].file;
								}
							}
							//else for (var i=0; i<modulelist.length; i++) modulelist[i].file = 'js'+modulelist[i].file;
							for (var i=0; i<modulelist.length; i++){
								if (!arrayContains(manufacturerlist, modulelist[i].manufacturer))
									manufacturerlist.push(modulelist[i].manufacturer);
							}
							for (var i=0; i<manufacturerlist.length; i++){
								if (manufacturerlist[i] == 'SVSi'){
									var t = manufacturerlist[0];
									manufacturerlist[0] = manufacturerlist[i];
									manufacturerlist[i] = t;
								}
							}
							str = '';
							for (var i=0; i<manufacturerlist.length; i++){
								str += '<option value="'+manufacturerlist[i]+'">'+manufacturerlist[i]+'</option>';
							}
							$('#modulemanufacturers').html(str);
							str = '';
							for (var i=0; i<modulelist.length; i++){
								if (modulelist[i].manufacturer == manufacturerlist[0])
									str += '<option value="'+modulelist[i].file+'">'+modulelist[i].make+'</option>';
							}
							$('#modules').html(str);
							
							$.ajax({url: $('#modules').val(), cache: false, dataType: 'text', success: function(val){
								editor.setValue(val, -1);
							}});
							
							$('#modules').change(function(){
							
								$.ajax({url: $('#modules').val(), cache: false, dataType: 'text', success: function(val){
									editor.setValue(val, -1);
								}, error: function(e,f,g){editor.setValue(e.responseText, -1);}});
							
							});
							$('#modulemanufacturers').change(function(){
							
								str = '';
								for (var i=0; i<modulelist.length; i++){
									if (modulelist[i].manufacturer == $('#modulemanufacturers').val())
										str += '<option value="'+modulelist[i].file+'">'+modulelist[i].make+'</option>';
								}
								$('#modules').html(str);
								
								$.ajax({url: $('#modules').val(), cache: false, dataType: 'text', success: function(val){
									editor.setValue(val, -1);
								}, error: function(e,f,g){editor.setValue(e.responseText, -1);}});
								
							});
							$('#modules').change();
						}
					}, 'server.php');
				});
				
				
				
				$('#themes').change(function(){
					editor.setTheme("ace/theme/"+$('#themes').val());
				});
				
			});
			
			function update(){
				TWEEN.update();
				requestAnimationFrame(update);
			}
			update();
			
		</script>
	</head>
	<body style="background: black;">
		<div style="position: absolute; left: 4.8%; top: calc(10% - 56px);">
			<select id="themes" style="position: absolute; z-index: 60;">
				<option value="vibrant_ink">Default</option>
				<optgroup label="Light">
					<option value="chrome">Chrome</option>
					<option value="clouds">Clouds</option>
					<option value="crimson_editor">Crimson Editor</option>
					<option value="dawn">Dawn</option>
					<option value="dreamweaver">Dreamweaver</option>
					<option value="eclipse">Eclipse</option>
					<option value="github">Github</option>
					<option value="solarized_light">Solarized Light</option>
					<option value="textmate">TextMate</option>
					<option value="tomorrow">Tomorrow</option>
					<option value="xcode">XCode</option>
					<option value="kuroir">Kuroir</option>
					<option value="katzenmilch">KatzenMilch</option>
				</optgroup>
				<optgroup label="Dark">
					<option value="ambiance">Ambiance</option>
					<option value="chaos">Chaos</option>
					<option value="clouds_midnight">Clouds Midnight</option>
					<option value="cobalt">Cobalt</option>
					<option value="idle_fingers">Idle Fingers</option>
					<option value="krtheme">krTheme</option>
					<option value="merbivore">Merbivore</option>
					<option value="merbivore_soft">Merbivore Soft</option>
					<option value="mono_industrial">Mono Industrial</option>
					<option value="monokai">Monokai</option>
					<option value="pastel_on_dark">Pastel on Dark</option>
					<option value="solarized_dark">Solarized Dark</option>
					<option value="terminal">Terminal</option>
					<option value="tomorrow_night">Tomorrow Night</option>
					<option value="tomorrow_night_blue">Tomorrow Night Blue</option>
					<option value="tomorrow_night_bright">Tomorrow Night Bright</option>
					<option value="tomorrow_night_eighties">Tomorrow Night 80s</option>
					<option value="twilight">Twilight</option>
					<option value="vibrant_ink">Vibrant Ink</option>
				</optgroup>
			</select>
		</div>
		<div style="position: absolute; left: 4.8%; top: calc(10% - 28px);">
			<select id="modulemanufacturers" style="position: relative; z-index: 60;"></select>
			<select id="modules" style="position: relative; z-index: 60;"></select>
		</div>
		<div style="position: absolute; top: 3%; left: 0%; width: 100%; text-align: center;
					color: white; font-size: 25px; font-family: Helvetica;">Modules</div>
		<img style="position: absolute; right: 4.8%; top: 3%; height: 5%;" src="images/svsi/svsi2.png" />
		<div id="modulecontainer" style="width: 90%; height: 79%; border: 1px solid black;
			position: absolute; right: 5%; top: 10%; overflow: hidden; background: #eeeeee;">
			<div id="modulecode" style="width: 100%; height: 100%;"></div>
		</div>
		<div id="save-button" type="button"
			onmouseover="$(this).css({background: 'white', color: 'black'});"
			onmouseout="if ($(this).data('active') != true)
				$(this).css({background: '#333', color: 'white'});"
			style="position: absolute; right: calc(7% + 140px); top: 91%; width: 120px; height: 45px; color: white;
				background: #333; line-height: 45px; font-size: 22px; text-align: center; border-radius: 25px;
				cursor: pointer; display: inline-block;">Save</div>
		<div id="revert-button" type="button"
			onmouseover="$(this).css({background: 'white', color: 'black'});"
			onmouseout="if ($(this).data('active') != true)
				$(this).css({background: '#333', color: 'white'});"
			style="position: absolute; right: 7%; top: 91%; width: 120px; height: 45px; color: white;
				background: #333; line-height: 45px; font-size: 22px; text-align: center; border-radius: 25px;
				cursor: pointer; display: inline-block;">Revert</div>
				
		<div id="dialog-pane" class="mainpane" style="display: none; position: fixed; top: 0px; left: 0px;
			width: 100%; height: 100%; background: none;
			z-index: 500000000001;">
			
			<div id="dialog-minipane" class="minipane" 
				style="display: block; background: none; position: absolute;">
					
				<div class="titletext titlebar" id="dialog_title" style="text-align: center; font-weight: bold;
					font-size: 22px;"></div>
					
				<div id="dialog_content">
					</div>
				
				<div id="dialog_buttons" style="position: absolute; left: 0px; bottom: 14px; width: 95%;">
					<input id="dialog_extra" type="button" value="none" style="float: right; margin-right: 6px;"></input>
					<input id="dialog_cancel" type="button" value="cancel" style="float: right; margin-right: 6px;"></input>
					<input id="dialog_confirm" type="button" value="ok" style="float: right; margin-right: 6px;"></input>
				</div>
				
			</div>
			
		</div>
		<div id="dialog-mousecatch" style="z-index: 19999; position: absolute; left: 0px; top: 0px;
			width: 100%; height: 100%; opacity: 0.1; background: #000; display: none;"></div>		
				
		<script>
			$('#save-button').click(function(){
				var currentfile = $('#modules').val();
				openDialog({
					content: 'Overwrite old module file?',
					style: {height: '120px'},
					onConfirm: function(){
						//console.log('filename?', $('#modules').val().substring($('#modules').val().lastIndexOf("/")+1));
						var file = new Blob([editor.getValue()], {type : 'text'});
						var fd = new FormData();
						fd.append("module", file, $('#modules').val().substring($('#modules').val().lastIndexOf("/")+1));
						fd.append("opts", JSON.stringify({command: 'write_module', manufacturer: $('#modulemanufacturers').val()}));
						if (wallcon||standalone) sendFile(file, {command: 'module', 
							filename: $('#modules').val().substring($('#modules').val().lastIndexOf("/")+1),
							manufacturer: $('#modulemanufacturers').val()}, function(data){
							//console.log('back', data);
						});
						else server({formdata: fd, callback: function(data){
							console.log(data);
						}});
						closeDialog();
					},
					onCancel: function(){
						closeDialog();
					}
				});
			});
			$('#revert-button').click(function(){
				openDialog({
					content: 'Revert and lose all changes?',
					style: {height: '120px'},
					onConfirm: function(){
						$.ajax({url: $('#modules').val(), cache: false, dataType: 'text', success: function(val){
							editor.setValue(val, -1);
						}, error: function(e,f,g){editor.setValue(e.responseText, -1);}});
						closeDialog();
					},
					onCancel: function(){
						closeDialog();
					}
				});
				
			});
			var openDialog = function(opts){
				if (dialogopen){
					waitfor(
						function(){if (!dialogopen) return true; else return false;}, 
						function(){openDialog(opts)}
					);
					return;
				}
				if (undef(opts)) var opts = {};
				var type = opts.hasOwnProperty('type') ? opts.type : 'warning';
				var title = opts.hasOwnProperty('title') ? opts.title : false;
				var content = opts.hasOwnProperty('content') ? opts.content : false;
				var confirm = opts.hasOwnProperty('confirm') ? opts.confirm : "ok";
				var cancel = opts.hasOwnProperty('cancel') ? opts.cancel : "cancel";
				var extra = opts.hasOwnProperty('extra') ? opts.extra : false;			
				var onConfirm = opts.hasOwnProperty('onConfirm') ? opts.onConfirm : function(){closeDialog();};
				var onCancel = opts.hasOwnProperty('onCancel') ? opts.onCancel : function(){closeDialog();};
				var onExtra = opts.hasOwnProperty('onExtra') ? opts.onExtra : false;
				var init = opts.hasOwnProperty('init') ? opts.init : noop;
				var width = opts.hasOwnProperty('width') ? opts.width : 400;
				var height = opts.hasOwnProperty('height') ? opts.height : 300;
				var style = opts.hasOwnProperty('style') ? opts.style : {};
				var buttonstyle = opts.hasOwnProperty('buttonstyle') ? opts.buttonstyle : false;
				$('#dialog_title').hide();
				$('#dialog_content').hide();
				$('#dialog_confirm').hide();
				$('#dialog_cancel').hide();
				$('#dialog_extra').hide();
				if (title){
					$('#dialog_title').show();
					$('#dialog_title').html(title);
				}
				if (content){
					$('#dialog_content').show();
					$('#dialog_content').html(content);
					if ($('#dialog_content')[0].children[0] && $('#dialog_content')[0].children[0].style) 
						$('#dialog_content')[0].children[0].style.margin = '15px';
					$('#dialog_content')[0].style.margin = '15px';
				}
				if (confirm){
					$('#dialog_confirm').show();
					$('#dialog_confirm').val(confirm);
				}
				if (cancel){
					$('#dialog_cancel').show();
					$('#dialog_cancel').val(cancel);
				}
				if (extra){
					$('#dialog_extra').show();
					$('#dialog_extra').val(extra);
				}
				if (onConfirm){
					$('#dialog_confirm')[0].onclick = onConfirm;
				}
				if (onCancel){
					$('#dialog_cancel')[0].onclick = onCancel;
				}
				if (onExtra){
					$('#dialog_extra')[0].onclick = onExtra;
				}
				$('#dialog-pane').css({display: 'block'});
				$('#dialog-minipane').css({
					width: width+'px',
					height: height+'px',
					background: 'black',
					color: 'white',
					'border-radius': '15px'
				});
				$('#dialog-minipane').css(style);
				$('#dialog-minipane').css({
					left: 'calc(50% - '+($('#dialog-minipane').width()/2)+'px)',
					top: 'calc(50% - '+($('#dialog-minipane').height()/2)+'px)'
				});
				if (buttonstyle){
					$('#dialog_confirm').css(buttonstyle);
					$('#dialog_cancel').css(buttonstyle);
					$('#dialog_extra').css(buttonstyle);
				}
				tweencss({
					object: $('#dialog-pane')[0],
					time: 0.2,
					ease: TWEEN.Easing.Sine.Out,
					props: {opacity: 0, scale: 0.2},
					to: {opacity: 1, scale: 1.0}
				});
				init();
				switch (type) {
					case 'warning': default:
						$('#dialog-mousecatch').click(function(){closeDialog()});
						break;
					case 'error':
						break;
					case 'confirm':
						break;
				}
			}
			var closeDialog = function(onComplete){
				tweencss({
					object: $('#dialog-pane')[0],
					time: 0.2,
					ease: TWEEN.Easing.Sine.Out,
					props: {opacity: 1, scale: 1.0},
					to: {opacity: 0, scale: 0.2},
					onComplete: function(func){
						dialogopen = false;
						$('#dialog-pane').css({display: 'none'});
						if (func) func();
					}.bindArgs(onComplete)
				});
			}
			var dialogopen = false;
		</script>
	</body>
</html>