var imgTarget = '';
var clicked;
var URLdeletar,
    btn_deletar;
    
var ttImg;
    
$(window).on('load', function(){
    galeria();
    ttImg = $('.container-imagens').find('.box').length;
    
    iniFileupload();
    
});

$('select[name=item]').parent().remove();

var group = $('#sortable').sortable({
   group: 'serialize',
   pullPlaceholder: true,
   placeholder: '<li class="placeholder">Arraste e solte a imagem aqui</li>',
   handle: '.icon-move',
  // animation on drop
  onDrop: function  ($item, container, _super) {
    var $clonedItem = $('<li/>').css({height: 0});
    $item.before($clonedItem);
    $clonedItem.animate({'height': $item.height()});

    $item.animate($clonedItem.position(), function  () {
        $clonedItem.detach();
        _super($item, container);
        
        var data = $('#sortable').sortable("serialize").get();
        
        update_galery_priority({'data':data[0]});
    });
  },
  
  // set $item relative to cursor position
  onDragStart: function ($item, container, _super) {
    var offset = $item.offset(),
        pointer = container.rootGroup.pointer;

    adjustment = {
      left: offset.left - $item.width() ,
      top: pointer.top - $item.height()
    };
    
    /*adjustment = {
      left: pointer.left - offset.left,
      top: pointer.top - offset.top
    };*/
    
    $item.width($('li.sort-item:eq(1)').width());
    $item.height($('li.sort-item:eq(1)').height());

    _super($item, container);
  },
  onDrag: function ($item, position) {
    $item.css({
      left: position.left ,
      top: position.top - $item.height()
    });
    
    /*$item.css({
      left: position.left - adjustment.left,
      top: position.top - adjustment.top
    });*/
  }
});

function update_galery_priority($data)
{
    var target = base_url + URI.galeriaAjax+'order_priority';
    $data['edit_lancamento'] = edit_lancamento;
    $.ajax(
    {
        url: target,
        dataType: 'json',
        type: 'POST',
        data: $data,
        success: function(result)
        {
            //console.log(result)
        }
    });
}

$(document).on('click','.delete-img', function(){

    URLdeletar = $(this).parents('.image-block').find('input[type=checkbox]').data('url');
    btn_deletar = $(this);
    var row = $(this).parents('tr');
    var body = '<div id="retorno" class="alert alert-warning" role="alert" style="display:none;"></div>'+
               '<img src="'+row.find('img').attr('src')+'" alt="Imagem a deletar" class="img-rounded profile-user-img img-responsive"><br>'+
               '<p>Você tem certeza que deseja excluir a imagem?</p>';
    
    showModal('Excluir imagem', body, 'warning', 'Excluir', 'danger');
});

$('body').on('click', '.excluir_foto', function(){
    
    btn_deletar = $(this);
    var url = new URL(btn_deletar.data('url'));
    var file = url.searchParams.get("file");
    var link = base_url+URI.galeriaAjax+'deletar?id_imovel='+id_imovel+'&file='+file;
        
    $.ajax(
    {
        url: link,
        type: 'GET',
        dataType: 'json',
        success: function(result)
        {
            if(result.valid === true)
            {
                btn_deletar.parent().parent().remove();
                ttImg--;
                updateColBtnUpload();
                
                ajusta_height();
            }
            else 
            {
                console.log('deu ruim');
            }
        },
        error: function(result)
        {
            console.log('deu ruim');
        }
    });
});

$('body').on('change', '.descricao_imagem', function(){
    
    var target = base_url +URI.galeriaAjax+'update_img_galeria';
    var data = {
        id_imovel: id_imovel,
        imagem:  $(this).data('imagem'),
        descricao: $(this).val(),
    };
    
    //console.log(data);
    
    $.ajax(
    {
        url: target,
        dataType: 'json',
        type: 'POST',
        data: data,
        success: function(result)
        {
            if(result.valid === true)
            {
                
            } 
            else 
            {
                
            }
        }
    });
});

