/*
 * @include "/searchfood/web/js/lib/prototype.js" @include
 * "/searchfood/web/js/lib/scriptaculous.js" @include
 * "/searchfood/web/js/lib/builder.js" @include
 * "/searchfood/web/js/lib/controls.js" @include
 * "/searchfood/web/js/lib/effects.js" @include
 * "/searchfood/web/js/lib/sound.js" @include "/searchfood/web/js/lib/slider.js"
 * @include "/searchfood/web/js/lib/dragdrop.js"
 * @include "/searchfood/web/jwchat/jsjac.js"
 */

var ol_fgcolor = '#d7ebfe';
var ol_bgcolor = '#658bb2';
var ol_border = "1";
var ol_captionsize = "12px";
var nbphotos = 1;
var photodivcontent = '';
var mesid = '';
var nbCuisineEl = 0;
var quartiers = [];

onload = windowLoaded;
onunload = windowUnloaded;

function windowLoaded() {
	checkConnected();
	new PeriodicalExecuter(checkConnected, 60);
}

function checkConnected() {
	new Ajax.Request('/userconnection/refreshConnection');
}

function windowUnloaded() {

}

function modifyImage(what) {
	$('new' + what + '_photook').hide();
	$('new' + what + '_photo').show();

}

function cancelModifyImage(what) {
	$('new' + what + '_photo').hide();
	$('new' + what + '_photook').show();
}

function leftmenuN1clicked(name) {
	hideOthers();
	Effect.SlideDown("submenu" + name);
	$(name).className = "actualmenuelement";

	return false;

}

function leftmenuN2clicked(nameN2) {
	restoreN2Styles();
	$(nameN2).className = "actualmenuelementN2";

	return false;

}

function hideOthers() {
	$$(".actualmenuelement").each( function(mn1) {
		mn1.className = "menun1"
	});
	$$(".actualmenuelementN2").each( function(mn1) {
		mn1.className = "menun2"
	});
	var others = $$(".submenu");
	others.each( function(n1) {
		n1.hide();
	});
}
function restoreN2Styles() {
	$$(".actualmenuelementN2").each( function(mn1) {
		mn1.className = "menun2"
	});
}

function addPhoto() {
	var thisphoto = 'photo' + nbphotos;
	$('listephotos').innerHTML += "<div class='formitem' id='" + thisphoto
			+ "'>" + $('photo').innerHTML + "<A href='#' onclick=\"$('"
			+ thisphoto + "').remove()\" class='rightsideinput'>X</A></div>";
	nbphotos++;
}

function selectImage(id, url_preview) {
	$$('.selected_image').each( function(el) {
		el.className = "unselected_image";
	});
	$$('.selected_defimage').each( function(el) {
		el.className = "unselected_defimage";
	});
	if ($(id).className == "unselected_defimage"
			|| $(id).className == "selected_defimage") {
		$(id).className = "selected_defimage";
	} else {
		$(id).className = "selected_image";
	}
	new Effect.Appear('ajaxrond');
	new Ajax.Updater('preview_image', url_preview, {
		asynchronous :true,
		evalScripts :true,
		method :'get',
		parameters : {
			idimage :id
		},
		onSuccess : function(transport) {
			new Effect.Fade('ajaxrond');
		}

	});

}

function getAutoCompleteSelectionId(text, li) {
	alert(li.id);
}

function editProduct(id, url_edit) {
	new Ajax.Updater('contentweb2', url_edit, {
		asynchronous :true,
		evalScripts :true,
		method :'get',
		parameters : {
			idproduct :id
		},
		onSuccess : function(transport) {
			showWeb2();
		}

	});
}

function showErrMessage(message) {
	window.clearTimeout(mesid);

	$('infomessages').innerHTML = message;
	$('infomessages').className = "error_message";
	new Effect.Appear('infomessages', {
		from :0,
		to :1,
		duration :0.5
	});
	mesid = window.setTimeout('hideMessage()', 3000);
}

function setCp(villecp) {
	a = villecp.split("(");
	if (a.length == 2) {
		$('cp').value = a[1].split(")")[0];
		return false;
	}
}

function selectService(id) {
	if ($(id + '_info')) {
		setDisabled(id + '_info', !$(id + 'cb').checked);
		$(id + '_info').disabled = !$(id + 'cb').checked;
		if ($(id + '_info').disabled) {
			$(id).className = 'servicecol_disabled';
			disableImage("paiement_cash_" + id + "_img", "euro_35", true);
			disableImage("paiement_cheque_" + id + "_img", "cheque", true);
			disableImage("paiement_cb_" + id + "_img", "paiement_info", true);
			disableImage("paiement_ticket_" + id + "_img", "ticket_35", true);
		} else {
			$(id).className = 'servicecol';
			disableImage("paiement_cash_" + id + "_img", "euro_35", false);
			disableImage("paiement_cheque_" + id + "_img", "cheque", false);
			disableImage("paiement_cb_" + id + "_img", "paiement_info", false);
			disableImage("paiement_ticket_" + id + "_img", "ticket_35", false);
			checkprix(id);
		}

	}
}

function checkCBs() {
	if ($('paiement_cb_livraison').checked || $('paiement_cb_emporter').checked
			|| $('paiement_cb_surplace').checked)
		$('min_cb_div').show();
	else
		$('min_cb_div').hide();

}

function disableImage(id, img, disabled) {
	if (disabled) {
		$(id).innerHTML = "<img src='/images/" + img + "_d.png'>";
	} else {
		$(id).innerHTML = "<img src='/images/" + img + ".png'>";
	}
}

function checkprix(id) {

	if ($('sup_repas_' + id))
		$('sup_repas_' + id).disabled = (!$('prixsup_repas_' + id).checked);
	if ($(id + '_prixmin_accept'))
		setDisabled(id + '_prixmin_accept', !$(id + 'hasprixmin').checked);
	if ($('prix_min_' + id))
		$('prix_min_' + id).disabled = !$(id + 'hasprixmin').checked;
	if ($('sup_accept_lessprixmin_' + id))
		$('sup_accept_lessprixmin_' + id).disabled = (!$(id + 'acceptlessprixmin').checked || !$(id + 'hasprixmin').checked);
}

