<?php namespace AloVoice; ?>
<style>
	.alv_table_lines .nowrp {
		white-space: nowrap;
	}
	.loadingline{
		display:none;
	}
</style>
<center>
	<h3 class="h3 mt-3 card-body">Скрипты звонков</h3> 
	<div class="loadingline"></div>
	<a href="#" id="callsctipt_add_button" onClick="show_new_script_win()" class="btn btn-primary title_line_button"><i class="fa fa-plus"></i> Добавить скрипт </a>
</center>
<br/>

<table class="table" id="stats_block_table">
	<thead>
		<tr id="alvcallscripts_table_header"></tr>
	</thead>
	<tbody id="alvcallscripts_table_body">
	</tbody> 
</table>
<style>
	.pop_info{
		display:none;
		position:absolute;
		padding:20px;
		margin:10%;
		background:#fff;
		left:0;
		top:0;
		width:80%;
		height:80%;
		box-shadow: 1px 1px 10px #ccc;
		border-radius:5px;
		overflow-y: scroll;
	    border: 10px solid #ccc;
	}	
	.pop_closer{
		position:absolute;
		padding:2px;
		margin:0;
		background:red;
		color:#fff;
		right:10px;
		top:10px;
		width:30px;
		height:30px;
		border-radius:50%;
		box-shadow: 1px 1px 5px #615b5b;
		font-weight: bold;
		font-size: 18px;
		cursor: pointer;
		text-align: center;
	}
	#new_call_script_area{
		width:100%;
		height:300px;
	}
</style>

<div class="pop_info" id="pop_info"><span class="pop_closer">x</span>
	<div class="form-row">
		<label class="col-2"> Название скрипта:</label> 
		<div class="col-9">
			<input type="text" class="form-control" id="new_call_script_name"> 
			<i>* Только буквы, цифры и пробел</i>
		</div>
	
	</div>
	<div class="form-row"><br></div>
	<div class="form-row">
		<label class="col-2">Тело скрипта:</label> 
		<div class="col-9">
			<textarea id="new_call_script_area" class="editor"></textarea>
			<i>* Только HTML код (Картинки не работают...)</i>
		</div>
		
	</div>
	
	<br>
	<div class="btn btn-primary" onClick="send_new_callscript()">Сохранить</div>
</div>
<script src="/bx24/template/js/tinymce/tinymce.min.js"></script>
<script>

var afterLoadPage = function(){
	var isHeadered = false;
	
	window.send_new_callscript = function(){
		var newScriptName = $("#new_call_script_name").val();
		var newScriptBody = $("#new_call_script_area").val();
		
		console.log("AloVoice Sending NEW Script file:",newScriptName, newScriptBody);
		var restobj = {"restmethod":"alovoice_save_new_callscript","scriptname":newScriptName, "scriptbody":newScriptBody};
		loadAloVoiceInfo(restobj,function(res){
			console.log("AloVoice NEW Script RES:",res);
			$("#pop_info").hide();
			$("#new_call_script_name").val("");
			$("#new_call_script_area").val("");
			scriptsUpdate();
		});
	}
	
	window.show_new_script_win = function(){
		console.log("Test click:");
		$("#pop_info").show(); //.click(function(){
		makeEditor();
		$(".pop_closer").click(function(){
			$("#pop_info").hide();
		});
		
	}
	
	var scriptsUpdate = function(){

		loadAloVoiceInfo("alovoice_callscripts_list",function(res){
			console.log("AloVoice Scripts RES:",res);
			
			if(!isHeadered){
				if(typeof res.headers != 'undefined' ){
					isHeadered = true;
					$("#alvcallscripts_table_header").html('');
					
					$.each( res.headers, function( key, value ) {					
						console.log("Each Header:",key, value);
						$("#alvcallscripts_table_header").append('<th id="hd_'+key+'">'+value+'</th>');
					});
				}
			}
			
			if(typeof res.datas != 'undefined' ){
				
				$("#alvcallscripts_table_body").html('');
				
				$.each( res.datas, function( tkey, csrpt ) {
					console.log("Each Script:",csrpt);
					var lineHTML = '<tr class="alv_table_callscriptlines" id="trk_line_'+tkey+'">'
						+'<td class="nowrp" > <b>'+csrpt.filename+'</b></td>'
						+'<td class="nowrp" >'+csrpt.filesize +' b</td>'
						// +'<td class="nowrp" ><a href="#" class="alv_table_callscriptdels" data-fnm="'+csrpt.filename+'" ><i class="fa fa-trash"></i> Изменить</a></td>'
						+'<td class="nowrp" >'
							+'<a href="#" class="alv_table_callscriptdels" data-fnm="'+csrpt.filename+'" ><i class="fa fa-trash"></i> Удалить</a>'
							+'<a href="#" class="alv_table_callscriptedits ml-3" data-fnm="'+csrpt.filename+'" ><i class="fa fa-pencil"></i> Изменить</a>'
						+'</td>'
						+'</tr>';
					
					$("#alvcallscripts_table_body").append(lineHTML);
				});
				
				$("#callsctipt_add_button").click(function(){
					console.log("Add Script test!");
				});
				
				$(".alv_table_callscriptedits").click(function(){
					var fnm = $(this).attr('data-fnm');
					console.log("Getting script:", fnm);
					var restobj = {"restmethod":"alovoice_get_callscript","scriptname":fnm};
					loadAloVoiceInfo(restobj,function(res){
						console.log("AloVoice Edit Script RES:",res);
						$("#new_call_script_name").val(res.script);
						$("#new_call_script_area").val(res.body);
						show_new_script_win();
					});
				});
				
				$(".alv_table_callscriptdels").click(function(){
					var fnm = $(this).attr('data-fnm');
					console.log("AloVoice Sending Del Script file:",fnm);
					var restobj = {"restmethod":"alovoice_callscripts_delete","filename":fnm};
					loadAloVoiceInfo(restobj,function(res){
						console.log("AloVoice Del Script RES:",res);
						scriptsUpdate();
					});
				});
			}
			
			//setTimeout(donglesUpdate,100000);
		}); 
	}
	
	scriptsUpdate();
	
};
//ondClick="delOneCallScript(\''+csrpt.filename+'\');"
</script>

