// Constante pour le EBooking
EB_AVAILABILITYMODE_QUANTITY = 1;
EB_AVAILABILITYMODE_TIME = 2;
EB_AJAXACTION_AVAILABILITY = 'Availability';
EB_AJAXACTION_AVAILABILITY_LIST = 'AvailabilityList';
EB_AJAXACTION_BOOKING = 'Booking';

// structure de l'objet EBProperties:
//
// objEBProperties.lngAvailabilityMode	:	Mode de disponibilité (EB_AVAILABILITYMODE_QUANTITY, EB_AVAILABILITYMODE_TIME)
//											Paramètre obligatoire dans la fonction qsGetAvailability
// objEBProperties.lngQuantity			:	Quantité de la ressource
// objEBProperties.dtmFrom				:	Date de
// objEBProperties.dtmTo				:	Date au
// objEBProperties.lngDataNodeFK		:	Numéro du noeud de la ressource à réserver au à vérifier les disponibilités
// objEBProperties.lngFirstDataNodeFK	:	Numéro de base du noeud si le noeud (lngDataNodeFK) réservé n'est pas le numéro du noeud N séléctionné (n'est pas utilisé pour l'instant)
// objEBProperties.onSuccess(req)		:	Fonction à executer lorsque la fonction de réservation a fonctionné.
//
// structure de l'objet ECProperties:
//
// Cet objet est retourné comme propriété dans la fonction onSuccess
// objECProperties.dtmFrom				:	Date de
// objECProperties.dtmTo				:	Date au
// objECProperties.lngQuantity			:	Quantité de la ressource
// objECProperties.lngRessourceNodeFK	:	Numéro du noeud de la ressource réservé
// objECProperties.blnConfirm			:	Indique si la ressource a été résérvé convenablement
// objECProperties.blnAddToBasket		:	Indique que la ressource est de type ebooking et qu'elle doit être ajouté au panier
// objECProperties.strMessage			:	Message html de retour

//greffe a toutes les class .EBAdd l'action de réservation
$(document).ready(function(){
	$('.EBArt .EBAdd').click(qsBtAddToBooking);	
});

//greffe a toutes les class .EBDisp l'action de recherche des disponnibilités
$(document).ready(function(){
	$('.EBArt .EBDisp').click(qsBtGetAvailability);	
});

// DTA v426 15.4.2008 greffe a toutes les class .EBDisp2 l'action de recherche des disponnibilités en list
$(document).ready(function(){
	$('.EBArt .EBDisp2').click(qsBtGetAvailabilityList);	
});

function qsListPresent(objContainer) {
	// on test si le div englobant contient le tableau des disponnibilités 
	// si il n'est pas présent, on l'ajoute

	if (objContainer) {
		var objList = $(objContainer).find('div.EBDispList').get(0);

		if (!(objList)) {
			var objArticle = $(objContainer).find('div.qsArt').get(0);
			if (objArticle) {
				$(objArticle).append('<div class="EBDispList"></div>')
				objList = $(objArticle).find('div.EBDispList').get(0);
			}
		}
	}
}


// Retourne sous forme d'un tableau les disponnibilités
function qsGetAvailability(pobjEBProperties){

	var objList = $('div.EBDispList').get(0);

	// prépare les paramètres d'envoi
	var arrParams = Array(
		{	name:'Ajax',					value:'EBooking' },
		{	name:'Action',					value:EB_AJAXACTION_AVAILABILITY },
		{	name:'lngAvailabilityMode',		value:pobjEBProperties.lngAvailabilityMode },
		{	name:'lngQuantity',				value:pobjEBProperties.lngQuantity },
		{	name:'dtmFrom',					value:pobjEBProperties.dtmFrom },
		{	name:'dtmTo',					value:pobjEBProperties.dtmTo },
		{	name:'N',						value:pobjEBProperties.lngDataNodeFK },
		{	name:'lngRessourceNode',		value:pobjEBProperties.lngDataNodeFK },
		{	name:'lngNumOfPerson',			value: pobjEBProperties.lngNumOfPerson }
	);
	
	$.ajax({
		type:		'GET',
		cache:		false,
		dataType:	'html',
		url:		'/qsPortal/Ajax/Get.asp',
		data:		$.fn.paramForm(arrParams),
		beforeSend:	function(){
						$(objList).html("<img src='/qsPortal/Images/AjaxProcess.gif' alt='Please wait...'/>");
					},
		success:	function(req){
						$(objList).html(req);
						$('.EBArt .EBConfirm').click(qsBtAddToBooking);	
					},
		error:		function(req, err){
						alert('Error!');
						$(objList).html(req.responseText);
					}
	});
	
}

