/*
 * Fichier Javascript.
 *
 * @author   TML
 * @created  18/07/06 22:00
 * @modified 07/08/06 21:40
 */
/*-----------------------------------------------------------------*/

 /*Ajouts MML======================================================*/
 /*Reconnecte*/  
 function Reconnecte()
{
delete client[1];
gl_nb --;
}

 
/* Lance l'une des trois applis */
function  saisiecommandes(valeur)
{
switch(valeur)
{
case 1:
window.location="precos.html";
break;
case 2:
window.location="TarifCPDL.php";
break;
case 3:
window.location="CPDLFormSaisieArt.htm";
break;
case 4:
window.location="formulaire_test.php";
break;
}
}

 
 /* Remet taille en fond blanc après alerte "rouge" */
function Fondblanc(idnb)
{ 
 document.getElementById('taille_' + idnb).style.background = gl_white;
} 

 
 /* Fonction de contrôle du focus */
function DonneFocus()
{ 
 	document.getElementById('Article').focus();
}
  
 /* Fonction de contrôle de l'existence d'une apostrophe dans Client final */
function CoteEnCliFinal(idnb)
{
var modele=/\'/;
var text=document.getElementById('client_' + idnb).value;
if (modele.test(text)) 
{
alert('Ne saisissez  pas d\'apostrophe dans le nom de la cliente')
}
}  
 
 /* Fonction de contrôle de l'existence d'une taille */
function ExisteTaille(idnb)
{
if ((document.getElementById('taille_' + idnb).value=='') || (document.getElementById('taille_' + idnb).value==null))
{
alert ("Vous devez sélectionner une taille");
document.getElementById('taille_' + idnb).focus();
document.getElementById('taille_' + idnb).style.background = gl_red;
}
else
document.getElementById('taille_' + idnb).style.background = gl_white;

}

 /*Supprime la dernière ligne NO GOOD*/  
 function SupDerLig()
{
delete client[1];
gl_nb --;
}

/* Teste la saisie de la zone Cient*/
 function TesteSaisieClients()
{
	var OK = true;
  var elem_cour;
	for (var i = 0; i < gl_nb; i++)     
	{
  j=i+1;
	elem_cour = document.getElementById('client_' + i);
   
	 if	(!elem_cour)
    continue;
   else if (elem_cour.value=='')
      {
      alert ("La zone \"Client(Prénom NOM)\" ne doit pas être vide à la ligne "  + j);
      OK = false;
      }
      if	((document.getElementById('alivrer_' + i).value==0) && (document.getElementById('stock_' + i).value==0))
      {
	    alert ("Les quantités ne peuvent pas être simultanément nulles à la ligne "  + j);
	    OK=false;
      }
      /* Ajout du 11/03/2007*/
     /* alert (document.getElementById('refart_' + i).value);
      alert (document.getElementById('name_' + i).value);
      Cette modif s'accompagne de la création de la vue 
      VuePourCheckArticle utilisée dans le Select d'accès aux 
      données article dans ajax_query.php*/

      if	((document.getElementById('refart_' + i).value=='')) /*|| (document.getElementById('refart_' + i).value==null))*/
      {
	    alert ("Il manque le code article à la ligne "  + j);
	    OK=false;
      }
      if	((document.getElementById('taille_' + i).value=='') || (document.getElementById('taille_' + i).value==null))
      {
	    alert ("Il manque la taille à la ligne "  + j);
	    OK=false;
      }

      if	((document.getElementById('prix_' + i).value=='') || (document.getElementById('prix_' + i).value==null))
      {
	    alert ("Il manque le prix à la ligne "  + j);
	    OK=false;
      }

      /* Fin ajout */ 
      
  }
if (OK == true) 
  {
    document.getElementById('cpdl_form').submit();
  }
}

/* Contrôle la validité du PWD */
function lance(mdp)
{
if (mdp=="CPDL")
{
window.location="menu.html";
}
else if (mdp=="MML")
{
window.location="menu_test.html";
}
else if (mdp=="POISSON")
{
window.location="stock.html";
}
else 
{
alert("Mot de passe erroné");
}
}
 /*Fin ajouts MML======================================================*/
 