// ------------------------PRODUITS-------------------------------------

var nbOptionElements = 0;
var nbMenuOpEl = 0;
var nbAchatEl = 0;
var nbOffertEl = 0;

function addElement(nom, prix) {

	ok = true;
	if (nom != '') {
		$$('.el_nom').each( function(el) {
			if (el.value.toLowerCase() == nom.toLowerCase()) {
				alert("Une valeur avec le même nom existe déjà");
				new Effect.Pulsate('op' + el.id, {
					pulses :3,
					duration :1
				});
				$('new_element_nom').focus();
				ok = false;

			}
		});
		if (ok) {
			if (!IsNumeric(prix) || Number(prix) < 0) {
				alert("Le prix doit être un chiffre supérieur ou égale à 0");
				return false;
			} else {
				nbOptionElements++;
				champ = "<div id='opelement_" + nbOptionElements
						+ "' class='option_element'>"
						+ "<input type='hidden' name='element_nom[]' value=\""
						+ nom + "\" id='element_" + nbOptionElements
						+ "' class='el_nom'>" + nom;
				if (prix != '0') {
					champ = champ + "(+" + prix + "€)";
				}
				champ = champ
						+ "<input type='hidden' name='element_prix[]' value='"
						+ prix + "' class='el_prix' size='4'>"
						+ "<a href='#' onclick=\"$('opelement_"
						+ nbOptionElements
						+ "').innerHTML=''\";return false;\">Supprimer</a>"
						+ "</div>";
				$('elements').innerHTML += champ;
			}
		}
	}
	return false;

}

function addAchatElement(idprod, menu, nom) {
	ok = true;
	if (nom != '') {
		$$('.el_achat')
				.each(
						function(el) {
							if (el.value == idprod
									&& (($('menu_' + el.id).value == 'Menus' && menu == 'Menus') || ($('menu_' + el.id).value != 'Menus' && menu != 'Menus'))) {
								alert("Ce produit/menu est déjà ajouté");
								new Effect.Pulsate('achat' + el.id, {
									pulses :3,
									duration :1
								});
								$('new_achat_element_prod').focus();
								ok = false;

							}
						});
		if (ok) {

			nbAchatEl++;
			$('achat_elements').innerHTML += "<div id='achatelement_"
					+ nbAchatEl
					+ "' class='option_element'>"
					+ "<input type='hidden' name='element_achat[]' value='"
					+ idprod
					+ "' id='element_"
					+ nbAchatEl
					+ "' class='el_achat'>"
					+ "<input type='hidden' name='element_achat_menu[]' value='"
					+ menu + "' id='menu_element_" + nbAchatEl
					+ "' class='el_achat_menu'>" + menu + '-' + nom
					+ "<a href='#' onclick=\"$('achatelement_" + nbAchatEl
					+ "').innerHTML=''\";return false;\">Supprimer</a>"
					+ "</div>";
			$('new_achat_element_prod').selectedIndex = 0;
			$('new_achat_element_prod').focus();
		}
	}
	return false;
}

function addOffertElement(idprod, nom, prix) {
	ok = true;
	if (nom != '') {
		$$('.el_offert').each( function(el) {
			if (el.value == idprod) {
				alert("Ce produit est déjà ajouté");
				new Effect.Pulsate('offert' + el.id, {
					pulses :3,
					duration :1
				});
				$('new_element_prod').focus();
				ok = false;

			}
		});
		if (!isInteger(!$('new_element_prix').value)
				|| $('new_element_prix').value < 0) {
			ok = false;
			alert("Le prix supplémentaire doit être un entier suppérieur ou égale à 0");
			$('new_element_prix').focus();
			$('new_element_prix').select();
		}
		if (ok) {
			if (prix == '')
				prix = '0';
			if (prix == '0')
				prixText = 'gratuit';
			else
				prixText = '+' + prix + ' €';
			nbOffertEl++;
			$('offert_elements').innerHTML += "<div id='offertelement_"
					+ nbOffertEl
					+ "' class='option_element'>"
					+ "<input type='hidden' name='element_offert[]' value='"
					+ idprod
					+ "' id='element_"
					+ nbOffertEl
					+ "' class='el_offert'>"
					+ "<input type='hidden' name='element_offert_prix[]' value='"
					+ prix + "'>" + nom + " (" + prixText + ")"
					+ "<a href='#' onclick=\"$('offertelement_" + nbOffertEl
					+ "').innerHTML=''\";return false;\">Supprimer</a>"
					+ "</div>";
			$('new_element_prod').selectedIndex = 0;
			$('new_element_prix').value = '0';
			$('new_element_prix').disabled = true;
			$('new_element_prod').focus();
		}
	}

	return false;
}

function addMenuElement(idprod, nom, prix) {
	ok = true;
	if (nom != '') {
		$$('.el_prod').each( function(el) {
			if (el.value == idprod) {
				alert("Ce produit est déjà ajouté");
				new Effect.Pulsate('op' + el.id, {
					pulses :3,
					duration :1
				});
				$('new_element_nom').focus();
				ok = false;

			}
		});
		if (ok) {
			if (prix == '')
				prix = '0';
			if (prix == '0')
				prixText = 'sans supplément';
			else
				prixText = '+' + prix + ' €';
			nbMenuOpEl++;
			$('elements').innerHTML += "<div id='opelement_" + nbMenuOpEl
					+ "' class='option_element'>"
					+ "<input type='hidden' name='element_prod[]' value='"
					+ idprod + "' id='element_" + nbMenuOpEl
					+ "' class='el_prod'>"
					+ "<input type='hidden' name='element_prix[]' value='"
					+ prix + "'>" + nom + " (" + prixText + ")"
					+ "<a href='#' onclick=\"$('opelement_" + nbMenuOpEl
					+ "').innerHTML=''\";return false;\">Supprimer</a>"
					+ "</div>";
			$('new_element_prod').selectedIndex = 0;
			$('new_element_prix').value = '0';
			$('new_element_prix').disabled = true;
			if($('new_element_prod').style.display!="none" && !$('new_element_prod').disabled)
			$('new_element_prod').focus();
		}
	}

	return false;
}