<script>
function makeEditor(){
	if(typeof tinymce != 'undefined'){
		tinymce.init({
			selector: ".editor",
			theme: "modern",
			plugins: [
				"advlist autolink autosave link image lists charmap print preview hr anchor pagebreak spellchecker",
				"searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
				"save table contextmenu directionality emoticons template textcolor paste fullpage textcolor colorpicker"
			],
			external_plugins: {
				//"moxiemanager": "/moxiemanager-php/plugin.js"
			},
			// content_css: "css/development.css",
			add_unload_trigger: false,
			autosave_ask_before_unload: false,
			// autosave_interval: '2s',
			toolbar1: "save newdocument fullpage | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | styleselect formatselect fontselect fontsizeselect",
			toolbar2: "cut copy paste pastetext | searchreplace | bullist numlist | outdent indent blockquote | undo redo | link unlink anchor image media help code | insertdatetime preview | forecolor backcolor",
			toolbar3: "table | hr removeformat | subscript superscript | charmap emoticons | print fullscreen | ltr rtl | spellchecker | visualchars visualblocks nonbreaking template pagebreak restoredraft | insertfile insertimage",
			menubar: false,
			toolbar_items_size: 'small',
			setup : function(editor) {
			  editor.on("change keyup", function(e){
				// console.log('saving');
				// tinyMCE.triggerSave(); // updates all instances
				editor.save(); // updates this instance's textarea
				// $(editor.getElement()).trigger('change'); // for garlic to detect change
			  });
			},
			style_formats: [
				{title: 'Bold text', inline: 'b'},
				{title: 'Red text', inline: 'span', styles: {color: '#ff0000'}},
				{title: 'Red header', block: 'h1', styles: {color: '#ff0000'}},
				{title: 'Example 1', inline: 'span', classes: 'example1'},
				{title: 'Example 2', inline: 'span', classes: 'example2'},
				{title: 'Table styles'},
				{title: 'Table row 1', selector: 'tr', classes: 'tablerow1'}
			],

			// templates: [
				// {title: 'My template 1', description: 'Some fancy template 1', content: 'My html'},
				// {title: 'My template 2', description: 'Some fancy template 2', url: 'development.html'}
			// ],

			// spellchecker_callback: function(method, data, success) {
				// if (method == "spellcheck") {
					// var words = data.match(this.getWordCharPattern());
					// var suggestions = {};

					// for (var i = 0; i < words.length; i++) {
						// suggestions[words[i]] = ["First", "second"];
					// }

					// success({words: suggestions, dictionary: true});
				// }

				// if (method == "addToDictionary") {
					// success();
				// }
			// }
		});
	}
	else {
		console.log("TinyMC not loaded...");
	}
}
</script>