//*******************************************************
// Extension module
//*******************************************************
var x31_reprint_receipt                                   = 'Ristampa Scontrini DGFE';
var x31_reprint_invoice                                   = 'Ristampa Fattura DGFE';
var x31_reprint_invoice_data                              = 'Ristampa Fatture in Data';
var x31_invalid_data                                      = 'Invalid data';
var devlistindices      = [];
var Reptypestartdate    = null;
var saveReptype         = -1;
var ecrselected         = -1;
var SelectDate          = '';
var ecrdevlist_indices  = [];                     // Reset device indices
var ecrdevlist_names    = [];
var _ext_info           = "My Front Office Module, v1.00a, 26-09-2016";
var PRNStyle            = { NORMAL:0, DOUBLEHEIGHT:1, DOUBLEWIDTH:2, EMPHASIZED:4, WHITEBLACK:8 };
// Only whit this parameter work OK "WHITEBLACK" style
var WHITEBLACK_A  = PRNStyle.NORMAL       | PRNStyle.WHITEBLACK;
var WHITEBLACK_B  = PRNStyle.DOUBLEHEIGHT | PRNStyle.WHITEBLACK;

////////////////////// Array of custom keys (available in front office keyb config)
var _ext_keys = [
/// id:Unique String, text:Button Text, callback:Name and parameters for function to call, image:use same for all for now,  idicon:use same for all for now
  { id:'extkb1',  text:'Ext/Info',                   callback:"ext_info_fn()",         image:"selico_items", idicon:'_icon' },
  { id:'extkb2',  text:'Ristampa Ultimo Scontrino',  callback:"ristampa_scontrino()",  image:"",             idicon:'_icon' },
  { id:'extkb3',  text:'TabValue',                   callback:"Set_client_tabvalue()", image:"selico_items", idicon:'_icon' },
  { id:'extkb4',  text:'Ristampa Scontrini DGFE',    callback:"ReprintECR(0)",         image:"",             idicon:'_icon' },
  { id:'extkb5',  text:'Ristampa Fattura DGFE',      callback:"ReprintECR(1)",         image:"",             idicon:'_icon' },
  { id:'extkb6',  text:'Ristampa Fatture per data',  callback:"ReprintECR(2)",         image:"",             idicon:'_icon' },  
  { id:'extkb7',  text:'PRN report',                 callback:"ext_make_report()",     image:"selico_items", idicon:'_icon' },  
  { id:'extkb8',  text:'',                           callback:"",                      image:" ",            idicon:'_icon' },  // A "do nothing" key
  { id:'extkb9',  text:'PLU',                        callback:"call_PLU()",            image:"",             idicon:'_icon' }
];
/*

  { id:'extkb8', text:'PLU',          callback:"FoundItembyinputcode()",image:"selico_items", idicon:'_icon' },  
  { id:'extkb6', text:'Ristampa Fatture per data',   callback:"ext_send_commands_fp()",image:"selico_items", idicon:'_icon' },  
  { id:'extkb10', text:'My Test',                    callback:"my_ext_function()",     image:"selico_items", idicon:'_icon' },
  { id:'extkb11', text:'ECR report',                 callback:"ext_send_commands_fp()",image:"selico_items", idicon:'_icon' }  
  
*/
////////////////////// Custom functions

function call_PLU()
{
  var i, idx;
  if(swipe.active) return;
  if(!instr.length) return;
  
  for(i=0; i<db_items_list.length; i++) {
    idx = db_items_list[i];
    if(item_match_barcode(db_items[idx], instr)) {
      instr="";
      if(cfg[0].miscflags.charAt(15) == '1' && !shift_started) {  // Auto open shift & shift not open
        if(!check_shift( function () { issue_item_sale(idx); return; } )) return;
      } else {
        if(!check_shift()) return;
      }
      issue_item_sale(idx);
      instr="";
      return;
    }
  }
  instr="";
  err("PLU non trovato");
}

function ext_info_fn()
{
  msgbox("Extension info", '', '<b>Extension information:</b><br>'+_ext_info);
}

function my_ext_function()
{
  ask("My msg title", "Here is my exteral function. Do you like it?",
    //////////////// YES: This function will be executed only if user presses "yes" button
    function() { 
      msgbox("YES title", '', 'Thanks so much');
    }, 
    //////////////// NO: This function will be executed only if user presses "no" button
    function() { 
      msgbox("NO title",  '', 'That\' too bad..');
    }
  );
}

