$(document).ready(function() {


    /*=======================================================
    =             REMOVE TICKETS                        =
    =======================================================*/  
    $('.ticket_remove').on('click', function(e) {
        e.preventDefault();
        var $this = $(this);
        var id = $this.val();

        swal({   
            title: "Are you sure to delete?",   
            text: "By deleting any ticket all replies related to it will be deleted too and it can not be undone.",   
            type: "warning",   
            showCancelButton: true,   
            confirmButtonColor: "#FF474C",   
            confirmButtonText: "Yes, delete it!",   
            cancelButtonText: "Cancel!",   
            closeOnConfirm: false,   
            closeOnCancel: false 
        }, 
        function(isConfirm){   
            if(isConfirm) {

                processTicketRemoveAjaxRequest($this, id);

            } else {
                // Notify the user
                swal({   
                    title: "Cancelled",   
                    type: 'error',
                    text: "Deletion action has been cancelled :)",   
                    timer: 1500,   
                    showConfirmButton: true 
                });
            }
        });

    });

    function processTicketRemoveAjaxRequest($this, id) {

        //  Send the ajax request
        $.ajax({
            url: siteUrl + '/ticket/remove',
            type: 'POST',
            data: {id : id, _token: token},
            success: function(data) {

                // Delete the row
                $this.closest('.ticket_row').remove();
                // Notify the user
                swal({   
                    title: "Deleted",   
                    type: 'success',
                    text: "Deleted successfully.",   
                    timer: 1500,   
                    showConfirmButton: true 
                });

            },
            error: function(data) {
                swal({   
                    title: "Error",   
                    type: 'error',
                    text: "Sorry, an error occured. Please try again later.",   
                    timer: 1500,   
                    showConfirmButton: true 
                });
            }
        });  
    }


    /*=======================================================
    =             Ajax Reply System                         =
    =======================================================*/  

    $('#reply-textarea').on('keyup', function() {
        $('.reply-body').removeClass('has-error');
    })

    $('#createReply').on('submit', function(e) {
        e.preventDefault();

        // Initialize variables
        var route= $('#createReply').attr('action'),
            data = new FormData( $("#createReply")[0] ),
            editorContent = tinyMCE.get('reply-textarea').getContent(),
            valid = '';


        // Empty the form status first
        $('.reply_form_status').removeClass('alert').html(' ');

        // Check if the body length is less than or equal to 10
        if( editorContent == '' ) {
            valid = 'invalid';
            $('.reply_form_status').removeClass('alert-success').addClass('animated fadeInUp alert alert-danger').html(' Reply <strong>body </strong> is required');
        } else {
            valid = '';
            $('.reply_form_status').removeClass('alert').html('  ');
        }

        if( valid !== '') {
            $('.reply_form_status').removeClass('alert-success').addClass('animated fadeInUp alert-danger').find('.help-block').html('Please fill out the form properly');
        } else {
            $('.reply_form_status').removeClass('alert-danger').html(' ');

            // Perform the AJAX Ticket Creating Submission
            ajaxReplyCreate(route, data);
        }

        function ajaxReplyCreate(route, data) {
            $.ajax({
                url: route,
                type: 'POST',
                data: data,
                dataType: 'json',
                contentType: false,
                processData: false,
                beforeSend: function() {
                    $('.reply_form_status').removeClass('alert-warning').addClass('animated fadeInUp alert alert-info').html('<i class="fa fa-circle-o-notch fa-spin"></i> Processing data...');
                },
                success: function(data) {
                     $('.reply_form_status').removeClass('alert-warning alert-info').addClass('animated fadeInUp alert alert-success').html('<i class="fa fa-check"></i> Your reply has been posted.');

                    // Reset the form
                    $("#createReply")[0].reset();
                    tinyMCE.get('reply-textarea').setContent(' ');
                    $('.reply-body label span').html(' Attach file&hellip; ');

                    // Append the reply the data to the page
                    appendReplyData(data);


                },
                error: function(data) {

                    var errMsg = '';

                    var errors = (data.responseJSON);

                    $.each(errors, function(index, value){

                        errMsg += '<li>'+ value +'</li>';

                    });

                    $('.reply_form_status').removeClass('alert-success').addClass('animated fadeInUp alert alert-warning').html( errMsg );
                }
            });
        }


        // Append reply data to the page
        function appendReplyData( data ) {
            var user = data.user;
            var reply = data.reply;
            var output = '<div id="reply-'+reply.id+'" class="single-reply reply-hide ">'
                        +'<div class="media">'
                          +'<div class="media-left reply-user-img">';
                                if( user.profile_img == undefined ) {
                                    output +='<img class="media-object" src="/assets/img/users/avatar.png" alt="...">'
                                } else {
                                    output +='<img class="media-object" src="/uploads/profile_images/'+ user.profile_img +'" alt="...">'
                                }
                          output += '</div>'
                          +'<div class="media-body reply-user-details">'
                            +'<h4 class="media-heading">'
                                + user.first_name + ' ' + user.last_name 
                                + '<button class="remove-reply pull-right" onclick="removeReply(this);" value="'+ reply.id +'"><i class="fa fa-times"></i></button>'
                            +'</h4>'
                            +'<div class="row">';
                                if( user.role_name !== null ) {
                                    output    += '<p class="pull-left user-role">'+  user.role_name +'</p>';
                                } else {
                                    output    += '<p class="pull-left user-role">  </p>';
                                }
                                output    += '<p class="pull-right reply-date">  0 minutes ago  </p>'
                            +'</div>'
                            +'<div class="reply-message">'
                                +'<p> </p><p>'+ reply.body +'</p> <p></p>'
                            +'</div>';

                            //  If there has any attached file
                            if( reply.file !== undefined) {

                                output  += '<div class="file-attached">'
                                            +'<div class="file-single">'
                                               +' <div class="file-t">'
                                                    + '<span>Attached File:</span>'
                                                +'</div>'
                                                +'<div class="file-name">'
                                                    +'<span>'
                                                        +'<a href="/uploads/'+ reply.file +'"> '+ reply.file +' </a>'
                                                    +'</span>'
                                                +'</div>'
                                            +'</div>'
                                        +'</div>';

                            }
                                
                        output    += '</div>'
                        +'</div>'
                    +'</div>';

            // Append reply data
            $('.reply-container').append( output );
            $('#reply-'+reply.id+'').slideDown();

        }
    });



    /////////////////////////
    // Update User Profile //
    /////////////////////////
    $('#profile_update_form').on('submit', function(e) {
        e.preventDefault(); 

        var route = $('#profile_update_form').attr('action'),
            data  = new FormData( $("#profile_update_form")[0] );

            //  Send the ajax request
            $.ajax({
                url: route,
                type: 'POST',
                data: data,
                dataType: 'json',
                contentType: false,
                processData: false,
                beforeSend: function() {
                    $('.profile_form_status').removeClass('alert-warning alert-info').addClass('animated fadeInUp alert alert-success').html('<i class="fa fa-circle-o-notch fa-spin"></i> Processing data...');
                },
                success: function(data) {
                     $('.profile_form_status').removeClass('alert-warning alert-info').addClass('animated fadeInUp alert alert-success').html('<i class="fa fa-check"></i> Your profile has been updated.');

                     // Reset the form
                     $('.settings-tab .inputfile span').html('Select your picture...');
                },
                error: function(data) {

                    var errMsg = '';

                    var errors = (data.responseJSON);

                    $.each(errors, function(index, value){

                        errMsg += '<li>'+ value +'</li>';

                    });

                    $('.profile_form_status').removeClass('alert-success').addClass('animated fadeInUp alert alert-warning').html( errMsg );
                }
            });   
    });
    
});







