<link rel="stylesheet" type="text/css" href="<?php echo $this->config->item('admin_assets_folder'); ?>dist/css/dropzone.css">
<script src="<?php echo $this->config->item('admin_assets_folder'); ?>dist/js/dropzone.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="<?php echo $this->config->item('admin_assets_folder'); ?>dist/js/bootstrap.min.js"></script>

<script type="text/javascript">
    var base_url = "<?php echo base_url().$this->config->item('admin_folder'); ?>";
    var m1 = true;
    var input_type = "";
    var main_div = "show_selected_media";

    $(document).ready(function(){
    	get_media_count();
        var a = $("#media_count").val();
        load_more(a, 0);

        $(".show_selected_media").sortable({ 
            tolerance: 'pointer', 
            update: function(event, ui) {
                var h = "";
                $(".show_selected_media").find(".ui-sortable-handle").each(function(){
                    h += $(this).find(".selected_media_ids").val()+",";
                });
                h = h.replace(/,\s*$/, "");
                $(this).parent().children("input[type='hidden']:first").val(h);
            }
        });
    });

	$(function () {

        $("#add_new_media").click(function () {
            if ($(this).attr("data-value") == "hide") {
                $("#add_media_div").fadeIn();
                $(this).attr("data-value", "show");
            } else {
                $("#add_media_div").fadeOut();
                $(this).attr("data-value", "hide");
            }
        });
    });


    Dropzone.options.myAwesomeDropzone = {
        maxFilesize: 5000, // Size in MB
        paramName: "file",
        uploadMultiple: true,
        timeout:500000,
        //addRemoveLinks: true,
        parallelUploads: 100,
        //acceptedFiles: 'image/*, video/*, application/pdf, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/docx, application/msword, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        /*removedfile: function(file) {
            var fileRef;
            return (fileRef = file.previewElement) != null ? fileRef.parentNode.removeChild(file.previewElement) : void 0;
        },*/
        success: function(file, response) {
            response = JSON.parse(response);
            if(response["status"] == true){
                $("#success_message").html(response["message"]);
                $(".alert.alert-success").fadeIn();
                /*if(response["errors"] != ""){
                    $("#error_message").html(response["errors"]);
                    $(".alert.alert-danger").fadeIn();
                }*/

                
            }else{
                $("#error_message").html(response["message"]);
                $(".alert.alert-danger").fadeIn();
            }

            setTimeout(function(){

                //$(".alert").fadeOut();
                if(response["result"]){
                    $("#media_data").prepend(response["result"]);
                    $('label.image-checkbox').addClass(input_type); 
                }
                var media_index = $("#media_index").val();
                if(media_index == 1){
                    mediadatatable.draw();
                }

                $(".alert").fadeOut();
            }, 1000);
        },
        queuecomplete: function(){
            this.removeAllFiles();
        },
        error: function(file, response) {
            console.log(response);
        }
    }

    function get_media_count(){
    	$.ajax({
            type: "POST",
            dataType: "json",
            global:false,
            url: base_url+'/media/get_media_count',
            success: function(result) {
                if(result["status"] == true){
                    $("#media_count").val(result["total_count"])
                }
            }
        });
    }

    function remove_media(id){
        $.ajax({
            type: "POST",
            dataType: "json",
            url: base_url+'/media/remove_media',
            data: {
                'id' : id
            },
            success: function(result) {
                if(result["status"] == true){
                    $("#sort_"+id).fadeOut('slow');
                }
            }
        });
    }

    $("#media_data").scroll(function() {
        /*var m = $('.show_more');
        alert(m.length);
        if (m.length) {*/
            var a = $("#media_count").val();
            var hT = $('.show_more').offset().top,
                hH = $('.show_more').outerHeight(),
                wH = $("#media_data").height(),
                wS = $(this).scrollTop()
                page_no = $("#page_no").val();
            //if (wS < (hT + hH - wH) && (hT > wS) && (wS + wH < hT + hH) && a > 12 && m1) {
            if (a > 12 && m1) {
                m1 = false;
                load_more(a, page_no);
            }
        //}
    });

    function load_more(total_count, page_no){
        page_no = parseInt(page_no) + 1;

        $.ajax({
            type: "POST",
            dataType: "html",
            global:false,
            url: base_url+"/media/load_more",
            data: {
                'total_count' : total_count,
                'page_no' : page_no
            },
            success: function(result) {
                if(result){
                    m1 = true;
                    $("#media_data").append(result);
                    $("#page_no").val(page_no);

                    $('label.image-checkbox').removeClass("radio_div");
					$('label.image-checkbox').removeClass("checkbox_div");
					$('label.image-checkbox').addClass(input_type); 
                }else{
                    m1 = false;
                }        
            }
        });
    }


    $(document).on("click", ".checkbox_div", function (e) {
        $(this).toggleClass('image-checkbox-checked');
        var $checkbox = $(this).find('input[type="checkbox"]');
        $checkbox.prop("checked",!$checkbox.prop("checked"));
        e.preventDefault();
    });


    $(document).on("click", ".radio_div", function (e) {
        
        $(".radio_div").find(".hc_media").removeAttr('checked');
        $(".radio_div").removeClass("image-checkbox-checked");


        $(this).toggleClass('image-checkbox-checked');
        var $radio = $(this).find('input[type="checkbox"]');
        $radio.attr("checked", "checked");
        e.preventDefault();
    });

    $('#media_modal').on('show.bs.modal', function (event) {
		var button = $(event.relatedTarget);
		var type = button.data('type');
		var show_div = main_div = button.data('showdiv');
        var id = button.data('id');
		var modal = $(this);

		$(".hc_media").removeAttr('checked');
        $("label.image-checkbox").removeClass("image-checkbox-checked");

		modal.find('label.image-checkbox').removeClass("radio_div");
		modal.find('label.image-checkbox').removeClass("checkbox_div");
		modal.find('label.image-checkbox').addClass(type);
		modal.find('button#media_select').attr("data-showdiv", show_div);
		modal.find('button#media_select').attr("data-id", id);
        modal.find('button#media_select').attr("data-type", type);

		input_type = type;
	});

	$(document).on("click", "button#media_select", function(){
		var show_div = main_div = $(this).attr("data-showdiv");
        var a = $(this).attr("data-id");
		var select_type = $(this).attr("data-type");
		var selected_id = [];
		if($("#"+a).val()){
            selected_id = $("#"+a).val().split(",");   
        }

        var id = [];
        var images = [];
        var i = 0;

        $("label.image-checkbox").each(function () {

        	var $checkbox = $(this).find('input[type=checkbox]');

        	if ($(this).find('input[type=checkbox]').is(":checked")) {
        		if(select_type == "radio_div"){
					id = [];
		            images = [];
		            selected_id = [];
		    	}


	        	id.push($checkbox.val());
	            images.push($(this).find('img').attr("data-url"));

	            selected_id.push($checkbox.val());
                if(select_type == "radio_div"){
                    $(this).prop('checked', false); 
                }else{
                    $checkbox.prop("checked",!$checkbox.prop("checked"));
                }
	            //
                

	            $(this).removeClass("image-checkbox-checked");
	        }

        });

        $("#"+a).val(selected_id.join(','));

        console.log(id);
        console.log(images);
        console.log(a);


        $.ajax({
            type: "POST",
            dataType: "html",
            global:false,
            url: base_url+"/media/load_selected_media",
            data: {
                'id' : id,
                'images' : images,
                'field_name': a,
                'select_type' : select_type
            },
            success: function(result) {
                if(result){

                    if(select_type == "radio_div"){
                        $("."+show_div).html("");
                        $("."+show_div).html(result);
                    }else{
                        $("."+show_div).append(result);
                    }

                    
                    if($("#is_sortable").val() == 1){
                        $("."+show_div).sortable();
                    }
                }     
            }
        });

	});

    $(document).on("click", ".remove_selected_media", function(){
        var field_name = $(this).data("field");
        var selected_id = $(this).data("id");
        var select_type = $(this).data("type");
        var id = $("#id").val();
        var thisVal = $(this);

        $.ajax({
            type: "POST",
            dataType: "json",
            global:false,
            url: base_url+"/media/remove_selected_media",
            data: {
                'selected_id' : selected_id,
                'id' : id,
                'field_name': field_name,
                'select_type' : select_type
            },
            success: function(result) {
                if(result["status"] == true){
                    thisVal.parent().parent().fadeOut();
                    thisVal.parent().parent().remove();

                    if(select_type == "radio_div"){
                       $("#"+field_name).val(""); 
                    }else{
                        var a = $("#"+field_name).val();
                        var arr = a.split(",");
                        arr.splice($.inArray(selected_id, arr),1);
                        $("#"+field_name).val(arr.join(','));
                    }
                }     
            }
        });
    });

    $('#search_value').keypress(function(event){
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if(keycode == '13'){
            search_result();
        }
    });

    function search_result(){
        var page_no = 1;
        var total_count = $("#media_count").val();

        $.ajax({
            type: "POST",
            dataType: "html",
            global:false,
            url: base_url+"/media/load_more",
            data: {
                'total_count' : total_count,
                'page_no' : page_no,
                'search_value' : $("#search_value").val()
            },
            success: function(result) {
                if(result){
                    m1 = true;
                    $("#media_data").html(result);
                    $("#page_no").val(page_no);

                    $('label.image-checkbox').removeClass("radio_div");
                    $('label.image-checkbox').removeClass("checkbox_div");
                    $('label.image-checkbox').addClass(input_type); 
                }else{
                    m1 = false;
                }       
            }
        });
    }

</script>