/*
    $Revision$
    $Id$

    File:        mld_opdr_materiaal.js
*/

function showRightButtons()
{
  // Altijd de volgende stap: ook als er geen vaste mateerialen zijn gekozen
  // moet het mogenlijk zijn variabele materialen in te vullen.
    $("#buttons1").show();
    $("#buttons2").hide();
}

function moveLeftRight(direction)
{
  if (direction == "L")
    var from = "matExist"; // moveLeft
  else
    var from = "matPossible"; // moveRight

  var mat_key_str_selected = new Array();
  $("#" + from + " :selected").each(function(j, selected)
                                    {
                                      mat_key_str_selected[j] = $(selected).val();
                                    });

  var mat_key_str_exist = new Array();
  $("#matExist option").each(function(k, option)
                             {
                               mat_key_str_exist[k] = $(option).val();
                             });

  if (direction == "L")
  { // Verwijder materialen uit de geselecteerde lijst
    for (var i = 0; i < mat_key_str_selected.length; i++)
    {
      for (var j = 0; j < mat_key_str_exist.length; j++)
      {
        if (mat_key_str_exist[j] == mat_key_str_selected[i])
        {
          mat_key_str_exist.splice(j, 1);
          break;
        }
      }
    }
  }
  else
  { // direction == "R": Voeg materialen toe aan de geselecteerde lijst
    for (var i = 0; i < mat_key_str_selected.length; i++)
    {
      mat_key_str_exist.push(mat_key_str_selected[i]);
    }
  }

  // De juiste waarden in de selectboxen weergeven gesorteerd op omschrijving
  $("#matPossible").load("loadMaterialOptions.asp",
                         {
                           matkeystr: mat_key_str_exist.join(","),
                           filter: "P"
                         });
  $("#matExist").load("loadMaterialOptions.asp",
                      {
                        matkeystr: mat_key_str_exist.join(","),
                        filter: "E"
                      },
                      function()
                      {
                        showRightButtons();
                      });
}

function moveRight()
{
  moveLeftRight("R");
}

function moveLeft()
{
  moveLeftRight("L");
}

function isGoodCurrency(str, digits)
{
  var anum = /^([-\+]?\d{1,6}[.,]?|[-\+]?\d{0,6}[.,]\d{1,2})$/
  //var anum = /^([-\+]?\d+[.,]?|[-\+]?\d+[.,]\d+$)$/
  return anum.test(str);
}

function checkInput(str, field, typeNC)
{
  if (str != "" && (  (typeNC == "C" && !isGoodCurrency(str.replace(',', '.')))
                   || (typeNC == "N" && !isGoodNumber(str.replace(',', '.'),false,true,8,2))
                   ))
  {
    FcltMgr.alert(L("lcl_mld_opdr_invalid_sum"));
    field.select();
    field.focus();
    return false;
  }
  return true;
}

function onChangeAmount(key)
{
  var amount = $("#amount" + key).val().replace(',', '.') || 0;
  var price  = $("#price"  + key).val().replace(',', '.') || 0;
  if (!checkInput(amount, $("#amount" + key), "N")) return;

  // show the total price of the selected artikel
  $("#amount" + key).val(parseFloat(amount));
  if (!$("#price" + key).attr("readonly"))
    $("#price" + key).val(num2currEditable(parseFloat(price)));
  $("#total" + key).val(num2currEditable(amount * parseFloat(price)));

  // Sla aantal op in matExistArray
  matExistArray[$("#amount" + key).attr("index")].amount = amount;
  matExistArray[$("#amount" + key).attr("index")].sum = amount * price;
  setTotal(-1);
}

