$(document).ready(function(){
    $("#form-div,#table-div").height($(window).height()-80);

   $("#edit_btn").hide();

$("#table-div").hide();

$(".slide1").click(function(){

$("#form-div").hide();
$("#table-div").show(500);
 fetch_view_table();
});


$(".slide2").click(function(){

$("#form-div").show(500);
$("#table-div").hide();
});




 function  show_form(){
    $("#form-div").show(500);
$("#table-div").hide();
}



/* 
$("#table-div").slimScroll({
    height: '430px', 
    color: 'rgb(176, 180, 185) none repeat scroll 0% 0%'
  });

 */




$('#dynamic_ajax_table').DataTable({
    dom: 'lBfrtip',
    buttons: [
        'copy', 'csv', 'excel', 'pdf', 'colvis'
    ],
    "bLengthChange": true,
    "bSort" : true,
     "lengthMenu": [[ 20, 50,75,100, -1], [ 20, 50,75,100, "All"]],
     "pagingType": "full_numbers",
    columnDefs: [ {
        visible: false
    } ]
    
    
});





});




$('.focusable').each(function(key,val){

    if($(val).attr('disabled')||$(val).attr('readonly')||$(val).attr('type')=='hidden' ){

$(val).removeClass('focusable');
    }



  })




 $('.focusable').keydown(function (e) {
     if (e.which === 13) {
var index = $('.focusable').index(this) + 1;

         $('.focusable').eq(index).focus();

     }
 });

 $('.caps').on('keyup',function(){

    $(this).val($(this).val().toUpperCase()); 
    
    
    });


function fetch_view_table()
{

	$("#table_result").html("<img src='../images/loading.gif' style='margin-left:35%;height:300px;width:300px;'>");
    

    
    var sp_sort = $('#table_settings_field').attr('sp_sort');
    
    var sp_date_picker = $('#table_settings_field').attr('sp_date_picker');
    var header_from_date = $('#table_settings_field').attr('header_from_date');
    var header_till_date = $('#table_settings_field').attr('header_till_date');
    
    $.ajax({
                type: 'POST',
                   url: '/fetch_table_view_json',
                data: {
                     '_token':  $('meta[name="csrf-token"]').attr('content'),
                   sort_value: sp_sort,
                   sp_date_picker:sp_date_picker,
                   header_from_date:header_from_date,
                   header_till_date: header_till_date
                },
                error: function (request, error) {
                   // alert("Please Wait, Loading...");
                },
                success: function (response) {
                    
            generate_table(response);   

                    
                    }
            });
    
}




