// Global variables, are known in all functions
var cText;
var cPeuro;
var cNordered;
var rowOrdered;
var cTotalEuro;
// var cv = document.cookie;

// Stores the data of the row selected by entering the number of items
// rowName : cr1_1 first row first colomn, cr1_2 is second column
// numOrdered: Number entered in table.
// Sequence of table values.
// 1: Nieuw or empty, 2: "Map" and number, 3: "Map" description
// 4: Price in Euro
function storeData (rowName, numOrdered)
{
   var i;
   var rowId;
   var comValue;
   var tmpValue;
   var varia;

   comValue = "";
   // Compose a line of table data
   // TEST: alert (rowName, + " " + numOrdered);
   for (i = 1; i < 5; i++)
   {
      rowId = rowName + "_" + i;
      varia = document.getElementById(rowId);
      comValue = comValue + varia.innerText + ";";
   }

   // Add the numOrdered value to the composed line.
   // It may not contain invalid chars.
   if (isNaN(parseInt(numOrdered)) || parseInt(numOrdered) < 0)
   {
      numOrdered = 0;
      parent.bestellijst.document.all[rowName].value = numOrdered;   
   }

   // Check if the limit of 20 has been reached.
   if (numOrdered > 0 && numberOfCookies() >= 20)
   {
      alert ("U heeft het maximale aantal (20) van deze bestelling bereikt, verstuur de bestelling. Daarna kunt u een nieuwe bestelling aanmaken");
      parent.bestellijst.document.all[rowName].value = 0;   
      readCookies ();
   }
   else
   {
      comValue = comValue + numOrdered;
      // TEST: alert ("comValue " + comValue);
      if (numOrdered != 0)
      {
         // alert ("write cookie");
         // Write the cookie
         setCookie(rowName, comValue, "", "");
      }
      else // In this case the numOrdered was reset so clean up the cookie.
      {
         // alert ("delete cookie");
         deleteCookie(rowName);    
      }
 
      // Calculate the totals like total ordered and price in Euro.
      calculateTotals (rowName);

      // Display the totals in the above frame.
      dispTotals ();
   }
}

/* Here we are really writing the cookie.
   Be aware that the maximum number of items in the cookie is
   limited to 20
*/
function setCookie(cookieName, cookieVal, cookiePath, cookieExpires)
{
   cookieVal = escape(cookieVal);
   var nowDate = new Date();

   if (cookieExpires == "")
   {
      nowDate.setMonth(nowDate.getMonth() + 6);
      cookieExpires = nowDate.toGMTString();
   }

   if (cookiePath != "")
   {
      cookiePath = "c:\\" + cookiePath;
   }

   document.cookie = cookieName + "=" + cookieVal + 
          ";expires=" + cookieExpires + cookiePath;
}


function deleteCookie (cookieName)
{
   var yesterday;
   var nowDate = new Date();
   nowDate.setMonth(nowDate.getMonth() - 1);
   yesterday = nowDate.toGMTString();

   setCookie(cookieName, "", "", yesterday);
}

function getCookieValues (cookieName, dispList)
{
   var cookieVal = document.cookie;
   var cookieStartsAt = cookieVal.indexOf(" " + cookieName + "=");

   // First reset these values before using them.
   cText         = "";
   cPeuro        = parseFloat("00.00");

   if (cookieStartsAt == -1)
   {
      cookieStartsAt = cookieVal.indexOf(cookieName + "=");
   }

   if (cookieStartsAt == -1)
   {
      cookieVal = null;
   }
   else
   {
      cookieStartsAt = cookieVal.indexOf("=", cookieStartsAt) + 1;
      var cookieEndsAt = cookieVal.indexOf(";", cookieStartsAt);
      if (cookieEndsAt == -1)
      {
         cookieEndsAt = cookieVal.length;
      }

      cookieVal = unescape(cookieVal.substring(cookieStartsAt,cookieEndsAt));

      cookieVal = cookieVal.split(";");

      /* 	0: Nieuw or empty
  	        1: "Map" and number
		2: "Map" description
		3: Price in Euro
		4: number of items entered
      */

      // only pick the number of the string.
      cookieVal[3] = cookieVal[3].substr(3);

      // These are the values of the row that was active.
      cText     = cookieVal[1] + cookieVal[2];
      cPeuro    = parseFloat(cookieVal[3]);
      rowOrdered= parseFloat(cookieVal[4]);
      // Debug: alert ("cPeuro " + cPeuro + " Ordered " + rowOrdered);
      // Do a recount
      cNordered     = cNordered + rowOrdered;
      cTotalEuro    = cTotalEuro + rowOrdered * cPeuro;

      if (dispList)
         dspOrderedBestellijst (cookieName, rowOrdered);	 
   }

   return cookieVal;
}