/**
 * Javascript round function return an integer
 *
 * @param nb : the number to round
 * @param cent : the number of digits afert '.'
 */

 
function realRound(nb, cents)
{
	if (cents == 'undefined')
	{
		cents = 0;
		x = 1;
	}
	for (x = 0; cents; cents--)
	{
		if (x)
		{
			x *= 10;
		}
		else
		{
			x = 10;
		}
	}
	return (Math.round(nb * x) / x);
}

/**
 * Look for an element in an Array
 *
 * @param source : the array to look into
 * @param data   : the data to look for
 * @return       : the index of the data in the array if found, false if not
 */
function inArray(source, data)
{
	len = source.length;
	for (var i = 0; i < len; i++)
	{
		if (source[i] == data)
		{
			return i;
		}
	}
	return false;
}

/*-----------------------------------------------------------------*/

// Error messages
var noSuchRef  = 'La référence entrée est incorrecte';

// Global variables
var gl_nb      = 1;
var gl_requete = null;
var gl_red     = '#ff7272';
var gl_orange  = '#ffd279';
var gl_green   = '#79d279';
var gl_white   = '#FFFFFF';
var gl_sizes   = new Array();

/*-----------------------------------------------------------------*/

// Initiate XMLHttpRequest for Ajax matters
if (window.XMLHttpRequest) // IE
{
	gl_requete = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
	gl_requete = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
	alert('Veuillez mettre à jour votre navigateur');
	document.localtion.href = "http://getfirefox.com";
}

/*-----------------------------------------------------------------*/

/**
 * Add a line to command an article
 */
function addArticle()
{
	table = document.getElementById('command');

	var new_tr = document.createElement('tr');
	new_tr.setAttribute('id', 'mytr_' + gl_nb);
	var td1    = document.createElement('td');
	var td2    = document.createElement('td');
	var td3    = document.createElement('td');
	var td4    = document.createElement('td');
	var td5    = document.createElement('td');
	var td6    = document.createElement('td');
	var td7    = document.createElement('td');
	var td8    = document.createElement('td');
	var td9    = document.createElement('td');
	td1.innerHTML = '<a href="#" onClick="delete_element(\'mytr_' + gl_nb + '\');">Suppr</a>';
	td2.innerHTML = '<input type="text" name="client[]" style="width: 180px;" id="client_' + gl_nb + '" />';
	td3.innerHTML = '<input type="text" name="article[]" style="width: 80px;" id="refart_' + gl_nb + '" onChange="this.value=this.value.toUpperCase() , checkArticle(this.value, this, ' + gl_nb + ');" />';
	td4.innerHTML = '<div id="div_name_' + gl_nb + '">&nbsp;</div><input type="hidden" name="artname[]" style="width: 330px;" id="name_' + gl_nb + '" value="" />';
	td5.innerHTML = '<select name="taille[]" id="taille_' + gl_nb + '" disabled="true" onChange="Fondblanc(0), checkTaille(this.value, this, ' + gl_nb + ');"><option>Choisissez d\'abord un article</option></select>';
	td6.innerHTML = '<input type="text" name="alivrer[]" id="alivrer_' + gl_nb + '" style="width: 50px;" value="0" onChange="ExisteTaille(' + gl_nb + ') , updateTotalValue(' + gl_nb + ');" />';
	td7.innerHTML = '<input type="text" name="stock[]" id="stock_' + gl_nb + '" style="width: 50px;" value="0" onChange="ExisteTaille(' + gl_nb + ') , updateTotalValue(' + gl_nb + ');" />';
	td8.innerHTML = '<div style="text-align: center;" id="div_prix_' + gl_nb + '">&nbsp;</div><input type="hidden" id="prix_' + gl_nb + '" name="prix[]"  style="width: 50px;" value="" />';
	td8.innerHTML += '<input type="hidden" id="prix_ach_' + gl_nb + '" name="prixach[]" value="" />';
	td9.innerHTML = '<div style="text-align: center;" id="div_total_' + gl_nb + '">&nbsp;</div><input type="hidden" id="total_' + gl_nb + '" name="total[]" style="width: 50px;" value="" />';
	new_tr.appendChild(td1);
	new_tr.appendChild(td2);
	new_tr.appendChild(td3);
	new_tr.appendChild(td4);
	new_tr.appendChild(td5);
	new_tr.appendChild(td6);
	new_tr.appendChild(td7);
	new_tr.appendChild(td8);
	new_tr.appendChild(td9);
	table.appendChild(new_tr);

	document.getElementById('client_' + gl_nb).focus();

	gl_nb++;
}

