@extends('layouts.app')

@section('content')
    {{--<div class="crumbs">--}}
    {{--<ul>--}}

    <?php $active_unit = $subtask->task->unit; ?>


    @if($user->userCanViewSubtask($subtask->id))


        <div class="breads">

            @if($user->canCreateSubtask($subtask->task->unit_id) || $subtask->task->userTagCanViewTask($subtask->task->id,$subtask->task->unit_id))
                <a  class="btn btn-default " href="{{URL::to('/')}}/tasks/{{$subtask->task->id}}/unit/{{$subtask->task->unit_id}}/show"><< Volver a la tarea </a>
            @endif
        </div>

    {{--</ul>--}}

    <br>
    <br>

    @if(session()->has('message'))
        <div class="alert alert-success alert-dismissable">
            <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>

            {{ session()->get('message') }}
        </div>
    @endif
    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    <div class="task-single">
        <div class="task-header">
            <div class="task-panel ">
                <div class="task-panel-main panel">
                    <h4>{{ $subtask->title }}</h4>

                    <h5 style="font-weight: 600">Descripción:</h5>
                    <div class="task-description">
                        {!!  $subtask->description !!}

                    </div>
                </div>
                <div class="task-panel-secondary ">


                    <div class="task-panel-secondary-inside panel">


                        <h5><b>Creada por</b>: {{ $subtask->createdBy->name }} {{ $subtask->createdBy->surname }} </h5>
                        <h5><b>Asignada a:</b> {{ $subtask->assignedTo->name }} {{ $subtask->assignedTo->surname }}
                        <h5><b>Creada:</b> {{ date('d-m-Y', strtotime(str_replace('/', '-', $subtask->created_at)))  }}
                        </h5>


                        <h5><b>Estado:</b>
                            <form style="margin-top: 3px;"action="{{ URL::to('/') }}/subtasks/update-status" method="post">
                                <select name="status_id" id="">
                                    {{--<option value="">Seleccionar estado</option>--}}

                                    @foreach($statuses as $status)
                                        <?php  if ($subtask->status->id == $status->id) {
                                            $selected = 'selected';
                                        } else {
                                            $selected = '';
                                        }; ?>
                                        <option {{ $selected }} value="{{$status->id}}">{{ $status->name }}</option>
                                    @endforeach

                                </select>
                                <input type="hidden" name="_token" value="{{ csrf_token() }}">

                                <input type="hidden" name="id" value="{{ $subtask->id }}">
                                <input type="hidden" name="user" value="{{ $user->id }}">
                                <input style="position:relative;top:-2px;" type="button" class="btn btn-primary btn-xs" value="cambiar" onclick="form.submit()">
                            </form>
                        </h5>
                        <h5>Lapso de tiempo de trabajo: <i style="color: #019d95">{{$timeInSubtask}}</i></h5>

                    </div>
                </div>
            </div>
            <br>
            <br>

        </div>