function calculateTotals (rName)
{
   var i;
   var cookie;

   cTotalEuro    = 0;
   cNordered     = 0;

   // TEST: alert ("Calculating Totals " + rName);
   for (i = 1; i <= 200; i++)
   {
      rName = rName.substring(0, 2) + i;
      // alert (rName);
      if (getCookieValues (rName, 1) == null)
	 continue;

      // alert (cText + " " + cNordered + " " + cTotalEuro);
   }
}

function dispTotals ()
{
   var temp;

   // parent.besteltotaal.document.all["desc"].innerText = cText;
   temp = cnv2DigitsFloat (cTotalEuro, 0);
   parent.besteltotaal.document.all["ordered"].innerText = cNordered;
   parent.besteltotaal.document.all["price"].innerText = "€ " + temp;
      
   temp = cnv2DigitsFloat (cTotalEuro, 4.25);
   parent.besteltotaal.document.all["TotalPrice"].innerText = "€ " + temp;
}


function dspOrderedBestellijst (cName, rOrder)
{
   parent.bestellijst.document.all[cName].value = rOrder;   
}


// Used in the window.onload of bestellijst.htm
// reads all data of the cookie into the pages.
function readCookies ()
{
   calculateTotals ("cr1");
   dispTotals ();
}

function fillOrderView ()
{
   var i, j;
   var iName;
   var iTekst;
   var iOrder;
   var iPrice;

   // cv = document.cookie;

   cTotalEuro    = parseFloat("00.00");
   cNordered     = 0;
   j = 1;

   iName  = "cr";
   iTekst = "rowTekst";
   iOrder = "rowOrder";
   iPrice = "rowPrice";
   for (i = 1; i <= 200; i++)
   {
      iName = iName.substring(0, 2) + i;
      if (getCookieValues (iName, 0) == null)
	 continue;
      else
      {
          dspCreaBestelOverzicht (iTekst, iOrder, iPrice, j, "LINE");
          updHiddenCreaBestelOverzicht (j, "LINE");
	  j++;
      }
   }

   if (cNordered > 0)
   {
      dspCreaBestelOverzicht (iTekst, iOrder, iPrice, j, "VERZEND");
      updHiddenCreaBestelOverzicht (j, "VERZEND");

      j++;
      dspCreaBestelOverzicht (iTekst, iOrder, iPrice, j, "TOTAL");
      updHiddenCreaBestelOverzicht (j, "TOTAL");
   }
}

function dspCreaBestelOverzicht (iTxt, iOrd, iPri, j, pos)
{ 
   var subtotal;

   iTxt = iTxt.substring(0, 8) + j;
   iOrd = iOrd.substring(0, 8) + j;
   iPri = iPri.substring(0, 8) + j;
   if (pos == "LINE")
   { 
      document.all[iTxt].innerText = cText;
      document.all[iOrd].innerText = rowOrdered;
      subtotal = rowOrdered * cPeuro;
      subtotal = cnv2DigitsFloat (subtotal, 0);
      document.all[iPri].innerText = "€ " + subtotal;
   }
   else if (pos == "VERZEND")
   { 
      document.all[iTxt].innerText = "Verzendkosten";
      document.all[iOrd].innerText = " ";
      document.all[iPri].innerText = "€ 4.25";
   }
   else
   {
      document.all[iTxt].innerText = " ";
      document.all[iOrd].innerText = "+ --------";
      document.all[iPri].innerText = "+ --------";
      
      cTotalEuro = cnv2DigitsFloat (cTotalEuro, 4.25);
 
      j++;

      iTxt = iTxt.substring(0, 8) + j;
      iOrd = iOrd.substring(0, 8) + j;
      iPri = iPri.substring(0, 8) + j;

      document.all[iTxt].innerText = " Totaal";
      document.all[iOrd].innerText = cNordered;
      document.all[iPri].innerText = "€ " + cTotalEuro;
   }
}

