$(function() {
  $.getScript('/static/imio/common.js', function() { });

  /*Set readonly attributes on "input, textarea and select" element when meeting a .readonly css class on div parent*/
  $form_divs_readonly = $('form.quixote div.readonly');
  $form_divs_readonly.each(function() {
   $("input", this).prop('readonly', true);
   $("textarea", this).prop('readonly', true);
   $("select", this).prop('readonly', true);
  });

  /*Remove "Belgique" from select box.*/
  $country_datasrc_without_belgium = $('.without_belgium select');
  $country_datasrc_without_belgium.each(function() {
   $(this).children('option[value="Belgique"]').remove();
  });

  /*
  If a form table have a class ".is_filtering_table" and on the same page, there is a textbox
  with a table_filter css class
  SO this table could be filtering thanks to textbox text content... if "title" table row is in textbox text
  MANDATORY REQUIREMENT IN A PAGE FORM :
  .is_filtering_table on a table
  .table_filter on a textbox
  */
  $filtering_table = $('.is_filtering_table tbody > tr')
  $filtering_table.each(function() {
      $(this).hide()
      filtres = $('.table_filter > div.content > input').val().toLowerCase().split(',');
      if ($.inArray($(this).text().toLowerCase(), $.map(filtres, $.trim)) > -1)
      {
         $(this).show();
      }
  });

/* textboxfield with var "txt_selected_motifs" + tablefield in the same page to manage multi motifs selection and number of copies.
     Table MUST have n lines for n motivations max.
     Table MUST have 2 columns "Motifs" keep motivation name and "Nb exemplaire" to input number of copies*/
  $table_nb_motifs = $('span#txt_selected_motifs').parent().parent().next();
  $table_nb_motifs.attr("id","var_table_nb_motifs");
  $table_nb_motifs = $('div#var_table_nb_motifs table')
  $table_nb_motifs.each(function() {
      var extraCol = false;
      $('span#txt_selected_motifs').hide();
      $lst_selected_motifs = $('span#txt_selected_motifs').text().split(', ');
      $tr = $('div#var_table_nb_motifs table > tbody > tr');
      $('div#var_table_nb_motifs table thead tr th').toggle();
      $tr.each(function(tr) {
          var nbcol = $(this)[0].cells.length;
          if (nbcol > 3) {
              extraCol = true;
          }
          $name = $(this).find('input').attr('name');
          var new_motif_input_name = $name.split('-')[0] + '-' + tr + '-' + $name.split('-')[2];
          var new_nb_ex_input_name = $name.split('-')[0] + '-' + tr + '-' + (parseInt($name.split('-')[2]) + 1);
          var input_motif = "<input id=\"form_"+new_motif_input_name+"\" name=\""+new_motif_input_name+"\" type=\"text\" value=\""+$lst_selected_motifs[tr]+"\" />";
          /* Default value set to 1 but if we return back... this is a problem.*/
          var input_nb_ex = "<input id=\"form_"+new_nb_ex_input_name+"\" name=\""+new_nb_ex_input_name+"\" type=\"text\" value='1' />";
          var new_td = "";
          if (tr < $lst_selected_motifs.length)
          {
              if (extraCol == true) {
                  for (var i=3;i<nbcol;i++) {
                      var new_extra_col_name = $name.split('-')[0] + '-' + tr + '-' + (parseInt($name.split('-')[2]) + (i -1));
                      new_td += "<td><input id=\"form_"+new_extra_col_name+"\" name=\""+new_extra_col_name+"\" test='test' type=\"text\" value='' /></td>";
                  }
              }
              $(this).replaceWith("<tr><th style='text-align:left;'>"+$lst_selected_motifs[tr]+"</th><td style='display:none'>"+input_motif+"</td><td>"+input_nb_ex+"</td>"+new_td+"</tr>");
          }
          else {
              $(this).remove();
          }
    });
  });
/* END textboxfield with var "txt_selected_motifs" ... */

/* Hide field's title*/
  $hide_title = $('.hide_title')
  $hide_title.each(function() {
    $(this).children('.title').hide();
  });

/* Empty basket page*/
    $basket_page = $('body.page-panier > div#page > div#main-content-wrapper div#columns')
    $basket_page.each(function() {
        if (!$('div.lingobasketcell').length) {
            $(this).append('<div id="empty_basket"><h2>Votre panier est actuellement vide.</h2></div>');
        }
    });

/* GENERATE CSV FILE thanks to a table and a link .export */
  function exportTableToCSV($table, filename) {

    var $rows = $table.find('tr:has(td)'),

      // Temporary delimiter characters unlikely to be typed by keyboard
      // This is to avoid accidentally splitting the actual contents
      tmpColDelim = String.fromCharCode(11), // vertical tab character
      tmpRowDelim = String.fromCharCode(0), // null character

      // actual delimiter characters for CSV format
      colDelim = '|',
      rowDelim = '\r\n',

      // Grab text from table into CSV formatted string
      // csv = '"' + $rows.map(function(i, row) {
      csv = $rows.map(function(i, row) {
        var $row = $(row),
          $cols = $row.find('td');

        return $cols.map(function(j, col) {
          var $col = $(col),
            text = $col.text();

          return text.replace(/"/g, '""'); // escape double quotes

        }).get().join(tmpColDelim);

      }).get().join(tmpRowDelim)
      .split(tmpRowDelim).join(rowDelim)
      .split(tmpColDelim).join(colDelim); // + '"';

    // Deliberate 'false', see comment below
    if (false && window.navigator.msSaveBlob) {

      var blob = new Blob([decodeURIComponent(csv)], {
        type: 'text/csv;charset=utf8'
      });

      // Crashes in IE 10, IE 11 and Microsoft Edge
      // See MS Edge Issue #10396033
      // Hence, the deliberate 'false'
      // This is here just for completeness
      // Remove the 'false' at your own risk
      window.navigator.msSaveBlob(blob, filename);

    } else if (window.Blob && window.URL) {
      // HTML5 Blob
      var blob = new Blob([csv], {
        type: 'text/csv;charset=utf-8'
      });
      var csvUrl = URL.createObjectURL(blob);

      $(this)
        .attr({
          'download': filename,
          'href': csvUrl
        });
    } else {
      // Data URI
      var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

      $(this)
        .attr({
          'download': filename,
          'href': csvData,
          'target': '_blank'
        });
    }
  }

  // This must be a hyperlink
  $(".export").on('click', function(event) {
    // CSV
    var args = [$('table.stats'), 'export.csv'];
    exportTableToCSV.apply(this, args);
  });
/* end of GENERATE CSV FILE thanks to ... */


/* Remove "BOSA" out of backoffice treatment */
  $('table#listing td:contains("BOSA REDIRECTION")').parent().remove();


  $( document ).ajaxComplete(function() {
        $('table#listing td:contains("BOSA REDIRECTION")').parent().remove();
  });
/* end of Remove "BOSA" ... */

  if(document.getElementById('form_captcha$q')){
    var $captcha = $('form.quixote div.CaptchaWidget > div.content > input#form_captcha$q');
    $captcha.each(function() {
      $(this).attr("style", "display: block!important;");
    });
  }

/* NAMUR PREPROD UNIQUEMENT*/
    var toplinks = $('div#toplinks');
    toplinks.each(function(){
        if (document.location.hostname == 'namur-citoyen.lescommunes.be') {
            $(this).remove();
        }
    });

    var login_page = $('div#login-page p').first();
        login_page.each(function() {
            if (document.location.hostname == 'namur-auth.lescommunes.be') {
                $(this).after('<div style="margin:1em;font-weight:bold;text-align:center;width=100%;color:red"><h2> Ceci est une version de test de l\'e-guichet de Namur. Si toutefois vous parvenez &agrave; acc&eacute;der &agrave; cette page, veuillez vous rendre &agrave; cette adresse <br /> <a style="text-decoration:underline;color:red;font-weight:bold;"  href="https://namur.guichet-citoyen.be/">https://namur.guichet-citoyen.be/</a></h2></div>')
            }
        });

/* END OF NAMUR PREPROD... */

});

