
var pendingList = {},
    select2Opt = {minimumResultsForSearch: -1, dropdownAutoWidth: false, width: '100%', allowDuplicates: true};

function initFileUploader(){
    $('[id^="fileupload_"]').fileupload({
        url: '{{ app.controller_alias }}/upload-theme-img',
        type: 'POST',
        autoUpload: false,
        multipart: true,
        singleFileUploads: true,
        maxFileSize: 2000000,
        maxNumberOfFiles: 1,
        acceptFileTypes: /(\.|\/)(jpe?g|png)$/i,
        //disableImagePreview: true,
        disableImageResize: true,
        previewThumbnail: false,
        previewCanvas: false
    }).bind('fileuploadadd', function (e, data) {
        var id, _this = $(this);
        id = e.currentTarget.id.replace('fileupload', '').replace(/\_/g, '');

        var imgOption = {
            '169' : {
                previewMaxWidth: 302,
                previewMaxHeight: 169,
                previewMinWidth: 153,
                previewMinHeight: 95
            },
            '43' : {
                previewMaxWidth: 141,
                previewMaxHeight: 108,
                previewMinWidth: 101,
                previewMinHeight: 59
            },
            'logo' : {
                previewMaxWidth: '15.7%',
                previewMaxHeight: '13%',
                previewMinWidth: '15.5%'
            }
        }

        $.each(imgOption[id], function(key, val){
            _this.fileupload(
                'option',
                key,
                val
            );
        });

    }).bind('fileuploadadded', function (e, data) {
        var img, params = {}, currentFile, id;

        id = e.currentTarget.id.replace('fileupload', '').replace(/\_/g, '');
            params = {
                id: '{{ app.launcher_theme.id }}',
                size: id == '169' ? 1080 : ( id == '43' ? 576 : 'logo')
            }

            currentFile = data.files[0];

            switch (id) {
                case '169': {
                    img = $("#launcher_bg_1080, #launcher_bg_720");
                    break;
                }
                case '43': {
                    img = $("#launcher_bg_576, #launcher_bg_480");
                    break;
                }
                case 'logo': {
                    img = $("img[id^='launcher_logo_']");
                    params['logoAlign'] = $("#logo_position").val();
                    img.removeClass('align-left align-center align-right').addClass('align-' + params['logoAlign']);
                    break;
                }
            }

        if (!pendingList[id]) {
            img.attr('src', currentFile.preview.toDataURL(currentFile.type));

            if (!img.is(':visible')) {
                img.show();
            }
            data.formData = params;
            pendingList[id] = data;
            $('span.fileinput-button.delete', e.currentTarget).attr('data-visible', '1');
            $("[id^='to_default_" + id + "']").attr('disabled', 'disabled');
        } else {
            delete(pendingList[id]);
            img.attr('src', img.data('original-src'));
            $('span.fileinput-button.delete', e.currentTarget).attr('data-visible', '0');
            $("[id^='to_default_" + id + "']").removeAttr('disabled');
        }
    }).bind('fileuploadalways', function (e, data) {
        if (typeof(data.progressWorkTimer) != "undefined") {
            window.clearInterval(data.progressWorkTimer);
        }

        var name = '';
        if (typeof(data.files) != "undefined" && data.files.length) {
            name = "{{ 'Image'|trans }} " + data.files[0].name;
        }

        var progress_id = ( typeof(data.progress_id) != "undefined" ? data.progress_id: 'qq-progress-bar-' + data.formData.size);

        $('#' + progress_id).attr('aria-valuenow', 100);
        $('#' + progress_id).closest('div.qq-progress-bar-container-selector').prev('span').html(name + ' ' + "{{ 'saving'|trans }}");
        $('#' + progress_id + " > div").css("width", "100%");
        var id = e.currentTarget.id.replace('fileupload', '').replace(/\_/g, '');
        if (Object.keys(pendingList).length && pendingList[id]) {
            delete(pendingList[id]);
        }
    }).bind('fileuploadprogress', function (e, data) {
        var name = '';
        if (typeof(data.files) != "undefined" && data.files.length) {
            name = "{{ 'Image'|trans }} " + data.files[0].name;
        }
        var value_now = Math.round(data.loaded / data.total * 100);
        var progress = '"' + name + '" '+"{{ 'uploading'|trans }}"+'...  ' + value_now + '%';
        var progress_id = ( typeof(data.progress_id) != "undefined" ? data.progress_id: 'qq-progress-bar-' + data.formData.size);
        if (data.loaded < data.total) {
            $('#' + progress_id).attr('aria-valuenow', value_now);
            $('#' + progress_id).closest('div.qq-progress-bar-container-selector').prev('span').html(progress);
            $('#' + progress_id + " > div").css("width", value_now + "%");
        } else {
            $('#' + progress_id).attr('aria-valuenow', 100);
            $('#' + progress_id).closest('div.qq-progress-bar-container-selector').prev('span').html(name + ' ' + "{{ 'saving'|trans }}");
            $('#' + progress_id + " > div").css("width", "100%");
        }
    }).bind('fileuploaddone', function (e, data) {
        var response;
        if (data && data.jqXHR && data.jqXHR.status && data.jqXHR.status == 200 && data.jqXHR.responseJSON) {
            response = data.jqXHR.responseJSON;
        } else {
            JSErrorModalBox();
            return false;
        }
        if (response.success) {
            ajaxSuccess(response, false);
        }
        $("#save_channels").removeClass("hidden");
        $("#clean_channels").removeClass("hidden");
        return false;
    }).bind('fileuploadfail', function (e, data) {
        if (data && data.jqXHR && data.jqXHR.status && data.jqXHR.responseJSON) {
            JSErrorModalBox(data.jqXHR.responseJSON);
        } else {
            JSErrorModalBox();
        }
    });
    return true;
}

