
if($('#compose_invitation').length)
{
  $(document).on('click','#compose_invitation',function(){
    //$('#compose_invitation_modal').modal('show');
    location.href= '/invitation/compose';
  });
}

if($('#cancel_inv').length)
{
  $(document).on('click','#cancel_inv',function(){
    //$('#compose_invitation_modal').modal('show');
    location.href= '/invitations';
  });
}

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


if($('#composeInvitationForm').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: '/invitation_typeahead?user_name=%QUERY',
        wildcard: '%QUERY'
      }
    });

  /*$('#to').typeahead(null, {
      name: 'best-pictures',
      display: 'value',
      source: bestPictures,
      templates: {
        empty: [
          '<div class="empty-Invitation">',
            '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']);
    });*/

    $("#to").select2({
      ajax: {
        url: "/invitation_typeahead",
        dataType: 'json',
        delay: 250,
        data: function (params) {
          return {
            user_name: params.term, // search term
          };
        },
        processResults: function (data) {
          //alert('hi');
          // parse the results into the format expected by Select2.
          // since we are using custom formatting functions we do not need to
          // alter the remote JSON data
          var results = [];
         // console.log(data);
          $.each(data, function(index, item){
            results.push({
              id: item.id,
              text: item.value
            });
          });
          return {
              results: results
          };
        },
        cache: true
      },
      escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
      //minimumInputLength: 1,
      maximumSelectionLength: 5
      //templateResult: formatRepo, // omitted for brevity, see the source of this page
      //templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
    });

  /* End To Address Profile Typeahead*/
  $(document).on('click','.clear_form',function(){
    window.location=window.location;
  });

$(document).on('change','#subject',function(){
  var subj = $(this).val();
  if(subj == 'Invitation to an event')
    $('#message').val('Hi we are please to invite you to an event');
  else
    $('#message').val('Hi we are pleased to invite you to a job');

  $('#message').change();
});

$("#composeInvitationForm").bootstrapValidator({        
      message: 'This value is not valid',
      feedbackIcons: {
          valid: 'glyphicon glyphicon-ok',
          invalid: 'glyphicon glyphicon-remove',
          validating: 'glyphicon glyphicon-refresh'
      },
      excluded: ':disabled', // <=== Add the excluded option
      fields: {
        'to[]': {
              validators: {
                  notEmpty: {
                      message: 'The To should not be empty'
                  },
                  /*remote: {
                      Invitation : 'invalid to address',
                      url: "/Invitation/check_username",
                      type: "get",
                      data: {
                      to: function() {
                                      return $("#to").val();
                                  }
                      }
                  }*/
              },
          },
        'title': {
              validators: {
                  notEmpty: {
                      message: 'The Title should not be empty'
                  },
              }
          },
        'company_name': {
              validators: {
                  notEmpty: {
                      message: 'The Company Name should not be empty'
                  },
              }
          },
        'subject': {
              validators: {
                  notEmpty: {
                      message: 'The Subject should not be empty'
                  },
              }
          },
        'message': {
              trigger: 'change keyup',
              validators: {

                  notEmpty: {
                      message: 'The Message should not be empty'
                  },
              }
          },
        'attachments': {
              validators: {
                  file: {
                      extension: 'jpeg,jpg,png,gif,bmp,doc,docx,pdf,rtf,xlsx,xls,txt',
                      type: 'image/gif,image/jpeg,image/png,image/bmp,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/rtf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,text/plain',
                      message: 'The Attachment must be a file of type: jpeg, png, bmp, gif,doc,docx,pdf,rtf,xlsx,xls,txt. '
                       },
              }
          },
      }
  });

}

if($("#replyInvitationForm").length)
{
  $("#replyInvitationForm").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: {
                        Invitation : 'invalid to address',
                        url: "/Invitation/check_username",
                        type: "get",
                        data: {
                        to: function() {
                                        return $("#to").val();
                                    }
                        }
                    }*/
                },
            },
          'subject': {
                validators: {
                    notEmpty: {
                        message: 'The Subject should not be empty'
                    },
                }
            },
          'Invitation': {
                validators: {
                    notEmpty: {
                        message: 'The Invitation should not be empty'
                    },
                }
            },
        }
    });
}

/* User Organiazation Profile Datatables Load*/
if($('#users-invitation-all-table').length)
{
  $('#users-invitation-all-table').DataTable({
    "language": {
        "emptyTable":     "No invitation found"
    },
	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 invitations found"
    },
	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",".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;
    });  
});



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","#delete_invitation",function(){
  var Invitation_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 Invitation?", function(result) {
      if(result)
      $('#deleteInvitationForm').submit();
    });  
  }  
  else
  {
    bootbox.alert("Select atleast one Invitation");
  }
});

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