function onChangePrice(key)
{
  var price = $("#price" + key).val().replace(',', '.') || 0;
  var amount = parseInt($("#amount" + key).val(), 10) || 0;
  if (!checkInput(price, $("#price" + key), "C")) return;

  // show the total price of the selected artikel
  $("#amount" + key).val(amount);
  if (!$("#price" + key).attr("readonly"))
    $("#price" + key).val(num2currEditable(parseFloat(price)));
  $("#total" + key).val(num2currEditable(amount * parseFloat(price)));

  // Sla prijs op in matExistArray
  matExistArray[$("#price" + key).attr("index")].price = price;
  matExistArray[$("#price" + key).attr("index")].sum = amount * price;
  setTotal(-1);
}

function checkKey(evt, mode)
{
  evt = evt || window.event;
  kc = evt.keyCode;
  if ((kc < 48 || kc > 57) && !(mode == 1 && (kc == 44 || kc == 46)))
    evt.returnValue = false;
}


//HTML Voor het standaardmateriaal
function makeMaterialHtml(matExistArray)
{
  // Tekst html-safe maken
  var newDiv = document.createElement("div"); // wordt wel door Garbage Collect opgeruimd.

  var matHtml = "<thead>"
              + "<tr>"
              + "<th>"
              +   "<img title='"+L("lcl_add")+"' src='../pictures/plus.png' style=cursor:pointer OnClick='AddItem();FcltMgr.resized();'>"
              + "</th>"
              + "<th style='text-align:right'><label>" + L("lcl_mld_opdr_aantal") + "</label></th>"
              + "<th><label>" + L("lcl_descr") + "</label></th>"
              + "<th style='text-align:left'><label>" + L("lcl_mld_opdr_eenheid") + "</label></th>"
              + "<th style='text-align:right'><label>" + L("lcl_mld_opdr_prijs") + "</label></th>"
              + "<th style='text-align:left'><label>" + L("lcl_mld_opdr_btw") + "</label></th>"
              + "<th style='text-align:right'><label>" + L("lcl_mld_opdr_totaal") + "</label></th>"
              + "</tr>"
              + "</thead>";
  matHtml += "<tbody>";
  for (var i = 0; i < matExistArray.length; i++)
  {
  	if (typeof newDiv.innerText != 'undefined')
            newDiv.innerText = matExistArray[i].descript
      else
          newDiv.textContent = matExistArray[i].descript;
    var descr = newDiv.innerHTML.replace(/\'/g,'&#39;'); // '

    matHtml += "<tr class='matline' id='mat" + matExistArray[i].key + "' valign='top'>"
             + "<td></td>"
             + "<td>"
             + "<input class='fldmatamount number' type='text' name='amount" + matExistArray[i].key + "'"
             + " id='amount" + matExistArray[i].key + "' value='" + parseFloat(matExistArray[i].amount) + "'"
             + " index='" + i + "' maxlength='8' onChange='onChangeAmount(" + matExistArray[i].key + ");'"
             + " size='8' onKeyPress='checkKey(event, 1);'>&nbsp;"
             + "</td>"
             + "<td>"
             + "<input type='text' class='fld'"
             + " id='descript" + matExistArray[i].key + "' value='" + descr + "' readonly>"
             + "</td>"
             + "<td>"
             // Eenheid kolom.
             + "</td>"
             + "<td>"
             + "<input class='fldmatprice currency' type='text' name='price" + matExistArray[i].key + "'"
             + " id='price" + matExistArray[i].key + "' value='" + num2curr(parseFloat(matExistArray[i].price)) + "'"
             + " index='" + i + "' maxlength='10'" + (matExistArray[i].roprice? " readonly" : "")
             + " size='10' onChange='onChangePrice(" + matExistArray[i].key + ")'"
             + " onKeyPress='checkKey(event, 1);'>&nbsp;"
             + "</td>"
             + "<td>"
             // BTW kolom.
             + "</td>"
             + "<td>"
             + "<input class='fldmattotal currency' type='text' name='total" + matExistArray[i].key + "'"
             + " id='total" + matExistArray[i].key + "' value='" + num2curr(matExistArray[i].amount * parseFloat(matExistArray[i].price)) + "'"
             + " index='" + i + "'"
             + " size='16' readonly>&nbsp;"
             + "</td>"
             + "</tr>";
  }

  matHtml += "</tbody>";
  return "<table class='tab_mld_materials' id='sel_items'>" + matHtml + "</table>";
}


var matExistArray = new Array();
var matUserArray = new Array();
var rowIndex = -1;

function nextInvoer()
{
  function material(matopdrkey, key, amount, descript, price, roprice)
  { // Vaste materialen hebben geen eenheid en btw.
  	this.matopdrkey = matopdrkey;
    this.key = key;
    this.amount = amount;
    this.descript = descript;
    this.price = price;
    this.sum = amount * price;
    this.roprice = roprice;
  }

  var matkeystrArr = matkeystr.split(",");
  var matexiststr = FcltMgr.dialogArguments().matexiststr;
  var matexiststrArr = (matexiststr != "" ? matexiststr.split(",") : []);
  var matopdrkeystr = FcltMgr.dialogArguments().matopdrkeystr;
  var matopdrkeystrArr = (matopdrkeystr != "" ? matopdrkeystr.split(",") : []);
  var matamountstr = FcltMgr.dialogArguments().matamountstr;
  var matamountstrArr = (matamountstr != "" ? matamountstr.split(",") : []);
  var matunitstr = FcltMgr.dialogArguments().matunitstr;
  var matunitstrArr = (matamountstr != "" ? matunitstr.split(",") : []);
  var matpricestr = FcltMgr.dialogArguments().matpricestr;
  var matpricestrArr = (matpricestr != "" ? matpricestr.split(",") : []);
  var matbtwstr = FcltMgr.dialogArguments().matbtwstr;
  var matbtwstrArr = (matbtwstr != "" ? matbtwstr.split(",") : []);
  var matdescriptstrArr = FcltMgr.dialogArguments().matdescriptarr; //deze krijgen we rechtsteeks als array

  // Maak een array met alle gegevens van de vaste materialen die eerder zijn gekozen
  // en eventueel nieuw erbij geselecteerd, uitgezonderd die zojuist uit de lijst zijn verwijderd.
  $("#matExist option").each(function (index, domEle)
                             { // initialisatie nieuw vast materiaal
                               var matopdrkey = -1;
                               var amount = 1;
                               var price = domEle.getAttribute("prijs").replace(',', '.') || 0; // Prijs uit database
                               var descript = domEle.text;
                               var roprice = domEle.getAttribute("prijs")? true : false; // Prijs readonly weergeven als er geen prijs voor materiaal is ingevuld
                               for (var i = 0; i < matkeystrArr.length; i++)
                               {
                                 if ((matkeystrArr[i] == domEle.value) && (matexiststrArr[i] == 1))
                                 { // gegevens bestaand vast materiaal overnemen
                                 	 matopdrkey = matopdrkeystrArr[i]; // Record key
                                   amount = matamountstrArr[i]; // Aantal die al eerder ingevoerd was
                                   price = matpricestrArr[i]; // Prijs die al eerder ingevoerd was
                                   descript = domEle.text;
                                   break;
                                 }
                               }
                               matExistArray[matExistArray.length] = new material(matopdrkey, domEle.value, amount, descript, price, roprice);
                             });

  // Eerst het standaardmateriaal
  var matHtml = makeMaterialHtml(matExistArray);
  setTotal(-1);
  $("#materialselect").hide();
  $("#aantalpricetable")[0].innerHTML = matHtml;

  // Maak de lijst met bestaande vrije materialen.
  // Het bijbehorende array wordt hierdoor gevuld.
  for (var i = 0; i < matexiststrArr.length; i++)
  {
  	if (matexiststrArr[i] == 0)
  	{
  		CreateRow(matamountstrArr[i], matunitstrArr[i], matpricestrArr[i], matbtwstrArr[i], matdescriptstrArr[i], matopdrkeystrArr[i]);
  		setTotal(rowIndex);
  	}
  }

  $("#aantalpriceselect").show();
  FcltMgr.resized(window);
}

function previousInvoer()
{
  $("#aantalpriceselect").hide();
  $("#aantalpricetable")[0].innerHTML = "";
  matExistArray = [];
  matUserArray = [];
  rowIndex = -1;
  setTotal(rowIndex);
  $("#materialselect").show();
  FcltMgr.resized(window);
}

function submit()
{
  if (!validateForm("u2"))
    return false;

  var total = $("#total").val();
  FcltMgr.closeDetail(window, { matTotal: total, matExistArray: matExistArray, matUserArray: matUserArray });
}

function mat_info()
{
   var sel = $('#materialselect :selected');
   if (sel.length > 0)
   {
      var mat_key = sel[0].value;
      var url = "appl/mgt/fac_usrtab.asp?mode=show&model=fac%5Fusrdatas&usertable=" + mld_ordermaterial_fac_usrtab_key + "&id=" + mat_key;
      FcltMgr.openDetail(url, "");
   }
}


// overige materialen

function MldItem(qty, unit, prc, btw, sum, descr, key)
{
  this.matopdrkey = key;
  this.unit = unit;
  this.amount = qty;
  this.price = prc;
  this.btw = btw;
  this.descript = descr;
  this.sum = sum;
}

function AddItem()
{
  CreateRow(1, "", 0, -1, "", -1);
}

function CreateRow(qty, unit, prc, btw, descr, key)
{
  rowIndex++;
  var table = $("#sel_items")[0];
  var sum = qty * prc;

  // Insert data rows
  var tr = table.insertRow(-1);

  // Create drop button
  var cell = tr.insertCell(-1);
  cell.innerHTML = "<img src='../Pictures/order_cancel.gif' OnClick='CancelMaterial(" + rowIndex + ")' style='cursor:pointer'>";

  // Create quantity field
  cell = tr.insertCell(-1);
  cell.innerHTML = "<input type='text' class='fldfinsom'"
                 + " onfocus='this.select();'"
                 + " onblur='QtyChanged(event);'"
                 + " id='qty" + rowIndex + "' name='qty" + rowIndex + "' maxlength='10' value='" + parseFloat(qty) + "'>";
  cell.align = 'left';

  // Create description field
  cell = tr.insertCell(-1);
  cell.innerHTML = "<input type='text' class='fld required'"
                 + " onblur='DesChanged(event);'"
                 + " id='descript" + rowIndex + "' name='descript" + rowIndex + "' maxlength='255'>";
  $("input", cell).val(descr); // safe oplossing

  // Create unit field
  cell = tr.insertCell(-1);
  cell.innerHTML = "<input type='text' class='fldshort'"
                 + " onfocus='this.select();'"
                 + " onblur='UnitChanged(event);'"
                 + " id='unit" + rowIndex + "' name='unit" + rowIndex + "' value='" + unit + "'>";
  cell.align = 'left';

  // Create price field
  cell = tr.insertCell(-1);
  cell.innerHTML = "<input type='text' class='fldfinsom'"
                 + " onfocus='this.select();'"
                 + " onblur='PrcChanged(event);'"
                 + " id='prc" + rowIndex + "' name='prc" + rowIndex + "' maxlength='10' value='" + num2curr(parseFloat(prc)) + "'>";
  cell.align = 'left';

  // Create BTW field
  cell = tr.insertCell(-1);
  cell.innerHTML = "<div id='btwdiv" + rowIndex + "'></div>";
  cell.align = 'left';
  cell.className = 'fldbtw';

  // Create total field
  cell = tr.insertCell(-1);
  cell.innerHTML = num2curr(sum)
                 + "<input type='hidden' id='sum" + rowIndex
                 + "' value='" + num2curr(parseFloat(sum)) + "'>";
  cell.align = 'right';

  $("#btwdiv" + rowIndex).load("../Shared/loadBtwTabel.asp",
                               { fieldname: "btw" + rowIndex,
                                 sel_key: "key", // select key is fin_btwtabelwaarde_key
                                 btw_key: btw,
                                 bedrijf_key: uitv_key,
                                 required: true,
                                 selectjustone: true,
                                 extraclass: "btwdiv",
                                 onChange: "BtwChanged(event)",
                                 emptyOption: ""
                               },
                               function () { // Als er maar eentje is gaat de onChange niet af
                                    var curval = $("#btw" + rowIndex).val();
                                	if (curval)
                                  	    matUserArray[rowIndex].btw = parseInt(curval, 10);
                                }
                              );

  matUserArray[rowIndex] = new MldItem(qty, unit, prc, btw, sum, descr, key);
  matUserArray[rowIndex].row = tr;
}

function QtyChanged(evt)
{
  evt = evt || window.event;
  var obj = evt.srcElement || evt.target;
  var qty = parseFloat(obj.value.replace(',', '.'));
  var defaultamount = 0;
  if (obj.value == '')
    obj.value = qty = defaultamount;
  if (obj.value == '' || isNaN(qty > 0? qty : -qty) ||
     !isGoodNumber(obj.value,false,true,8,2))
  {
     FcltMgr.alert(L("lcl_mld_opdr_invalid_quantity"));
     obj.focus();
     return;
  }
  obj.value = qty;
  var index = obj.id.substring(3);

  matUserArray[index].amount = qty;
  setTotal(index);
}

function UnitChanged(evt)
{
  evt = evt || window.event;
  var obj = evt.srcElement || evt.target;
	var unit = obj.value;
	var index = obj.id.substr(4);

  matUserArray[index].unit = unit;
}

function PrcChanged(evt)
{
  evt = evt || window.event;
  var obj = evt.srcElement || evt.target;
  var sum = parseFloat(obj.value.replace(',', '.'));
  var defaultprice = 0;
  if (obj.value == '')
    obj.value = sum = defaultprice;
  if (obj.value == '' || isNaN(sum > 0? sum : -sum) ||
     !isGoodCurrency(obj.value + "", false))
  {
     FcltMgr.alert(L("lcl_mld_opdr_invalid_sum"));
     obj.focus();
     return;
  }
  obj.value = num2curr(sum);
  var index = obj.id.substring(3);

  matUserArray[index].price = sum;
  setTotal(index);
}

function BtwChanged(evt)
{
  evt = evt || window.event;
  var obj = evt.srcElement || evt.target;
	var btw = parseInt(obj.value, 10);
	var index = obj.id.substr(3);

  matUserArray[index].btw = btw;
}

function DesChanged(evt)
{
  evt = evt || window.event;
  var obj = evt.srcElement || evt.target;
	var des = obj.value;
	var index = obj.id.substr(8);

  matUserArray[index].descript = des;
}

function setTotal(index)
{
	if ((matUserArray.length != 0) && (index >= 0))
	{ // Na wijzigen van amount of price moet de sum van deze regel worden aangepast.
    matUserArray[index].sum = parseFloat(matUserArray[index].amount * matUserArray[index].price);
    matUserArray[index].row.cells[6].innerHTML = "<nobr>" + num2curr(matUserArray[index].sum) + "</nobr>" + "&nbsp;";
  }
  var total = 0;
  for (var i in matExistArray)
  {
  	total += matExistArray[i].sum;
  }
  for (var i in matUserArray)
  {
    total += matUserArray[i].sum;
  }
  document.forms.u2.total.value = num2curr(total);
  document.getElementById("total_txt").innerHTML = currency_pref + num2curr(parseFloat(total)) + currency_suff;
}

function CancelMaterial(index)
{
  if (matUserArray[index] != null)
  {
    // remove from total
    var tr = matUserArray[index].row;
    var trIndex = tr.rowIndex;
    document.getElementById("sel_items").deleteRow(trIndex);

    matUserArray[index].row = null;
    matUserArray[index] = null;
    matUserArray.splice(index,1);

    setTotal(-1);
  }
}