function editProductPoints(id) {
	$('point_' + id).innerHTML = "<input type='text' id='value_" + id
			+ "' size='1' value='" + $('point_' + id).innerHTML + "'>";
	// $('text_point_'+id).hide();
	$('edit_' + id).hide();
	$('save_' + id).show();
	$('value_' + id).focus();
	$('value_' + id).select();
}

function savePointFor(id, url) {
	if (!isInteger($('value_' + id).value)) {
		alert('Le nombre de points de fidélité doit être un nombre entier');
		$('value_' + id).focus();
		$('value_' + id).select();
	} else {
		new Ajax.Updater('point_' + id, url, {
			parameters :'pid=' + id + '&points=' + $('value_' + id).value,
			onLoading : function() {
				$('save_' + id).hide();
			},
			onSuccess : function(response) {
				$('edit_' + id).show();
				new Effect.Highlight('point_' + id);
			}
		});
	}
}

function editMenuPoints(id) {
	$('menu_point_' + id).innerHTML = "<input type='text' id='menuvalue_" + id
			+ "' size='1' value='" + $('menu_point_' + id).innerHTML + "'>";
	// $('text_point_'+id).hide();
	$('edit_menu_' + id).hide();
	$('save_menu_' + id).show();
	$('menuvalue_' + id).focus();
	$('menuvalue_' + id).select();
}

function savePointForMenu(id, url) {
	if (!isInteger($('menuvalue_' + id).value)) {
		alert('Le nombre de points de fidélité doit être un nombre entier');
		$('menuvalue_' + id).focus();
		$('menuvalue_' + id).select();
	} else {
		new Ajax.Updater('menu_point_' + id, url, {
			parameters :'pid=' + id + '&points=' + $('menuvalue_' + id).value,
			onLoading : function() {
				$('save_menu_' + id).hide();
			},
			onSuccess : function(response) {
				$('edit_menu_' + id).show();
				new Effect.Highlight('menu_point_' + id);
			}
		});
	}
}

function fadeallerr() {
	new $('dateerr').hide();
	new $('datedeberr').hide();
	new $('datefinerr').hide();
	if ($('datefurthererr'))
		$('datefurthererr').hide();
}

function validateDates(url) {
	if (!validDate($('date_deb').value)) {
		new Effect.Fade('date_interval_value');
		fadeallerr();
		new Effect.Appear('datedeberr');
		return false;
	} else if (!validDate($('date_fin').value)) {
		new Effect.Fade('date_interval_value');
		fadeallerr();
		new Effect.Appear('datefinerr');
		return false;
	} else if (!checkDateIntervalEqual($('date_deb').value, $('date_fin').value)) {
		new Effect.Fade('date_interval_value');
		fadeallerr();
		new Effect.Appear('dateerr');
		return false;
	} else if (url != undefined && url != null) {
		fadeallerr();
		new Ajax.Updater('date_interval_value', url, {
			parameters :'deb=' + $('date_deb').value + '&fin='
					+ $('date_fin').value,
			onComplete : function() {
				new Effect.Appear('date_interval_value');
				new Effect.Hightlight('date_interval_value', {
					duration :2
				});
			}
		});
		return false;
	}
	return false;

}

function checkDateIntervalEqual(startdate, enddate) {
	var start = Date.fromDDMMYYYY(startdate);
	var end = Date.fromDDMMYYYY(enddate);
	if (end >= start) {
		return true;
	} else {
		return false;
	}
}

function validateDateTimes(url) {
	if (!validDate($('startday').value)) {
		new Effect.Fade('date_interval_value');
		fadeallerr();
		new Effect.Appear('datedeberr');
		return false;
	} else if (!validDate($('endday').value)) {
		new Effect.Fade('date_interval_value');
		fadeallerr();
		new Effect.Appear('datefinerr');
		return false;
	} else if (!checkDateTimeInterval($('startday').value,
			$('starttime_hour').value, $('starttime_minute').value,
			$('endday').value, $('endtime_hour').value,
			$('endtime_minute').value)) {
		new Effect.Fade('date_interval_value');
		fadeallerr();
		new Effect.Appear('dateerr');
		return false;
	} else if (!checkDateFurtherToNow($('startday').value,
			$('starttime_hour').value, $('starttime_minute').value,10)) {
		new Effect.Fade('date_interval_value');
		fadeallerr();
		$('date_min_val').innerHTML=addMinutes(new Date(),10).toLocaleString();
		new Effect.Appear('datefurthererr');
		return false;
	} else if (url != undefined && url != null) {
		fadeallerr();
		new Ajax.Updater('date_interval_value', url, {
			parameters :'deb=' + $('startday').value + '&debh='
					+ $('starttime_hour').value + '&debm='
					+ $('starttime_minute').value + '&fin=' + $('endday').value
					+ '&finh=' + $('endtime_hour').value + '&finm='
					+ $('endtime_minute').value,
			onComplete : function() {
				new Effect.Appear('date_interval_value');
				new Effect.Hightlight('date_interval_value', {
					duration :2
				});
			}
		});
		return false;
	}
	return false;
}

function showPromoPeriode(url, id) {
	new Ajax.Updater('contentweb2', url, {
		parameters :'pid=' + id,
		onComplete : function() {
			showWeb2()
		},
		evalScripts :true
	});
}

