
if($('#compose_message').length)
{
  $(document).on('click','#compose_message',function(){
    $('#compose_message_modal').modal('show');
  });
}

if($('#reply_message').length)
{
  $(document).on('click','#reply_message',function(){
    $('#reply_message_modal').modal('show');
  });
}

if($('.send_message').length)
{   
   $(document).on('click','.send_message',function(){
        var u_id=$(this).attr('user_id');
    // $('#send_message_modal').load('send_message.blade.php?u_id='+u_id);
      var dataString = 'u_id='+ u_id +  '&_token=' + $("input[name=_token]").val();
       $.ajax({
                    type: "POST",
                    url : "/connections/send_msg",
                    data : dataString,
                    success : function(data){
                      $('#send_message_modal').html(data);
                      $('#send_message_modal').modal('show');
                       }
                },"json");
     
   // $('#send_message_modal').modal('show');
  });
}

if($('#composeMessageForm').length)
{
  /*Compose To Address Profile Typeahead*/
  var bestPictures = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      //prefetch: '../data/films/post_1960.json',
      remote: {
        //url: '{{url("profile_typeahead")}}?profile_name=%QUERY',
        url: '/username_typeahead?user_name=%QUERY%',
        wildcard: '%QUERY%'
      }
    });

  $('#to').typeahead(null, {
      name: 'best-pictures',
      display: 'value',
      source: bestPictures,
      templates: {
        empty: [
          '<div class="empty-message">',
            'unable to find any profile name that match the current query',
          '</div>'
        ].join('\n'),
//        suggestion: Handlebars.compile('<p><img src="{{url("uploads/profile_images/")}}/@{{#if profile_image}}@{{profile_image}}@{{else}}default-profile.png@{{/if}}" class="img-circle" width="50px" height="50px">&nbsp;<strong>@{{value}}</strong> – @{{username}}</p>')
        suggestion: Handlebars.compile('<p><img src="/uploads/profile_images/{{#if profile_image}}{{profile_image}}{{else}}default-profile.png{{/if}}" class="img-circle" width="50px" height="50px">&nbsp;<strong>{{value}}</strong></p>')
      }

    }).on('typeahead:selected', function($e, datum){
        $("#sel_to_prof_id").val(datum['id']);
         $("#msg_id").val(datum['message_id']);
    });
  /* End To Address Profile Typeahead*/
  $(document).on('click','.clear_form',function(){
    window.location=window.location;
  });

$("#composeMessageForm").bootstrapValidator({        
      message: 'This value is not valid',
      feedbackIcons: {
          valid: 'glyphicon glyphicon-ok',
          invalid: 'glyphicon glyphicon-remove',
          validating: 'glyphicon glyphicon-refresh'
      },
      fields: {
        'to': {
              validators: {
                  notEmpty: {
                      message: 'The To should not be empty'
                  },
                  /*remote: {
                      message : 'invalid to address',
                      url: "/message/check_username",
                      type: "get",
                      data: {
                      to: function() {
                                      return $("#to").val();
                                  }
                      }
                  }*/
              },
          },
        'subject': {
              validators: {
                  notEmpty: {
                      message: 'The Subject should not be empty'
                  },
              }
          },
        'message': {
              validators: {
                  notEmpty: {
                      message: 'The Message should not be empty'
                  },
              }
          },
      }
  });

}

if($("#replyMessageForm").length)
{
  $("#replyMessageForm").bootstrapValidator({        
        message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
          'to': {
                validators: {
                    notEmpty: {
                        message: 'The To should not be empty'
                    },
                    /*remote: {
                        message : 'invalid to address',
                        url: "/message/check_username",
                        type: "get",
                        data: {
                        to: function() {
                                        return $("#to").val();
                                    }
                        }
                    }*/
                },
            },
          'subject': {
                validators: {
                    notEmpty: {
                        message: 'The Subject should not be empty'
                    },
                }
            },
          'message': {
                validators: {
                    notEmpty: {
                        message: 'The Message should not be empty'
                    },
                }
            },
        }
    });
}

