/**
* @version		$Id: pack-interface.js 2008-08-25 Frederic $
* @package		CMS.Framework
* @subpackage	Pack
*/

/**
* Gère l'interface de location.
*
* @param String lang Code langue utilisé
* @param String firstDay 1er jour de location sélectionné
* @param String lastDay Dernier jour de location sélectionné
* @param Boolean cart Indique si le panier contient un article ou plus (true) ou pas (false)
* @access public
* @since 1.0
*/
function RentalInterface(lang, firstDay, lastDay, cart) {
	/**
	 * Code langue utilisé.
	 *
	 * @var String
	 */
	this.lang = lang;
	
	/**
	 * 1er jour de location sélectionné (temps Unix).
	 *
	 * @var Integer
	 */
	this.firstDay = firstDay;
	
	/**
	 * Dernier jour de location sélectionné (temps Unix).
	 *
	 * @var Integer
	 */
	this.lastDay = lastDay;
	
	/**
	 * Indique si le panier contient un article ou plus (true) ou pas (false).
	 *
	 * @var Boolean
	 */
	this.cart = cart;
	
	/**
	 * Liste des messages suivant la langue.
	 *
	 * @var Array
	 */
	this.msg = new Array();
	
	/**
	* Charge les messages suivant la langue.
	*
	* @access public
	* @since 1.0
	*/
	this.load = function() {
		if(this.lang == 'fr') {
			this.msg['delete-cart'] = 'Votre panier contient des éléments. Vous devez les supprimer pour changer de date. Voulez-vous vider votre panier ?';
		}
		else {
			this.msg['delete-cart'] = 'You have several equipments in your shopping cart. You must remove these elements to select another period. Do you want to empty your cart ?';
		}
	}
	
	/**
	* Renvoit l'une des deux dates de location comme objet date.
	*
	* @param String dateField Nom de l'attribut date
	* @return Date Objet date correspondant
	* @access public
	* @since 1.0
	*/
	this.getDate = function(dateField) {
		eval('var date = this.' + dateField + ';');
		return new Date(parseInt(date));
		/*eval('date = this.' + dateField + ';');
		return this.dateFromCalendarToObject(date);*/
	}
	
	/**
	* Convertit une date renvoyée par le calendrier en objet Date.
	*
	* @param String value Date renvoyée par le calendrier
	* @return Date Objet de cette date
	* @access public
	* @since 1.0
	*/
	this.dateFromCalendarToObject = function(value) {
		dateD = 1;
		dateM = 1;
		dateY = 1970;
		
		//if(this.lang == 'fr') {
			expression = /([0-9]{2})-([0-9]{2})-([0-9]{4})/;
			expression.exec(value);
			dateD = parseInt(formatInfoDate(RegExp.$1));
			dateM = parseInt(formatInfoDate(RegExp.$2));
			dateY = parseInt(RegExp.$3);
		//}
		//else {
		//	expression = /([0-9]{2})\/([0-9]{2})\/([0-9]{4})/;
		//	expression.exec(value);
		//	dateD = parseInt(formatInfoDate(RegExp.$2));
		//	dateM = parseInt(formatInfoDate(RegExp.$1));
		//	dateY = parseInt(RegExp.$3);
		//}
		
		return new Date(dateY, dateM - 1, dateD);
	}
	
	/**
	* Convertit une date renvoyée par le calendrier en temps Unix.
	*
	* @param String value Date renvoyée par le calendrier
	* @return Integer Temps Unix de cette date
	* @access public
	* @since 1.0
	*/
	this.dateFromCalendarToUnix = function(value) {
		return Date.parse(this.dateFromCalendarToObject(value));
	}
	
	/**
	* Met à jour l'affichage d'un pack.
	*
	* @param Integer pack Identifiant du pack
	* @access public
	* @since 1.0
	*/
	this.displayPack = function(pack) {
		basePrice = this.getPriceFromDuration(pack, 6);
		rentalPrice = this.getPriceFromDuration(pack);
		
		optionComplete = this.getOptionEntry(document.getElementById('addForm-' + pack), 'option', 'complete');
		if(optionComplete == undefined || optionComplete.checked) {
			shopPrice = basePrice[0];
			internetPrice = rentalPrice[0];
			/*shopPrice = document.getElementById('addForm-' + pack).shop_price_complete.value;
			internetPrice = document.getElementById('addForm-' + pack).internet_price_complete.value;*/
		}
		else {
			shopPrice = basePrice[1];
			internetPrice = rentalPrice[1];
			/*shopPrice = document.getElementById('addForm-' + pack).shop_price_ski_only.value;
			internetPrice = document.getElementById('addForm-' + pack).internet_price_ski_only.value;*/
		}
		
		/*shopPrice = this.getPrice(shopPrice);
		internetPrice = this.getPrice(internetPrice);*/
		
		// Packs " service " ne font l'objet de promotion
		promo = this.getPromotion();
		if(promo == 0.00 || !this.packWithPromo(pack)) {
			//promo = 100 * (1 - internetPrice / shopPrice);
			document.getElementById('shop-' + pack).style.display = 'none';
			document.getElementById('promo-' + pack).style.display = 'none';
		}
		else {
			//internetPrice = shopPrice * (1 - promo / 100);
			shopPrice = internetPrice;
			internetPrice = internetPrice * (1 - promo / 100);
			document.getElementById('shop-' + pack).style.display = 'block';
			document.getElementById('promo-' + pack).style.display = 'block';
		}
		
		optionGuarantee = this.getOptionEntry(document.getElementById('addForm-' + pack), 'option', 'guarantee');
		if(optionGuarantee != undefined && optionGuarantee.checked) {
			option = this.getOption(pack);
			shopPrice += option;
			internetPrice += option;
		}
		
		document.getElementById('shop-' + pack).innerHTML = formatPrice(shopPrice) + ' &euro;';
		document.getElementById('internet-' + pack).innerHTML = formatPrice(internetPrice) + ' &euro;';
		document.getElementById('promo-' + pack).innerHTML = '- ' + replaceString('-', '', formatPrice(promo, 0)) + ' %';
	}
	
	/**
	* Met à jour l'affichage de la durée de location.
	*
	* @access public
	* @since 1.0
	*/
	this.displayDuration = function() {
		document.getElementById('duration').innerHTML = this.getDuration();
	}
	
	/**
	* Met à jour l'affichage des prix.
	*
	* @access public
	* @since 1.0
	*/
	this.displayPrice = function() {
		for(i = 0; i < document.forms.length; i++) {
			this.displayPack(document.forms[i].item.value, document.forms[i].option);
		}
	}
	
	/**
	* Traite l'envoi du formulaire de validation de panier.
	*
	* @param String pack Identifiant du dernier pack listé
	* @access public
	* @since 1.0
	*/
	this.validateCart = function(pack) {
		document.getElementById('addForm-' + pack).action = replaceString('add-cart', 'validate-cart', document.getElementById('addForm-' + pack).action);
		document.getElementById('addForm-' + pack).dateD.value = this.firstDay;
		document.getElementById('addForm-' + pack).dateF.value = this.lastDay;
		document.getElementById('addForm-' + pack).submit();
	}
	
	/**
	* Traite l'envoi d'un formulaire d'ajout de pack.
	*
	* @param String pack Identifiant du pack concerné
	* @access public
	* @since 1.0
	*/
	this.addPack = function(pack) {
		document.getElementById('addForm-' + pack).dateD.value = this.firstDay;
		document.getElementById('addForm-' + pack).dateF.value = this.lastDay;
		document.getElementById('addForm-' + pack).submit();
	}
	
	/**
	* Met à jour le 1er jour de location.
	*
	* @param String value 1er jour de location
	* @access public
	* @since 1.0
	*/
	this.changeFirstDay = function(value) {
		/*update = true;
		if(this.cart) {
			if(update = window.confirm(this.msg['delete-cart'])) {
				
			}
		}*/
		
		//if(update) {
			this.firstDay = this.dateFromCalendarToUnix(value);
			document.getElementById('first-day').innerHTML = this.dateFormat(this.getDate('firstDay'));
			document.getElementById('first-calendar').href = 'javascript:calDateD.popup(\'' + value + '\');';
			
			if(this.lastDay < this.firstDay) {
				this.lastDay = this.firstDay + 1000 * 3600 * 24 * 6;
				document.getElementById('last-day').innerHTML = this.dateFormat(this.getDate('lastDay'));
				document.getElementById('last-calendar').href = 'javascript:calDateF.popup(\'' + replaceString('/', '-', this.dateFormat(this.getDate('lastDay'))) + '\');';
			}
			
			this.displayDuration();
			this.displayPrice();
		//}
	}
	
	/**
	* Met à jour le dernier jour de location.
	*
	* @param String value Dernier jour de location
	* @access public
	* @since 1.0
	*/
	this.changeLastDay = function(value) {
		lastDay = this.dateFromCalendarToUnix(value);
		if(lastDay < this.firstDay) {
			this.firstDay = lastDay - 1000 * 3600 * 24 * 6;
			document.getElementById('first-day').innerHTML = this.dateFormat(this.getDate('firstDay'));
			document.getElementById('first-calendar').href = 'javascript:calDateD.popup(\'' + replaceString('/', '-', this.dateFormat(this.getDate('firstDay'))) + '\');';
		}
		
		this.lastDay = lastDay;
		document.getElementById('last-day').innerHTML = this.dateFormat(this.getDate('lastDay'));
		document.getElementById('last-calendar').href = 'javascript:calDateF.popup(\'' + value + '\');';
		this.displayDuration();
		this.displayPrice();
	}
	
	/**
	* Traite la sélection de l'option d'un pack.
	*
	* @param HTMLInputElement option Option cochée / décochée
	* @param Integer pack Identifiant du pack
	* @access public
	* @since 1.0
	*/
	this.changeOption = function(pack) {
		this.displayPack(pack);
	}
	
	/**
	* Renvoit la durée de la location.
	*
	* @return Float Durée de la location
	* @access public
	* @since 1.0
	*/
	this.getDuration = function() {
		var duration = (this.lastDay - this.firstDay) / 1000 / 3600 / 24 + 1;
		return (duration < 1 ? duration : formatNumber(duration, 0));
	}
	
	/**
	* Renvoit le prix suivant la durée de la location.
	*
	* @param Float price Prix de base sur 6 jours
	* @return Float Prix de la location
	* @access public
	* @since 1.0
	*/
	this.getPrice = function(price) {
		var duration = this.getDuration();
		
		/*if(duration % 7 == 0) {
			duration -= duration / 7;
		}*/
		
		return price * duration / 6;
	}
	
	/**
	* Renvoit le prix de location d'un pack sur une durée.
	*
	* @param Integer pack Identifiant du pack
	* @param Integer duration durée de location
	* @return Array Prix du pack complet et prix avec les skis seuls
	* @access public
	* @since 1.0
	*/
	this.getPriceFromDuration = function(pack, duration) {
		var price = new Array(0.00, 0.00);
		
		if(duration == undefined) {
			duration = this.getDuration();
		}
		
		requestURL = 'index.php?lang=' + lang + '&page=pack&tache=load-price'
		           + '&art=' + pack
		           + '&duration=' + duration;
		objXMLHR = createXMLHttpRequest();
		objXMLHR.open('get', requestURL, false); // mode synchrone pour éviter que l'objet ne soit remplacé par le suivant du même nom
		
		objXMLHR.send(null);
		
		var repXML = objXMLHR.responseXML;
		if(repXML.getElementsByTagName('prix_complet')[0] != undefined) {
			if(repXML.getElementsByTagName('prix_complet')[0].firstChild != undefined) {
				if(isDefined(repXML.getElementsByTagName('prix_complet')[0].firstChild.data)) {
					price[0] = parseFloat(repXML.getElementsByTagName('prix_complet')[0].firstChild.data);
				}
			}
		}
		if(repXML.getElementsByTagName('prix_seul')[0] != undefined) {
			if(repXML.getElementsByTagName('prix_seul')[0].firstChild != undefined) {
				if(isDefined(repXML.getElementsByTagName('prix_seul')[0].firstChild.data)) {
					price[1] = parseFloat(repXML.getElementsByTagName('prix_seul')[0].firstChild.data);
				}
			}
		}
		
		return price;
	}
	
	/**
	* Renvoit la promotion de la location.
	*
	* @return Float Promotion de la location
	* @access public
	* @since 1.0
	*/
	this.getPromotion = function() {
		firstDay = this.getDate('firstDay');
		lastDay = this.getDate('lastDay');
		
		firstDayM = firstDay.getMonth() == 12 ? 1 : firstDay.getMonth() + 1;
		lastDayM = lastDay.getMonth() == 12 ? 1 : lastDay.getMonth() + 1;
		requestURL = /*(this.lang == 'en' ? '../rental/' : 'rental/')
		           +*/ 'index.php?lang=' + lang + '&page=rental&tache=load-promo'
		           + '&date1=' + firstDay.getFullYear() + '-' + firstDayM + '-' + firstDay.getDate()
		           + '&date2=' + lastDay.getFullYear() + '-' + lastDayM + '-' + lastDay.getDate();
		objXMLHR = createXMLHttpRequest();
		objXMLHR.open('get', requestURL, false); // mode synchrone pour éviter que l'objet ne soit remplacé par le suivant du même nom
		
		objXMLHR.send(null);
		
		var repXML = objXMLHR.responseXML;
		if(repXML.getElementsByTagName('montant')[0] != undefined) {
			if(repXML.getElementsByTagName('montant')[0].firstChild != undefined) {
				if(isDefined(repXML.getElementsByTagName('montant')[0].firstChild.data)) {
					return parseFloat(repXML.getElementsByTagName('montant')[0].firstChild.data);
				}
			}
		}
		
		return parseFloat(0.00);
	}
	
	/**
	* Renvoit la valeur de l'option choisie.
	*
	* @param Integer pack Identifiant du pack
	* @return Float Montant de l'option
	* @access public
	* @since 1.0
	*/
	this.getOption = function(pack) {
		var price = 0.00;
		
		requestURL = 'index.php?lang=' + lang + '&page=pack&tache=load-option'
		           + '&art=' + pack
		           + '&lang=' + this.lang;
		objXMLHR = createXMLHttpRequest();
		objXMLHR.open('get', requestURL, false); // mode synchrone pour éviter que l'objet ne soit remplacé par le suivant du même nom
		
		objXMLHR.send(null);
		
		var repXML = objXMLHR.responseXML;
		if(repXML.getElementsByTagName('valeur')[0] != undefined) {
			if(repXML.getElementsByTagName('valeur')[0].firstChild != undefined) {
				if(isDefined(repXML.getElementsByTagName('valeur')[0].firstChild.data)) {
					price = parseFloat(repXML.getElementsByTagName('valeur')[0].firstChild.data);
				}
			}
		}
		
		return price;
	}
	
	/**
	* Indique si un pack est pris en compte pour le calcul des promotions.
	*
	* @param Integer pack Identifiant du pack
	* @return Boolean Le pack est pris en compte pour le calcul des promotions (true) ou pas (false)
	* @access public
	* @since 1.0
	*/
	this.packWithPromo = function(pack) {
		var price = 0.00;
		
		requestURL = 'index.php?lang=' + lang + '&page=pack&tache=with-promo'
		           + '&art=' + pack;
		objXMLHR = createXMLHttpRequest();
		objXMLHR.open('get', requestURL, false); // mode synchrone pour éviter que l'objet ne soit remplacé par le suivant du même nom
		
		objXMLHR.send(null);
		
		return objXMLHR.responseText == 'true';
	}
	
	/**
	* Formate une date pour l'affichage dans le bloc.
	*
	* @param Date date Date à formater
	* @return String Date formatée
	* @access public
	* @since 1.0
	*/
	this.dateFormat = function(date) {
		day = date.getDate();
		month = date.getMonth();
		month = (month == 12) ? 1 : month + 1;
		return (day <= 9 ? '0' + day : day) + '/' + (month <= 9 ? '0' + month : month) + '/' + date.getFullYear();
		/*stringDate = date.toLocaleString();
		stringDate = replaceString('é', 'e', stringDate);
		return stringDate.replace(/(\w{3})(\w+) (\d+) (\w{3})(\w+) 00:00:00/, '$1 $3 $5');*/
	}
	
	/**
	* Renvoit une option de pack parmi les entrées du formulaire correspondant.
	*
	* @param HTMLFormElement form Formulaire du pack
	* @param String entryName Nom de l'entrée recherchée
	* @param String optionName Nom de l'option recherchée
	* @return HTMLInputElement Entrée du formulaire trouvée
	* @access public
	* @since 1.0
	*/
	this.getOptionEntry = function(form, entryName, optionName) {
		for(var i = 0; i < form.elements.length; i++) {
			entryName2 = entryName + '[' + optionName + ']';
			if(form.elements[i].name == entryName2) {
				return form.elements[i];
			}
		}
		
		return null;
	}
	
	/**
	* Renvoit toutes les informations sur la location.
	*
	* @return String lang Informations sur la location
	* @access public
	* @since 1.0
	*/
	this.toString = function() {
		return('RentalInterface Object : ' + '<br /><br />'
             + 'rentalInterface.lang : ' + this.lang + '<br />'
             + 'rentalInterface.firstDay : ' + this.firstDay + '<br />'
             + 'rentalInterface.lastDay : ' + this.lastDay);
	}
	
	this.load();
}

