jQuery.cookie=function(b,j,m){if(typeof j!="undefined"){m=m||{};if(j===null){j="";m.expires=-1}var e="";if(m.expires&&(typeof m.expires=="number"||m.expires.toUTCString)){var f;if(typeof m.expires=="number"){f=new Date();f.setTime(f.getTime()+(m.expires*24*60*60*1000))}else{f=m.expires}e="; expires="+f.toUTCString()}var l=m.path?"; path="+(m.path):"";var g=m.domain?"; domain="+(m.domain):"";var a=m.secure?"; secure":"";document.cookie=[b,"=",encodeURIComponent(j),e,l,g,a].join("")}else{var d=null;if(document.cookie&&document.cookie!=""){var k=document.cookie.split(";");for(var h=0;h<k.length;h++){var c=jQuery.trim(k[h]);if(c.substring(0,b.length+1)==(b+"=")){d=decodeURIComponent(c.substring(b.length+1));break}}}return d}};

$(document).on('click', 'a.sidebar-control', function() {
    var miniSidebar = $.cookie('mini_sidebar');
    if (miniSidebar === null) {
        $.cookie('mini_sidebar', true, { expires: 7, path: '/' });
        $('body').addClass('sidebar-xs');
    } else {
        $.cookie('mini_sidebar', false, { expires: -1, path: '/' });
        $('body').removeClass('sidebar-xs');
    }
});


// TODO не забыть заметь imageId на id во все пуктах добавление контента

// добавление информации к картинке в галереи
function editPictureInfo(imageId, confirm, module) {
    let $this = $('#edit_image_'+imageId);
    var title = $this.attr('data-title'), alias = $this.attr('data-alias'), description =$this.attr('data-description'), link = $this.attr('data-link'), position = $this.attr('data-position');
    // position = $this.attr('data-position');
    bootbox.prompt({
        title: confirm,
        message:'<div class="form-group mb-3">'+
                '   <label class="form-group-float-label is-visible">Заголовок</label>'+
                '   <input type="text" class="form-control" id="image_title" value="'+title+'" />'+
                '</div>' +
                '<div class="form-group mb-3">' +
                '   <label class="form-group-float-label is-visible">Альтернативный заголовок</label>'+
                '   <input type="text" class="form-control" id="image_alias" value="'+alias+'" />' +
                '</div>' +
                '<div class="form-group mb-3">' +
                '   <label class="form-group-float-label is-visible">Описание</label>' +
                '   <textarea rows="3" cols="3" class="form-control" placeholder="" id="image_description">'+description+'</textarea>'+
                '</div>' +
                '<div class="form-group mb-3">'+
                '   <label class="form-group-float-label is-visible">Ссылка</label>'+
                '   <input type="text" class="form-control" id="image_link" value="'+link+'" />'+
                '</div>',
        inputType: 'select',
        value: position,
        inputOptions: [
            { text: 'По умолчанию', value: 'default' },
            { text: 'Банер', value: 'banner' },
            { text: 'Галерея', value: 'gallery' },
            { text: 'Карусель', value: 'carousel' },
            { text: 'Коллекция', value: 'collection' },
            { text: 'Станция', value: 'station' },
            { text: 'Блок', value: 'block' },
            { text: 'Логотип', value: 'logo' },
            // { text: 'Клиенты', value: 'clients' },
            // { text: 'Партнеры', value: 'partners' },
        ],
        buttons: {
            cancel: { label: 'Отмена', className: 'btn-sm btn-light' },
            confirm: { label: 'Сохранить', className: 'btn-sm  btn-primary' }
        },
        callback: function (result) {
            var link = $('#image_link').val(), title = $('#image_title').val(), alias = $('#image_alias').val(), description = $('#image_description').val();
            console.log(result);
            if (result !== null) {
                $.post('index.php?mod=' + module + '&action=editPictureInfo', { imageId: imageId, 'picture[title]': title, 'picture[alias]' : alias, 'picture[description]': description, 'picture[link]': link, 'picture[position]' : result }, function (response) {
                    console.log(response);
                    if (response.status === 200) {
                        $('#edit_image_' + imageId).attr('data-title', response.title).attr('data-alias', response.alias).attr('data-description', response.description).attr('data-link', response.link).attr('data-position', response.position);
                        $('#meta_image_' + imageId + ' #im_title').text(response.title);
                        $('#meta_image_' + imageId + ' #im_alias').text(response.alias);
                        $('#meta_image_' + imageId + ' #im_description').text(response.description);
                        $('#meta_image_' + imageId + ' #im_link').text(response.link);
                        $('#meta_image_' + imageId + ' #im_position').text(response.position);
                    }
                }, 'json');
            }
        }
    });
}