/////////////////////////////////////////////////////////////////
// update tabvalue in client
/////////////////////////////////////////////////////////////////
function Set_client_tabvalue()
{
  loading_show(msg.x1_load_ej);
  comms_setup(); 

  var clientID = 1;
  var tabvalue = 12.34;
  var oper     = 0;       // 0=add tabvaleu 1=sub tabvalue  
  $.getScript('settabvalue.js?client='+clientID+'&amount='+tabvalue+'&oper='+oper+'')
    .done(function(script, textStatus) 
    {
      loading_hide();
      if(textStatus == 'success') {
        if('errmsg' in window) {
          if(errmsg == 'OK') {
            var txt = 'clientID =['+clientID+'] Old tabvalue=['+oldtabvalue+'] New tabvalue=['+newtabvalue+']';
            msgbox(errmsg, "", txt); return;
          } else { err(errmsg); return; }
        }
      } else err('done textStatus->'+textStatus);
      return;
    })
    .fail(function(jqxhr, settings, exception) 
    {
      loading_hide();
      err('fail '+exception);
      return;
    });
}

//================ Reporting ===============================================
function begin_report()                   { user_report_data = [];                                                     }
function add_report_line(actstyle, data)  { user_report_data += actstyle+data+'\r\n';                                  }
function add_feed_cut()                   { user_report_data += '0!~0\r\n';                                            }
function prn_report()                     { 
  var mode = 1; 
  var rep_opt = '?m='+mode+'&t=Demo Repoer';  
  Oper_issue_report(rep_opt, user_report_data);
}

function ext_make_report()
{
  msgbox("Customer Report", '', '<b>Press OK to print...</b>', function(){  
    begin_report();
    add_report_line(PRNStyle.NORMAL,                      'Printing NORMAL style data');
    add_report_line(PRNStyle.NORMAL|PRNStyle.EMPHASIZED,  'Printing NORMAL & EMPHASIZED style data');
    add_report_line(PRNStyle.DOUBLEHEIGHT,                'Printing DOUBLEHEIGHT style data');
    add_report_line(PRNStyle.DOUBLEWIDTH,                 'Printing DOUBLEWIDTH style data');
    add_report_line(WHITEBLACK_A,                         'Printing WHITEBLACK_A style data');
    prn_report();
  });
}
//==========================================================================

function begin_fp(ecrdev) 
{
  var dev = Find_FP_dev();
  EFD.selected_dev = dev;
  if(ecrdev != undefined) {
    EFD.selected_dev = -1;
    if(devlistindices.length) {
      if(devlistindices.indexOf(ecrdev) > -1) EFD.selected_dev = ecrdev;
    }  
  }
  EFD.text          = '';
  EFD.commands      = [];
  return(EFD.selected_dev);
}

function add_fp_commnd(command)
{
  if(EFD.selected_dev == -1) return;  // Dont select valis device
  EFD.commands.push(command);
}

function do_efd_commands()
{
  if(EFD.selected_dev == -1) { err("No device selected.."); return; }

  EFD.curline = 0;
  EFD.aborted = 0;

  var nextRequest = function() 
  {

    if(EFD.aborted) {  err('Response [ (Aborted) ]'); return;  }
    if(EFD.curline >= EFD.commands.length)            return;
    var req = EFD.commands[EFD.curline++];
    if(req.length == 0) { nextRequest();              return; }
    fp_raw_request(req, 
      function(res) {
        if(EFD.aborted) { msgbox('Command ['+req+']', '', 'Response [ (Aborted) ]', function() { return; } ); return; }
        if(res == null) res = '-';
        nextRequest();
      }, 
      function() {
        if(EFD.aborted) { msgbox('Command ['+req+']', '', 'Response [ ABORTED]', function() { return; } ); return; }
        var errmsg = '';
        nextRequest();
      },
      function() {
        EFD.aborted = 1;
      }
    );
  }
  nextRequest();
}

function ext_send_commands_fp()
{
  if(begin_fp() == -1) { err('Not found FP device'); return; }                    //Not found FP device for request
  add_fp_commnd('=c');
  add_fp_commnd('=K');
  add_fp_commnd('=o');
  add_fp_commnd('="/( 1this is reportt 1 )');
  add_fp_commnd('="/( 2this is reportt 2 )');
  add_fp_commnd('="/( 3this is reportt 3 )');
  add_fp_commnd('="/( 4this is reportt 4 )');
  add_fp_commnd('="/( 5this is reportt 5 )');
  add_fp_commnd('=c');  
  do_efd_commands();
}

