// Constante pour le EBooking
EB_AVAILABILITYMODE_QUANTITY = 1;
EB_AVAILABILITYMODE_TIME = 2;
EB_AJAXACTION_AVAILABILITY = 'Availability';
EB_AJAXACTION_AVAILABILITY_LIST = 'AvailabilityList';
EB_AJAXACTION_JSON_AVAILABILITY_LIST = 'AvailabilityListJson';
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)

//
// 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.blnEcom				:	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);
});

//rempli les champs si ils existent
$(document).ready(function () {
	aVars = getUrlVars();

	if (aVars["dtmFrom"] != "")
		$(".EBFrom").val(aVars["dtmFrom"]);
	if (aVars["dtmTo"] != "")
		$(".EBTo").val(aVars["dtmTo"]);
	if (aVars["lngQuantity"] != "")
		$(".EBQuantity").val(aVars["lngQuantity"]);
	if (aVars["lngNumOfPerson"] != "")
		$(".EBNumOfPerson").val(aVars["lngNumOfPerson"]);
	if (aVars["lngInterval"] != "")
		$(".EBInterval").val(aVars["lngInterval"]);

});

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:		$.param(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:		$.param(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');
	var objResponseBooking = null;

	if (typeof (pobjEBProperties.lngEBookingFK) == "undefined") {
		pobjEBProperties.lngEBookingFK = -1;
	}
	if (typeof (pobjEBProperties.strSelectedSlots) == "undefined") {
		pobjEBProperties.strSelectedSlots = "";
	}
	if (typeof (pobjEBProperties.xmlBusinessData) == "undefined") {
		pobjEBProperties.xmlBusinessData = {};
	}

	// DTA v466 15.06.2011 permet de completer les paramètres de l'ajout à l'ecommerce avec la fonction onBeforeAddToBooking
	if (typeof (onBeforeAddToBooking) == "function") {
		pobjEBProperties = onBeforeAddToBooking(pobjEBProperties);
	}

	// 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 },
		{	name:'strBusinessData',			value: pobjEBProperties.strBusinessData },
		{	name:'memComment',				value: pobjEBProperties.memComment },
		{	name:'strSelectedSlots',		value: pobjEBProperties.strSelectedSlots }
	);
		
		data = $.param(arrParams);
		$.each(pobjEBProperties.xmlBusinessData, function (index, value) {
			var s = new String(value);
			s = escape(s);
			s = s.replace(/\+/g, "%2B");
			data += '&xmlBusinessData.' + index + '=' + s;
		});

		$.ajax({
			type: 'GET',
			cache: false,
			dataType: 'json',
			async: false,
			url: '/qsPortal/Ajax/Get.asp',
			data: data,
			beforeSend: function () {
				$objList.html("<img src='/qsPortal/Images/AjaxProcess.gif' alt='Please wait...'/>");
			},
			success: function (arrReserv) {

				for (i = 0; i < arrReserv.length; i++) {

					req = arrReserv[i];

					$objList.html(req.strMessage);

					// si l'élément est de type ebooking, on l'ajoute au panier
					if (req.blnConfirm) {
						// si l'article est également de type ecommerce
						if (req.blnEcom) {
							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 || req.blnAcceptNullPrice)
									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 = req.lngQuantity;

									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);
									}

								}
							}

						}
						else {
							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 (typeof (pobjEBProperties.onSuccess) != 'undefined')
							pobjEBProperties.onSuccess(req);

					}

					
				}

				objResponseBooking = arrReserv;

			},
			error: function (req, err) {
				alert('Error!');
				$objList.html(req.responseText);
			}
		});

	return objResponseBooking;
}

// 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;
	this.strBusinessData = '';
	this.memComment = '';
	this.strSelectedSlots = '';

}

// 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 objInterval = $(objArticle).find('input.EBInterval').get(0);
	if (!objInterval)
		var objInterval = $(objArticle).find('select.EBInterval').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 {
			if (objInterval) {
				aDate = qsCreateDate(objEBProperties.dtmFrom);
				aDate.setDate((parseInt(aDate.getDate()) + parseInt(objInterval.value)));
				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 objComment = $(objArticle).find('.EBComment').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;
	else
		objEBProperties.lngNumOfPerson = -1;

	if (objComment)
		objEBProperties.memComment = objComment.value;
	else
		objEBProperties.memComment = "";

	// 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();
}

function getUrlVars() {
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for (var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}

// DTA v460 1.12.2010
// Retourne sous forme d'un tableau les disponnibilités
function qsGetJsonAvailabilityList(pobjEBProperties) {
	var objRet;
	// prépare les paramètres d'envoi
	var arrParams = Array(
		{ name: 'Ajax', value: 'EBooking' },
		{ name: 'Action', value: EB_AJAXACTION_JSON_AVAILABILITY_LIST },
		{ name: 'dtmFrom', value: pobjEBProperties.dtmFrom },
		{ name: 'dtmTo', value: pobjEBProperties.dtmTo },
		{ name: 'lngRessourceNode', value: pobjEBProperties.lngDataNodeFK }

	);


	$.ajax({
		type: 'GET',
		cache: false,
		dataType: 'json',
		async: false,
		url: '/qsPortal/Ajax/Get.asp',
		data: $.param(arrParams),
		beforeSend: function () {
		},
		success: function (req) {
			objRet = req;
		},
		error: function (req, err) {
			alert('Error!');
			alert(req.responseText);
		}
	});

	return objRet;

}
