// Ajout des listeners
Event.observe(window, 'load', initialiseLeEvenement, false);

// -----------------
// Les fonctions
function initialiseLeEvenement(e) {
	var newCatType = $('newCatType')

	if (newCatType != null && newCatType != undefined) {
		if (newCatType.nodeName == "SELECT") {
			for (var i=0; i < newCatType.options.length; i++) {
				name = newCatType.options[i].text
				if (newCatType.options[i].text == "typecatHard")
					name = "Périphérique"
				if (newCatType.options[i].text == "typecatSoft")
					name = "Logiciel"
				if (newCatType.options[i].text == "typecatMach")
					name = "Machine"
				if (newCatType.options[i].text == "typecatCons")
					name = "Consommable"
				newCatType.options[i].text 			= name
				newCatType.options[i].textContent 	= name
				newCatType.options[i].innerHTML 	= name
			}
		}
	
		loadNewSousCatType()
		Event.observe(newCatType, 'change', loadNewSousCatType, false);

		if(window.location.href.match(/voir_LFC\.php\?action=commander/))
			Event.observe(newCatType, 'change', showHideInput, false);
	}
	
	var newSousCatType = $('newSousCatType')
	if (newSousCatType != null && newSousCatType != undefined) {
		loadNewSousLibType()
		Event.observe(newSousCatType, 'change', loadNewSousLibType, false);
	}
}

/* Affiche ou cache des champs du formulaire en fonction du type d'article inseré. */
function showHideInput (e) {
	var targ
	if (!e) 
		var e = window.event
	if (e.target) 
		targ = e.target
	else 
		if (e.srcElement) 
			targ = e.srcElement
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode
	
	if (targ.options[targ.selectedIndex].value == "typecatSoft")
		$('num_serie').parentNode.parentNode.style.display 	= "";
	else
		$('num_serie').parentNode.parentNode.style.display 	= "none";
	/*
	var mesLibelle = null
	var mesDisplay = null
	if (targ.options[targ.selectedIndex].value == "typecatMach") {
		mesLibelle = new Array("Nom", "", "", "Description")
		mesDisplay = new Array("", "none", "none", "")
	}
	if (targ.options[targ.selectedIndex].value == "typecatHard" || 
		targ.options[targ.selectedIndex].value == "typecatCons") 
	{
		mesLibelle = new Array("Marque", "Modèle", "", "Remarque")
		mesDisplay = new Array("", "", "none", "")
	}
	if (targ.options[targ.selectedIndex].value == "typecatSoft") {
		mesLibelle = new Array("Nom", "Remarque", "Numéro de série", "")
		mesDisplay = new Array("", "", "", "none")
	}

	$('lbl_marque').innerHTML							= mesLibelle[0] + " :"
	$('lbl_modele').innerHTML							= mesLibelle[1] + " :"
	$('lbl_num_serie').innerHTML						= mesLibelle[2] + " :"
	$('lbl_rmq').innerHTML								= mesLibelle[3] + " :"
	$('marque').parentNode.parentNode.style.display 	= mesDisplay[0]
	$('modele').parentNode.parentNode.style.display 	= mesDisplay[1]
	$('num_serie').parentNode.parentNode.style.display 	= mesDisplay[2]
	$('rmq').parentNode.parentNode.style.display 		= mesDisplay[3]
	*/
}

function loadNewSousLibType (e) {
	var newSousLibType = $('newSousLibType')
	var newSousCatType = $('newSousCatType')
	if (newSousLibType != null && newSousLibType != undefined && newSousCatType != null && newSousCatType != undefined) {
		var url = 'inc/ajax/stocks/Ajax_stock.php';

	    var opts = { method : "get",
	                 parameters : "action=loadNewSousLibType&loadNewCatType=" + newSousCatType.options[newSousCatType.selectedIndex].value,
					 onLoading : show_hide_Waiting,
	                 onComplete : showLibType,
	                 asynchronous : true };

		var req = new Ajax.Request(url, opts);
	}
}

