/*
 * Libreria principal de recursos de la web
 *
 * 
 */

var overlay;
window.addEvent('domready', function() {
	//overlay = new Overlay({container: $('cont_general')});
	overlay = new Overlay();
	
	// LOGIN 
	/*if ($defined($('formlogin'))) {
		$('formlogin').addEvent('submit', function(e) {
			//Prevents the default submit event from loading a new page.
			e.stop();
			this.set('send', {onComplete: function(response) { 
				var datos = JSON.decode(response);
				
				if (datos.error == 0) {
					hideLoginLayer();
					document.location = datos.location;
				}
				else {
					$('errorlogin').setStyle('display','block');
				}
				
			}});
			
			//Send the form.
			this.send();
		});
		
		$('cancelarlogin').addEvent('click', function(e) {
			hideLoginLayer();
		});
	}*/
	
	// TURNOS 
	/*if ($defined($('formcontturnos'))) {
		$('formcontturnos').addEvent('submit', function(e) {
			//Prevents the default submit event from loading a new page.
			e.stop();
			
			// Validamos si el usuario ha marcado algún checkbox
			var marcado = 0;
			$$('#tblturnos input').each(function (item,index) {
				if (item.getProperty('type') == 'checkbox') {
					if (item.checked) marcado = 1;
				}
			});
			
			if (marcado) {
				$('errorcontturnos').setStyle('display','none');
				this.set('send', {onComplete: function(response) { 
					var datos = JSON.decode(response);
					
					if (datos.error == 0) {
						setTurnosWeb(datos.turnos);
					}
					else {
						showErrorWeb(1);						
					}
					
				}});
			}
			else {
				$('errorcontturnos').setStyle('display','block');
			}
			
			//Send the form.
			this.send();
		});
		
		$('cancelarturnos').addEvent('click', function(e) {
			hideTurnosLayer();
		});
	}
	*/
	if ($defined($('a_reservar'))) {
		$('a_reservar').addEvent('click', function(e) {
			if (!idusuari) {
				e.stop();
				$('purlreturn').value = this.getProperty('href');
				showLoginLayer();
			}
		});
	}
	
	// Si estoy en la pagina de seleccion de turnos compruebo si ya estoy viendo turnos
	if ($defined($('tblturnosweb'))) {
		if ($$('#tblturnosweb td').length > 0) {
			$('ayudareserva').setStyle('display','block');
			$('reservaweb').setStyle('display','block');
		} 
		else {
			$('ayudareserva').setStyle('display','block');
			$('reservaweb').setStyle('display','none');
		}
		
	/*	// Activamos el enlace de eliminar turnos
		$('eliminar').addEvent('click', function(e) {
			eliminarTurnosSel();
		}); */
	}
	
	// VALORACIÓN
	if ($defined($('star_1'))) {
		for (i=1;i<=5;i++) {
			$('star_'+i).setStyle('cursor','pointer');
			
			$('star_'+i).addEvent('mouseover', function() {
				indice = this.id.substring(5,6);
				for (j=1; j<=Number(indice); j++) {
					srctemp = $('star_'+j).getProperty('src');
					$('star_'+j).setProperty('src',srctemp.replace(/_off.gif/,'_on.gif'));
				}
			});
			
			$('star_'+i).addEvent('mouseout', function() {
				indice = this.id.substring(5,6);
				for (j=1; j<=Number(indice); j++) {
					srctemp = $('star_'+j).getProperty('src');
					$('star_'+j).setProperty('src',srctemp.replace(/_on.gif/,'_off.gif'));
				}
			});
			
			$('star_'+i).addEvent('click', function () {
				indice = this.id.substring(5,6);
				
				var request = new Request.JSON({
					url: 'indexajax.php?accion=valoraractividad&valor='+indice+'&id='+$('idactividad').value,
					onComplete: function(jsonObj) {
						if (jsonObj.error) {
							// No hacemos nada
							alert('El torn no s\'ha pogut eliminar.\n Provau-ho una altra vegada més tard.');
						}
						else {
							// Actualizamos el valor de la valoracion
							nuevoValor = jsonObj.media;
							for (j=1;j<=5;j++) {
								if (nuevoValor >= j-(0.5)) $('star_'+j+'_media').setProperty('src',srctemp.replace(/_off.gif/,'_on.gif'));
								else $('star_'+j+'_media').setProperty('src',srctemp.replace(/_on.gif/,'_off.gif'));
								
								$('star_'+j+'_media').setProperty('title','Valoració: '+nuevoValor);
							}
 						}
					}
				}).send();
			});
		}
	}
});