function generate_table(response)
{

var data = JSON.parse(response);


if(Object.keys(data).length<=1){
          no_records='<h2>No Records Found</h2>';
          $("#table_result").html(no_records);
          $("#myModaltable > .modal-dialog  > .modal-content > .modal-body > .modal_form").html(no_records);
      }
      else
      {

var column_heading = $('#table_settings_field').attr('column_heading').split('`');
var column_width = $('#table_settings_field').attr('column_width').split('`');
var column_alighn = $('#table_settings_field').attr('column_alighn').split('`');
var column_conversion = $('#table_settings_field').attr('column_conversion').split('`');

    
    t_table='<table   border="1" class="table table-bordered  table-hover datbl"   id="dynamic_ajax_table">';
t_colgroup='';  
t_thead='';
t_tfoot='';
t_tbody='';
t_table_end='';
modal_content='';

t_alihn= {
  L: 'left',
  R : 'right',
  C :  'center'
};



$(data).each(function(i,val)
{

var k =1;   
    
$.each(val,function(key2,val2)
{
    //row code starts here
    
    if(key2==1)
    {
    t_colgroup +='<colgroup> <col width="40px">';   
    t_thead +='<thead><tr> <th>SL</th>';    
    t_tfoot +='<tfoot style="display: table-header-group;"><tr> <th></th>';
    }
    else 
    {
    t_tbody +='<tr><td>'+k+'</td>';     
    }


        $.each(val2,function(key3,val3)
        {
            //td code starts here
            /*alert(key3 + " : " + val3);*/  
            
            if(key3>1)
            {
                key_index = (parseInt(key3) - 2);
            
            if(key2==1)
                {
                
                
                if(typeof column_heading[key_index] === "undefined" || column_heading[key_index]=="")
                {
                default_column_heading=val3;
                }
                else
                {
                default_column_heading=column_heading[key_index];   
                }
                
                
                if(typeof column_width[key_index] === "undefined"  || column_width[key_index]=="")
                {
                default_column_width=100;
                }
                else
                {
                default_column_width=column_width[key_index];   
                }
                
                
                
                alighn_select='<select name="td_alighn[]" class="form-control">';   
                
                left_option_select='';
                right_option_select='';
                center_option_select='';
                                
                    
                    if(column_alighn[key_index]=="L" || column_alighn[key_index]=="")
                    { 
                    left_option_select='selected';
                    }
                    else if(column_alighn[key_index]=="R")
                    { 
                    right_option_select='selected';
                    }
                    else if(column_alighn[key_index]=="C")
                    { 
                    center_option_select='selected';
                    }
                    else
                    {
                    left_option_select='selected';
                    }
                
                alighn_select+='<option value="L" '+left_option_select+' >Left</option>';   
                alighn_select+='<option value="R"  '+right_option_select+' >Right</option>';    
                alighn_select+='<option value="C"  '+center_option_select+' >Center</option>';
                
                alighn_select+='</select>';
                
                
                
                
                convertion_select='<select name="format[]" class="form-control">';  
                
                convertion_option_I='';
                convertion_option_i='';
                convertion_option_d='';
                convertion_option_D='';
                convertion_option_m='';
                convertion_option_M='';
                convertion_option_S='';
                convertion_option_C='';
                convertion_option_c='';
                convertion_option_T='';
                convertion_option_t='';
                convertion_option_R='';
                
                
                
                    if(column_conversion[key_index]=="I")
                    { 
                    convertion_option_I=' selected ';
                    }
                    else if(column_conversion[key_index]=="i")
                    { 
                    convertion_option_i=' selected ';
                    }
                    else if(column_conversion[key_index]=="d")
                    { 
                    convertion_option_d=' selected ';
                    }
                    else if(column_conversion[key_index]=="D")
                    {
                    convertion_option_D=' selected ';
                    }
                    else if(column_conversion[key_index]=="m")
                    { 
                    convertion_option_m=' selected ';
                    }
                    else if(column_conversion[key_index]=="M")
                    { 
                    convertion_option_M=' selected ';
                    }
                    else if(column_conversion[key_index]=="S" || column_conversion[key_index]=="")
                    { 
                    convertion_option_S=' selected ';
                    }
                    else if(column_conversion[key_index]=="C")
                    { 
                    convertion_option_C=' selected ';
                    }
                    else if(column_conversion[key_index]=="c")
                    { 
                    convertion_option_c=' selected ';
                    }
                    else if(column_conversion[key_index]=="T")
                    { 
                    convertion_option_T=' selected ';
                    }
                    else if(column_conversion[key_index]=="t")
                    { 
                    convertion_option_t=' selected ';
                    }
                    else if(column_conversion[key_index]=="R")
                    { 
                    convertion_option_R=' selected ';
                    }
                    else
                    {
                    convertion_option_S=' selected ';
                    }
                    
                convertion_select+='<option value="I" '+convertion_option_I+' >Int</option>';
                convertion_select+='<option value="i" '+convertion_option_i+' >Int(_)</option>';
                convertion_select+='<option value="d" '+convertion_option_d+' >Date(dd/mmm/yy)</option>';
                convertion_select+='<option value="D" '+convertion_option_D+' >Date(dd/mmm/yyyy)</option>';
                convertion_select+='<option value="m" '+convertion_option_m+' >Date(mm-yy)</option>';
                convertion_select+='<option value="M" '+convertion_option_M+' >Date(mmm-yyyy)</option>';
                convertion_select+='<option value="S" '+convertion_option_S+' >String</option>';
                convertion_select+='<option value="C" '+convertion_option_C+' >Cur(0.00)</option>';
                convertion_select+='<option value="c" '+convertion_option_c+' >Cur(0.000)</option>';
                convertion_select+='<option value="T" '+convertion_option_T+' >LongTime</option>';
                convertion_select+='<option value="t" '+convertion_option_t+' >ShortTime</option>';
                convertion_select+='<option value="R" '+convertion_option_R+' >INR Format</option>';
                
                
                convertion_select+='</select>';
                
                
                
                t_colgroup +='<col width="'+default_column_width+'px">';
                
                t_thead +='<th>'+default_column_heading+'</th>';
                
                    
                t_tfoot +='<th><input type="text" placeholder="Search" autocomplete="false"  class="form-control dtbl_frm_cntrl"  /></th>';
                 
 
modal_content+='<div class="form-group row" style="clear:both !important;">                                                                                                                                 <label class="control-label  col-sm-3 col-md-3 col-lg-3 col-xs-12 original_alias">'+val3+'</label>                                                                                                                                  <div class="col-sm-3 col-md-3 col-lg-3 col-xs-12">                                                                                                                                                                                                                                                      <input type="text" name="colname[]"   onfocus="this.select();"  class="form-control input-sm  colname" value="'+default_column_heading+'" >                                                                                                                                                                                                                             </div>                                                                                                                                                                                          <div class=" col-sm-2 col-md-2 col-lg-2 col-xs-12">                                                                                                                                                 <input type="text" name="wid[]"   onfocus="this.select();"  onkeypress="return isNumber(event, this.value);"   class="form-control input-sm" value="'+default_column_width+'" >                                                                                                         </div>                                                                                                                                                                                      <div class=" col-sm-2 col-md-2 col-lg-2 col-xs-12">'+alighn_select+'</div>                                                                                                                              <div class=" col-sm-2 col-md-2 col-lg-2 col-xs-12">'+convertion_select+'</div>                                                                                                                                                                                                                                                                                                                                      </div>';
                
                }
                else
                {
                    if(column_alighn[key_index]=="")
                    {
                    default_column_alighn='left';
                    }
                    else
                    {
                    default_column_alighn=t_alihn[column_alighn[key_index]];    
                    }
                    
                t_tbody +='<td  align="'+default_column_alighn+'">'+val3+'</td>';   
                }
            }
            else
            {
            hiddenid="'"+val3+"'";  
            }
            
        });
        
        
    if(key2==1)
    {     
      $('.additional_btns').each(function(index, element) {
          col_width = $(this).attr('col_width');
        t_colgroup +='<col width="'+col_width+'px">';
        t_thead +='<th></th>'; 
        t_tfoot +='<th></th>'; 
    });
    
    
    }
    else
    {
    
        $('.additional_btns').each(function(index, element) {
           btn_text = $(this).attr('btn_text');
            btn_click_function = $(this).attr('btn_click_function');
             btn_class = $(this).attr('btn_class');
             
             t_tbody+='<td class="masked" >                                                                                                                                                                         <input type="button" name="'+btn_text+'" title="'+btn_text+'" onclick="'+btn_click_function+'('+hiddenid+');"  value="'+btn_text+'" hiddenid="'+hiddenid+'" class="'+btn_class+'" />                                                                                                                                                                                                    </td>';
        });
        
        
        
    }
        
        
        
    if(key2==1)
    {
    t_colgroup +='</colgroup>';
    t_thead +='</tr></thead>';  
    t_tfoot +='</tr></tfoot>';  
    }
    else
    {
    t_tbody +='</tr>';  
    }
k++;
});


});

t_table_end +='</table>';

full_table=t_table+t_colgroup+t_thead+t_tfoot+t_tbody+t_table_end;

settings_row_id= $('#table_settings_field').attr('settings_row_id');
csrf=$('meta[name="csrf-token"]').attr('content');
modal_header='<div class="form-group row"> <input type="hidden"  name="_token" value="'+csrf+'" >                                                                                                                                                                 <label class="control-label col-sm-3 col-md-3 col-lg-3 col-xs-12">SP Alias</label>                                                                                                                                  <label class="control-label  col-sm-3 col-md-3 col-lg-3 col-xs-12">Fields   <span onClick="copy_from_alias();" style="color:red; font-size:9px;">Copy Alias</span></label>                                                                                                                              <label class="control-label  col-sm-2 col-md-2 col-lg-2 col-xs-12">Width</label>                                                                                                                                            <label class="control-label  col-sm-2 col-md-2 col-lg-2 col-xs-12">Alighn</label>                                                                                                                       <label class="control-label  col-sm-2 col-md-2 col-lg-2 col-xs-12">Format</label></div>'+
modal_content+'                                                                                                                                                                                              <div class="form-group">                                                                                                                                                                                            <input type="hidden" name="rowid" value="'+settings_row_id+'">                                                                                                                                                                                  <input type="submit" name="tablesettings" class="btn btn-success" style="float:right !important; margin-top: 5px;" value="SAVE">                                                                                                                                                                                                            </div>';


$("#myModaltable > .modal-dialog  > .modal-content > .modal-body > .modal_form").html(modal_header);

$("#table_result").html(full_table);
$('#load_ajax_result').val('1');
    
load_datatables();  

      }

}


