(function() {
	
	'use strict';

	function testForEnter(event)
	{
		if (event.key === "Enter") {
			$("#mobilefirestarter-submit").click()
		}
	}


	/*
	 * Саджесты тасков
	 */

	$(".mobilefirestarter-suggest__task").bind('click', function(event){
		var task_input_field = $("input#task_input");
		task_input_field.val($(this).text());
		event.preventDefault()
    });


	/*
	 * Саджесты танков
	 */

	$(".mobilefirestarter-suggest__tank").bind('click', function(event){
		var target_input_field = $("input#tank_input");
		target_input_field.val($(this).text());
		event.preventDefault()
    });


    /*
     * Кнопка "Огонь!"
     */
    
    $("button#submitMobileFire").bind('click', function() {
        $(this).prop('disabled', true);

        var $krutilka = $('#krutilka');
        var $error = $('#error_block');
        var $form = $('#mobileFireForm');
        $error.hide();
        $krutilka.show();
        $.ajax({
			url: $form.attr('action'),
			type: 'post',
			data : $form.serialize(),
			datatype: 'json'
        }, 'json'
		).done(function(data) {
			if (data.success) {

				var text = "В очереди созданы стрельбы с номерами " + data.jobs + ", они очень ждут, когда их заберет танк по имени " + data.tank;

			    alert(text)
			}
			else {
			    $error.text(data.error);
			    $error.show();
			    $("button#submitMobileFire").prop('disabled', false);
			}
		}
		).fail(function(error) {
			$error.text(data.error);
		    $error.show();
			$("button#submitMobileFire").prop('disabled', false);
		}
		).always(function() {
			$krutilka.hide();
		});
    });

	/*
	* Кнопка загрузки APK
	*/
	$('#uploadAPKForm').submit(function () {
		var formData = new FormData($(this)[0]);
		$('#upload_apk_submit').prop('disabled', true);
		$('#apkKrutilka').show();
		$.ajax({
			url: "/mobilefirestarter/upload_apk",
			type: 'POST',
			data: formData,
			async: true,
			dataType : 'json',
			success: function (data) {
				if (data['success'] === true) {
					$('#upload_apk_cancel').click();
					var $apkSelect = $('#apk_select');
					$apkSelect.prepend('<option value="'+data['path']+'" style="font-weight: bold;">'+data['dsc']+'</option>');
                    $('select[name=apk_select]').val(1);
                    $apkSelect.selectpicker('refresh');
                    // UPDATE EDITOR
                    var editor = ace.edit('editor');
                    var apkfile_string = editor.find('^apkfile\=?.+$', {regExp: true});
                    if (apkfile_string) {
                        editor.replace('apkfile=' + data['path']);
                    } else {
                        var section_string = editor.find('[phantom]', {regExp: false});
                        if (section_string){
                            var row = section_string["start"]["row"] + 2;
                            editor.gotoLine(row);
                            editor.insert('apkfile=' + data['path'] + '\n');
                        }
                        else {
                            editor.gotoLine(0);
                            editor.insert('[phantom]\napkfile=' + data['path'] + '\n');
                        }
                    }
				} else {
					alert(data['error'])
				}
			},
			complete: function() {
				$('#upload_apk_submit').prop('disabled', false);
				$('#apkKrutilka').hide();
			},
			cache: false,
			contentType: false,
			processData: false
		});
		return false;
	});
	
	
	/*
	* Кнопка загрузки APK с тестами
	*/
	$('#uploadTestsForm').submit(function () {
		var formData = new FormData($(this)[0]);
		$('#upload_tests_submit').prop('disabled', true);
		$('#testsKrutilka').show();
		$.ajax({
			url: "/mobilefirestarter/upload_tests",
			type: 'POST',
			data: formData,
			async: true,
			dataType : 'json',
			success: function (data) {
				if (data['success'] === true) {
					$('#upload_tests_cancel').click();
					var $testsSelect = $('#tests_select');
					$testsSelect.prepend('<option value="'+data['path']+'" style="font-weight: bold;">'+data['dsc']+'</option>');
                    $('select[name=tests_select]').val(1);
                    $testsSelect.selectpicker('refresh');
                    // UPDATE EDITOR
                    var editor = ace.edit('editor');
                    var testsfile_string = editor.find('^testsfile\=?.+$', {regExp: true});
                    if (testsfile_string) {
                        editor.replace('testsfile=' + data['path']);
                    } else {
                        var section_string = editor.find('[phantom]', {regExp: false});
                        if (section_string){
                            var row = section_string["start"]["row"] + 2;
                            editor.gotoLine(row);
                            editor.insert('testsfile=' + data['path'] + '\n');
                        }
                        else {
                            editor.gotoLine(0);
                            editor.insert('[phantom]\ntestsfile=' + data['path'] + '\n');
                        }
                    }
				} else {
					alert(data['error'])
				}
			},
			complete: function() {
				$('#upload_tests_submit').prop('disabled', false);
				$('#testsKrutilka').hide();
			},
			cache: false,
			contentType: false,
			processData: false
		});
		return false;
	});

			
})();