function confirmLanguageChange(sbmButton) {
    // bootbox.confirm({
    //     message: lang['sureToChangeLang'] + ' "'+sbmButton.form.defaultLang.options[sbmButton.form.defaultLang.selectedIndex].label+'"?',
    //     callback: function(result) {
    //         console.log(result);
    //         if (result === true) {
    //             sbmButton.form.submit();
    //         }
    //     }
    // });

    if (window.confirm(lang['sureToChangeLang'] + ' "'+sbmButton.form.defaultLang.options[sbmButton.form.defaultLang.selectedIndex].label+'"?') == false) return false;
    sbmButton.form.submit();
}

function languageOptionChange(thisSelect) {
    document.getElementById('codename').value     = thisSelect.value;
    document.getElementById('languageName').value = thisSelect.options[thisSelect.selectedIndex].text
    if (typeof lang2charset != 'undefined') {
        if (lang2charset[thisSelect.value]) {
            var charsetOptions = document.getElementById('charsetOptions').options;
            for (i = 0; i < charsetOptions.length; i++) {
                if (charsetOptions[i].value == lang2charset[thisSelect.value]) {
                    charsetOptions[i].selected = true;
                    break;
                }
            }

            // var adminLanguageOptions = document.getElementById('adminLanguageOptions').options;
            // for (i = 0; i < adminLanguageOptions.length; i++) {
            //     if (adminLanguageOptions[i].value == thisSelect.value) {
            //         adminLanguageOptions[i].selected = true;
            //         break;
            //     }
            // }
        }
    }
}

function deleteStats() {

    if (!ajaxIsFree())
        return false;

    var settingsForm = document.getElementById('settings');
    var date = settingsForm['date'].value;

    bootbox.confirm({
        closeButton: false,
        message: lang['sureToDeleteStats'] + ' '+date+'?',
        callback: function(result) {
            console.log(result);
            if (result === true) {
                postData("index.php?mod=settings&action=delete_stats&date=" + date);
                deleteStatsMessage();
            }
        }
    });

    return false;
}

function clearCache() {
    if(!ajaxIsFree()) return false;
    postData("index.php?mod=settings&action=clear_cache");
    clearCacheMessage();

    return false;
}

function approve(id, url) {
    if (!ajaxIsFree()) return false;
    bootbox.confirm({
        closeButton: false,
        message: 'Вы действительно хотите одобрить без модерации?',
        callback: function(result) {
            console.log(result);
            if (result === true) {
                postData('index.php?mod='+url+"&action=approve&id="+id);
            }
        }
    });
    return false;
}

// рабочее удаление id, заголовок, ссылка
function newRemove(id, title, module) {
    if (!ajaxIsFree()) return false;
    bootbox.confirm({
        closeButton: false,
        message: lang['sureToDelete'] + ' "'+title+'"?',
        callback: function(result) {
            if (result === true) {
                $.post('index.php?mod=' + module + "&action=remove", { id: id }, function(response) {
                    if (response.status === 200) {
                        console.log(module)
                        removeElement(id, module.slice(0, -1));
                    }
                    new Noty({ text: response.message, type: response.type }).show();
                }, 'json');

            }
        }
    });
    return false;
}

// рабочее удаление id, заголовок, ссылка
function remove(id, title, module) {
    if (!ajaxIsFree()) return false;
    bootbox.confirm({
        closeButton: false,
        message: lang['sureToDelete'] + ' "'+title+'"?',
        callback: function(result) {
            if (result === true) {
                postData('index.php?mod=' + module + "&action=remove&id=" + id);
                // $.post('index.php?mod=' + module + "&action=remove", { id: id }, function(response) {
                //     if (response.status === 200) {
                //         removeElement(id, module);
                //     }
                //     new Noty({ text: response.message, type: response.type }).show();
                // }, 'json');

            }
        }
    });
    return false;
}

