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

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

$(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);
    
    $.ajax(
    {
        url: btn_deletar.data('url'),
        type: 'GET',
        dataType: 'json',
        success: function(result)
        {
            if(result.valid === true)
            {
                btn_deletar.parent().parent().remove();
                ttImg--;
                updateColBtnUpload();
                
                ajusta_height();
            }
            else 
            {
                alert('deu ruim');
            }
        }         
    });
});

$('body').on('change', '.descricao_imagem', function(){
    
    var target = base_url + 'comdono/ajax/galeria_ajax/update_img_galeria';
    var data = {
        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()
{
    //console.log(ttImg)
    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+'comdono/ajax/galeria_ajax/deletar?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);
    }
});



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

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

$(function () {
    
    //'use strict';
    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
        dropZone: $('#fileupload_div'),
        formData: {id_imovel: getIdImovel()},
        url: base_url + 'comdono/ajax/galeria_ajax/do_upload_galery',
        autoUpload: true,
        acceptFileTypes: /(\.|\/)(gif|jpeg|jpg|png)$/i,
        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 10 Mb',
          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('fileuploadadded', function (e, data) {
      
        
        
        var cloneLoad = '<div class="col-lg-4 container-upload-load '+data.files[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></div>';
        $(cloneLoad).insertBefore($('.btn-upload'));
        
    })
    .fileupload().bind('fileuploaddone', function (e, data) 
    {      
        //console.log(data);    
        $('.'+data.files[0].lastModified).hide();
        
        var error = data.result.files[0].error;
        if(error === undefined)
        {
            
            updateColBtnUpload();
            var img = data.result.files[0].name;
            var result = {
                id_imovel: id_imovel,
                uri: data.result.files[0].uri,
                imagem: img, 
                size: data.result.files[0].size
            };
            
            update(result);
            
            var col = (ttImg == 1) ? 'col-lg-12' : 'col-lg-4';
            var gridH = (ttImg == 1) ? 'principal' : 'grid';
            var clone = '<div class="'+col+'">';
            clone += '<div class="box">';
            clone += '<div class="container-exluir icon act-click" data-id="0"><i class="material-icons"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="none" d="M0 0h24v24H0V0z"/><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z"/></svg></i></div>';
            clone += '<div class="container-exluir pergunta excluir_foto" data-pergunta="0" data-url="'+data.result.files[0].deleteUrl+'" >Remover?</div>';
	        clone += '<a href="'+data.result.files[0].url+'" title="'+data.result.files[0].name+'" download="<?php e($imagens[$i]->imagem); ?>" data-gallery="" class="previewLink" >';
	        clone += '<div class="content-img '+gridH+'" style="background-image: url('+data.result.files[0].url+');"></div>';
            clone += '</a>';
        	clone += '</div>';
        	clone += '<div class="add-legenda"><input  class="descricao_imagem"  type="text" name="descricao" value=""  data-imagem="'+data.result.files[0].name+'" placeholder="Adicionar Legenda"></div>';
            clone += '</div>';
            
            $(clone).insertBefore($('.btn-upload'));
            
            ajusta_height();
            
        } 
        else
        {
            alert(error);
            alert('Erro ao carregar imagem', body, 'danger');
        }
    })
    .bind('fileuploadprocessfail', function (e, data) {
      
        var error = data.files[0].error;
        $.growl.error({
          title: "Ops!",
          message: error
        });
       
        
    });

    // Load existing files:

    //$('#fileupload').addClass('fileupload-processing');

}); 



function update(parametros)
{
    //console.log(parametros);
    var target = base_url + 'comdono/ajax/galeria_ajax/update_galery';
    $.ajax(
    {
        url: target,
        dataType: 'json',
        type: 'POST',
        data: parametros
    });
}

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);
    });
}



/*$('#modalImg').on('show.bs.modal', function (e) {
    
    $('input[name=principal]').iCheck(
    {
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });    

    clicked = $(e.relatedTarget);
    var name = clicked.parent().parent().parent().find('.nome').text().trim();
    var desc = clicked.parent().parent().parent().find('input[name=descricao_img]').val();
    var src = clicked.parent().parent().parent().find('.previewImg').attr('src');
    var isPrincipal = clicked.parent().parent().parent().find('.previewImg').hasClass('main');
    var deleteUrl = clicked.parents('.image-block').find('input[type=checkbox]').data('url');
    var image = src.split('/').pop();    
    
    src = src.replace("thumbnail", "medium");

    clicked.parent().parent().parent().find('input[name=descricao_img]').attr('id', 'current_description');
    clicked.parent().parent().parent().find('.nome').attr('id', 'current_name');

    $(this).find('input[name=alt]').val(name);
    $(this).find('input[name=descricao_img]').val(desc);
    $(this).find('input[name=file]').val(image);
    $(this).find('img').attr('src', src);
    $(this).find('.btn-danger').attr('data-url', deleteUrl);    

    if(isPrincipal === true)
    {
        $('input[name=principal]').iCheck('check');
        //$(this).find('input[type=checkbox]').prop( "checked", true );
    } else {
        $('input[name=principal]').iCheck('uncheck');
        //$(this).find('input[type=checkbox]').prop( "checked", false );
    }
});*/

/*$('#modalImg .btn-danger').on('click', function(e){
    var url = $(this).data('url');
    var btn = $('.galeria').find('[data-url="'+url+'"]');
    btn.trigger('click');
    //$('#modalImg').modal('hide');
});*/

/*$('#modalImg .btn-success').on('click', function(e){
    var btn = $(this);
    var target = base_url + 'comdono/ajax/galeria_ajax/update_img_galeria';
    var arr = $("form").serialize();

    $.ajax(
    {
        url: target,
        dataType: 'json',
        type: 'POST',
        data: arr,
        success: function(result)
        {
            if(result.valid === true)
            {
                $('#retorno').addClass('alert-success');
                $('#retorno').removeClass('alert-danger');

                $('#current_description').val(result.desc);
                $('#current_name').text(result.name);
                
                if ($('#modalImg input[type=checkbox]').is(':checked')) {
                    var prev = $('.main').parent().parent().parent().parent();
                    prev.find('img').removeClass('main');
                    prev.find('.princ-img').removeAttr('disabled');
                    
                    var alt = $('form input[name=alt]').val();
                    
                    clicked.parent().find('.princ-img').attr('disabled', true);
                    clicked.parent().parent().parent().find('img').addClass('main');

                }

            } else {
                $('#retorno').addClass('alert-danger');
                $('#retorno').removeClass('alert-success');
            }
            $('#retorno').text(result.msg).fadeIn('fast');
        }

    });

});*/

/*$('#modalImg').on('hide.bs.modal', function (e) {
    $('input[name=principal]').iCheck('destroy');
    $('#modalImg').find('input[name=alt]').val('');
    $('#modalImg').find('input[name=file]').val('');
    $('#modalImg').find('input[name=descricao]').val('');
    $('#modalImg').find('img').attr('src', '');
    $('#modalImg').find('.btn-danger').attr('data-url', '');
    $('#current_description').removeAttr('id');
    $('#current_name').removeAttr('id');
    $('#retorno').text('');
    $('#retorno').css('display', 'none');
    clicked = null;
})*/