$(document).ready(function () {
    "use strict";

    // Стиль скина
    var editor = ace.edit("editor");
    editor.setOptions({readOnly: true,});
    editor.setTheme("ace/theme/chrome");
    editor.session.setMode("ace/mode/less");
    
    // Стиль базового скина
    var editorBase = ace.edit("editor-base");
    editorBase.setOptions({readOnly: true,});
    editorBase.setTheme("ace/theme/chrome");
    editorBase.session.setMode("ace/mode/less");
    
    // Помечаем цветом поля конфига:
    var
        $configWrap = $('.form-group-config'),
        $configFields = $('input.form-control, select.form-control', $configWrap),
        $sizeWidth = $configFields.filter('.size.width'),
        $sizeHeight = $configFields.filter('.size.height'),
        $itemsCols = $configFields.filter('.items.cols'),
        $itemsRows = $configFields.filter('.items.rows'),
        $logoVert = $configFields.filter('.logo.vert'),
        $logoHor = $configFields.filter('.logo.hor'),
        $logoInner = $configFields.filter('.logo.inner'),
        $logoWidth = $configFields.filter('.logo.width'),
        $logoHeight = $configFields.filter('.logo.height'),
        $animationName = $configFields.filter('.animation.name'),
        $animationLoopTimeout = $configFields.filter('.animation.loopTimeout');
        
    function markConfigControl($this)
    {
        //if ($this.data('base') == $this.val() && $this.val()) {$this.addClass('from-base');}
        $this.attr('placeholder', $this.attr('data-base'));
    }
    
    function markAllConfigControls()
    {
        $configFields.each(function() {
            markConfigControl($(this));
        });
    }
    
    markAllConfigControls();
    
    // Смена базового конфига:
    $('.form-control.skin-base').on('change', function(){
        
        var
            action = $configWrap.data('action'),
            method = 'POST',
            data = {
                'get_data_skin': $(this).val(),
            };

        $.ajax(action, {
            type: method,
            data: data,
            success: function(data) {
                console.log('AAA success ', data.data);
                var
                    style = data.data.style,
                    conf = data.data.config;
                
                // Устанавливаем стили в базовом редакторе:
                editorBase.setValue(style);
                editorBase.session.selection.clearSelection();
                
                // Устанавливаем значения базового конфига:
                $sizeWidth.attr('data-base', conf.size.width || '');
                $sizeHeight.attr('data-base', conf.size.height || '');
                $itemsCols.attr('data-base', conf.items.cols || '');
                $itemsRows.attr('data-base', conf.items.rows || '');
                $animationName.attr('data-base', conf.animation.name || '');
                $animationLoopTimeout.attr('data-base', conf.animation.loopTimeout || '');
                $logoVert.attr('data-base', conf.logo.pos.vert || '');
                $logoHor.attr('data-base', conf.logo.pos.hot || '');
                $logoInner.attr('data-base', conf.logo.pos.inner || '');
                $logoWidth.attr('data-base', conf.logo.size.width || '');
                $logoHeight.attr('data-base', conf.logo.size.height || '');
        
                markAllConfigControls();
            },
            error: function(rew, status, err) {
                console.log(status, err);
            }
        });
        
        
    });
    
    // Клик на "Редактировать", "Сохранить", "Опубликовать":
    var
        $editButton = $('button.btn.btn-primary.edit'),
        $saveButton = $('button.btn.btn-primary.save'),
        $saveControls = $('.b-save'),
        $leftFade = $('.b-left-fade');

    $editButton.click(function(){
        $leftFade.hide();
        $saveControls.show();
        return false;
    });
    
    $saveButton.click(function(){
        
        
        var
            $form = $('#skin-create-form'),
            action = $form.attr('action'),
            method = $form.attr('method'),
            formData = new FormData();
        
        console.log('AAA saveButton ', action);
        
        $.ajax(action, {
            type: method,
            data: formData,
            cache:false,
            contentType: false,
            processData: false,
            success: function(data) {
                console.log('AAA saveButton success');
                return false;
                
                if(data) {
                    if(data.result === true && data.redirect) {
                        document.location.href = data.redirect;
                    }
                    if(data.result === false && data.msg) {
                        $.showMessage('error', data.msg);
                    }
                } 
            },
            error: function(rew, status, err) {
                console.log(status, err);
                $.showMessage('error', err);
            }
        });
        
        return false;
    });
    
});