// remove preview - если предпоказ
function removePreviewImage() {

    // удалить кноку удаления
    const buttonRemove = document.getElementById('content-image-preview-remove');
    buttonRemove.parentNode.removeChild(buttonRemove);

    // удаляем картинку
    const preview = document.getElementById('content-image-preview');
    if (preview.hasChildNodes()) {
        preview.removeChild(preview.children[0]);
    }
    document.getElementById('content-image-preview-add').innerHTML = '<i class="ph-image me-2"></i>Загрузить файл';

    return false;

}
// delete preview - если была загружена в базу
function deletePreviewImage(imageId, module) {
    bootbox.confirm({
        closeButton: false,
        message: lang['sureToDeleteImage'] + '?',
        callback: function(resultCallback) {
            if (resultCallback === true) {
                $.post('index.php?mod=' + module + "&action=deleteImage", { imageId: imageId }, function(response) {
                    if (response.status === 200) {
                        // удалить кноку удаления
                        const buttonRemove = document.getElementById('content-image-preview-remove');
                        buttonRemove.parentNode.removeChild(buttonRemove);

                        // удаляем картинку
                        const preview = document.getElementById('content-image-preview');
                        if (preview.hasChildNodes()) {
                            preview.removeChild(preview.children[0]);
                        }

                    }
                    new Noty({ text: response.message, type: response.type }).show();
                }, 'json');
            }
        }
    });
    return false;
}

// удаление картинки из галереи - если предпоказ
function removePicture(imageId) {
    const elem = document.getElementById('gallery-item-' + imageId);
    elem.parentNode.removeChild(elem);
    return false;
}

// удаление картинки из галереи - если была загружена в базу
function deletePicture(imageId, module) {
    var el = document.getElementById("gallery-item-" + imageId);
    $.post('index.php?mod='+module, { imageId: imageId, action: 'deletePicture' }, function(data){
        if (data.status === 200){
            el.parentNode.removeChild(el);
        }
        new Noty({ text: data.message, type: data.type }).show();
    }, 'json');
}

// TODO не забыть заметь imageId на id во все пуктах добавление контента
// удаление картинки из галереи
function deleteDocs(fileId, module) {
    var el = document.getElementById("docs-item-" + fileId);
    $.post('index.php?mod='+module, { imageId: fileId, action: 'deleteDocs' }, function(data){
        if (data.status === 200) {
            el.parentNode.removeChild(el);
        }
        new Noty({ text: data.message, type: data.type }).show();
    }, 'json');
}
function deleteSongs(fileId, module) {
    var el = document.getElementById("song-item-" + fileId);
    $.post('index.php?mod='+module, { imageId: fileId, action: 'deleteSongs' }, function(data){
        if (data.status === 200) {
            el.parentNode.removeChild(el);
        }
        new Noty({ text: data.message, type: data.type }).show();
    }, 'json');
}
// добавление информации к картинке в галереи
function editSongInfo(imageId, confirm, module) {
    let $this = $('figure#song-item'+imageId);
    var input = $('figure#song-item-' + imageId + ' .song_title')
    var title = input.val();
    console.log($this)
    console.log(title)
    bootbox.prompt({
        title: confirm,
        value: title,
        // message:'<div class="form-group mb-3">'+
        //     '   <label class="form-group-float-label is-visible">Название песни</label>'+
        //     '   <input type="text" class="form-control" id="song_title" value="' + title + '" />'+
        //     '</div>',
        buttons: {
            cancel: { label: 'Отмена', className: 'btn-sm btn-light' },
            confirm: { label: 'Сохранить', className: 'btn-sm  btn-primary' }
        },
        callback: function (result) {

            console.log(result);
            if (result !== null) {
                $.post('index.php?mod=' + module + '&action=editSongInfo', { imageId: imageId, 'picture[title]': result }, function (response) {
                    console.log(response);
                    if (response.status === 200) {
                        input.val(response.title);
                    }
                }, 'json');
            }
        }
    });
}



function deleteImage(imageId, module) {
    if (!ajaxIsFree()) return false;
    bootbox.confirm({
        closeButton: false,
        message: lang['sureToDeleteImage'] + '?',
        callback: function(result) {
            if (result === true) {
                $.post('index.php?mod='+module + "&action=deleteImage", { imageId: imageId, }, function(response){
                    if (response.status === 200) {
                        const preview = document.getElementById('content-image-preview');
                        if (preview.hasChildNodes()) {
                            preview.removeChild(preview.children[0]);
                        }
                        const buttonRemove = document.getElementById('content-image-preview-remove');
                        console.log(buttonRemove)
                        buttonRemove.parentNode.removeChild(buttonRemove);
                    }
                    new Noty({ text: response.message, type: response.type }).show();
                }, 'json');
            }
        }
    });
    return false;
}

function deleteTemplate(fileName){
    if (!ajaxIsFree()) return false;
    bootbox.confirm({
        closeButton: false,
        message: lang['sureToDelete'] + ' "'+fileName+'"?',
        callback: function(res) {
            if (res === true) {
                writeStatus(lang['deletingTemplate'] + '...');
                postData("index.php?mod=template&action=delete&template[fileName]="+fileName);
            }
        }
    });
    return false;
}