function load_datatables()
{
    
    var header_from_date = $('#table_settings_field').attr('header_from_date');
    var header_till_date = $('#table_settings_field').attr('header_till_date');
    var sp_date_picker = $('#table_settings_field').attr('sp_date_picker');


  var table = $('#dynamic_ajax_table').DataTable({
        dom: 'lBfrtip',
        'autoWidth':false,
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'colvis'
        ],
        "bLengthChange": true,
        "bSort" : true,
         "lengthMenu": [[ 20, 50,75,100, -1], [ 20, 50,75,100, "All"]],
         "pagingType": "full_numbers",
        columnDefs: [ {
            visible: false
        } ]
        
        
    });
    
    
    if(sp_date_picker=="1")
    {   
    /* onChange="sp_header_date_change();" */   
        console.log("inside if");   
     $('#dynamic_ajax_table_filter').append('<label class="formsplabel"> From:</label><input class="formsp_dates form-control  form-control-sm" readonly type="text" value="'+header_from_date+'" id="formspfrom"  size="8"    > <label class="formsplabel">- To:</label><input class="formsp_dates form-control  form-control-sm" readonly type="text" value="'+header_till_date+'" id="formspto" size="8"><input type="button" class="btn btn-warning btn-sm" value="Load Records" onClick="sp_header_date_change();" />');  
     
    
    
    $('#formspfrom,#formspto').datetimepicker({
timepicker:false,
format:'d-m-Y',
formatDate:'d-m-Y',
closeOnDateSelect:true
});
    /*elem=document.querySelector('#formspfrom');
new Datepicker(elem,{
 dateFormat: 'dd-mm-yy' 
});*/    
    
    }
    
    
     $('.dt-buttons').append('<button class="btn btn-primary buttons-collection dropdown-toggle buttons-colvis" data-toggle="modal" data-target="#myModaltable" onclick="load_tb_mdl();" id="wrench" title="Table Settings" type="button" ><i class="icon-wrench" style="color:#FFF;"></i></button>');
    
    
    
    
     // Apply the search
    table.columns().every( function () {
        var that = this;
 
        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                
                that.search( this.value ).draw(); 
                
            }
        } );
    } );
    
    
    
     table.on( 'order.dt search.dt', function () {
        table.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
            cell.innerHTML = i+1;
        } );
    } ).draw();
                        
    
}