function addCuisine(idcuisine, nom) {
	ok = true;
	if (nom != '') {
		if ($$('.el_cuisine').length >= 5) {
			alert("Vous pouvez ajouter 5 cuisines au maximum");
			return false;
		} else {
			$$('.el_cuisine').each( function(el) {
				if (el.value == idcuisine) {
					alert("Cette cuisine est déjà ajoutée");
					new Effect.Pulsate('cuisine' + el.id, {
						pulses :3,
						duration :1
					});
					$('cuisine').focus();
					ok = false;

				}
			});

			if (ok) {

				nbCuisineEl++;
				$('cuisines_div').innerHTML += "<div id='cuisineelement_"
						+ nbCuisineEl + "' class='option_element'>"
						+ "<input type='hidden' name='cuisines[]' value='"
						+ idcuisine + "' id='element_" + nbCuisineEl
						+ "' class='el_cuisine'>"
						+ "<input type='hidden' name='cuisines_nom[]' value='"
						+ nom + "'>" + nom
						+ "<a href='#' onclick=\"$('cuisineelement_"
						+ nbCuisineEl
						+ "').innerHTML=''\";return false;\">Supprimer</a>"
						+ "</div>";
				$('cuisine').selectedIndex = 0;

			}
		}
	}

	return false;
}

function addCuisinePref(idcuisine, nom) {
	ok = true;
	if (nom != '') {
		if ($$('.el_cuisine').length >= 5) {
			alert("Vous pouvez ajouter 5 cuisines au maximum");
			return false;
		} else {
			$$('.el_cuisine').each( function(el) {
				if (el.value == idcuisine) {
					alert("Cette cuisine est déjà ajoutée");
					new Effect.Pulsate('cuisine' + el.id, {
						pulses :3,
						duration :1
					});
					$('cuisine').focus();
					ok = false;

				}
			});

			if (ok) {

				nbCuisineEl++;
				$('cuisines_div').innerHTML += "<div id='cuisineelement_"
						+ nbCuisineEl
						+ "' class='option_element'>"
						+ "<input type='hidden' name='cuisines[]' value='"
						+ idcuisine
						+ "' id='element_"
						+ nbCuisineEl
						+ "' class='el_cuisine'>"
						+ "<input type='hidden' name='cuisines_nom[]' value='"
						+ nom
						+ "'>"
						+ nom
						+ "<a href='#' onclick=\"if($('cuisine') && !$('cuisine').disabled){$('cuisineelement_"
						+ nbCuisineEl
						+ "').innerHTML='';}return false;\">Supprimer</a>"
						+ "</div>";
				$('cuisine').selectedIndex = 0;

			}
		}
	}

	return false;
}


function addQuartier(idv, idq, nom, url, minprice, acceptlessforprice, supprice, newlyadded) {
	ok = true;
	if (nom != '') {
		$$('.el_quartier').each( function(el) {
			var ville_el = $('ville_' + el.id);
			if (el.value == idq && idv == ville_el.value) {
				alert("Ce quartier est déjà ajouté");
				new Effect.Pulsate('quartier' + el.id, {
					pulses :3,
					duration :1
				});
				$('quartier').focus();
				ok = false;

			}
		});

		if (ok) {

			nbCuisineEl++;
			$('quartiers').innerHTML += "<div id='quartierelement_"
					+ nbCuisineEl + "' class='option_element'>"
					+ "<input type='hidden' name='quartiers_ville[]' value='"
					+ idv + "' id='ville_element_" + nbCuisineEl
					+ "' class='el_quartier_ville'>"
					+ "<input type='hidden' name='quartiers[]' value='" + idq
					+ "' id='element_" + nbCuisineEl + "' class='el_quartier'>"
					+ "<input type='hidden' name='quartiers_nom[]' value=\""
					+ nom + "\">" + nom
					+ (minprice==0 && supprice==0?"<span id='conditions_spec_quartier_"+nbCuisineEl+"'>&nbsp;|&nbsp;<a href='#' onclick=\"$('quartierminprice_"+ nbCuisineEl+"').show();$('conditions_spec_quartier_"+nbCuisineEl+"').remove();"
					+ "return false;\">Conditions spécifiques</a></span>":"")
					+ "&nbsp;|&nbsp;<a href='#' onclick=\"deleteQuartier(servicesmap, '"
					+ (idq != "" ? idq : 'v' + idv) + "','" + nbCuisineEl
					+ "');return false;\">Supprimer</a>"
					+ "<div id='quartierminprice_"
					+ nbCuisineEl + "' class='formitem'"+((minprice==0 && supprice==0)?" style='display:none'>":">")
					+ "<input type='checkbox'"+(minprice>0?" checked":"")+" name='quartier_has_min[]' id='quartier_has_min_"+nbCuisineEl+"' onclick=\"$('quartier_minprice_"+nbCuisineEl+"').disabled=!$(this).checked;$('quartier_doesacceptlessforprice_min"+nbCuisineEl+"').disabled=!$(this).checked;if(!$(this).checked){$('quartier_acceptlessforprice_"+nbCuisineEl+"').disabled=!$(this).checked;}else{$('quartier_acceptlessforprice_"+nbCuisineEl+"').disabled=!$('quartier_doesacceptlessforprice_min"+nbCuisineEl+"').checked;}\"/>"
					+ "&nbsp;<label class='checkbox_label' for='quartier_has_min[]'>Montant minimum pour livrer cette zone :&nbsp;</label>"
					+"<input type='text' size='3' name='quartier_minprice_"+(idq != ""?idq:idv)+"' id='quartier_minprice_"+nbCuisineEl+"' value='"+(minprice>0?minprice:"")+"'"+(minprice==0?" disabled='disabled'":"")+"/> €"
					+ "<div id='quartieracceptlessforprice_"
					+ nbCuisineEl + "' class='formitem acceplessprix'>"
					+ "<input type='checkbox'"+(acceptlessforprice>0?" checked":"")+" name='quartier_doesacceptlessforprice_min[]' id='quartier_doesacceptlessforprice_min"+nbCuisineEl+"'"+(minprice==0?" disabled='disabled'":"")+" onclick=\"$('quartier_acceptlessforprice_"+nbCuisineEl+"').disabled=!$(this).checked;\">"
					+ "&nbsp;<label class='checkbox_label' for='quartier_doesacceptlessforprice_min[]'>Accepter les commandes inférieures à ce montant avec un supplément de :&nbsp;</label>"
					+"<input type='text' size='3' name='quartier_acceptlessforprice_"+(idq != ""?idq:idv)+"' id='quartier_acceptlessforprice_"+nbCuisineEl+"' value='"+(acceptlessforprice>0?acceptlessforprice:"")+"'"+(acceptlessforprice==0?" disabled='disabled'":"")+"/> €"
					+"</div>"
					+ "<div id='quartiersupprice_"
					+ nbCuisineEl + "' class='formitem'>"
					+ "<input type='checkbox'"+(supprice>0?" checked":"")+" name='quartier_hassupprice[]' id='quartier_hassupprice_"+nbCuisineEl+"' onclick=\"$('quartier_supprice_"+nbCuisineEl+"').disabled=!$(this).checked;\">"
					+ "&nbsp;<label class='checkbox_label' for='quartier_hassupprice[]'>Prix supplémentaire de livraison :&nbsp;</label>"
					+"<input type='text' size='3' name='quartier_supprice_"+(idq != ""?idq:idv)+"' id='quartier_supprice_"+nbCuisineEl+"' value='"+(supprice>0?supprice:"")+"'"+(supprice==0?" disabled='disabled'":"")+"/> €"
					+"</div>"
					+"</div></div>";
			if (idq != "") {
				new Ajax.Updater('quartierelement_' + nbCuisineEl, url, {
					parameters :'id=' + nbCuisineEl + '&idq=' + idq,
					insertion :Insertion.Bottom,
					evalScripts :true
				});
			} else {
				new Ajax.Updater('quartierelement_' + nbCuisineEl, url, {
					parameters :'id=' + nbCuisineEl + '&idv=' + idv,
					insertion :Insertion.Bottom,
					evalScripts :true
				});
			}
			$('quartier').selectedIndex = 0;

		}
	}

	return false;
}