function deleteFile(path, file, module) {
    bootbox.confirm({
        closeButton: false,
        message: lang['sureToDelete'] + ' "'+file+'"?',
        callback: function(res) {
            if (res === true) {
                document.location = 'index.php?mod='+module+'&path='+path+'&action=remove&file[name]='+file;
            }
        }
    });
    return false;
}



function deleteFileAjax(path, file, module) {
    if (!ajaxIsFree()) return false;
    bootbox.confirm({
        closeButton: false,
        message: lang['sureToDelete'] + ' "'+file+'"?',
        callback: function(res) {
            console.log(res);
            if (res === true) {
                postData('index.php?mod=' + module + "&path=" + path + "&action=remove&file[name]=" + file);
            }
        }
    });
    return false;
}

function deleteAFile(file) {
    bootbox.confirm({
        closeButton: false,
        message: lang['sureToDelete'] + ' "'+file+'"?',
        callback: function(res) {
            if (res === true) {
                document.location = 'index.php?mod=files&action=remove&file[name]='+file;
            }
        }
    });
    return false;
}
function deleteProductColor(id, module, index) {
    let element = document.getElementById("color-" + index);
    $.post('index.php?mod='+module+"&action=deleteColors", { imageId: id }, function(response) {
        if (response.status === 200) element.parentNode.removeChild(element);
        new Noty({ text: response.message, type: response.type }).show();
    }, 'json');
}


function deleteColorNew(id, module, type, index) {
    let element = document.getElementById(type + "-" + index);
    $.post('index.php?mod='+module+"&action=deleteColors", { imageId: id }, function(response) {
        if (response.status === 200) element.parentNode.removeChild(element);
        new Noty({ text: response.message, type: response.type }).show();
    }, 'json');
}

// сортировка таблицы
function tableSort(element, module) {
    if (!ajaxIsFree()) return false;

    var sortBy = element.getAttribute('data-sort-by')
    var sortOrder = element.getAttribute('data-sort-order')

    $.post('index.php?mod='+module+"&action=sort_table", { sortBy: sortBy, sortOrder: sortOrder }, function(response) {
        console.log(response)
        window.location.reload();
    }, 'json');
}

// очистка сортировка таблицы
function clearTableSort(element, module) {

    if (!ajaxIsFree()) return false;

    $.post('index.php?mod='+module+"&action=clear_sort_table", function(response) {
        console.log(response)
        window.location.reload();
    }, 'json');
}

function removeElement(elementId, elementPrefix) {
    console.log(elementId);
    node = document.getElementById(elementPrefix+'-'+elementId);
    console.log(node);
    node.parentNode.removeChild(node);
}

function proposeFileName(srcName, destName, formName, separator, convertToLowerCase) {
    form = document.getElementById(formName);
    if (form[destName].value == '') {
        re = new RegExp('(^\\'+separator+'|\\'+separator+'$)', 'gi');
        form[destName].value = form[srcName].value.replace(/[^0-9a-zA-Z\-_\.]+/gi, separator).replace(re, '');
        if (convertToLowerCase == '1') form[destName].value = form[destName].value.toLowerCase();
    }
}

function writeStatus(message, messageClass, destElementId) {
    newTime = new Date;
    if (message == '' && (newTime.getTime() - lastTime) < 2000) return false;
    if (typeof destElementId == 'undefined' || destElementId == '') destElementId = 'ajaxStatus';
    statusField = document.getElementById(destElementId);
    if (messageClass) {
        statusField.innerHTML = '<span class="' + messageClass + '">' + message + '</span>';
    } else {
        statusField.innerHTML = message;
    }

    lastTime = newTime.getTime();
    return false;
}

function ajaxIsFree() {
    if (typeof waitingResponse != 'undefined' && waitingResponse == true) {
        bootbox.alert(lang['processingRequest']);
        return false;
    }
    return true;
}

function handleHttpResponse() {
    if (XMLHttp.readyState === 4) {
        if (XMLHttp.status === 200) {
            try {
                eval(XMLHttp.responseText);
            } catch (e) {
                if (typeof httpResponseEvalOnError != 'undefined' && httpResponseEvalOnError != '') {
                    httpResponseText = XMLHttp.responseText;
                    eval(httpResponseEvalOnError);
                } else {
                    bootbox.alert(lang['operationError'] + ": " + XMLHttp.responseText);
                    document.location = document.location.pathname;
                }
            }
            waitingResponse = false;
        } else {
            bootbox.alert(lang['operationError'] + ": " + XMLHttp.responseText);
            document.location = document.location.pathname;
        }
    }
}