/* User Inbox Datatables Load*/
if($('#users-inbox-table').length)
{
  $('#users-inbox-table').DataTable({
	  "language": {
        "emptyTable":     "No messages found"
    },
    processing: true,
    serverSide: true,
    ajax: '/message/ajax_messages?msg_type=I',
    filter: false,
    columns: [
      {data: 'checkbox', name: 'checkbox', width:'5%', orderable: false, searchable: false},
      {data: 'sender', name: 'sender', width:'25%', orderable: false, searchable: false},
      {data: 'title', name: 'title', width:'60%', orderable: false, searchable: false},
      {data: 'created_at', name: 'created_at', width:'15%'}
    ],
    createdRow: function ( row, data, index ) {
          //$(row).attr('data-id',data['id']);
          $('td',row).attr('data-id',data['id']);
          $(row).addClass('message_det');
          $('td:eq(1),td:eq(2)',row).addClass('message_view_det');          
        },
    "order": [[ 3, "desc" ]]
  });
}

/* User Sent Box Datatables Load*/
if($('#users-sent-table').length)
{
  $('#users-sent-table').DataTable({
	  "language": {
        "emptyTable":     "No messages found"
    },
    processing: true,
    serverSide: true,
    ajax: '/message/ajax_messages?msg_type=S',
    filter : false,
    columns: [
      {data: 'checkbox', name: 'checkbox', width:'5%', orderable: false, searchable: false},
      {data: 'sender', name: 'sender', width:'25%', orderable: false, searchable: false},
      {data: 'title', name: 'title', width:'55%', orderable: false, searchable: false},
      {data: 'created_at', name: 'created_at', width:'15%'}
    ],
    createdRow: function ( row, data, index ) {
          //$(row).attr('data-id',data['id']);
          $('td',row).attr('data-id',data['id']);
          $(row).addClass('message_det');
          $('td:eq(1),td:eq(2)',row).addClass('message_view_det');          
        },
    "order": [[ 3, "desc" ]]
  });
}

/* User Sent Box Datatables Load*/
if($('#users-trash-table').length)
{
  $('#users-trash-table').DataTable({
	  "language": {
        "emptyTable":     "No messages found"
    },
    processing: true,
    serverSide: true,
    ajax: '/message/ajax_messages?msg_type=T',
    filter : false,
    columns: [
      {data: 'checkbox', name: 'checkbox', width:'5%', orderable: false, searchable: false},
      {data: 'sender', name: 'sender', width:'25%', orderable: false, searchable: false},
      {data: 'title', name: 'title', width:'55%', orderable: false, searchable: false},
      {data: 'created_at', name: 'created_at', width:'15%'}
    ],
    createdRow: function ( row, data, index ) {
          //$(row).attr('data-id',data['id']);
          $('td',row).attr('data-id',data['id']);
          $(row).addClass('message_det');
           $('td:eq(1),td:eq(2)',row).addClass('message_view_det');  
        },
    "order": [[ 3, "desc" ]]
  });
}

if($("#select_all_check").length)
{
  $(document).on("click","#select_all_check",function(){
    if(this.checked) { // check select status
            $('.select_msg_check').each(function() { //loop through each checkbox
                this.checked = true;  //select all checkboxes with class "msg_check"              
            });
        }else{
            $('.select_msg_check').each(function() { //loop through each checkbox
                this.checked = false; //deselect all checkboxes with class "msg_check"                      
            });        
        }
  });
}
$(document).on("click",".message_view_det",function(){
  var message_id = $(this).attr('data-id');
  location.href = '/messages/details/'+message_id;
});

$(document).on("click","#delete_message",function(){
  var message_id = $(this).attr('data-id');
  var checked_num = $('input[name="msg_check[]"]:checked').length;
  if(checked_num)
  {
    bootbox.confirm("Are you sure, you want to delete message?", function(result) {
      if(result)
      $('#deleteMessageForm').submit();
    });  
  }  
  else
  {
    bootbox.alert("Select atleast one message");
  }
});

$(document).on("click",".delete",function(){
  var message_id = $(this).attr('data-id');
  bootbox.confirm("Are you sure, you want to delete message?", function(result) {
    if(result)
    location.href = '/messages/delete/'+message_id;
  });  
});

$(document).on("click",".deletementor",function(){
  var message_id = $(this).attr('data-id');
  bootbox.confirm("Are you sure, you want to delete message ?", function(result) {
    if(result)
    location.href = '/mentor/delete/'+message_id;
  });  
});