function getTurnos(fecha,activitat) {
	var request = new Request.JSON({
		url: 'indexajax.php?id=' + activitat + '&fecha=' + fecha,
		onComplete: function(jsonObj) {
			if (jsonObj.error) {
				// No hacemos nada
			}
			else {
				$('fechaturnos').empty();
				$('fechaturnos').appendText(jsonObj.fecha);
				$('numtorns').setProperty('value',jsonObj.turnos.length);
				$('fechatorns').setProperty('value',jsonObj.fechasql);
				$('fechaestorns').setProperty('value',jsonObj.fechaes);
	
				viewTurnos(jsonObj.turnos);
			}
		}
	}).send();
}

function viewTurnos(turnoObj) {
	var latabla = $('tblturnos');
	
	$$('#tblturnos tbody').each(function (item,index) {
		item.destroy();
	});
	
	var tbody = new Element('tbody');
	
	for (i=0; i<turnoObj.length; i++) {
		tr = new Element('tr');
		
		td = new Element('td');
		if (i==turnoObj.length-1) td.addClass('ult');
		input = new Element('input', {
			'type'	:	'checkbox',
			'id'	:	'chktorn_'+i,
			'name'	:	'chktorn_'+i,
			'value'	:	turnoObj[i]["idtorn"]
		});
		td.grab(input);
		inputhidden = new Element('input', {
			'type'	:	'hidden',
			'name'	:	'tornex_'+i,
			'id'	:	'tornex_'+i,
			'value'	:	turnoObj[i]["idtornex"]
		});
		inputhidden.inject(td);
		tr.grab(td);
		
		// horaini
		if (turnoObj[i]["tornexhorai"]) horai = turnoObj[i]["tornexhorai"];
		else horai = turnoObj[i]["tornhorai"]
		tdhoraini = new Element('td');
		if (i==turnoObj.length-1) tdhoraini.addClass('ult');
		tdhoraini.appendText(horai);
		inputhiddenhorai = new Element('input', {
			'type'	:	'hidden',
			'name'	:	'horai_'+i,
			'id'	:	'horai_'+i,
			'value'	:	horai
		});
		inputhiddenhorai.inject(tdhoraini);
		tr.grab(tdhoraini);

		// horafin
		if (turnoObj[i]["tornexhoraf"]) horaf = turnoObj[i]["tornexhoraf"];
		else horaf = turnoObj[i]["tornhoraf"]
		tdhorafin = new Element('td');
		if (i==turnoObj.length-1) tdhorafin.addClass('ult');
		tdhorafin.appendText(horaf);
		inputhiddenhoraf = new Element('input', {
			'type'	:	'hidden',
			'name'	:	'horaf_'+i,
			'id'	:	'horaf_'+i,
			'value'	:	horaf
		});
		inputhiddenhoraf.inject(tdhorafin);
		tr.grab(tdhorafin);
		
		// plazas
		if (turnoObj[i]["tornexcap"]) plazas = turnoObj[i]["plazas"];
		else plazas = turnoObj[i]["plazas"]
		tdplazas = new Element('td');
		if (i==turnoObj.length-1) tdplazas.addClass('ult');
		tdplazas.appendText(plazas);
		inputhiddenhoraf = new Element('input', {
			'type'	:	'hidden',
			'name'	:	'plazas_'+i,
			'id'	:	'plazas_'+i,
			'value'	:	plazas
		});
		inputhiddenhoraf.inject(tdplazas);
		tr.grab(tdplazas);
		
		tbody.grab(tr);		
	}
	
	latabla.grab(tbody);
	
	showTurnosLayer();
	//alert(turnoObj[0]["idtorn"]);
}
		