function deleteQuartier(gmap, idq, nbEl) {
	if (quartiers[idq] != null) {
		gmap.removeOverlay(quartiers[idq]);
		quartiers.slice(idq, 1);
	}
	if (quartiers['q' + idq] != null) {
		gmap.removeOverlay(quartiers['q' + idq]);
		quartiers.slice('q' + idq, 1);
	}
	$('quartierelement_' + nbEl).innerHTML = '';
	gmap.setCenter(fournpoint, gmap.getZoom());
}

function addAllQuartiers(idv, url, newlyadded) {
	if ($('quartier').options.length > 1) {
		for ( var i = 1; i < $('quartier').options.length; i++) {
			addQuartier(
					idv,
					$('quartier').options[i].value,
					$('ville_quartier').options[$('ville_quartier').selectedIndex].text
							+ '-' + $('quartier').options[i].text, url, 0, 0, 0, newlyadded);
		}
	} else {
		addQuartier(
				idv,
				'',
				$('ville_quartier').options[$('ville_quartier').selectedIndex].text
						+ '-'
						+ $('quartier').options[$('quartier').selectedIndex].text,
				url, 0, 0, 0, newlyadded);
	}
	return false;
}

function addPolygonToMap(gmap, poly, idq, marker, quartierName) {

	gmap.addOverlay(poly);
	poly.show();
	quartiers[idq] = poly;
	marker.bindInfoWindowHtml("<b>" + quartierName + "</b>");
	quartiers['q' + idq] = marker;

	gmap.addOverlay(marker);
	gmap.setCenter(marker.getLatLng(), gmap.getZoom());
	marker.openInfoWindowHtml("<b>" + quartierName + "</b>");
}

function addVilleIconToMap(gmap, marker, cpv, address) {

	gmap.addOverlay(marker);
	quartiers[cpv] = marker;
	marker.bindInfoWindowHtml("<b>" + address + "</b>");
	gmap.setCenter(marker.getLatLng(), gmap.getZoom());
	marker.openInfoWindowHtml("<b>" + address + "</b>");

}

function setPromoProdServices(whichclicked) {
	if ((!$('surplace') || !$('surplace').checked)
			&& (!$('emporter') || !$('emporter').checked)
			&& (!$('livraison') || !$('livraison').checked)) {
		$('new_achat_element_cat').disabled = true;
		$('new_offert_element_cat').disabled = true;
		$('new_achat_element_prod').disabled = true;
		$('new_element_prod').disabled = true;
	} else {
		$('new_achat_element_cat').disabled = false;
		$('new_offert_element_cat').disabled = false;

		new Ajax.Updater(
				'ajax_response_div',
				'/promotions/checkPromoProdServices?clicked=' + whichclicked,
				{
					parameters :Form.serialize('newpromoprodform'),
					asynchronous :false,
					evalScripts :true
				});

	}

}

function delProdAchete(idprod, menu, nom) {
	$$('.el_achat')
			.each(
					function(el) {
						if (el.value == idprod
								&& (($('menu_' + el.id).value == 'Menus' && menu == 'Menus') || ($('menu_' + el.id).value != 'Menus' && menu != 'Menus'))) {
							$('achat' + el.id).remove();
						}
					});
	return false;
}

function delProdOffert(idprod, nom) {
	$$('.el_offert').each( function(el) {
		if (el.value == idprod) {
			$('offert' + el.id).remove();

		}
	});
	return false;
}

function checkPeriodeServices(ismodif) {
	if ($('new_element_cat').selectedIndex == 0
			|| $('new_element_prod').selectedIndex == 0) {
		if ($('surplace')) {
			$('surplace').checked = false;
			$('surplace').disabled = true;
		}
		if ($('emporter')) {
			$('emporter').checked = false;
			$('emporter').disabled = true;
		}
		if ($('livraison')) {
			$('livraison').checked = false;
			$('livraison').disabled = true;
		}
	} else {
		var ismenu = "0";
		if ($('new_element_cat').value == "menus") {
			ismenu = "1";
		}
		new Ajax.Request(
				'/products/getServicesToDisable?ismenu='
						+ ismenu
						+ '&id='
						+ $('new_element_prod').value
						+ "&ismodif="
						+ (ismodif == undefined || ismodif == false ? "0" : "1"),
				{
					onComplete : function(transport) {
						eval(transport.responseText);
					},
					evalScripts :true,
					asynchronous :false
				});
	}
}