// DTA v426 15.4.2008
// Retourne sous forme d'un tableau les disponnibilités
function qsGetAvailabilityList(pobjEBProperties){

	var objList = $('div.EBDispList').get(0);

	// prépare les paramètres d'envoi
	var arrParams = Array(
		{	name:'Ajax',					value:'EBooking' },
		{	name:'Action',					value:EB_AJAXACTION_AVAILABILITY_LIST },
		{	name:'lngAvailabilityMode',		value:pobjEBProperties.lngAvailabilityMode },
		{	name:'lngQuantity',				value:pobjEBProperties.lngQuantity },
		{	name:'dtmFrom',					value:pobjEBProperties.dtmFrom },
		{	name:'dtmTo',					value:pobjEBProperties.dtmTo },
		{	name:'lngContextNode',			value:pobjEBProperties.lngContextNode },
		{	name:'lngNumOfPerson',			value:pobjEBProperties.lngNumOfPerson }
		
	);
	
	$.ajax({
		type:		'GET',
		cache:		false,
		dataType:	'html',
		url:		'/qsPortal/Ajax/Get.asp',
		data:		$.fn.paramForm(arrParams),
		beforeSend:	function(){
						$(objList).html("<img src='/qsPortal/Images/AjaxProcess.gif' alt='Please wait...'/>");
					},
		success:	function(req){
						$(objList).html(req);
					},
		error:		function(req, err){
						alert('Error!');
						$(objList).html(req.responseText);
					}
	});
	
}


// ajoute l'article au système de réservation
function qsAddToBooking(pobjEBProperties){

	var objList = $('div.EBDispList').get(0);

	// prépare les paramètres d'envoi
	var arrParams = Array(
		{	name:'Ajax',					value:'EBooking' },
		{	name:'Action',					value:EB_AJAXACTION_BOOKING },
		{	name:'lngQuantity',				value:pobjEBProperties.lngQuantity },
		{	name:'dtmFrom',					value:pobjEBProperties.dtmFrom },
		{	name:'dtmTo',					value:pobjEBProperties.dtmTo },
		{	name:'N',						value:pobjEBProperties.lngDataNodeFK },
		{	name:'lngRessourceNode',		value:pobjEBProperties.lngDataNodeFK },
		{	name:'lngNumOfPerson',			value:pobjEBProperties.lngNumOfPerson }
		
	);
	
	$.ajax({
		type:		'GET',
		cache:		false,
		dataType:	'json',
		async:		false,
		url:		'/qsPortal/Ajax/Get.asp',
		data:		$.fn.paramForm(arrParams),
		beforeSend:	function(){
						$(objList).html("<img src='/qsPortal/Images/AjaxProcess.gif' alt='Please wait...'/>");
					},
		success:	function(req){
						$(objList).html(req.strMessage);
						
						// si l'élément est de type ebooking, on l'ajoute au panier
						if(req.blnAddToBasket && req.blnConfirm)
						{
							if (!req.objECProperties.blnFixPrice) {
								// obtient le prix selon la quantité
								dblPice = qsGetDiscountQuantity(req.objECProperties);
								if(dblPice > -1)
									req.objECProperties.dblUnitPrice = dblPice;

								dblPice = qsGetDiscountTime(req.objECProperties);
								if (dblPice > -1)
									req.objECProperties.dblUnitPrice = dblPice;

								req.objECProperties.dblQuantity = req.objECProperties.lngNbrInterval * req.lngQuantity;

								// DTA v448 20.10.2009 Permet dans le cadre de GiroudEvent de modifier les valeurs de l'Ecommerce avant l'envoie dans le panier.
								if (typeof (customECProperties) != 'undefined') {
									req.objECProperties = customECProperties(req.objECProperties);
								}
								// ajoute dans le panier la réservation uniquement si le prix unitaire est suppérieur à -1
								if (req.objECProperties.dblUnitPrice > 0)
									qsAddToBasket(req.objECProperties);
								
							} else {
								// obtient le prix selon la quantité
								objFixPrice = qsGetFixPrice(req.objECProperties);
								if (objFixPrice.TotalPrice > -1) {
									req.objECProperties.lngNbrInterval = 1;
									req.objECProperties.dblQuantity = 1;
									req.lngQuantity = 1;

									for (i = 0; i < objFixPrice.Prices.length; i++)
									{
										req.objECProperties.dblUnitPrice = objFixPrice.Prices[i].Price;
										req.objECProperties.strBusinessData = objFixPrice.Prices[i].Description;
										qsAddToBasket(req.objECProperties);
									}
									
								}
							}
							
							if (req.blnImmediateCheckout) {
								// DTA v425b 17.4.2008 passage directe au panier ecommerce
								// document.location.href = '/qsPortal/Home.asp?Action=-7';
								gotoCheckout(req.blnCheckoutPopup);
							}								
							

						}
						
						if(req.blnConfirm)
							if(typeof(pobjEBProperties.onSuccess) != 'undefined')
								pobjEBProperties.onSuccess(req);
						
					},
		error:		function(req, err){
						alert('Error!');
						$(objList).html(req.responseText);
					}
	});
}