/**
 * Verify if the number in the field is a positive number
 * (ie not a negative number nor a
 */

function verifNumber(elm)
{
	if (isNaN(elm.value) || (elm.value < 0))
	{
		elm.value = '0';
	}
}

/**
 * Calculate the price every client will have to pay :)
 */
function getPerClientPrice()
{
	var placeInArray;
	var elm;
	var value;
	var clients = new Array();
	var totals  = new Array();

	for (var i = 0; i < gl_nb; i++)
	{
		elm = document.getElementById('client_' + i);
		if (elm == null || elm.background == gl_red || elm.value == '')
			continue;

		placeInArray = inArray(clients, elm.value);
		value = parseFloat(document.getElementById('total_' + i).value);
		if (isNaN(value))
			continue;

		if (placeInArray === false)
		{
			placeInArray = clients.push(elm.value) - 1;
			totals.push(value);
		}
		else
		{
			totals[placeInArray] += value;
		}
	}
	if (totals.length)
	{
		var tot_div = document.getElementById('totaux');
		tot_div.innerHTML = '';
		if (document.getElementById('totaux_h1').style.display == 'none')
		{
			document.getElementById('totaux_h1').style.display = 'block';
			tot_div.style.display = 'block';
		}
		else if (tot_div.style.display == 'none')
		{
			tot_div.style.display = 'block';
		}
		for (var i = 0; i < totals.length; i++)
		{
			document.getElementById('totaux').innerHTML += '<strong>' + clients[i] + ' :</strong> ' + totals[i] + '&euro;<br />';
		}
	}
}

/** Made by MML
 * Calculate the global price :)
 */
 function getGlobalPrice()
{
	var elm;
	var value;
	var cumul=0;


	for (var i = 0; i < gl_nb; i++)
	{
		elm = document.getElementById('client_' + i);
		if (elm == null || elm.background == gl_red || elm.value == '')
			continue;

		value = parseFloat(document.getElementById('total_' + i).value);
	if (isNaN(value))
			continue;
			
      cumul +=value;
  }
			document.getElementById('total').innerHTML = '<strong>Total de la Commande :</strong> ' + cumul + '&euro;<br />';
}
/* Fin du made by MML


/**
 * Calculate the total value, depending on the article's price, and the number of items
 *
 * @param line : the line where we're working on
 */
function updateTotalValue(line)
{
	toDeliver = parseFloat(document.getElementById('alivrer_' + line).value);
	inStock   = parseFloat(document.getElementById('stock_' + line).value);
	price     = parseFloat(document.getElementById('prix_' + line).value);

	if (isNaN(price))
		return;

	total_price = ((toDeliver + inStock) * price);

	document.getElementById('div_total_' + line).innerHTML = total_price;
	document.getElementById('total_' + line).value = total_price;
}

/**
 * Query DB to get information about wether the data exists or not
 *
 * @param name : What is typed in the input field
 * @param elm  : The input field itself
 */
function checkClient(name, elm)
{
	gl_requete.open('get', 'ajax_query.php?client=' + name, true);
	gl_requete.onreadystatechange = function()
	{
		if (gl_requete.readyState == 4)
		{
			if (gl_requete.responseText != 0)
			{
				elm.style.background = gl_green;			
				array = gl_requete.responseText.split("|");
				document.getElementById('host_title').innerHTML   = '&nbsp;' + array[0] + '&nbsp;';
				document.getElementById('host_name_').innerHTML   = '&nbsp;' + array[1] + '&nbsp;';
				document.getElementById('host_address').innerHTML = '&nbsp;' + array[2] + ' ' + array[3] + ' ' + array[4] + '&nbsp;';
				document.getElementById('host_phone').innerHTML   = '&nbsp;' + array[5] + '&nbsp;';
				document.getElementById('host_re_no').value       = array[6];
				document.getElementById('host_mail_').innerHTML   = '&nbsp;' + array[7] + '&nbsp;';
				document.getElementById('host_mail').value        = array[7]; 
				document.getElementById('host_qualite_').innerHTML   = '&nbsp;' + array[8] + '&nbsp;';
				document.getElementById('host_qualite').value        = array[8]; 		
			}
			else
			{
				elm.style.background = gl_red;
				tmp = alert(noSuchRef);
				alert('ATTENTION : le code hotesse est erroné. Votre commande ne serait pas traitée. Saisissez un code correct.');
			}
		}
	}
	gl_requete.send(null);
}