{{---------------------------Etiquetar Usuario-------------------------------------------}}

        <div class="panel panel-default"  id="#takstags">

            @if($user->canTagOthers())
                <div class="panel-heading">

                    <input type="hidden" name="_token" value="{{ csrf_token() }}">
                    <input type="hidden" name="type" value="task">
                    <input type="hidden" name="relation_id" value="{{ $subtask->id }}">
                    {{--<input type="hidden" name="user_id" value="obtener usuarios"  >--}}

                    <div class="form-group" style="width: 50% ;font-weight: normal;">
                        <h4>Etiquetar usuarios</h4>
                        <div class="s2-example" style="">

                            <select class="js-example-data-array" multiple="multiple" data-placeholder="" id="userTL" name="selectUser[]"  style="width:80%">
                                <option value="" >Seleccione usuario</option>

                                @foreach($users as $u)

                                    <option  value="{{$u->id}}">{{$u->name}}</option>

                                @endforeach

                            </select>
                            <button class="btn btn-primary" id="etiquetar">+</button>
                    </div>
                    </div>

                </div>

            @endif

            <div   id="tabla_tasktags_ajax"  class="panel-body" style="font-size: small"  >
                <h4>Etiquetados :<br></h4>

                @foreach($usersEtiq as $index=>$u)


                    <button id="user-{{$index}}">
                        <span class="glyphicon-class"></span><label>{{$u['name']}}&nbsp&nbsp</label>

                        @if($user->canTagOthers())

                            <span onClick=untag({{$index}})  class="glyphicon glyphicon-remove" aria-hidden="true"> </span>
                        @endif

                    </button>

                @endforeach

            </div>

        </div>
{{-----------------------fin etiquetar     --------------------}}
        <br>
        <div class="task-bottom">
            <div class="comments-container">
                @include('comments::comments-react', [
                    'content_type' => App\Subtask::class,
                    'content_id' => $subtask->id,
                    'unit_id'=> $subtask->task->unit->id
                ])
            </div>
            <div class="task-sidebar">




                            <?php $exist = 0;?>

                            @if (is_countable($attachments))

                                @if($user->isTeamLeaderInUnit($task->unit_id ))

                                <div class="sidebar-container panel">

                                <div class="form-group" >
                                    <h5 style="font-weight: 600;text-align: center">Agregar archivos de la tarea:</h5>
                                    
                                      <select multiple="" id="taskAttach_multiple" name="taskAttach_multiple" class="form-control" style="width:100%;text-align: center;display: none;font-size: 11px">


                                              @if (is_countable($attachdelivered))
                                            @foreach($attachdelivered as $v)

                                                <option title="Archivos entregados" disabled data-filename="{{ $v['filename'] }}" data-createdat="{{ date('d/m/Y', strtotime($v['created_at']))}}" class="attachtask_{{ $v['id'] }} opt_delivered" value="{{ $v['id'] }}" style="color: #BCBCBC;">{{ $v['original_name'] }}</option>

                                            @endforeach
                                        @endif                                          
                                        @foreach($task->attachments as $attach)

                                            {{--  $attachdelivered --}}

                                            @if(!in_array($attach->id, $subtaskattach)) 

                                            <option data-filename="{{ $attach->filename }}" data-createdat="{{ date('d/m/Y', strtotime($attach->created_at))}}" class="attachtask_{{ $attach->id }}" value="{{ $attach->id }}" >{{ $attach->original_name }}</option>

                                            @else

                                            <?php $exist++;?> 

                                            @endif

                                        @endforeach
                                      </select>
                                      <div class="alltach" style="display:none;text-align:center">Todos los archivos de la tarea fueron asignados a la subtarea.</div>

                                                                    
                                </div>
                                    <div style="text-align: center">
                        
                                    <button type="button" style="font-size: 11px;width: 154px;text-align: center;display:none;padding-left: 9px;" class="btn  btn-info btn-sm addsubtask" style="display:none">Agregar a la subtarea</button>

                                    </div>  
            
                                    </div>
                                    @endif
                            @endif


                            <div class="sidebar-container panel content_subAttach" >


{{-- dd($subtask_item->toArray()) --}}



                            <div class="no-content subAttach subtask_element">
                                

                                    @if (is_countable($subtask_item))


                                    <h5  style="font-weight: 600">Archivos adjuntos en la subtarea:</h5>
                                    @foreach($subtask_item as $attach)