// DTA v426 15.4.2008 class vierge de EBProperties
function clsEBProperties()
{
	this.lngAvailabilityMode = -1;
	this.lngDataNodeFK = -1;
	this.strDescription = '';
	this.lngQuantity = -1;
	this.dtmFrom = '';
	this.dtmTo = '';
	this.lngContextNode = -1;
	this.lngNumOfPerson = -1;
	this.lngFirstDataNodeFK = -1;
}

// DTA v426 15.4.2008 événement du bouton de disponibilités au format de liste
function qsBtGetAvailabilityList(){

	var objArticle = $(this).parents('div.EBArt').get(0);
	qsListPresent(objArticle);

	var objEBProperties = new clsEBProperties();

	objEBProperties = LoadEBProperties(objArticle, objEBProperties);

	if (objEBProperties.blnCheckAvailability == true)
		qsGetAvailabilityList(objEBProperties);
}



// événement du bouton de disponibilités
function qsBtGetAvailability(){

	var objArticle = $(this).parents('div.EBArt').get(0);
	// var objArticle = $(objArticleContent).find('div.qsArt').get(0);
	qsListPresent(objArticle);

	//récupère l'id
	var lngNodeId = objArticle.id;
	//The id is supposed to be qsArtNNN
	//Extract the Node ID
	lngNodeId = lngNodeId.substring(5);
	// obtient l'objet des propriétés de l'ebooking
	var objEBProperties = eval('EBProperties' + lngNodeId);

	objEBProperties = LoadEBProperties(objArticle, objEBProperties);

	if (objEBProperties.blnCheckAvailability == true)
		qsGetAvailability(objEBProperties);
}

function LoadEBProperties(objArticle, objEBProperties) {

	var objContext = $(objArticle).find('input.EBContext').get(0);
	var objFrom = $(objArticle).find('input.EBFrom').get(0);
	var objTo = $(objArticle).find('input.EBTo').get(0);

	var objQuantity = $(objArticle).find('input.EBQuantity').get(0);
	if (!objQuantity)
		var objQuantity = $(objArticle).find('select.EBQuantity').get(0);

	var objNumOfPerson = $(objArticle).find('input.EBNumOfPerson').get(0);
	if (!objNumOfPerson)
		var objNumOfPerson = $(objArticle).find('select.EBNumOfPerson').get(0);

	if (objNumOfPerson)
		objEBProperties.lngNumOfPerson = objNumOfPerson.value;

	objEBProperties.blnCheckAvailability = false;

	if (objContext)
		objEBProperties.lngContextNode = objContext.value;

	if (objFrom) {
		objEBProperties.lngAvailabilityMode = EB_AVAILABILITYMODE_TIME;
		objEBProperties.dtmFrom = objFrom.value;

		if (objQuantity)
			objEBProperties.lngQuantity = objQuantity.value;
		else
			objEBProperties.lngQuantity = 1;

		if (objTo) {
			objEBProperties.dtmTo = objTo.value;
		}
		// si il n'y a pas de date to
		else {
			aDate = qsCreateDate(objEBProperties.dtmFrom);
			aDate.setDate((parseInt(aDate.getDate()) + parseInt(objEBProperties.lngQuantity)));
			objEBProperties.dtmTo = aDate.getDate() + "." + (aDate.getMonth() + 1) + "." + aDate.getFullYear();
		}
		objEBProperties.blnCheckAvailability = true;

	}
	else if (objQuantity) {
		objEBProperties.lngAvailabilityMode = EB_AVAILABILITYMODE_QUANTITY;
		objEBProperties.lngQuantity = objQuantity.value;
		objEBProperties.blnCheckAvailability = true;
	}
	else {
		objEBProperties.lngAvailabilityMode = EB_AVAILABILITYMODE_QUANTITY;
		objEBProperties.lngQuantity = 1;
		objEBProperties.blnCheckAvailability = true;
	}
	
	return objEBProperties;
	
}