/**
 * Query DB to get information about wether the article exists or not
 *
 * This function will also get in DB the Name and price of the article
 *
 * @param name : What is typed in the input field
 * @param elm  : The input field itself
 * @param idnb : The id number, where to put the response elements
 */
function checkArticle(name, elm, idnb)
{
	gl_requete.open('get', 'ajax_query.php?article=' + name, true);
	gl_requete.onreadystatechange = function()
	{
		if (gl_requete.readyState == 4)
		{
			if (gl_requete.responseText == '0')
			{
				elm.style.background = gl_red;
				document.getElementById('div_prix_' + idnb).innerHTML = '&nbsp;';
				alert(noSuchRef);
			}
			else
			{
				elm.style.background = gl_green;
				array = gl_requete.responseText.split('|');
				document.getElementById('div_name_' + idnb).innerHTML = array[0];
				document.getElementById('name_' + idnb).value = array[0];
				document.getElementById('div_prix_' + idnb).innerHTML = realRound(array[1], 2);
				document.getElementById('prix_' + idnb).value = realRound(array[1], 2);
				document.getElementById('prix_ach_' + idnb).value = realRound(array[2], 2);
				updateTotalValue(idnb);

				sizes     = array[3].split(',');
				selectBox = document.getElementById('taille_' + idnb);
				selectBox.disabled = false;
				for (var x = 0; x < sizes.length; x++)
				{
					if (!x)
					{
						selectBox.innerHTML = '';
					}
					var option = document.createElement('option');
					var text   = document.createTextNode(sizes[x]);
					option.setAttribute('value', sizes[x]);
					option.appendChild(text);
					selectBox.appendChild(option);
				}
			document.getElementById('taille_' + idnb).value='';	
			document.getElementById('taille_' + idnb).focus();	
			}
		}
				else 
			{
				elm.style.background = gl_orange;
	      document.getElementById('div_name_' + idnb).innerHTML= 'Code erreur ' +  gl_requete.readyState;
			}
	}
	gl_requete.send(null);
}

/**
 * Query DB to get information about wether the article exists or not
 *
 * This function will also get in DB the Name and price of the article
 *
 * @param name : What is typed in the input field
 * @param elm  : The input field itself
 * @param idnb : The id number, where to put the response elements
 */
function checkTaille(taille, elm, idnb)
{								  

	gl_requete.open('get', 'ajax_query.php?clef=' + document.getElementById('refart_' + idnb).value + '_' + taille, true);
	gl_requete.onreadystatechange = function()
	{
		if (gl_requete.readyState == 4)
		{
			if (gl_requete.responseText == '0')
			{
				elm.style.background = gl_red;
				document.getElementById('div_prix_' + idnb).innerHTML = '&nbsp;';
				alert(noSuchRef);
			}
			else
			{	 
				elm.style.background = gl_green;
				array = gl_requete.responseText.split('|');
				document.getElementById('div_prix_' + idnb).innerHTML = realRound(array[0], 2);
				document.getElementById('prix_' + idnb).value = realRound(array[0], 2);
				updateTotalValue(idnb);


			}
		}
				else 
			{
				elm.style.background = gl_orange;
	      document.getElementById('div_prix_' + idnb).innerHTML= 'Code erreur ' +  gl_requete.readyState;
			}
	}
	gl_requete.send(null);
}


/**
 * Delete an element
 *
 * @param elm  : The id of the element to delete
 */
function delete_element(elm)
{
	var elem = document.getElementById(elm);
	if (elem)
		elem.parentNode.removeChild(elem);
}