updateColBtnUpload = function()
{
    if(ttImg < 1)
    {
        $('.col-lg-4.btn-upload').removeClass('col-lg-4').addClass('col-lg-12');
    }
    else
    {
        $('.col-lg-12.btn-upload').removeClass('col-lg-12').addClass('col-lg-4');
    }
}

$(document).on('click','.princ-img', function(){

    var obj = $(this);
    var target = base_url + 'comdono/ajax/galeria_ajax/main_img_galeria';
    var arr = {
        file: $(this).data('img')
    };

    $.ajax(
    {
        url: target,
        dataType: 'json',
        type: 'POST',
        data: arr,
        success: function(result)
        {
            if(result.valid === true)
            {
                var prev = $('.main').parent().parent().parent().parent();
                prev.find('img').removeClass('main');
                prev.find('.princ-img').removeAttr('disabled');
                
                obj.parent().parent().parent().find('img').addClass('main');
                obj.attr('disabled', true);
                
            } else {
                
                showModal('Erro', result.msg, 'warning');
            }
        }
    });
});

$(document).on('click', '.atualizar-alt', function(){

    var divNome = $(this).parent().parent().parent().find('.nome');
    var divInput = $(this).parent().parent();   

    var parametros = {
        alt: divInput.find('input[name=alt]').val(),
        imagem: divNome.data('img')
    };    

    var target = base_url + 'comdono/ajax/galeria_ajax/update_image_galery';
    $.ajax(
    {
        url: target,
        dataType: 'json',
        type: 'POST',
        data: parametros,  
        success:function(data) {
            if(data.valid === true)
            {
                divNome.removeClass('hidden').html(parametros.alt);
                divInput.addClass('hidden');
                divInput.find('input[name=alt]').val('');
            }
            else
            {
                divInput.find('input[name=alt]').val('');
            }
        }
    }); 
});

$('.delete-toggle').on('click', function(){
    var body = '<div id="retorno" class="alert alert-warning" role="alert" style="display:none;"></div>'+
               '<p>Deseja excluir todas as imagens selecionadas?</p>';
    
    showModal('Excluir imagem', body, 'warning', 'Excluir', 'danger');
});

$('#modal').on('click', '#btn_confirmar', function()
{
    var link = base_url+URI.galeriaAjax+'deletar?id_imovel='+id_imovel+'&file=';

    $.when(
        $('.checkbox').each(function() {
            if(true === $(this).prop("checked") && $(this).parents('tr:not(.clone)')){
                
                var fileUrl = $(this).data('url').split("=");
                var file = fileUrl[fileUrl.length-1];
                var selected = $(this).parents('tr:not(.clone)');             
    
                $.ajax(
                {
                    url: link+file,
                    type: 'GET',
                    dataType: 'json',
                    success:function() {
                        selected.remove();
                        $('#modal').modal('hide');
                    } 
                });
            }
        })
    ).then(function() {
        $('.toggle-galery').prop('checked', false);
        
        $('.checkbox').each(function() {
            $(this).prop('checked', false);
        });
    });
});

// Selecionar todas as checkbox
$(".toggle-galery").change(function()
{
    if($(".checkbox").parents('li:not(:first-child)'))
    {
        $(".checkbox").prop('checked', $(this).prop("checked"));
    }
});
 

$('.checkbox').change(function()
{ 
    // Desmarcar "selecionar todos" se um dos ítens for desmarcado
    if(false === $(this).prop("checked"))
    {
        $(".toggle-galery").prop('checked', false);
    }

    // Marcar "selecionar todos" se todos os ítens estiverem marcados
    if ($('.checkbox:checked').length == $('.checkbox').length )
    {
        $(".toggle-galery").prop('checked', true);
    }
});