{{-- <button type='button' onclick='deliverAttach($attach->id)' class='not_deliver btn btn-xs stack_newed elementTheTask deliver_$attach->id' >e</button>  --}}

                                <?php
                        
                                  if($attach->active == "1"){

                                    $isdeliver = "";

                                    if((!$attach->can_delivery)OR(($attach->delivered==0)AND($attach->can_delivery)AND($attach->deliveredtaskdeleted==0))){



                                        if($user->isTeamLeaderInUnit($task->unit_id )){
                                            $isdeliver = "<button type='button' title='Entregar a la tarea' alt='Entregar a tarea' onclick='deliverAttach($attach->id)' class='not_deliver btn btn-xs stack_newed elementTheTask deliver_$attach->id' >e</button> <i style='display:none' title='Archivo entregado a la tarea' class='fa fa-arrow-up delivered stack_newed elementTheTask nowdeliver_$attach->id' aria-hidden='true'></i>";
                                        }
                                    }elseif($attach->delivered==1){


                                         $isdeliver = "<span title='Archivo entregado a la tarea' alt='Archivo entregado a la tarea'><i  class='fa fa-arrow-up delivered stack_newed elementTheTask nowdeliver_$attach->id' aria-hidden='true'></i></span>";

                                    /*     $isdeliver = "<button title='entregado a la tarea' type='button' onclick='deliverAttach($attach->id)' class='delivered btn btn-xs stack_newed elementTheTask deliver_$attach->id'>e</button>";   */

                                    }

                                    ?>

                                     <div data-fileatta="{{$attach->filename}}" data-dateatta="{{ date('d/m/Y', strtotime($attach->created_at))}}" data-nameatta='{{ $attach->original_name }}' class="bdn subattachtask_element subattachtask_{{$attach->id}}"><a href='{{URL::to('/')}}/download/{{$attach->id}}' target='_blank'>{{ $attach->original_name}}<span class='minidatetask_{{$attach->id}}' style='margin-left: 6px;font-size: 11px;font-style: inherit;'>{{ date('d/m/Y', strtotime($attach->created_at))}}</span></a><button title='Eliminar archivo' alt='Eliminar archivo' type='button' onclick='subdeleteAttach({{ $attach->id}},false,"{{ $attach->original_name}}")' class='btn btn-danger btn-xs stack_deleted elementTheTask'>x</button><?php echo $isdeliver;?></div>
     
                                <?php 

                                }else{ 


                                    $attaname4 = '"'.$attach->original_name.'"';

                                     $activatebn = "<button title='Activar archivo' alt='Activar archivo 3333333' style='font-size: 8px !important;margin-bottom: 9px;margin-top: -3px;margin-left: 14px;padding-left: 2px;' type='button' onclick='subdeleteAttach($attach->id,true,$attaname4)' class='btn btn-success btn-xs stack_deleted elementTheTask'><i class='fa fa-check'></i></button>";

                                    ?>

                                     <div data-fileatta="{{$attach->filename}}" data-dateatta="{{ date('d/m/Y', strtotime($attach->created_at))}}" data-nameatta="{{ $attach->original_name}}" class="bdn subattachtask_element subattachtask_{{$attach->id}}"><div class="eliminado_{{$attach->id}} bdn subattachtask_element subattachtask_{{$attach->id}}" style="color: #979797">{{ $attach->original_name}}<span class="datin" style='margin-left: 6px;font-size: 11px;font-style: inherit;color: #979797;'>{{ date('d/m/Y', strtotime($attach->created_at))}}</span>{!! $activatebn !!}</div></div>
                                    
                                <?php
                                }
                                ?>

                            
                                 @endforeach
                                @else
                                <div class="subtask_text_borrador">No se encontraron archivos Adjuntos</div>
                                @endif

                            </div>



                            <div class="form-group box_supArchivo" style="text-align:-webkit-center">

                            <div class="subtask_temporal_progress">

                                <progress class="barProgress_subtask" max="100" value="0" style="display: none;margin-bottom: 6px;margin-left: 12%;margin-right: 12%"><span id="textProgress_subtask">22</span></progress>
                                <ul id="file-upload-progress_subtask" class="list-unstyled">
                                </ul>
                                <ul id="file-upload-list" class="list-unstyled file-upload-list_subtask" data-type="subtask">
                                </ul>

                            </div>            

                                <input type="hidden" name="jsonIdAttachments" id="jsonIdAttachments_subtask" value="">
                                <input type="hidden" name ="_token" value ="{{ csrf_token() }}" />
                                <input type="hidden" id="subtask_id" name="subtask_id" value="{{ $subtask->id }}">
                            </div>
                            <div class="nuevo_div">
                                <div>
                                    <button type="button" id="buttonDownload" style="width: 90px;display:none" class="btn btn-primary">Descargar</button>
                                    <span class="btn btn-success fileinput-button box_elegirArchivo" style="visibility: hidden">
                                        <i class="icon-plus icon-white"></i>
                                        <span>Subir Archivos </span>
                                        <input id="fileupload" class="fileupload" data-type="subtask" multiple type="file" name="file" data-url="{{ url('upload') }}" style="display: inline;">
                                        
                                    </span>
                                  </div>
                            </div>
                            <input type="hidden" class="delivered_active" value="1">

                            </div>

        </div>
    </div>