function postData(destination, data){
    if (window.XMLHttpRequest) {
         XMLHttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    method = 'POST';
    if (typeof data == 'undefined') method = 'GET';
    XMLHttp.open(method, destination, true);
    if (method === 'POST') XMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    XMLHttp.onreadystatechange = handleHttpResponse;
    XMLHttp.send(data);
    waitingResponse = true;
}

// Autocomplete */
(function($) {
    $.fn.autocomplete = function(option) {
        return this.each(function() {
            var $this = $(this);
            var $dropdown = $('<ul class="dropdown-menu" />');

            this.timer = null;
            this.items = [];

            $.extend(this, option);

            $this.attr('autocomplete', 'off');
            // Focus
            $this.on('focus', function() {
                this.request();
            });
            // Blur
            $this.on('blur', function() {
                setTimeout(function(object) {
                    object.hide();
                }, 200, this);
            });
            // Keydown
            $this.on('keydown', function(event) {
                switch(event.keyCode) {
                    case 27: // escape
                        this.hide();
                        break;
                    default:
                        this.request();
                        break;
                }
            });

            // Click
            this.click = function(event) {
                event.preventDefault();

                var value = $(event.target).parent().attr('data-value');
                if (value && this.items[value]) {
                    this.select(this.items[value]);
                }
            }

            // Show
            this.show = function() {
                var pos = $this.position();
                $dropdown.css({
                    top: pos.top + $this.outerHeight(),
                    left: pos.left
                });
                $dropdown.show();
            }

            // Hide
            this.hide = function() {
                $dropdown.hide();
            }

            // Request
            this.request = function() {
                clearTimeout(this.timer);

                this.timer = setTimeout(function(object) {
                    object.source($(object).val(), $.proxy(object.response, object));
                }, 200, this);
            }

            // Response
            this.response = function(json) {

                console.log(json);

                var html = '';
                var category = {};
                var name;
                var i = 0, j = 0;

                if (json.length) {
                    for (i = 0; i < json.length; i++) {
                        // update element items
                        this.items[json[i]['value']] = json[i];

                        if (!json[i]['category']) {
                            // ungrouped items
                            html += '<li data-value="' + json[i]['value'] + '"><a class="dropdown-item" href="#">' + json[i]['label'] + '</a></li>';
                        } else {
                            // grouped items
                            name = json[i]['category'];
                            if (!category[name]) {
                                category[name] = [];
                            }

                            category[name].push(json[i]);
                        }
                    }

                    for (name in category) {
                        html += '<li class="dropdown-header">' + name + '</li>';

                        for (j = 0; j < category[name].length; j++) {
                            if (category[name][j]['image'] == undefined || category[name][j]['image'] == null){
                                html += '<li data-value="' + category[name][j]['value'] + '"><a class="dropdown-item" href="#">&nbsp;&nbsp;&nbsp;' + category[name][j]['label'] + '</a></li>';
                            } else {
                                 html += '<li data-value="' + category[name][j]['value'] + '"><a class="dropdown-item" href="#"><span class="input-group-text"><img src="' + category[name][j]['image'] + '" width="30"/></span>' + category[name][j]['label'] + '</a></li>';
                            }
                        }
                    }
                }

                if (html) {
                    this.show();
                } else {
                    this.hide();
                }

                $dropdown.html(html);
            }

            $dropdown.on('click', '> li > a', $.proxy(this.click, this));
            $this.after($dropdown);
        });
    }
})(window.jQuery);




// function createRequestString(theForm){
//     vars = [];
//     for(i = 0; i < theForm.elements.length; i++){
//         element = theForm.elements[i];
//         if (element.tagName.toLowerCase() === "input") {
//             switch (element.type){
//                 case "text":
//                 case "hidden":
//                     vars.push(encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value));
//                     break;
//
//                 case "checkbox":
//                 case "radio":
//                     if(element.checked){
//                         vars.push(encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value));
//                     } else {
//                         vars.push(encodeURIComponent(element.name) + "=");
//                     }
//                     break;
//             }
//         }
//         if (element.tagName.toLowerCase() === "select"){
//             vars.push(encodeURIComponent(element.name) + "=" + encodeURIComponent(element.options[element.selectedIndex].value));
//         }
//         if (element.tagName.toLowerCase() === "textarea"){
//             vars.push(encodeURIComponent(element.name) + "=" + encodeURIComponent(element.value));
//         }
//     }
//     if(vars.length > 0){
//         return vars.join("&");
//     } else {
//         return false;
//     }
// }
//