function InitSelect2() {
    $('#logo_position').select2(select2Opt);
}

function yelp() {
    $(document).ready(function () {
        $( "#tabs" ).tabs({
            create: function(event, ui){
                var tabsData = $(event.target).data('ui-tabs');
                tabsData.anchors.each(function(idx, anchor){
                    var contentId = $(anchor).attr('href');
                    var $panel = $(tabsData.panels[idx]);
                    $panel.html($(contentId).remove().html());
                });
            },
            beforeLoad: function(event, ui){
                event.preventDefault();
            }
        });

        if (typeof (loadFileUploadScripts) != 'function' || !loadFileUploadScripts(initFileUploader)){
            JSErrorModalBox({msg: "{{ 'Cannot load File Upload plugin'|trans }}"})
        }

        $('#logo_position').on('change', function(){
            $("img[id^='launcher_logo_']").removeClass('align-left align-center align-right').addClass('align-' + $(this).val());
        });

        $(document).on('click', "#form_save", function(e){
            e.stopPropagation();
            e.preventDefault();

            saveForm();

            return false;
        });

        $(document).on('click', "#form_to_default", function(e){
            e.stopPropagation();
            e.preventDefault();

            if(confirm("{{ 'All changed settings will be reset to default values'|trans }}. {{ 'Continue'|trans }}?")){

                $('span.fileinput-button.delete').trigger('click');
                $('#logo_position').val('left').trigger('change');

                $("input[name^='to_default']").attr('disabled', 'disabled');
                $("#to_default_all").removeAttr('disabled');
            }
            return false;
        });

        $('span.fileinput-button.delete').on('click', function (e) {
            e.stopPropagation();
            e.preventDefault();

            var id, img;
            id = $(this).closest("div[id^='fileupload_']").attr('id').replace('fileupload', '').replace(/\_/g, '');

            switch (id) {
                case '169': {
                    img = $("#launcher_bg_1080, #launcher_bg_720");
                    break;
                }
                case '43': {
                    img = $("#launcher_bg_576, #launcher_bg_480");
                    break;
                }
                case 'logo': {
                    img = $("img[id^='launcher_logo_']");
                    break;
                }
            }

            $("[id^='to_default_" + id + "']").removeAttr('disabled');

            if (pendingList[id]) {
                delete(pendingList[id]);
            }
            img.attr('src', img.data('original-src'));
            $(this).attr('data-visible', '0');
        });

        LoadSelect2Script(InitSelect2);

        $('.form-group .i-hint').tooltip({
            animation: true,
            placement: "right"
        });
        
    });
}

document.addEventListener("DOMContentLoaded", yelp, false);

function saveForm() {
    if (Object.keys(pendingList).length != 0){
        if (!$("#modalbox").is(':visible')) {
            $('#modalbox').find('.modal-header-name span').text("{{ 'Uploading progress'|trans }}");
            $("#modalbox .devoops-modal-inner").empty();
            $("#modalbox").show();
        }
        $.each(pendingList, function (key, data) {
            var name = '';
            if (typeof(data.files) != "undefined" && data.files.length) {
                name = "{{ 'Image'|trans }} " + data.files[0].name;
            }
            var progress_id = 'qq-progress-bar-' + data.formData.size;
            data.progress_id = progress_id;
            $("#modalbox .devoops-modal-inner").append('\n\
                    <span class="col-sm-10 col-sm-offset-1" style="text-align: center;">'+name+'</span>\n\
                    <div class="qq-progress-bar-container-selector">\n\
                        <div id="' + progress_id + '" class="tu-progress-bar ui-progressbar ui-widget ui-widget-content ui-corner-all" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" style="width: 90%; margin-left: 5%;">\n\
                            <div class="qq-progress-bar-selector ui-progressbar-value ui-widget-header ui-corner-left" style="width: 0%;"></div>\n\
                        </div>\n\
                    </div>');
            data.submit();
        });
    }

    var submittedFileTimer = window.setInterval(function(){
        if (Object.keys(pendingList).length == 0 || (typeof (window.submitTry) != "undefined" && window.submitTry >= 300)){
            window.clearInterval(submittedFileTimer);
            if (typeof (window.submitTry) != "undefined" && window.submitTry >= 300) {
                JSErrorModalBox({msg: "{{ 'One or more images not be loaded'|trans }}"});
            }
            $('#form_').get(0).submit();
        } else {
            window.submitTry = typeof (window.submitTry) != "undefined" ? window.submitTry++: 0;
        }
    }, 100);
}