function setTurnosWeb(turnoObj) {
	var tbody = $$('#tblturnosweb tbody')[0];
	var totalTurnosPintados = $('totaltorns').getProperty('value');
	var nuevoTotal = totalTurnosPintados - ((-1)*turnoObj.length);

	for (j=totalTurnosPintados; j<nuevoTotal; j++) {
		i=j-totalTurnosPintados;
		
		tr = new Element('tr', {
			'id' :	'slotcentre_'+turnoObj[i]["idslotcentre"]
		});
		
		td = new Element('td');
		input = new Element('input', {
			'type'	:	'checkbox',
			'id'	:	'chkslotcentre_'+j,
			'name'	:	'chkslotcentre_'+j,
			'class' :	'slotcentre',
			'value'	:	turnoObj[i]["idslotcentre"]
		});
		td.grab(input);
		tr.grab(td);
		
		// fecha
		fechaes = turnoObj[i]["fechaes"];
		tdfechaes = new Element('td');
		tdfechaes.appendText(fechaes);
		tr.grab(tdfechaes);

		// horaini
		horai = turnoObj[i]["horai"]
		tdhoraini = new Element('td');
		tdhoraini.appendText(horai);
		tr.grab(tdhoraini);

		// horafin
		horaf = turnoObj[i]["horaf"]
		tdhorafin = new Element('td');
		tdhorafin.appendText(horaf);
		tr.grab(tdhorafin);
		
		// plazas
		plazas = turnoObj[i]["plazas"]
		tdplazas = new Element('td');
		tdplazas.appendText(plazas);
		tr.grab(tdplazas);
		
		tbody.grab(tr);	
	}
	
	$('totaltorns').setProperty('value', nuevoTotal);
	
	// 
	$('reservaerrorweb').setStyle('display','none');
	$('ayudareserva').setStyle('display','none');
	$('reservaweb').setStyle('display','block');
	
	hideTurnosLayer();
	
	//alert(turnoObj[0]["idtorn"]);
	
}		

function eliminarTurnosSel() {
	// Revisamos los turnos chequeados
	$$('#tblturnosweb .slotcentre').each(function (item,index) {
		if (item.checked) {
			// Eliminamos el slotcentre
			var request = new Request.JSON({
				url: 'indexajax.php?accion=eliminarslotcentre&id=' + item.value,
				onComplete: function(jsonObj) {
					if (jsonObj.error) {
						// No hacemos nada
						alert('El torn no s\'ha pogut eliminar.\n Provau-ho una altra vegada més tard.');
					}
					else {
						deleteTurno(jsonObj.idslotcentre);
					}
				}
			}).send();
			
		}
	});
}

function deleteTurno(id) {
	//alert('El turno ha sido eliminado con éxito.')
	$('slotcentre_'+id).destroy();
}
		
function showTurnosLayer() {
	overlay.show();
	$('errorcontturnos').setStyle('display','none');
	$('contturnos').setStyle('display','block');
} 

function hideTurnosLayer() {
	$('contturnos').setStyle('display','none');
	overlay.hide();
} 

function showLoginLayer() {
	overlay.show();
	$('errorlogin').setStyle('display','none');
	$('login').setStyle('display','block');


} 

function hideLoginLayer() {
	$('login').setStyle('display','none');
	overlay.hide();
} 

function changeResponsableReserva(pos) {
	if ($('responsable'+pos).value == -1) {
		$('nombreape'+pos).setProperty('disabled',false);
		$('telefono'+pos).setProperty('disabled',false);
		$('email'+pos).setProperty('disabled',false);
		$('nombreape'+pos).setStyles({
			'background-color' : '#FFFFFF',
			'border-top' : '1px solid #7C7C7C',
			'border-left' : '1px solid #C3C3C3',
			'border-bottom' : '1px solid #DDDDDD',
			'border-right' : '1px solid #C3C3C3'
		});
		$('telefono'+pos).setStyles({
			'background-color' : '#FFFFFF',
			'border-top' : '1px solid #7C7C7C',
			'border-left' : '1px solid #C3C3C3',
			'border-bottom' : '1px solid #DDDDDD',
			'border-right' : '1px solid #C3C3C3'
		});
		$('email'+pos).setStyles({
			'background-color' : '#FFFFFF',
			'border-top' : '1px solid #7C7C7C',
			'border-left' : '1px solid #C3C3C3',
			'border-bottom' : '1px solid #DDDDDD',
			'border-right' : '1px solid #C3C3C3'
		});
		$('nombreape'+pos).setProperty('value','');
		$('telefono'+pos).setProperty('value','');
		$('email'+pos).setProperty('value','');
		$('nuevoresponsable'+pos).setProperty('value',1);
		
		
	}
	else {
		// Configuramos el formulario
		
		$('nombreape'+pos).setStyles({
			'background-color' : 'transparent',
			'border' : '0px'
		});
		$('telefono'+pos).setStyles({
			'background-color' : 'transparent',
			'border' : '0px'
		});
		$('email'+pos).setStyles({
			'background-color' : 'transparent',
			'border' : '0px'
		});
		$('nuevoresponsable'+pos).setProperty('value',0);

		if ($('responsable'+pos).getProperty('value') == 0) {
			$('telefono'+pos).setProperty('value','');
			$('email'+pos).setProperty('value','');
			$('nombreape'+pos).setProperty('value','');
		}
		else {
			$('telefono'+pos).setProperty('value',responsable[$('responsable'+pos).value][0]);
			$('email'+pos).setProperty('value',responsable[$('responsable'+pos).value][1]);
			$('nombreape'+pos).setProperty('value',responsable[$('responsable'+pos).value][2]);
		}
	}
}