function showHors(idemp, idlivr, idsp) {
	if (idemp != null || idlivr != null || idsp != null) {
		var servals = (idemp != null ? "idemp=" + idemp
				+ (idlivr != null || idsp != null ? "&" : "") : "")
				+ (idlivr != null ? "idlivr=" + idlivr
						+ (idsp != null ? "&" : "") : "")
				+ (idsp != null ? "idsp=" + idsp : "");
		new Ajax.Updater('horvalues',
				'/profil/getScheValues', {
					parameters :servals,
					onLoading : function() {
						$('horvalues_loading').show();
					},
					onComplete : function() {
						$('horvalues_loading').hide();
						new Effect.Appear('horvalues');
					},
					evalScripts :true
				});
	}
	return false;
}

function showHorReals(idemp, idlivr, idsp) {
	if (idemp != null || idlivr != null || idsp != null) {
		var servals = (idemp != null ? "idemp=" + idemp
				+ (idlivr != null || idsp != null ? "&" : "") : "")
				+ (idlivr != null ? "idlivr=" + idlivr
						+ (idsp != null ? "&" : "") : "")
				+ (idsp != null ? "idsp=" + idsp : "");
		new Ajax.Updater('realhorvalues',
				'/profil/getRealScheValues', {
					parameters :servals,
					onLoading : function() {
						$('realhorvalues_loading').show();
					},
					onComplete : function() {
						$('realhorvalues_loading').hide();
						new Effect.Appear('realhorvalues');
					},
					evalScripts :true
				});
	}
	return false;
}
function updateSche(id) {

	new Ajax.Updater('sche_val_' + id,
			"/profil/getScheValDetail?id=" + id, {
				onComplete : function() {
					new Effect.SlideUp('sche_val_modif_' + id, {
						duration :0.5
					});
				}
			});
}

function updateRealSche(id) {
	new Ajax.Updater('sche_val_' + id,
			"/profil/getRealScheValDetail?id=" + id, {
				onComplete : function() {
					new Effect.SlideUp('sche_val_modif_' + id, {
						duration :0.5
					});
				},
				evalScripts: true
			});
}

function removeSche(id) {
	$('sche_val_' + id).remove();
	$("sche_val_modif_" + id).remove();
}

/* ======================COMMANDS================== */

function showCommandDetail(id) {
	showLoading();
	new Ajax.Updater('contentweb2',
			"/commands/getCommandDetail?id=" + id, {
				onComplete : function() {
					endLoading();
					showWeb2();
				},
				evalScripts :true
			});

}

function acceptCommand(id, finale) {
	new Ajax.Updater('command_bottom_infos_or_buttons',
			"/commands/acceptCommand", {
				onLoading : function() {
					$('command_action_buttons').hide();
					$('loading_div').show();
				},
				evalScripts :true,
				onComplete : function() {
					$('loading_div').hide();
				},
				parameters :"id="
						+ id
						+ (finale != undefined && finale != null ? "&final="
								+ finale : ""),
				onSuccess : function() {
					$('waiting_commands_list_table_tr_' + id).remove();
					refreshValidCommands();
				}
			});
}

function acceptModifiedCommand(id, finale) {
	var reg=new RegExp(",", "g");
	$("prix_tot").value = $('prix_tot').value.replace(reg,".");
	if(IsNumeric($('prix_tot').value)){
	new Ajax.Updater('contentweb2',
			"/commands/acceptCommand", {
				onLoading : function() {
					web2winLoading();
				},
				evalScripts :true,
				
				parameters :"id="
						+ id
						+ (finale != undefined && finale != null ? "&final="
								+ finale : "")
						+ "&newprice=" + $('prix_tot').value,
				onSuccess : function() {
					$('waiting_commands_list_table_tr_' + id).remove();
					refreshValidCommands();
				}
			});
	}
	else{
		alert("Le prix doit être un nombre (ex : 10,50).");
	}
}

function validateModifiedCommand(id, finale) {
	var reg=new RegExp(",", "g");
	$("prix_tot").value = $('prix_tot').value.replace(reg,".");
	if(IsNumeric($('prix_tot').value)){
		new Ajax.Updater('contentweb2',
				"/commands/modifyCommand", {
					onLoading : function() {
						web2winLoading();
					},
					evalScripts :true,
					
					parameters :"id="
							+ id
							+ (finale != undefined && finale != null ? "&final="
									+ finale : "")
							+ "&newprice=" + $('prix_tot').value,
					onSuccess : function() {
						$('waiting_commands_list_table_tr_' + id).remove();
						refreshValidCommands();
					}
				});
	}
	else{
		alert("Le prix doit être un nombre (ex : 10,50).");
	}
}

function refreshValidCommands() {
	new Ajax.Updater("valid_commands",
			"/commands/getValidCommands", {
				onLoading : function() {

					$('valid_coms_loading').show();
				},
				onComplete : function() {
					$('valid_coms_loading').hide();
				},
				parameters: 'all='+($('just_for_now').checked?"false":"true")

			});
}

function refuseCommand(id, reasonid) {
	web2winLoading();
	new Ajax.Updater('command_bottom_infos_or_buttons',
			"/commands/refuseCommand", {
				parameters :"id=" + id + '&rid=' + reasonid,
				evalScripts :true,

				onComplete : function() {
					closeWeb2();

				},
				onSuccess : function() {
					if ($('waiting_commands_list_table_tr_' + id))
						$('waiting_commands_list_table_tr_' + id).remove();
					if ($('valid_commands_list_table_tr_' + id))
						$('valid_commands_list_table_tr_' + id).remove();
				}
			});
}

function editCommand(id, reasonid) {
	web2winLoading();
	new Ajax.Updater('contentweb2',
			"/commands/editCommand", {
				parameters :"id=" + id + '&rid=' + reasonid,
				evalScripts :true
			});
}