/*excluir foto*/
$(document).on('click', '.act-click', function(){
    
    var value = $(this).parent().find(".container-exluir.pergunta").show();
    $(this).hide();
    
    var btn = $(this);
    
    setTimeout(function(){
        btn.parent().find(".container-exluir.pergunta").hide();
        btn.show();
    }, 3000);
    
});


/* -------------------- File Upload -------------------- */

function getIdImovel(){
    return $('#id_imovel').val();
}

function getMeuCadastro()
{
    return $('#meuCadastro').data('meucadastro');
}

/*function getDadosPerfil()
{
    xVal = $("input[name='doc_perfil']:checked").val()
    return (xVal == undefined) ? 'xxx' : xVal;
}*/

function iniFileupload(){

$(function () {
    
    //'use strict';
    // Initialize the jQuery File Upload widget:
    id_cadastro=0;
    
    if(typeof getMeuCadastro() !== typeof undefined){
        id_cadastro = getMeuCadastro().id_cadastro;
    }
    
    
    //id_cadastro = (getMeuCadastro().id_cadastro != undefined)?getMeuCadastro().id_cadastro:0;
    
    $('#fileupload').fileupload({
        dropZone: $('#fileupload_div'),
        formData: {id_imovel: getIdImovel(), id_cadastro: id_cadastro},
        url: base_url + URI.galeriaAjax+'do_upload_galery',
        autoUpload: true,
        acceptFileTypes: /(\.|\/)(gif|jpeg|jpg|png)$/i,
        //maxFileSize: 1024 * 468 * 1,
        maxFileSize: 1024 * 1024 * 20, // 3 Mb NA TEORIA
        // Enable image resizing, except for Android and Opera,
        // which actually support image resizing, but fail to
        // send Blob objects via XHR requests:
        disableImageResize: /Android(?!.*Chrome)|Opera/
            .test(window.navigator.userAgent),
        previewMaxWidth: 668,
        previewMaxHeight: 350,
        previewCrop: true,
        messages : {
          maxNumberOfFiles: 'Limite máximo atingido',
          acceptFileTypes: 'Extensão não permitida',
          maxFileSize: 'Limite máximo permitido de 1Mb',
          minFileSize: 'Imagem menor que... '
        },
        uploadTemplateId: null,
        uploadTemplate: function (o) {
        var rows = $();
        
        ttImg = ttImg + 1;
        
        if(ttImg == 1){
            var col = 'col-lg-12';   
            var gridH = 'principal';
        }
        else
        {
            var col = 'col-lg-4';
            var gridH = 'grid';
        }
        
        $.each(o.files, function (index, file) {
            var row = $('<div class="template-upload '+col+'">' +
                    '<div class="box">' +
                        '<div class="progress-upload"></div> ' +
                        '<div class="content-img '+gridH+'">' +
                            '<span class="preview"></span>' +
                        '</div>' +
                    '</div>' +
                '</div>' 
                );
            row.find('.name').text(file.name);
            row.find('.size').text(o.formatFileSize(file.size));
            if (file.error) {
                row.find('.error').text(file.error);
            }
            rows = rows.add(row);
        });
        return rows;
    },
        
    })
    .bind('fileuploadadd', function(e,data) {
        var currentfiles = [];
        $(this).fileupload('option').filesContainer.children().each(function(){
            currentfiles.push($.trim($('.name', this).text()));
            console.log($.trim($('.name', this).text()))
        });
        data.files = $.map(data.files, function(file,i){
            if ($.inArray(file.name,currentfiles) >= 0) { 
                return null; 
            }
            return file;
        });
    })
    .bind('fileuploadadded', function (e, data) {
        
      
        var cloneLoad = '<li class="sort-item container-upload-load '+data.originalFiles[0].lastModified+'">';
        cloneLoad += '<div class="box text-center container-img-load">';
        cloneLoad += '<label><i class="fa fa-circle-o-notch fa-spin"></i></label>';
        cloneLoad += '</div></li>';
        $('#sortable').append(cloneLoad);
        
    })
    .fileupload().bind('fileuploaddone', function (e, data) 
    {        
        $('.container-upload-load.'+data.originalFiles[0].lastModified).remove();
        
        //var error = data.result.file.error;
        //if(error === undefined)
        if(data.result.valid == true)
        {
            
            updateColBtnUpload();
            var img = data.result.file.name;
            var result = {
                id_imovel: id_imovel,
                uri: data.result.file.uri,
                imagem: img, 
                size: data.result.file.size,
                edit_lancamento: edit_lancamento
            };
            
            update(result);
            
            var clone = '<li class="sort-item" data-id="" data-name="'+data.result.file.name+'" >';
            clone += '<div class="box">';
            clone += '<div class="container-actions container-move icon icon-move d-none-767"><i class="fa fa-arrows" aria-hidden="true"></i></div>';
            clone += '<div class="container-actions container-exluir icon act-click" data-id="0"><i class="fa fa-times" aria-hidden="true"></i></div>';
            clone += '<div class="container-actions container-exluir pergunta excluir_foto" data-pergunta="0" data-url="'+data.result.file.deleteUrl+'" >Remover?</div>';
	        clone += '<a href="'+data.result.file.url+'" title="'+data.result.file.name+'" download="'+data.result.file.name+'" data-gallery="" class="previewLink" >';
	        clone += '<div class="content-img grid" style="background-image: url('+data.result.file.url+');"></div>';
            clone += '</a>';
        	clone += '</div>';
        	clone += '<div class="add-legenda"><input  class="descricao_imagem"  type="text" name="descricao" value=""  data-imagem="'+data.result.file.name+'" placeholder="Adicionar Legenda"></div>';
            clone += '</li>';
            
            $('#sortable').append(clone);
            
            ajusta_height();
        } 
        else
        {
            alert(data.result.msg);
            //alert('Erro ao carregar imagem', body, 'danger');
        }
    })
    .bind('fileuploadprocessfail', function (e, data) {
      
        var error = data.files[0].error;
        $.growl.error({
          title: "Ops!",
          message: error
        });
    });
}); 

}