@else
    <?php $exist = 0;?> {{----se rompe si borra esta linea ----}}

    <div class="task-panel-main panel" style="height: 10%">

        <h5 style="margin: 3%">No tiene permiso de ver esta subtarea.</h5>

    </div>

@endif

    <style>

    .panel-footer.text-right .btn {
        display: none;
    }
    .bdn{
        color: red;
        height: 20px;
        font-size: 11px;
    }
    .stack_deleted{

        position: absolute !important;
        margin-left: 20px;
        line-height: 8px;
        height: 14px;
        font-size: 11px;
        width: 14px;
        padding-left: 3px;

    }

    .datin{
        margin-left: 2px;
        font-size: 11px;
        font-style: inherit;
        color: #979797;
        opacity: 0.7;
    }
    .stack_newed{
        color: white;
        float: none;
        height: 16px;
/*      background-color: orange;  */
        left: 40px;
        line-height: 2px;
        padding-left: 2.5px;
        top: 0px;
/*      font-weight: bold;  */
        height: 14px;
        margin-left: -2px;
        width: 14px;
        position: relative;
    } 


    .not_deliver{
        background-color: #FF8000;
        border-color: #FF8000;
        color:white;
    }

    .delivered{
/*      background-color: #549E54;
        border-color: #549E54;  */
        color:#549E54;
        margin-left: -6px;
    }


    .not_deliver:hover{
        background-color: #FF8000;
        border-color: #FF8000;
        color:white;
    }

    .delivered:hover{
/*      background-color: #549E54;
        border-color: #549E54;  */
        color:#549E54;
        margin-left: -6px;
    }
    .opt_delivered{
        color: #BCBCBC;
        background-color: #FFFFD2;
    }

    .stack_newed:focus{
    color:white;
    }
    </style>

    @endsection


    @section('scripts')
    <script>

        isteamleaderUnit = "{{ ($user->isTeamLeaderInUnit($task->unit_id ))?'1':'0' }}";


        function verifyAttachinTask(){

        

                $.ajax({

                    data: {task_id:{{ $task->id }},subtask_id:{{ $subtask->id }},getdelivered:true},
                    headers:{
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    },
                    dataType: 'json',
                    url:"{{ URL::to('/') }}/tasks/getAttachTask",
                    type:'POST',
                    success:  function (data) {

/*
                        console.log("aaaaaa");
                        console.log(data.attachs);
                        console.log(data.delivered);
                        console.log("vvvvvvvvv");

*/

                    $("#taskAttach_multiple").html("");

                        if(data.delivered){


                                    $("#taskAttach_multiple").html("");
                                

                                    linkAttach2 = "";

                                    data.delivered.forEach( function(valor2, indice, array) {


                                    var date = new Date(valor2.created_at);
                                    createdt = date.getDate()+'/'+(date.getMonth()+ 1)+'/'+date.getFullYear();



                                        linkAttach2 += '<option title="Archivos entregados" disabled data-filename="'+valor2.filename+'" data-createdat="'+createdt+'" class="attachtask_'+valor2.id+' opt_delivered" value="'+valor2.id+'" style="color: #BCBCBC;">'+valor2.original_name+'</option>';


                                    });

                                    $("#taskAttach_multiple").append(linkAttach2);

                            }




                        
                        if(data.attachs){

                            // console.log("sss 306");

                                if(!data.delivered){

                                    $("#taskAttach_multiple").html("");
                                }

                                    linkAttach = "";

                                    data.attachs.forEach( function(valor, indice, array) {


                                        linkAttach += '<option data-createdat='+valor.created_at+' data-filename="'+valor.filename+'" class="attachtask_'+valor.id+'" value="'+valor.id+'">'+valor.original_name+'</option>';


                                    });

                                    $("#taskAttach_multiple").append(linkAttach);

                            }


                                if($("#taskAttach_multiple option").length > 0){

                                    if(!$("#taskAttach_multiple").is(":visible")){

                                        $("#taskAttach_multiple").show();
                                        $(".alltach").hide();
                                        $(".addsubtask").show()

                                    }
                                }


                        dattachs   = (data.attachs)?data.attachs.length:0;
                        ddelivered = (data.delivered)?data.delivered.length:0;


                        if((dattachs + ddelivered) == 0){

                              $(".alltach").show();
                              $(".addsubtask").hide();
                              $("#taskAttach_multiple").hide();

                        }
                        
                    }
                });





        }





        function deliverAttach(id_item){



            if ( $(".deliver_"+id_item).hasClass("delivered") ) {
         
                swal(
                  'Entregado!',
                  'El archivo fue entregado a la tarea.',
                  'info'
                )

                $(".swal2-info").css("width","66px");
                $(".swal2-info").css("height","66px");
                $(".swal2-icon.swal2-info").css("line-height","70px");
                $(".swal2-confirm").attr("class","btn btn-primary swal2-confirm");

                return false; 
         
            }
         

            swal({
              title: 'Confirmar',
              text: "Estas seguro de enviar el archivo a la tarea?",
              type: 'warning',
              showCancelButton: true,
              confirmButtonColor: '#d33',
              cancelButtonColor: '#3085d6',
              confirmButtonText: 'Enviar'
            }).then((result) => {
              if (result.value) {




                $.ajax({

                    data: {task:{{ $task->id }},attachitem:id_item},
                    headers:{
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    },
                    dataType: 'json',
                    url:"{{ URL::to('/') }}/subtasks/{{ $subtask->id }}/deliverAttachsubtask",
                    type:'POST',
                    success:  function (data) {

                        if(data.status == "ok"){

                            //console.log(data);

                            swal(
                              'Entregado!',
                              'El archivo fue entregado a la tarea.',
                              'success'
                            )


                            $(".deliver_"+id_item).hide();
                            $(".nowdeliver_"+id_item).show();


                            verifyAttachinTask();

                        }
                    }
                });

              }
            })


            $(".swal2-confirm").attr("class","btn btn-danger swal2-confirm");
        //  $("swal2-popup").css("width","400px");
            $(".swal2-cancel").css("margin-left","6px");
            $(".swal2-cancel").attr("class","btn btn-primary swal2-cancel");
            $(".swal2-warning").css("width","66px");
            $(".swal2-warning").css("height","66px");
            $(".swal2-icon.swal2-warning").css("line-height","70px");



     
       }


       <?php $alltaskattach  = json_encode($alltaskattach);

       ?>
       alltaskattach = {{ $alltaskattach ? $alltaskattach :"[]" }};


        function subdeleteAttach(id_item,flag,name){

            
            delete_deliver = "";
            smsdelete      = "";

            if ( $(".nowdeliver_"+id_item).hasClass("delivered") && ($(".nowdeliver_"+id_item).is(":visible")) ) {

                delete_deliver = " entregado a la tarea";

            }

            if(flag){
                smsdelete = "Estas seguro de activar el archivo?";
            }else{
                smsdelete = "Estas seguro de eliminar el archivo"+delete_deliver+"?";
            }

            sweetsms = (flag)?"Activar":"Eliminar";
            coloract = (flag)?"#5cb85c":"#d33";

            swal({
              title: 'Confirmar',
              text: false,
              type: false,
              showCancelButton: true,
              confirmButtonColor: coloract,
              cancelButtonColor: '#3085d6',
              confirmButtonText: sweetsms
            }).then((result) => {
              if (result.value) {



                //  borrado unico o total

                all_deleted = null;


                if($(".nowdeliver_"+id_item).is(":visible")){

                    all_deleted = true;

                }

                comment = $(".comment_event").val();

                $.ajax({

                    data: {task:{{ $task->id }},subtask:{{ $subtask->id }},attachitem:id_item,all_deleted:all_deleted,activate:flag,task_id:{{ $task->id }},unit_id:{{ $subtask->task->unit_id }},comment:comment,name:name},
                    headers:{
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    },
                    dataType: 'json',
                    url:"{{ URL::to('/') }}/subtasks/{{ $subtask->id }}/deleteAttachsubtask",
                    type:'POST',
                    success:  function (data) {

                        if(data.status == "ok"){


                            if(flag){

                              //  Esto es cuando activa
                         
                                swal(
                                    'Activado!',
                                    'El archivo fue activado correctamente.',
                                    'success'
                                )
  

  /*                    
<div class="bdn subattachtask_element subattachtask_137"><a href="guntref.um/uploads/39737d7d0ee86e3cb282405aebd1c701.docx" target="_blank">Video_concurso_Res_de_conflictos_Procesado (1).docx<span class="minidatetask_137" style="margin-left: 6px;font-size: 11px;font-style: inherit;">01/02/2018</span></a><button title="Eliminar archivo" alt="Eliminar archivo" type="button" onclick="subdeleteAttach(137,false)" class="btn btn-danger btn-xs stack_deleted elementTheTask">x</button><button type="button" title="Entregar a la tarea" alt="Entregar a tarea" onclick="deliverAttach(137)" class="not_deliver btn btn-xs stack_newed elementTheTask deliver_137">e</button> <i style="display:none" title="Archivo entregado a la tarea" class="fa fa-arrow-up delivered stack_newed elementTheTask nowdeliver_137" aria-hidden="true"></i></div>

*/
                                // otherbtn = "";


                                //  si se baja esta en ambos, si se comparte entrega tambien

                                //  if(alltaskattach.indexOf(id_item) == "-1"){  comentado

                                //  allltaskattach es la variable de task attach
                                //  cuando no encuentra 

                                //    console.log("debe agregar botones");
                                //    console.log(data.delivered+"dddddddd");

                                    otherbtn = "";


                                    if(data.delivered == 1){

                                        //  esta en ambas tablas
                                        //  cual se creo mayor

                                        $(".attachtask_"+id_item).remove();

                                        /*
                                        otherbtn = "<span title='Archivo entregado a la tarea' alt='Archivo entregado a la tarea'><i  class='fa fa-arrow-up delivered stack_newed elementTheTask nowdeliver_$attach->id' aria-hidden='true'></i></span>";
                                        verifyAttachinTask()
                                        */

                                    }else{

                                        if ((!(typeof isteamleaderUnit === "undefined"))&&(isteamleaderUnit=="1")) {

                                        otherbtn = "<button type='button' title='Entregar a la tarea' alt='Entregar a tarea' onclick='deliverAttach("+id_item+")' class='not_deliver btn btn-xs stack_newed elementTheTask deliver_"+id_item+"' >e</button> <i style='display:none' title='Archivo entregado a la tarea' class='fa fa-arrow-up delivered stack_newed elementTheTask nowdeliver_"+id_item+"' aria-hidden='true'></i>";

                                        }

                                    }

                                //  }   comentado

                                lagr = '"'+$(".subattachtask_"+id_item).data("nameatta")+'"';


                                $(".subattachtask_"+id_item).html("<a href='{{ URL::to('/') }}/download/"+ id_item+"' target='_blank'>"+$(".subattachtask_"+id_item).data("nameatta")+"<span class='minidatetask_"+id_item+" minifecha' style='margin-left: 6px;font-size: 11px;font-style: inherit;'>"+$(".subattachtask_"+id_item).data("dateatta")+"</span></a><button type='button' title='Eliminar Archivo' onclick='subdeleteAttach("+id_item+",false,"+lagr+")' class='btn btn-danger btn-xs stack_deleted elementTheTask'>x</button>"+otherbtn);


                               //  console.log("aallalala");
                                return true;

   

                            }


/*
                            swal(
                              'Eliminado!',
                              'El archivo se elimino de la subtarea.',
                              'success'
                            )
*/

                        contentlink = $(".subattachtask_"+id_item).children("a").html();

                        var res = contentlink.split("<span class");

                      //  console.log("aaaaaaaa"+res[0]);

                        nameattt    = '"'+res[0]+'"';


                        $(".subattachtask_"+id_item).html("<div><span class='datin'>"+contentlink+"</span><button style='font-size: 8px !important;padding-left: 1.5px !important' type='button' onclick='subdeleteAttach("+id_item+",true,"+nameattt+")' class='btn btn-success btn-xs stack_deleted elementTheTask'><i class='fa fa-check'></i></button></div>");

                //      $(".subattachtask_"+id_item).html("<div class='datin eliminado_"+id_item+"'>"+$(".subattachtask_"+id_item).children().html()+"</div>");

                        // $(".subattachtask_"+id_item).remove(); solo textos

                        if($(".stack_deleted").length == "0"){   // subattachtask_element

                           
                            $(".nuevo_div").css("height","38px");

                        //  $(".subAttach").html("No se encontraron archivos Adjuntos");
                            $("#buttonDownload").hide();
                        }


                            verifyAttachinTask();

                        }
                    }
                });

              }
            })



            // console.log(flag);

            btndelete = (flag)?"btn-success":"btn-danger";

            $(".swal2-confirm").attr("class","btn "+btndelete+" swal2-confirm");

            if(flag){
                $(".swal2-confirm").attr("style","");
            }

        //  $(".swal2-confirm").attr("class","btn btn-danger swal2-confirm");
        //  $("swal2-popup").css("width","400px");
            $(".swal2-cancel").css("margin-left","6px");
            $(".swal2-cancel").attr("class","btn btn-primary swal2-cancel");
            $(".swal2-warning").css("width","66px");
            $(".swal2-warning").css("height","66px");
            $(".swal2-icon.swal2-warning").css("line-height","70px");


            nop = (flag)?"activar":"eliminar";

            $("#swal2-content").after('<div class="form-group"><p class="help">Ingresa un motivo para '+nop+' el archivo "'+name+'"</p><textarea style="margin-top: 6px;width: 100%;" name="comment_event" class="comment_event" cols="30" rows="10"></textarea></div>');

/*
            if($("#taskAttach_multiple option").length == 0){

                console.log("puta madreee");

                $(".alltach").show();
                $(".addsubtask").hide();
                $("#taskAttach_multiple").hide();

            }
*/

     
       }

 


        $(document).ready(function () {


            if({{ (count($task->attachments)+count($attachdelivered)) }} == {{ $exist }}){

                $("#taskAttach_multiple").hide();
                $(".alltach").show();
                $(".addsubtask").hide();

            }else{

                $("#taskAttach_multiple").show();
                $(".addsubtask").show();
            }





        $(".addsubtask").on("click",function(){


            if($('#taskAttach_multiple').val()){

                        $(".addsubtask").prop("disabled",true);


                        var multiple = []

                        multiple      = $('#taskAttach_multiple').val(); 

                        $.ajax({

                            data: {subtask:{{ $subtask->id }},attachtask:multiple},
                            headers:{
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                            },
                            dataType: 'json',
                            url:"{{ URL::to('/') }}/subtasks/{{ $subtask->id }}/addsubtask",
                            type:'POST',
                            success:  function (data) {

                                $(".addsubtask").prop("disabled",false);


                                if(data.status=="ok"){


                                    multiple.forEach( function(valor, indice, array) {

                                         $(".eliminado_"+valor).parent().remove();


                                            if($(".subattachtask_element").length == "0"){

                                                $(".subAttach").html("");
                                           
                                            }




                                            // idSubTaskAttach.push(parseInt(valor));

                                            ee = $(".attachtask_"+valor).html();
                                            fn = $(".attachtask_"+valor).data("filename");
                                     createdt  = $(".attachtask_"+valor).data("createdat");

                                    

                                        lagr2 = '"'+ee+'"';
/*
                                        var date = new Date(created);
                                        createdt = date.getDate()+'/'+(date.getMonth()+ 1)+'/'+date.getFullYear();
                                       */
                                            linkAttach = "<div data-fileatta='"+fn+"' data-dateatta='"+createdt+"' data-nameatta='"+ee+"' class='bdn subattachtask_element subattachtask_"+valor+"'><a href='"+url_tofs+"/download/"+valor+"' target='_blank'>"+ee+"<span class='minidatetask_"+valor+"' style='margin-left: 6px;font-size: 11px;font-style: inherit;'>"+createdt+"</span></a><button type='button' onclick='subdeleteAttach("+valor+",false,"+lagr2+")' class='btn btn-danger btn-xs stack_deleted elementTheTask'>x</button></div>";



                                             $(".attachtask_"+valor).remove();
                                            

                                             if(countAtachFiles==0){

                                                $(".subAttach").html("");
                                                countAtachFiles++;
                                             
                                             }


                                            $(".subAttach").append(linkAttach);
                                          
                                    });

                                    seeDownload();

                                    if($("#taskAttach_multiple option").length == 0){

                                          $(".alltach").show();
                                          $(".addsubtask").hide();
                                          $("#taskAttach_multiple").hide();

                                    }

                                }

                            }
                        });

                }






            });


            $("#buttonDownload").on("click",function(){

                var d = new Date();
                var n = d.getTime();

                location.href = "{{ URL::to('/') }}/subtasks/{{ $subtask->id }}/download?"+n;

            });


            countAtachFiles = parseInt("{{ count($subtask->attachments) }}");


            if(countAtachFiles>0){

                    seeDownload();
            
            }else{

                $(".nuevo_div").css("text-align","center");
                $(".box_elegirArchivo").css("visibility","visible");

                $(".box_supArchivo").css("margin-top","12px");
                $(".box_supArchivo").css("text-align","center");

            }




            $('#status-select').select2();


            $('.task-description').readmore({
                speed: 75,
                moreLink: '<a class="readmore more"href="#">Ver más</a>',

                lessLink: '<a class="readmore less"href="#">Ver menos</a>',
                heightMargin: 16,
            });


            $(window).resize(function () {

                ellipses1 = $("#bc1 :nth-child(2)")
                if ($("#bc1 a:hidden").length > 0) {
                    ellipses1.show()
                } else {
                    ellipses1.hide()
                }

                ellipses2 = $("#bc2 :nth-child(2)")
                if ($("#bc2 a:hidden").length > 0) {
                    ellipses2.show()
                } else {
                    ellipses2.hide()
                }

            })




        //----------------------------------------------------------------------------------

        //etiquetar usuarios


        var userselect = $(".js-example-data-array");


        userselect.select2({
            placeholder: 'Seleccione usuarios',
        });



        var userArray =[];//arreglo global ,guarda usuarios etiquetados


        userselect.on('select2:select', function (e) {
            userArray.push(e.params.data.id);
           // console.log(e.params.data.id);


        });

        userselect.on('select2:unselect', function (e) {
            var noUser = e.params.data.id;

            if(noUser != null){

                for(var x =0 ;x < userArray.length ;x++){

                    if(noUser == userArray[x]){
//                      //  console.log(noUser,userArray[x]);
                        userArray[x]=null;
                    }

                }
            }
        });

        //            userselect.on('select2-loaded', function(e) { log ("loaded (data property omitted f')or brevity)");})

        $('#etiquetar').click(function () {

            userselect.select2('val', 'all');

            var taskId = '{{$subtask->id}}';
            var type = 'subtask';


            if(userArray.length>0) {
                $.ajax({

                    type: 'POST',
                    url: '{{ URL::to('/') }}/subtaskTag',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    },
                    dataType: 'json',
                    data: {userId: userArray, taskId: taskId, type: type},
                    success: function (data) {

                        var usuarios = data;

                        if(usuarios.length >0 ){

                            for(var x=0 ; x < data.length; x++){

                                $('#tabla_tasktags_ajax').append('<button id="user-'+usuarios[x][1]+'" ><span class="glyphicon-class"></span><label>' + usuarios[x][0]+'&nbsp&nbsp</label>' +
                                    '@if($user->canTagOthers())'+
                                        '<span class="glyphicon glyphicon-remove" aria-hidden="true" onClick=untag('+usuarios[x][1]+')> </span>' +
                                        '@endif'+
                                '</button>');//concatena la variable

                            }
                        }
                    },
                });
                userArray =[];

            }else{

                alert("Debe seleccionar un usuario");
            }

        });

    });

    function untag(index) {


            $.ajax({

                data: {id_tag:index},
                headers:{
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                },
                dataType: 'json',
                url:"{{ URL::to('/') }}/untag",
                type:'POST',
                success:  function (data) {

              $("#user-"+index ).remove();

                }
            });
        }

    </script>
    @endsection