function showLibType(originalRequest)
{
	var newSousLibType = $('newSousLibType')
	if (newSousLibType != null && newSousLibType != undefined) {
		var desSousCat = originalRequest.responseXML.getElementsByTagName('uneSousCat');

		clearSelect(newSousLibType)
		displayError(originalRequest, newSousLibType)

		for (var i=0; i < desSousCat.length; i++)
		{
			var o = document.createElement('OPTION');
			o.value = getNodeValue(desSousCat[i],'SousCatTypeId')
			o.appendChild (document.createTextNode(getNodeValue(desSousCat[i], 'SousCatTypeLib')))
			newSousLibType.appendChild(o)
		}
	}
	show_hide_Waiting()
}

function loadNewSousCatType(e) {
	var newSousCatType = $('newSousCatType')
	var newCatType = $('newCatType')
	if (newSousCatType != null && newSousCatType != undefined && newCatType != null && newCatType != undefined) {
		var url = 'inc/ajax/stocks/Ajax_stock.php'
		var newCatTypeValue = null
		
		if (newCatType.nodeName == "INPUT")
			newCatTypeValue = newCatType.value
		else
			newCatTypeValue = newCatType.options[newCatType.selectedIndex].value
		
	    var opts = { method : "get",
	                 parameters : "action=loadNewSousCatType&loadNewCatType=" + newCatTypeValue,
					 onLoading : show_hide_Waiting,
	                 onComplete : showResponse,
	                 asynchronous : true };

		var req = new Ajax.Request(url, opts);
	}
}

function show_hide_Waiting (originalRequest) {
	if ($('img_working').style.backgroundPosition == "-50px 50%")
		$('img_working').style.backgroundPosition = "50% 50%";
	else {
		for (var i=0; i++; i==10000) {}
		$('img_working').style.backgroundPosition = "-50px 50%";
	}
}

function showResponse(originalRequest)
{
	var newSousCatType = $('newSousCatType')
	if (newSousCatType != null && newSousCatType != undefined) {
		// put returned XML in the textarea

		var desSousCat = originalRequest.responseXML.getElementsByTagName('uneSousCat');
		
		clearSelect(newSousCatType)
		displayError(originalRequest, newSousCatType)
		
		for (var i=0; i < desSousCat.length; i++)
		{
			var o = document.createElement('OPTION');
			o.value = getNodeValue(desSousCat[i],'SousCatTypeId')
			o.appendChild (document.createTextNode(getNodeValue(desSousCat[i], 'SousCatTypeLib')))
			newSousCatType.appendChild(o)
		}
	}
	loadNewSousLibType()
	show_hide_Waiting()
}
// --------------
// Utilitaires
function codeTouche(evenement) {
	for (prop in evenement)
		if(prop == 'which')
			return(evenement.which);
	return(evenement.keyCode);
}

function checkKeyAreNums(evenement) {
	var reCarSpeciaux = /[\x00\x08\,\.\-]/; // Modification LuR : Ajout du "-"
	var reCarValides = /\d/;

	var codeDecimal = codeTouche(evenement);
	var car = String.fromCharCode(codeDecimal);
	var autorisation = reCarValides.test(car) || reCarSpeciaux.test(car);

	return autorisation;
}

function remplaceAll(expr,a,b) {
	var i=0
	while (i!=-1) {
		i=expr.indexOf(a,i);
		if (i>=0) {
			expr=expr.substring(0,i)+b+expr.substring(i+a.length);
			i+=b.length;
		}
	}
	return expr
}
   
function getNodeValue(obj,tag)
{
	return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
}

function clearSelect (theSelect) {
	removectr = (theSelect.options.length) - 1;
	while (removectr > -1) {
	   theSelect.options[removectr] = null;
	   removectr--;
	}
}