function readyCommand(id) {

	new Ajax.Updater("contentweb2",
			"/commands/readyCom", {
				parameters :"id=" + id,
				onComplete : function() {
					setTimeout("closeWeb2()", 1500);
				}
			});
}

function delyCommand(id) {

	new Ajax.Updater("contentweb2",
			"/commands/deliverCom", {
				parameters :"id=" + id,
				evalScripts :true,
				onComplete : function() {
					setTimeout("closeWeb2()", 1500);
				}
				
			});
}

function contesterCommand(id) {
	web2winLoading();
	new Ajax.Updater("contentweb2",
			"/commands/contesterCom", {
				evalScripts :true,
				parameters :"id=" + id
			});
}

function finalizeCommand(id) {
	web2winLoading();
	new Ajax.Updater("contentweb2",
			"/commands/finalizeCom", {
				parameters :"id=" + id,
				evalScripts :true,
				onComplete : function() {
					setTimeout("closeWeb2()", 1500);
				},
				onSuccess : function() {
					$('valid_commands_list_table_tr_' + id).remove();
				}
			});
}

function checkAllDelyComs(val) {
	$$('.com_dely_check').each( function(cbox) {
		cbox.checked = val;
	});
	$('check_all_coms').checked = val;
}

function validDelyRoadButton() {
	var valid = false;
	$$('.com_dely_check').each( function(cbox) {
		if (cbox.checked) {

			valid = true;
		}
	});

	return valid;

}

function showDelyRoad() {
	if (validDelyRoadButton()) {
		new Ajax.Updater("contentweb2",
				"/commands/delyRoadComponent", {
					onComplete : function() {
						showWeb2();
						endLoading();
					},
					evalScripts :true,
					onLoading : function() {
						showLoading();
					},
					parameters :Form.serialize("dely_coms_list_form"),
					evalScripts :true
				});
	} else {
		alert($('no_dely_el_to_show').value);
	}
}

function upLivraisonComElement(elid) {
	var element = $(elid);
	var prev = element.previous();

	element = $(elid).remove();

	prev.insert( {
		before :element
	});
	checkArrows(prev);
	checkArrows(element);
	new Effect.Highlight(element);
	showDirectionOnMap(Sortable.sequence('dely_road_com_list'));
}

function downLivraisonComElement(elid) {
	var element = $(elid);
	var next = element.next();
	element = $(elid).remove();
	next.insert( {
		after :element
	});
	checkArrows(element);
	checkArrows(next);
	new Effect.Highlight(element);
	showDirectionOnMap(Sortable.sequence('dely_road_com_list'));
}

function delLivraisonComElement(elid) {
	var element = $(elid);
	var next = element.next();
	var prev = element.previous();
	new Effect.SlideUp(elid);
	$(elid).remove();
	checkArrows(prev);
	checkArrows(next);
	if ($$('.dely_road_comp_com_element').length == 0)
		closeWeb2();
	else
		showDirectionOnMap(Sortable.sequence('dely_road_com_list'));
}

function checkArrows(el) {
	if (el) {
		if (el.previous() != undefined)
			$('up_' + el.id).style.display = "";
		else
			$('up_' + el.id).style.display = "none";
		if (el.next() != undefined)
			$('down_' + el.id).style.display = "";
		else
			$('down_' + el.id).style.display = "none";
	}
}

function checkArrowsShowDirectionOnMap(elarray) {
	elarray.each( function(elid) {
		checkArrows($("dely_road_comp_com_element_" + elid));
	});
	showDirectionOnMap(elarray);
}

function showBillDetails(id) {

}

function downloadBill(id) {

}

function checkSupportTypeSelect() {
	$('command_no_div').hide();
	$('res_no_div').hide();
	if ($("probleme_support").value == '1') {
		$('command_no_div').show();
	} else if ($("probleme_support").value == '6') {
		$('res_no_div').show();
	}
}

function checkCommandsAndResas(first) {
	if ($('footer_coms_div_1') || $('footer_coms_div_0')) {
		var coms = "0";
		// var coms = "0";
		if ($('footer_coms_div_1'))
			coms = "1";

		if (first == undefined || first == null) {
			first = false;
		}

		new Ajax.Request("/commands/checkCommands", {
			onComplete : function(transport) {
				endFooterLoading();
				eval(transport.responseText);
			},
			onLoading :showFooterLoading(),
			parameters :"coms=" + coms + "&nbcom="
					+ $('footer_coms_div_' + coms).innerHTML
					+ (first == true ? "&first=true" : "")
		});
	}

	if ($('footer_resas_div_1') || $('footer_resas_div_0')) {
		var resas = "0";
		if ($('footer_resas_div_1'))
			resas = "1";

		new Ajax.Request("/reservations/checkResas", {
			onComplete : function(transport) {
				endFooterLoading();
				eval(transport.responseText);
			},
			onLoading :showFooterLoading(),
			parameters :"resas=" + resas + "&nbresas="
					+ $('footer_resas_div_' + resas).innerHTML
					+ (first == true ? "&first=true" : "")
		});
	}
}

footerloadings = 0;
function showFooterLoading() {
	$('footer_loading_div').show();
	footerloadings++;
}

function endFooterLoading() {
	footerloadings--;
	if (footerloadings <= 0)
		$('footer_loading_div').hide();
}

function refreshWaitingCommands() {
	new Ajax.Updater("waiting_commands",
			"/commands/getWaitingCommands", {
				onLoading : function() {

					$('waiting_coms_loading').show();
				},
				onComplete : function() {
					$('waiting_coms_loading').hide();
				}

			});
}

function setConnected() {
	new Ajax.Request("/userconnection/setConnected");
}

function checkOpenClose() {

	new Ajax.Updater("left_footer_bar_div",
			"/profil/checkOpenClose", {
				evalScripts :true,
				onLoading : function() {
					$('left_footer_bar_div_loading').show();
				},
				onComplete : function() {
					$('left_footer_bar_div_loading').hide();
				}
			});
}