function sp_header_date_change()
{
$('#table_settings_field').attr('header_from_date',$('#formspfrom').val());
$('#table_settings_field').attr('header_till_date',$('#formspto').val());
fetch_view_table(); 
}


function custom_call_print()
{
    //var oldPage = document.body.innerHTML;
    
    var divElements = document.getElementById('only_table').innerHTML;

    
    document.body.innerHTML = 
          "<html><head><title></title><style>@media screen{body{font-size:12px;}} @media print{body{font-size:12px;}a{display:none;}  } .masked,.cus_print_btn dt-button,.dt-buttons { display:none; } #dynamic_ajax_table_paginate,#dynamic_ajax_table_length,#dynamic_ajax_table_info,#dynamic_ajax_table_filter{ display:none; }  </style></head><body>" + 
          divElements + "</body>";    
          
    window.print() ;
    window.location.reload();
    //document.body.innerHTML = oldPage;
}



function custom_call_dos_print()
{
    
    var divElements = document.getElementById('only_table').innerHTML;
    
    document.body.innerHTML = 
          "<html><head><title></title><style>@media screen{body{font-size:12px;  font-family:Verdana, Geneva, sans-serif; letter-spacing:6px !important; }   .masked,.cus_print_btn dt-button,.dt-buttons { display:none; }    #dynamic_ajax_table_paginate, #dynamic_ajax_table_length, #dynamic_ajax_table_info, #dynamic_ajax_table_filter{ display:none; } #dynamic_ajax_table {  width:760px  !important; } }                               @media print{body{ font-size:12px  !important; font-family:Verdana, Geneva, sans-serif; letter-spacing:6px !important; }     .masked,.cus_print_btn dt-button,.dt-buttons { display:none; } #dynamic_ajax_table_paginate,#dynamic_ajax_table_length,#dynamic_ajax_table_info,#dynamic_ajax_table_filter{ display:none; }  #dynamic_ajax_table { width:760px  !important;    margin: 27mm 16mm 27mm 16mm; }  }  </style></head><body>" + 
          divElements + "</body>";        
    window.print() ;
    window.location.reload();
}