function ristampa_scontrino()
{
  if(begin_fp() == -1) { err('Not found FP device'); return; }                    //Not found FP device for request
  add_fp_commnd('=K');
  add_fp_commnd('=C3');
  add_fp_commnd('=C453/$1');
  add_fp_commnd('=C1');
  do_efd_commands();
}

function SelectActiveEcr()
{
  var selector = ecrdevlist_indices.indexOf(ecrselected);
  select_table(msg.x49_Select_terminal, ecrdevlist_names, null, selector, 620, 
    function(sel) { 
      ecrselected = ecrdevlist_indices[sel];
      $('#selecr').text(db_dev[ecrselected].name); 
      ReprintECR(saveReptype);
    }, 
    0, 
    function() {}
  );
}

function ReprintECRRec() { ReprintECR(0); }
function ReprintECRInv() { ReprintECR(1);}

function ReprintECR(Reptype)  // 0=RECEIPT 1=INVOICE
{
  Find_FP_dev();
  if(ecrdevlist_indices.length == 0) { err(msg.x49_err_No_EFD_devices_defined); return; }
  if(ecrselected == -1) ecrselected = ecrdevlist_indices[0];

  if(Reptypestartdate == null)  { 
    Reptypestartdate  = new Date();
    SelectDate = date2strddmmyy(Reptypestartdate);
  }
  //Marcoif(saveReptype == -1)         saveReptype       = Reptype;
  saveReptype       = Reptype;
  var out = '';
  var headertxt = x31_reprint_receipt;
  if(Reptype == 1) headertxt = x31_reprint_invoice;
  if(Reptype == 2) headertxt = x31_reprint_invoice_data;
  if(ecrselected != -1) headertxt+=' "'+db_dev[ecrselected].name+'"';
  ///// Header
  out  = '<table style="margin-top:5px;border-spacing:6px;">';
  out +=    '<tr>';
  out +=       '<td class="dlgtitle dlgbutton_rel" id="selecr" style="width:99%; font-weight:bold; vertical-align:middle; text-align:center;">'+headertxt+'</td>';
  out +=       '<td class="dlgbutton dlgbutton_release" id="repexit" style="color:rgb(130,0,0);">&nbsp;X&nbsp;</td>';
  out +=    '</tr>';  
  out += '</table><hr/>';
  out += '<table style="width:100%; font-size:14px; font-weight:normal;">';
  out +=   '<tr style="height:34px;">';
  out +=    '<td style="width:15%; text-align:right;">'+ msg.x55_Repdata_date+'&nbsp;</td>';
  out +=    '<td style="width:25%"><input id="repdata"  type="text" class="textin" style="width:200px;"  maxlength="16">&nbsp;&nbsp;</td>';
  out +=   '</tr>';
  out +=   '<tr id="allfldfrom" style="height:34px;">';
  out +=     '<td style="width:15%; text-align:right;">' + msg.x10_From+'&nbsp;</td>';
  out +=     '<td style="width:25%"><input id="repfrom"  type="text" class="textin" style="width:200px;"  maxlength="20">&nbsp;&nbsp;</td>';
  out +=   '</tr>';
  out +=   '<tr id="allfldto" style="height:34px;">';
  out +=     '<td style="width:15%; text-align:right;">' + msg.x10_to+'&nbsp;</td>';
  out +=     '<td style="width:25%"><input id="repto"  type="text" class="textin" style="width:200px;"  maxlength="20">&nbsp;&nbsp;</td>';
  out +=   '</tr>';
  out += '</table>';
  //////// FOOTER
  out += '<hr/>';
  out += '<table style="width:100%; height:42px;"><tr>';
  out +=   '<td></td>';
  out +=   '<td style="text-align:center;"><button id="repsend"  style="width:92px; height:32px; font:bold 15px helvetica; color:rgb(122,122,122);">'+msg.x1_Done + '</button></td>';
  out +=   '<td></td>';
  out += '</tr></table>';
  popup(out, 550);
  dialog_show_hide(1);  // 1->show 0->hide
  if(Reptype==1) $('#allfldto').hide();
  if(Reptype==2) {
    $('#allfldfrom').hide();
    $('#allfldto').hide();  
  }
  $('#repdata').val(date2str(Reptypestartdate));
  $('#repdata').html(date2str(Reptypestartdate));
  $('#repdata').unbind();
  $('#repdata').bind(clickevent(), function() {
    set_range();
  });  
  $('repexit').unbind();
  $('#repexit').bind(clickevent(), function() {
    hide_dialog(0);
    Reptypestartdate  = null;
    saveReptype       = -1;
  }); 
  $('repfrom').unbind();
  $('#repfrom').bind(clickevent(), function() {
    $('#repfrom').focus();
  }); 
  $('repto').unbind();
  $('#repto').bind(clickevent(), function() {
    $('#repto').focus();
  }); 
  $('selecr').unbind();
  $('#selecr').bind(clickevent(), function() {
    SelectActiveEcr();
  }); 


  $('repsend').unbind();
  $('#repsend').bind(clickevent(), function() {
    var from = 0;
    var to   = 0;
    if(Reptype==0) {
      from = $('#repfrom').val();         
      to   = $('#repto').val();
      if(!isNumeric(from) || !isNumeric(to))  { err(x31_invalid_data, function() { ReprintECR(saveReptype); }); return; }
      if(from == to && from == 0)             { err(x31_invalid_data, function() { ReprintECR(saveReptype); }); return; }
      if(from > to)                           { err(x31_invalid_data, function() { ReprintECR(saveReptype); }); return; }
    } 
    if(Reptype==1) {
      from = $('#repfrom').val();         
      if(!isNumeric(from) )                   { err(x31_invalid_data, function() { ReprintECR(saveReptype); }); return; }
      if(from == 0)                           { err(x31_invalid_data, function() { ReprintECR(saveReptype); }); return; }
    }
    if(Reptype==2) {
      if(!isNumeric(from) )                   { err(x31_invalid_data, function() { ReprintECR(saveReptype); }); return; }
    }

    if(begin_fp(ecrselected) == -1)           { err('Not found FP device', function() { ReprintECR(saveReptype); }); return; }
    var command = '';
    command = '=C3';
    add_fp_commnd(command);
    if(Reptype==0) {  // command for receipt
      command = '=C452/$1/&'+SelectDate+'/['+from+'/]'+to;
    } 
    if(Reptype==1) {          // command for invoice
      command = '=C454/$1/&'+SelectDate+'/['+from;
    }
    if(Reptype==2) {          // command for invoice data
      command = '=C473/$1/&'+SelectDate+'/['+SelectDate;
    }
    //Marco
    saveReptype       = -1;
    add_fp_commnd(outpatch(command));
    do_efd_commands();
  }); 
}