function openResto() {
	new Ajax.Updater("contentweb2",
			"/componenttools/openNow", {
				parameters :"open=" + $('proch_ouvr').value + "&close="
						+ $('proch_ferm').value,
				onLoading : function() {
					web2winLoading();
					showWeb2();
				},
				evalScripts :true
			});
}

function closeResto() {
	new Ajax.Updater("contentweb2",
			"/componenttools/closeNow", {
				onLoading : function() {
					web2winLoading();
					showWeb2();
				},
				evalScripts :true
			});
}

function refreshCalendarReal() {
	if ($('scheduleselements') && $('calendar_date_val'))
		new Ajax.Updater('scheduletimeline',
				'/profil/getRealScheduleTimeLine', {
					evalScripts :true,
					parameters :'dateval=' + $('calendar_date_val').value,
					onLoading : function() {
						$('calendarloading').show();
					},
					onComplete : function() {
						$('calendarloading').hide();
					}
				});
}

function refreshCalendarHebdo() {
	if ($('scheduleselements'))
		new Ajax.Updater('scheduletimeline',
				'/profil/getScheduleTimeLine', {
					evalScripts :true,
					onLoading : function() {
						$('calendarloading').show();
					},
					onComplete : function() {
						$('calendarloading').hide();
					}
				});

}

/* ==========RESAS======== */

function refreshWaitingResas() {
	new Ajax.Updater("waiting_resas",
			"/reservations/getWaitingResas", {
				onLoading : function() {

					$('waiting_resas_loading').show();
				},
				onComplete : function() {
					$('waiting_resas_loading').hide();
				}

			});

}

function refreshValidResas() {
	new Ajax.Updater("valid_resas",
			"/reservations/getValidResas", {
				onLoading : function() {

					$('valid_resas_loading').show();
				},
				onComplete : function() {
					$('valid_resas_loading').hide();
				},
				parameters: 'all='+($('just_for_now').checked?"false":"true")

			});
}

function showResaDetail(id) {
	showLoading();
	new Ajax.Updater('contentweb2',
			"/reservations/getResaDetail?id=" + id, {
				onComplete : function() {
					endLoading();
					showWeb2();
				},
				evalScripts :true
			});

}

function acceptResa(id, finale) {
	new Ajax.Updater('resa_bottom_infos_or_buttons',
			"/reservations/acceptResa", {
				onLoading : function() {
					$('command_action_buttons').hide();
					$('loading_div').show();
				},
				evalScripts :true,
				onComplete : function() {
					$('loading_div').hide();
				},
				parameters :"id=" + id+ (finale != undefined && finale != null ? "&final="
						+ finale : ""),
				onSuccess : function() {
					$('waiting_resas_list_table_tr_' + id).remove();
					refreshValidResas();
				}
			});
}

function finalizeResa(id) {
	web2winLoading();
	new Ajax.Updater("contentweb2",
			"/reservations/finalizeResa", {
				parameters :"id=" + id,
				evalScripts :true,
				onComplete : function() {
					setTimeout("closeWeb2()", 1500);
				},
				onSuccess : function() {
					$('valid_resas_list_table_tr_' + id).remove();
				}
			});
}


function okCancelResa(id, reasonid) {
	web2winLoading();
	new Ajax.Updater('resa_bottom_infos_or_buttons',
			"/reservations/okCancelResa", {
				parameters :"id=" + id,
				evalScripts :true,

				onComplete : function() {
					setTimeout("closeWeb2()", 1500);
				},
				onSuccess : function() {
					if ($('waiting_resas_list_table_tr_' + id))
						$('waiting_resas_list_table_tr_' + id).remove();
				}
			});
}



function refuseResa(id, reasonid) {
	web2winLoading();
	new Ajax.Updater('resa_bottom_infos_or_buttons',
			"/reservations/refuseResa", {
				parameters :"id=" + id + '&rid=' + reasonid,
				evalScripts :true,

				onComplete : function() {
					setTimeout("closeWeb2()", 1500);
				},
				onSuccess : function() {
					if ($('waiting_resas_list_table_tr_' + id))
						$('waiting_resas_list_table_tr_' + id).remove();
					if ($('valid_resas_list_table_tr_' + id))
						$('valid_resas_list_table_tr_' + id).remove();

				}
			});
}

function contesterResa(id) {
	web2winLoading();
	new Ajax.Updater("contentweb2",
			"/reservations/contesterResa", {
				evalScripts :true,
				parameters :"id=" + id
			});
}

function checkAuthModifFourn() {
	new Ajax.Request(
			"/componenttools/checkFournModifAuth", {
				onSuccess : function(transport) {
					eval(transport.responseText);
				},
				evalScripts :true
			});
}

function showHelp() {
	new Ajax.Updater('contentweb2', '/home/getHelp', {
		onSuccess :showWeb2,
		onLoading :showLoading,
		onComplete :endLoading
	});
}

function showDownloadManual() {
	new Ajax.Updater('contentweb2', '/home/getManual', {
		onSuccess :showWeb2,
		onLoading :showLoading,
		onComplete :endLoading
	});
}

var mesfournid = null;
function showFournMessage(message, timeout) {
	if (mesfournid)
		window.clearTimeout(mesfournid);

	$('header_message_div').innerHTML = "<div class='panier_popup_message_header1'>"
			+ message + "</div>";
	
	if (timeout == undefined || timeout == null){
		new Effect.Appear('header_message_div_outer', {
			duration :0.5
		});
		mesfournid = window.setTimeout('hideFournMessage()', 3000);
	}
	else if (isInteger(timeout) && timeout>0){
		new Effect.Appear('header_message_div_outer', {
			duration :0.5
		});
		mesfournid = window.setTimeout('hideFournMessage()', timeout);
	}
	else{
		
		showWeb2WithClose('hideFournMessage()');
	}
	
}

function hideFournMessage() {
	if ($('header_message_div_outer').style.display != "none") {
		new Effect.Fade('header_message_div_outer', {
			duration :0.5
		});
	}
}