// JavaScript Document

/**
*	Comprovem que la data d'inici és correcta segons la configuracio establerta
*	Si ho és, modifiquem els camps startDate i start_date, i posem a end_date i 
*	endDate la data de sortida minima
*/
function checkDate(cal) {
	// creem el objecte data amb la data seleccionada i el objecte min_start_date amb la data minima seleccionable
	start_date = cal.date;
	prova_start_date = start_date;
	var min_start_date = newDate(config["start_date"], config["DATE_FORMAT_MYSQL"]);
	today = new Date();
	today.setHours(0);
	today.setMinutes(0);
	today.setSeconds(0);
	today.setMilliseconds(0);
	// Comparem les dues dates i si la seleccionada es massa petita, deixem la minima
	if (start_date < min_start_date) { 
		if (start_date >= today && last_minute_rates.length > 0) {
			document.getElementById('startDate').value = start_date.format(config["DATE_FORMAT_MYSQL"]);		
		} else {
			document.getElementById("startDateUser").value = min_start_date.format(config["DATE_FORMAT_USER"]);
			document.getElementById('startDate').value = min_start_date.format(config["DATE_FORMAT_MYSQL"]);
			start_date = min_start_date;
			alert('Nomes pots reservar a partir del '+min_start_date.format(config["DATE_FORMAT_USER"])+"\n"+
			'Solo puedes reservar a partir del '+min_start_date.format(config["DATE_FORMAT_USER"])+"\n"+
			'You can only book from '+min_start_date.format(config["DATE_FORMAT_USER"]));
		}
	} else {
		document.getElementById('startDate').value = start_date.format(config["DATE_FORMAT_MYSQL"]);		
	}
	// li sumem la duracio estandar
	var end_date = new Date(start_date.getTime()+(parseInt(config['BOOKING_DURATION'])*86400000));
	// Actualitzem els camps del formulari amb la data de sortida
	document.getElementById("endDateUser").value = end_date.format(config["DATE_FORMAT_USER"]);
	document.getElementById('endDate').value = end_date.format(config["DATE_FORMAT_MYSQL"]);
}
/**
*	Comprovem que la data final seleccionada és correcta
*/
function checkEndDate(cal) {
	// creem el objecte data
	var end_date = cal.date;
	// Calculem la data final minima
	var start_date = newDate(document.getElementById("startDate").value, config["DATE_FORMAT_MYSQL"]);
	var min_end_date = new Date(start_date.getTime()+(parseInt(config['BOOKING_DURATION'])*86400000));	
	// Si la data seleccionada és més petita que la minima, canviem la seleccionada per la mínima
	if (end_date < min_end_date) {
		end_date = min_end_date;
	}
	var duration = end_date - start_date;
	// Actualitzem els camps de la data final
	document.getElementById("duration").value = duration/86400000;
	document.getElementById("endDateUser").value = end_date.format(config["DATE_FORMAT_USER"]);
	document.getElementById('endDate').value = end_date.format(config["DATE_FORMAT_MYSQL"]);
}
/**
*	Retorna un string amb la data proporcionada en el format demanat
*/
function dateFormat(obj_date,date_format) {

}
function dateToString(date,date_format) {
	// retornem una data segons el format dateFormat
//	date_format = config['DATE_FORMAT_USER'];
	if (date_format.search("/") != -1) separator = "/";
	if (date_format.search("-") != -1) separator = "-";
	dateFormat = date_format.split(separator);
	var returnDate = "";
	for (i=0; i<dateFormat.length; i++) {
		if (i > 0) { returnDate = returnDate + separator; }
		switch (dateFormat[i]) {
		case "d":
			var newValue = date.getDate();
			if (newValue < 10) newValue = '0'+newValue;
			returnDate = returnDate + newValue;
			break;
		case "m":
			mes = date.getMonth()+1;
			if (mes < 10) mes = '0'+mes;
			returnDate = returnDate + mes;
			break;
		case "Y":
			returnDate = returnDate + date.getFullYear();
			break;
		}
	}
	return returnDate;
}
/**
*	Retorna un objecte Date partint d'una cadena string i un format de data donat
*	Opcions del format:
*	d = dia (2 xifres)
*	m = mes	(2 xifres)
*	Y = any (4 xifres)
*/
function newDate(stringDate, dateFormat) {
	// busquem el separador correcte
	if (dateFormat.search("/") != -1) separator = "/";
	if (dateFormat.search("-") != -1) separator = "-";
	// creem els array de la data d'entrada i el format de dades
	dateFormat = dateFormat.split(separator);
	dateElements = stringDate.split(separator);
	var arrayDate = new Array();
	for (i=0; i<dateFormat.length; i++) {
		key = dateFormat[i];
		arrayDate[key] = dateElements[i];
	}
	// creem el objecte date
	varDate = new Date(arrayDate["Y"],arrayDate["m"]-1,arrayDate["d"]);
	return varDate;
}
function recalculate(key) {
	if (g('type'+key).value == 1) {
		var index = g('type'+key).value+'-'+g('num_pax'+key).value;
		g('price'+key).value = rates["data"]["lines"][index]['price'];
		g('priceSpan'+key).innerHTML = price(rates["data"]["lines"][index]['price']);
		// Calculem el numero de persones
		numpax = 0;
		for (i=0;i<=g('numLines').value;i++){
			if (g('type'+i).value == 1) {
				numpax += parseInt(g('num_pax'+i).value);
			}
		}
		g('num_pax').value = numpax;
		g('num_paxSpan').innerHTML = numpax;
	}
	var totalPrice = 0;
	for (i=0;i<=g('numLines').value;i++){
		var index = g('type'+i).value+'-';

		if (g('type'+i).value == 1) { index += g('num_pax'+i).value; } 
		else { index += g('element_id'+i).value; }
		
		var lprice = g('price'+i).value;

		if (g('price'+i).value == "") { lprice = 0; }
		else lprice = parseFloat(g('price'+i).value);

		if ((g('type'+i).value == 1) || (parseInt(g('store'+i).value) == 1)) {
			switch (rates["data"]["lines"][index]['price_application']) {
				case 'BOOKING':
					totalPrice += lprice;
					break;
				case 'DAY':
					totalPrice += lprice*parseInt(g('duration').value);
					break;
				case 'PAX':
					totalPrice += lprice*parseInt(g('num_pax').value);
					break;
				case 'PAX_DAY':
					totalPrice += lprice*parseInt(g('num_pax').value)*parseInt(g('duration').value);
					break;
			}
		}
	}
	g('price').value = totalPrice;
	g('priceSpan').innerHTML = price(totalPrice);
	g('prepayment').value = totalPrice*parseFloat(rates["data"]["prepayment"])/100;
	g('prepaymentSpan').innerHTML = price(totalPrice*parseFloat(rates["data"]["prepayment"])/100);
	
}
function xxrecalculatePrice(key,obj) {
	var type = bookingLines[key]["type"];
	var rate = document.getElementById("rateid").value;
	if (type == 1) {
		bookingLines[key]["num_pax"] = obj.value;

		var element_id = obj.value;
		var index = type+"-"+element_id;
		bookingLines[key]["price"] = rateElements[rate]["elements"][index]["assignedPrice"];
		document.getElementById("price"+key).value = buildPrice(bookingLines[key]["price"]);
		calcPax();
	} else {
		if (obj.checked) bookingLines[key]["included"] = "1";
		else bookingLines[key]["included"] = "0";
		var element_id = document.getElementById("element_id"+key).value;
	}
	var totalPrice = 0;
	for (i=0;i<bookingLines.length;i++){
		if (bookingLines[i]["type"] == 1) {
			totalPrice += calcPrice(i);
		} else {
			if (parseInt(bookingLines[i]["included"])) {
				totalPrice += calcPrice(i);
			}
		}
	}
	prepayment = totalPrice*parseFloat(rateElements[rate]["prepayment"])/100;
	document.getElementById("price").value = buildPrice(totalPrice.toFixed(2));
	document.getElementById("prepayment").value = buildPrice(prepayment.toFixed(2));
}
function showWarning(timeSelected) {
	if (timeSelected <= config['timeWarning']) {
		g('TimeArrivalWarning').style.display = 'block';
	} else {
		g('TimeArrivalWarning').style.display = 'none';	
	}
}
function changeRate(obj) {
	document.location = "index.php?option=com_bookman&prop="+config["prop"]+"&layout=continue&localiser="+g('localiser').value+"&rate="+obj.value;
}
function calcPax() {
	numpax = 0;
	for (i=0;i<bookingLines.length;i++){
		if (bookingLines[i]["type"] == 1) {
			numpax += parseInt(bookingLines[i]["num_pax"]);
		}
	}
	document.form.num_pax.value = numpax;
}
function calcPrice(i) {
	switch (bookingLines[i]["price_application"]) {
	case 'BOOKING':
		price = parseFloat(bookingLines[i]["price"]);
		break;
	case 'DAY':
		price = parseFloat(bookingLines[i]["price"])*duration;
		break;
	case 'ROOM':
		price = parseFloat(bookingLines[i]["price"])*num_rooms;
		break;
	case 'ROOM_X_DAY':
		price = parseFloat(bookingLines[i]["price"])*num_rooms*duration;
		break;
	case 'PAX':
		price = parseFloat(bookingLines[i]["price"])*numpax;
		break;
	case 'PAX_DAY':
		price = parseFloat(bookingLines[i]["price"])*numpax*duration;
		break;
	}
	return price;
}
function validateContinue() {
	text = msgs['textErrors']+":\n";
	error = 0;
	var name = g("name");
	var email = g("email");
	if (name.value == "") {
		text += msgs['nameEmpty']+"\n";
		error = 1;
	}
	emailText = email.value;
	// si falta @ o hi ha un espai generem error
	if ((emailText.search("@") <= 0) || (emailText.search(" ") > -1)) {
		text += msgs['emailError']+"\n";
		error = 1;
	}
	if (error == 1) {
		alert(text);
		return false;
	} else {
		return true;

	}
}
/**
*	Retornem un string formatada amb la configuracio de moneda
*/
function price(amount) {
	priceStr = config['currOnTheRight'] ? '' : config['currencySymbol'];
	priceStr += parseFloat(amount).toFixed(2);
	priceStr += config['currOnTheRight'] ? config['currencySymbol'] : '';
	return priceStr;
}
/**
*	Creem un calendari per que el client pugui seleccionar la data
*/
function showCalendar(inputFieldId, buttonId) {
	Calendar.setup({
        inputField     :    inputFieldId,      // id of the input field
        ifFormat       :    config['DATE_FORMAT_CALENDAR'],       // format of the input field
        showsTime      :    false,            // will display a time selector
        button         :    buttonId,   // trigger for the calendar (button ID)
        singleClick    :    true,           // double-click mode
        firstDay       :	1,
        weekNumbers    :	false,
        step           :    0                // show all years in drop-down boxes (instead of every other year as default)
    });
}
/**
*	Funcions auxiliars
*/
/**
*	wrapper for getElementById
*/
function g(id) {
	return document.getElementById(id);
}
/**********************
*	Funcions externes
*/
// Simulates PHP's date function
Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar])
			returnStr += replace[curChar].call(this);
		else
			returnStr += curChar;
	}
	return returnStr;
};
Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	
	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return "Not Yet Supported"; },
	// Year
	L: function() { return "Not Yet Supported"; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() == 0 ? 12 : (this.getHours() > 12 ? this.getHours() - 12 : this.getHours()); },
	G: function() { return this.getHours(); },
	h: function() { return (this.getHours() < 10 || (12 < this.getHours() < 22) ? '0' : '') + (this.getHours() < 10 ? this.getHours() + 1 : this.getHours() - 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (this.getTimezoneOffset() < 0 ? '-' : '+') + (this.getTimezoneOffset() / 60 < 10 ? '0' : '') + (this.getTimezoneOffset() / 60) + '00'; },
	T: function() { return "Not Yet Supported"; },
	Z: function() { return this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return "Not Yet Supported"; },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
}