function set_range()
{
  scroller_params.preset = 'date';
  Set_Scroller_format(scroller_params, 'full');
  delete scroller_params.wheels;
  input_scroller(300, msg.x44_Select_Date+'..', null,
    function(arr) { 
      Reptypestartdate = new Date(arr[2], arr[1], arr[0]);
      SelectDate = date2strddmmyy(Reptypestartdate);
      $('#repdata').val(date2str(Reptypestartdate));
      $('#repdata').html(date2str(Reptypestartdate));
      ReprintECR(saveReptype);
    },
    null, scroller_params
  );
  $('#scroller').scroller('setDate', Reptypestartdate, true);
}


function date2strddmmyy(date)
{
  var m, out = "";
  m = date.getDate().toString();      if(m.length == 1) m = '0' + m;  out += m;
  m = (date.getMonth()+1).toString(); if(m.length == 1) m = '0' + m;  out += m;
  m = date.getFullYear().toString(); 
  var yy = m.substring(2, 4);
  out += yy;
  return(out);
}


// Generic function found active ECRs
function Find_FP_dev()                                                  // Find fiscal ecr devices
{
  devlistindices      = [];
  ecrdevlist_indices  = [];                     // Reset device indices
  ecrdevlist_names    = [];
  for(var i=0; i<db_dev.length; i++) {
    if(db_dev[i].flags.charAt(0) != '1')  continue;                     // This device is deleted
    if(db_dev[i].cls != 4)                continue;                     // Filter EFD/FP devices only
    if(db_dev[i].conntype == 3)           continue;                     // This device is inactive
      devlistindices.push(i);                                             // Ok found FP device
    ecrdevlist_indices.push(i);
    ecrdevlist_names.push(db_dev[i].name);
  }
  if(devlistindices.length) return(devlistindices[0]); else return(-1); // if found device return 1st device else return -1(Not found)
}