function call_alert_msg_div(msg,color_code)
{
    alert(msg);
    /*if(color_code==0)
    {
    var bgcolor="#5cb85c";
    }
    else
    {
    var bgcolor="#ff6c60";  
    }
    $("#alert_msg_div").css("background-color", bgcolor);
    $("#alert_msg_div").html(msg);
    
     $("#alert_msg_div").fadeIn(1500);
     $("#alert_msg_div").fadeOut(3000);*/
}




function call_edit_modal(row_id)
{


    set_edit_form(row_id);  
/* $('#security_modal').modal('show'); 
$('#action_modal_row_id').val(row_id);
$('#modal_heading').html("Enter Edit Password");
$('#action_modal').val('1'); */



}


function call_remove_modal(row_id)
{


    remove_grid_row(row_id);

    
/* $('#security_modal').modal('show'); 
$('#action_modal_row_id').val(row_id);
$('#modal_heading').html("Enter Remove Password");
$('#action_modal').val('2'); */
}



    function remove_grid_row(row_id)
{

$( '#hidden_status' ).val("2");
$( '#row_id' ).val(row_id);     
Save_form();
    
}

$('#security_modal').on('shown.bs.modal', function () {
    $('#action_password').focus();
}) 

$(document).on('keypress', '#action_password', function (e) {  
var $action_modal = $('#action_modal').val();

    if (e.which === 13)
    {     
      go_for_action();
    }
    
}); 


function go_for_action()
{
$('#security_modal').modal('hide');
var action_password =  $('#action_password').val();
var row_id = $('#action_modal_row_id').val();
var request_type = $('#action_modal').val();

    if(request_type==1)
    {   
            
        if(action_password == $('#edit_password').val())
        {
            
        set_edit_form(row_id);  
        }
        else
        {
            
        call_alert_msg_div("Edit Password Mismatch",1); 
        }
    }
    else if(request_type==2)
    {
        
        if(action_password == $('#remove_password').val())
        {
            
        remove_grid_row(row_id) 
        }
        else
        {
            
        call_alert_msg_div("Remove Password Mismatch",1);       
        }
    }
    $('#action_password').val('');
}




function set_checkboxes(class_name,str)
{
$('.'+class_name).each(function () {
                var value=','+$(this).val()+',';
                if(str.indexOf(value) != -1){
                    $(this).prop('checked',true);
                }
            }); 
    
}




function set_table_local_storage(form_name,table_name)
{

var str="";

$('#'+table_name).find('thead th').each(function(){
      str += $(this).width()+"px,"; 

     //$(this).css('width','300px'); 
});

str = str.slice(0, -1); 


console.log(str);

localStorage.setItem(form_name, str );

}


function load_table(form_name,table_name)
{
    //alert("form_name"+form_name+"table_name"+table_name);
var s =  localStorage.getItem(form_name);

if(s===null)
{
    
$('#'+table_name).find('thead th').each(function(){ 
     $(this).css('width','170px'); 
}); 
    
}else{
var tabArr = s.split(',');  

$.each(tabArr,function(k, v)
{
    $('#'+table_name+' thead th ').eq(k).css('width',v);
});
}

}


function copy_from_alias()
{
$('.original_alias').each(function(index, element) {
    alias_text=$(this).html();
    $(this).closest('div').find('.colname').val(alias_text);
}); 
}




$(document).ready(function(e) {
   var win= $(window).height();     
   var h = win - 90;
   var panel = h - 35;
   
   
   $('.form-w3layouts').css('height', h+'px');
   $('#table_result').css('height', panel+'px');
    $('#form_body').css('height', panel+'px');
     $('#form_body').css('margin-bottom', '-8px');
     
    /* $("#table_result").slimScroll({
          height: panel+'px',
          axis: 'both', 
          color: 'rgb(176, 180, 185) none repeat scroll 0% 0%'
        });*/
     
});


$(".reset_btn").on('click',function(){

    reset_form()


})

function reset_form(){
    $(".input_text").val('');
}

function check_cookie_name(name) 
    {
      var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
      if (match) {
      
      }
      else{
        alert("Registartion Not Set");
        window.location.href = "/";
      }
   }


   check_cookie_name('c_id');

function check_login_sts(){


var lg_sts="{{ Session::get('login_sts')}}";

if(lg_sts==0){

    window.location.href = "/logout";
}



}



function load_tb_mdl(){
    $("#myModaltable").modal("show");
}