function update(parametros)
{
    var target = base_url + URI.galeriaAjax+'update_galery';
    $.ajax(
    {
        url: target,
        dataType: 'json',
        type: 'POST',
        data: parametros,
        success: function(result) {
            $('li[data-name="'+parametros.imagem+'"]').attr('data-id',result.id_img_rel);
        }
    });
}

function bytesToSize(bytes, precision)
{  
    var kilobyte = 1024;
    var megabyte = kilobyte * 1024;
    var gigabyte = megabyte * 1024;
    var terabyte = gigabyte * 1024;    

    if ((bytes >= 0) && (bytes < kilobyte)) 
    {
        return bytes + ' B';
    }
    else if ((bytes >= kilobyte) && (bytes < megabyte)) 
    {
        return (bytes / kilobyte).toFixed(precision) + ' KB';
    } 
    else if ((bytes >= megabyte) && (bytes < gigabyte)) 
    {
        return (bytes / megabyte).toFixed(precision) + ' MB';
    } 
    else if ((bytes >= gigabyte) && (bytes < terabyte)) 
    {
        return (bytes / gigabyte).toFixed(precision) + ' GB';
    } 
    else if (bytes >= terabyte) 
    {
        return (bytes / terabyte).toFixed(precision) + ' TB';
    } 
    else 
    {
        return bytes + ' B';
    }

}

function galeria()
{
    $(document).on('click', '.preview', function(event){
        event = event || window.event;
        //console.log(event.target)
        var target = event.target || event.srcElement,
            link = target.src ? target.parentNode : target,            
            options = {index: link, event: event, hidePageScrollbars: false},
            /*options = {index: link, event: event},*/
            links = $('.preview').find('a');
            //console.log(links)
        blueimp.Gallery(links, options);
    });
}