function updHiddenCreaBestelOverzicht (j, pos)
{
   var i = 1, len;
   var iName, prefix;
   var subtotal;
   var blanks;

   blanks = "____________________________________________________________";
   prefix = "hidpd" + j + "_";
 
   iName = prefix + i++;
   if (pos == "LINE")
   {
      len = cText.length;
      document.all[iName].value = cText + blanks.substring(0, 65 - len);
      iName = prefix + i++;
      document.all[iName].value = "  " + rowOrdered;   
      iName = prefix + i++;
      subtotal = rowOrdered * cPeuro;
      subtotal = cnv2DigitsFloat (subtotal, 0);
      document.all[iName].value = "  € " + subtotal;   
   }
   else if (pos == "VERZEND")
   { 
      document.all[iName].value = "Verzendkosten" + blanks.substring(0, 52);  
      iName = prefix + i++;
      document.all[iName].value = " ";   
      iName = prefix + i++;
      document.all[iName].value = "  € 4.25"; 
   }
   else
   {
      document.all[iName].value =  blanks.substring(0, 65);  
      iName = prefix + i++;
      document.all[iName].value = "+ --"; 
      iName = prefix + i++;
      document.all[iName].value = "+ --------";
     
      j++;
      i = 1;
      prefix = prefix.substring(0, 5) + j + "_";         
      iName = prefix + i++;

      document.all[iName].value = "Totaal" + blanks.substring(0, 59);  
      iName = prefix + i++;
      document.all[iName].value = "  " + cNordered;   
      iName = prefix + i++;
      document.all[iName].value = "  € " + cTotalEuro;   
   }
}


function ValidatePersonalData ()
{
   var i;
   var inx;
   var wrong;
  
   inx = "pd";
   wrong = 0;
   for (i = 1; wrong == 0 && i <= 6; i++)
   {
      inx = inx.substring(0, 2) + i;      

      if (document.all[inx].value == "")
         wrong = 1;
   }

   if (wrong == 1)
   {
      if (i == 2)
      {
         alert ("Ongeldige ingave, NAAM is verplicht");
         return (false);
      }
      else if (i ==3)
      {
         alert ("Ongeldige ingave, ADRES is verplicht");
         return (false);
      }
      else if (i ==4)
      {
         alert ("Ongeldige ingave, POSTCODE is verplicht");
         return (false);
      }
      else if (i ==5)
      {
         alert ("Ongeldige ingave, WOONPLAATS is verplicht");
         return (false);
      }
      else if (document.all["pd5"].value == "" && document.all["pd6"].value == "" )
      {
         alert ("Ongeldige ingave, TELEFOONNR. of EMAIL is verplicht");
         return (false);
      }
   }
   // Before sending the form clear the current Order.
   deleteAll ("Overzicht");
   return (true);
}


function deleteAll (page)
{
   var i;
   var rName;

   rName  = "cr";
   for (i = 1; i <= 200; i++)
   {
      rName = rName.substring(0, 2) + i;
      deleteCookie (rName);

      if (page.indexOf("Overzicht") == -1)
      {
         parent.bestellijst.document.all[rName].value = 0;            
      }
   }

   if (page.indexOf("Overzicht") == -1)
      readCookies ();
}


function goPage (page, fLevel)
{
   if (page.indexOf("creaFbestelling.htm") != -1)
   {
      if (!document.all)
         page = "altBestelling.htm";
   }

   if (fLevel == 0)
   {
      window.location.href = page;
   }
   else if (fLevel == 1)
   { 
      parent.frames["content"].location.href = page;
   }
   else if (fLevel == 2)
   { 
      parent.parent.frames["content"].location.href = page;
   }
}

function numberOfCookies ()
{
   var i, j = 0;

   for (i = 1; i <= 200; i++)
   {
      rName = "cr" + i;
      if (getCookieValues (rName, 1) == null)
	 continue;
      j++;
   }
   return j;
}

function cnv2DigitsFloat (amount1, addAmount)
{
   var temp, posDigit, digits;

   temp = amount1 * 100;
   if (temp > 0)
      temp = parseInt(temp) + (addAmount * 100);

   temp = parseFloat(temp) / 100;

   temp = " " + temp;
   posDigit = temp.indexOf (".");
   digits = temp.length - posDigit -1;

   // Found dot so add one or dot+two zeros
   if (posDigit >= 0)
   { 
      if (digits == 1)           // Missing one zero
         temp = temp + "0";
      else if (digits == 0)
          temp = temp + "00";   // Missing both zeros
   }
   else                         // No dot found, so add .00
      temp = temp + ".00";

   // alert ("digits =" +  digits + " " + posDigit + temp);  

   return (temp.substring (1, temp.length));
}