function displayError (originalRequest, obj_select) {
	var newSousCatType = $('newSousCatType')
	if (newSousCatType != null && newSousCatType != undefined) {
		var desSousCat = originalRequest.responseXML.getElementsByTagName('error');
		if (desSousCat) {
			for (var i=0; i < desSousCat.length; i++)
			{
				var o = document.createElement('OPTION');
				o.style.color = "rgb(245, 238, 238)"
				o.appendChild (document.createTextNode(getNodeValue(desSousCat[i], 'error_text')))
				obj_select.appendChild(o)
			}
		}
	}
}

/* Ci dessus était placé des listener qui écoutait les différents id de la page, les fonctions ci-dessous fonctionneront sur appel javascript 
ie: <span onclick="toto(this)">&nbsp;</span> */
/*
* Developpeur: BONNIEUX Stephane
* Date: 26-02-2007
*
* Description: 
=> La valeur du prix TTC calculée en fonction du prix HT est mauvaise !!!! et oui 19.7 au lieu de 19.6 déjà sa commence mal !!!
=> L'arrondi se fait à 2 chiffre après la virgule ce qui fausse certaines valeurs à cause du parseFloat(), on le change avec eval()

l.251: var newPrixAchat = parseFloat(remplaceAll(e.value, ',', '.'))
l.275: var ancienPrix = parseFloat(remplaceAll($("prixachatsav_"+id[1]).value , ',', '.'))
l.276: var difference = Math.abs ( parseFloat($('qtite').value) * (ancienPrix - newPrixAchat))
l.279: $('montHT').value = parseFloat($('montHT').value) - difference
l.281: $('montHT').value = parseFloat($('montHT').value) + difference
l.284: $('montHT').value = (Math.round(parseFloat($('montHT').value) * 100)) / 100
l.290: $('montTTC').value = Math.round((parseFloat($('montHT').value) + (parseFloat($('montHT').value) * 19.7 / 100)) * 100) / 100
*/
function changePrixAchat(e, qte) {
	var id = e.id.split('_')	// l'id contien est composant d'une partie texte et du numero de l'Id commande a modifier (ie. prixachat_15487)
	var Lcid = id[1] 			// apres le split on devrait avoir 15487
	
	var newPrixAchat = eval(remplaceAll(e.value, ',', '.'))
//alert(newPrixAchat);
	if (!(isNaN(Lcid))) { // on fait une verification sur le type de la valeur, si numérique on continue
		var url = 'inc/ajax/stocks/Ajax_stock.php';
		var opts = {method : "get",
					parameters : "action=changePrixAchat&idLcToChange=" + Lcid + "&newPrixAchat=" + newPrixAchat,
					onComplete : function (originalRequest) {
									e.style.backgroundColor = 'rgb(188, 210, 226)'
									var result = originalRequest.responseXML.getElementsByTagName('result');
									if (result) {
										var newtext = document.createElement("P")
											if (getNodeValue(result[0], 'resultText') == "effectuée") 
												newtext.style.color="rgb(0, 128, 0)" 
											else
												newtext.style.color="rgb(216, 134, 134)" 
											newtext.appendChild(document.createTextNode(getNodeValue(result[0], 'resultText')))
										e.parentNode.replaceChild (newtext, e.parentNode.firstChild)
									}
								},
					asynchronous : true };

		var req = new Ajax.Request(url, opts);
		
		// mise a jour du montant HT
		
		var ancienPrix = eval(remplaceAll($("prixachatsav_"+id[1]).value , ',', '.'));
		var difference = Math.abs(eval($('qtite_'+id[1]).value) * (ancienPrix - newPrixAchat));
		if (ancienPrix > newPrixAchat) {
			$('montHT').value = eval(eval($('montHT').value) - difference)
		} else if (ancienPrix < newPrixAchat) {
			$('montHT').value = eval(eval($('montHT').value) + difference)
		}

		// Une fois que tout est OK, on met a jour la valeur de référence du prix d'achat ...
		$("prixachatsav_"+id[1]).value = newPrixAchat
		// ... et le montant TTC

		$('montTTC').value = eval(eval($('montHT').value) + (eval($('montHT').value) * 0.196));
	}
}