function renderContent(route)
{
  $('#render-this').hide();
  $('#render-here').load(route + ' #render-this', function(){

    /*---------------------------------------------------
    |Invitation func replicaz
    |
    */
    /* User Organiazation Profile Datatables Load*/
    if($('#users-invitation-all-table').length)
    {
      $('#users-invitation-all-table').DataTable({
        "language": {
        "emptyTable":     "No messages in invitation"
    },
		processing: true,
        serverSide: true,
        ajax: '/invitation/ajax_invitations',
        filter: false,
        columns: [
          {data: 'updated_at', name: 'updated_at', width:'10%'},
          {data: 'sender', name: 'sender', width:'20%', orderable: false, searchable: false},
          {data: 'title', name: 'title', width:'40%', orderable: false, searchable: false},
          {data: 'action', name: 'action', width:'20%', orderable: false, searchable: false}
        ],
        createdRow: function ( row, data, index ) {
              //$(row).attr('data-id',data['id']);
              $('td',row).attr('data-id',data['id']);
              $(row).addClass('invitation_det');
              $('td:eq(0),td:eq(1),td:eq(2)',row).addClass('invitation_view_det');
            },
        "order": [[ 0, "desc" ]]
      });
    }

    /* Talent Profile Datatables Load*/
    if($('#users-invitation-table').length)
    {
      $('#users-invitation-table').DataTable({
        "language": {
        "emptyTable":     "No messages in invitation"
    },
		processing: true,
        serverSide: true,
        ajax: '/invitation/ajax_invitations?msg_type=I',
        filter: false,
        columns: [
          {data: 'updated_at', name: 'updated_at', width:'10%'},
          {data: 'sender', name: 'sender', width:'20%', orderable: false, searchable: false},
          {data: 'title', name: 'title', width:'35%', orderable: false, searchable: false},
          {data: 'action', name: 'action', width:'40%',orderable: false, searchable: false}
        ],
        createdRow: function ( row, data, index ) {
              //$(row).attr('data-id',data['id']);
              $('td',row).attr('data-id',data['id']);
              $(row).addClass('invitation_det');
              //$('td',row).addClass('invitation_det');
              $('td:eq(0),td:eq(1),td:eq(2)',row).addClass('invitation_view_det');
            },
        "order": [[ 0, "desc" ]]
      });
    }
    $(document).on('click','#compose_invitation',function(){
      location.href= '/invitation/compose';
    });
    $(document).on("click",".invitation_view_det",function(){
      var Invitation_id = $(this).attr('data-id');
      location.href = '/invitations/details/'+Invitation_id;
    });
    $(document).on("click",".update_inv_status",function(){
      var inv_id = $(this).attr('data-id');
      var inv_per_type = $(this).attr('data-type');
        bootbox.confirm("Are you sure, you want to continue this action?", function(result) {
          if(result)
          location.href = '/invitations/action_update/'+inv_id+'/'+inv_per_type;
        });  
    });
    $(document).on('click','.send_message',function(){
      var u_id=$(this).attr('user_id');
      var dataString = 'u_id='+ u_id +  '&_token=' + $("input[name=_token]").val();
      $.ajax({
        type: "POST",
        url : "/connections/send_msg",
        data : dataString,
        success : function(data){
          $('#send_message_modal').html(data);
          $('#send_message_modal').modal('show');
        }
      },"json");   
    });


    /*---------------------------------------------------
    |Back to nest .. fetch table again
    |
    */    
    $('#users-inbox-table').DataTable({
		"language": {
        "emptyTable":     "No messages in inbox"
    },
      processing: true,
      serverSide: true,
      ajax: '/message/ajax_messages?msg_type=I',
      filter: false,
      columns: [
        {data: 'checkbox', name: 'checkbox', width:'5%', orderable: false, searchable: false},
        {data: 'sender', name: 'sender', width:'25%', orderable: false, searchable: false},
        {data: 'title', name: 'title', width:'60%', orderable: false, searchable: false},
        {data: 'created_at', name: 'created_at', width:'15%'}
      ],
      createdRow: function ( row, data, index ) {
            //$(row).attr('data-id',data['id']);
            $('td',row).attr('data-id',data['id']);
            $(row).addClass('message_det');
            $('td:eq(0),td:eq(1),td:eq(2)',row).addClass('message_view_det');          
          },
      "order": [[ 3, "desc" ]]
    });

    // Page title alter
    $('.heading').text('Inbox');
  });
}