// ajoute l'article au système de réservation
function qsBtAddToBooking(){

	var objArticle = $(this).parents('div.EBArt').get(0);
	// var objArticle = $(objArticleContent).find('div.qsArt').get(0);

	//récupère l'id
	var lngNodeId = objArticle.id;
	//The id is supposed to be qsArtNNN
	//Extract the Node ID
	lngNodeId = lngNodeId.substring(5);
	// obtient l'objet des propriétés de l'ebooking
	var objEBProperties = eval('EBProperties' + lngNodeId);

	var objFrom = $(objArticle).find('input.EBConfirmFrom').get(0);
	var objTo = $(objArticle).find('input.EBConfirmTo').get(0);
	var objQuantity = $(objArticle).find('input.EBConfirmQuantity').get(0);
	var objRessourceNode = $(objArticle).find('input.EBConfirmRessourceNode').get(0);
	var objNumOfPerson = $(objArticle).find('input.EBConfirmNumOfPerson').get(0);
	var objList = $(objArticle).find('div.EBDispList').get(0);

	var objEBProperties = new clsEBProperties();

	if(objFrom) 
		objEBProperties.dtmFrom = objFrom.value;
	else
		objEBProperties.dtmFrom = "";
		
	if(objTo)
		objEBProperties.dtmTo = objTo.value;
	else
		objEBProperties.dtmTo = objEBProperties.dtmFrom;
	
	if(objQuantity)
		objEBProperties.lngQuantity = objQuantity.value;
	else 
		objEBProperties.lngQuantity = 1;

	if (objRessourceNode) {
		objEBProperties.lngFirstDataNodeFK = objEBProperties.lngDataNodeFK;
		objEBProperties.lngDataNodeFK = objRessourceNode.value;
	}

	if (objNumOfPerson)
		objEBProperties.lngNumOfPerson = objNumOfPerson.value;

	// si il y a une fonction de succès
	if(typeof(EBookingSuccess) != 'undefined')
		objEBProperties.onSuccess = EBookingSuccess;

	// ajoute la réservation
	qsAddToBooking(objEBProperties);

}

function qsCreateDate(pstrDate) {
	var arrSeparatorArray = new Array("-", "/", ".");
	var arrDate = new Array();
	var intSeparatorType = 0;

	for (intElementNr = 0; intElementNr < arrSeparatorArray.length; intElementNr++) {
		if (pstrDate.indexOf(arrSeparatorArray[intElementNr]) != -1) {
			arrDate = pstrDate.split(arrSeparatorArray[intElementNr]);
			intSeparatorType = intElementNr;
			break;
		}
	}

	if (arrDate.length != 3)
		return new Date();

	switch (intSeparatorType) {
		case 0: // "-"
			//return=new Date(annee,mois-1,jour,heure,min)
			return new Date(arrDate[0], arrDate[1] - 1, arrDate[2], 0, 0, 0);
		case 1: // "/"
			return new Date(arrDate[2], arrDate[0] - 1, arrDate[1], 0, 0, 0);
		case 2: // "."
			return new Date(arrDate[2], arrDate[1] - 1, arrDate[0], 0, 0, 0);
	}

	return new Date();
}