/*=============================================
=    Styling & Customizing File Inputs       =
=============================================*/

/*
  By Osvaldas Valutis, www.osvaldas.info
  Available for use under the MIT License
*/

( function ( document, window, index )
{
  var inputs = document.querySelectorAll( '.inputfile' );
  Array.prototype.forEach.call( inputs, function( input )
  {
    var label  = input.nextElementSibling,
      labelVal = label.innerHTML;

    input.addEventListener( 'change', function( e )
    {
      var fileName = '';
      if( this.files && this.files.length > 1 )
        fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
      else
        fileName = e.target.value.split( '\\' ).pop();

      if( fileName )
        label.querySelector( 'span' ).innerHTML = fileName;
      else
        label.innerHTML = labelVal;
    });

    // Firefox bug fix
    input.addEventListener( 'focus', function(){ input.classList.add( 'has-focus' ); });
    input.addEventListener( 'blur', function(){ input.classList.remove( 'has-focus' ); });
  });
}( document, window, 0 ));




/*=======================================================
=            Auto Grow Textarea          =
=======================================================*/
function autoGrow (oField) {
    if (oField.scrollHeight > oField.clientHeight) {
    oField.style.height = oField.scrollHeight + "px";
    }
}

/*=======================================================
=             Ajax Remove Reply                         =
=======================================================*/  
function removeReply(thisObject) {
    var $this = $(thisObject);
    var $parentDiv = $this.closest('.single-reply');
    var id = $this.val();

    $.ajax({
        url: siteUrl + '/remove-reply/' + id,
        type: 'POST',
        data: {id : id, _token: token},
        success: function(data) {
            $parentDiv.slideUp(400);
        },
        error: function(data) {
            
            // Notify the user
            swal({   
                title: "Error",   
                type: 'error',
                text: "Could not able to process the request. :)",   
                timer: 1500,   
                showConfirmButton: true 
            });  
        }
    });  
}