function ValidarReservaConcertada(obj) {
	var error = '';
	
	if (obj.dia.value == 0) error += 'Heu d\'indicar el dia de la reserva\n'; 
	if (obj.nivell.value == 0) error += 'Heu d\'indicar el nivell educatiu\n'; 
	if (obj.plazas.value == '') error += 'Heu d\'indicar el número de places\n'; 
	if (obj.curso.value == '') error += 'Heu d\'indicar el nom del curs\n'; 
	if (obj.responsable.value == 0) error += 'Heu d\'indicar el responsable\n'; 
	else if (obj.responsable.value == -1) {
		if (obj.nombreape.value == '') error += 'Heu d\'indicar el nom del responsable\n'; 
		if (obj.email.value == '') error += 'Heu d\'indicar el mail del responsable\n';
	} 
	
	if (error == '') return true;
	else {
		alert(error);
		return false;
	}
}

function ValidarReservasProgramadas(obj) {
	var error = '';
	
	for (i=0; i<obj.numturnos.value; i++) {
		var pre = 'Torn '+(i-(-1))+': ';
	
		if ($('nivell'+i).value == 0) error += pre+'Heu d\'indicar el nivell educatiu\n'; 
		if ($('plazas'+i).value == '') error += pre+'Heu d\'indicar el número de nins\n'; 
		if ($('plazasf'+i).value == '') error += pre+'Heu d\'indicar el número de nines\n';
		
		

		if (isNaN($('plazas'+i).value) || isNaN($('plazasf'+i).value)) {
			error += pre+'Número de nins i nines ha d\'esser numèric\n';
		} else {
			var num      = parseInt ($('plazas'+i).value);
			var numf     = parseInt ($('plazasf'+i).value);
			var totalpax = parseInt ($('totalpax'+i).value);
			if (num + numf > totalpax) {
				error += pre+'Número de places excedides\n';
			}
		}
		
		if ($('curso'+i).value == '') error += pre+'Heu d\'indicar el nom del curs\n'; 
		if ($('responsable'+i).value == 0) error += pre+'Heu d\'indicar el responsable\n'; 
		else if ($('responsable'+i).value == -1) {
			if ($('nombreape'+i).value == '') error += pre+'Heu d\'indicar el nom del responsable\n'; 
			if ($('email'+i).value == '') error += pre+'Heu d\'indicar el mail del responsable\n';
		} 
	}		
	
	if (error == '') return true;
	else {
		alert(error);
		return false;
	}
}

function getEquipamientos(idIsla) {
	if (idIsla == 'Pitiüses') idIsla = 'Pitiuses';
	var request = new Request.JSON({
		url: 'indexajax.php?id=' + idIsla + '&accion=cambioisla',
		onComplete: function(jsonObj) {
			//alert(jsonObj.error);
			//alert(jsonObj.isla);
			if (jsonObj.error) {
				// No hacemos nada
			}
			else {
				setEquipamientos(jsonObj.equipamientos);
			}
		}
	}).send();
}
function setEquipamientos(equipObj) {

	// Vamos a Cmbiar las opcinoes del select de 
	
	for (i=1; i<=equipObj.length; i++) {
		$('bequipament').options[i] = new Option(equipObj[(i-1)]["nombre"],equipObj[(i-1)]["id"]);
	}
	$('bequipament').options.length = equipObj.length - (-1);
}

