/**
 * Juan Servera - 31/08/2009
 * Javascript para pintar un cajetin de busqueda
 * incrustado en una pagina externa mediante 
 *  - la inclusion de JQUERY
 *  - la inclusion de este JS
 *  - la creacion de un div (con un ID determinado en la configuracion) donde tenga que ir el cajetin.
 * 
 * Todo con llamadas AJAX y JSON SIN problemas de CrossDomain! 
 */

/* ------  CONFIGURACIONES ------ */
var CUSTOMER = '';		// Numero de Customer Core.
var CHANNEL = '';		// Canal de venta.
var LNG = 'es';			// Lenguaje.
var LNG_ID = 1;			// Posicion del idioma en locales.
var MAXHAB = 4;			// Numero de habitaciones.
var MAXADS = 4;			// Numero maximo de adultos por habitacion.
var MAXNIN = 3;			// Numero maximo de niños por habitacion.
var MINEDS = 2;			// Edad minima para considerarse niños.
var MAXEDS = 12;		// Edad maxima para considerarse niños.
var DIV = "EasyDevel";	// Id del div donde se creara el cajetin.
//var URL = 'http://bookingcore.soncaliu.com/';	//Url base para las llamadas AJAX.
var URL = 'http://bookingcore.soncaliu.com/';	//Url base para las llamadas AJAX.
var URL_ACTION = 'http://bookingcore.soncaliu.com//pop_submit.xhtml';	//Url donde esta el listener para iniciar el proceso via pop-up's

/* --------  FIN CFG  ----------  */

/* ------ FUNCIONES MODIFICADORAS ------  */
function customer(id){CUSTOMER = id;}
function channel(id){CHANNEL = id;}
function url(url){URL=url;}
function url_action(urlaction){URL_ACTION=urlaction;}
function div(div){DIV=div;}
function lng(lng){
	if(lng=="es"){
		LNG = 'es';
		LNG_ID = 1;
	}else if(lng=="en"){
		LNG = "en";
		LNG_ID = 2;
	}else if(lng=="de"){
		LNG = "de";
		LNG_ID = 3;
	}else if(lng=="fr"){
		LNG = "fr";
		LNG_ID = 4;
	}else if(lng=="it"){
		LNG = "it";
		LNG_ID = 5;
	}else{
		LNG = "es";
		LNG_ID = 1;
	}
}
/* --------- FIN MODIFICADORAS ---------  */

/* -------------- LOCALES --------------  */
// 0:ninguno 1:es, 2:en, 3:de, 4:fr, 5:it
var l_entrada		= new Array('','Entrada',		'Check-in',	'Anreise',		'Date d\'arrivé',	'Da');
var l_noches		= new Array('','Noches',		'Night/s',	'Nächte',		'Nuit/s',			'Nottes');
var l_salida		= new Array('','Salida',		'Check-out','Abreise',		'Date de départ',	'Fino');
var l_habitaciones	= new Array('','Habitaciones',	'Rooms',	'Zimmer',		'Chambres',			'Camere');
var l_adultos		= new Array('','Adultos',		'Adults',	'Erwachsene',	'Adultes',			'Adulti');
var l_ninos 		= new Array('','Niños',			'Children',	'Kinder',		'Enfants',			'Bambini');
var l_edad			= new Array('','Edad del niño',	'Ages',		'Jahre',		'Âges',				'età');
var l_reservas			= new Array('','Reservas',	'Reservations',		'Reservierungen',		'',				'');
var l_ver_dispo			= new Array('','Ver Disponibilidad',	'Check Availability',		' Verfügbarkeit',		'',				'');
/* ------------  FIN LOCALES ------------  */

/* Y se pinta el cajetin */
jQuery(document).ready(function(){
	if( null == CUSTOMER || CUSTOMER == '' ){
		alert('No se ha definido un CUSTOMER.\nEl cajetin de disponibilidad no se cargara sin un identificador de cliente.');
	}else if( null == CHANNEL || CHANNEL == '' ){
		alert('No se ha definido un CHANNEL.\nEl cajetin de disponibilidad no se cargara sin un canal de venta.');
	}else{
		jQuery('#'+DIV).html("");
		jQuery('#'+DIV).append(getForm());
	}
	if(document.getElementById('form_oferta') != null){
	
	
		if (document.getElementById('form_oferta').oferta) {
			document.getElementById('form_disponibilidad').e_OFFER.value = document.getElementById('form_oferta').oferta.value;
		}
		if(document.getElementById('form_oferta').dia_oferta){
			document.getElementById('form_disponibilidad').e_DIA_E.value = document.getElementById('form_oferta').dia_oferta.value;
			document.getElementById('form_disponibilidad').e_MES_E.value = document.getElementById('form_oferta').mes_oferta.value +" - "+ document.getElementById('form_oferta').anio_oferta.value;
			changeDate(null, null, true);
			
		}
	}
});

function getForm(){
	
	i  = '<fieldset Style=" border: 0px solid white; margin-top: 0px;margin-bottom: -45px; *margin-bottom: -45px;">';
	i += '<p style="margin-bottom: -30px; *margin-bottom: -30px;"><img src="img/reservas_'+LNG+'.jpg"/></p>';
	i += '<form action="'+ URL_ACTION +'?lng='+LNG+'&e_channel='+CHANNEL+'" id="form_disponibilidad" method="post" target="consulta_disponibilidad">';
	i += '<table id="llegada">';
	i += '<tr>';
	i += '<td>';
	i += l_entrada[LNG_ID];
	i += getDiaLlegadaInput();
	i += getMesLlegadaInput();
	i += '</td>';
	i += '<td>';
	i += l_noches[LNG_ID];
	i += getNochesInput();
	i += '</td>';
	i += '<script type="text/javascript">';
	i += 'changeDate(null, null, true);';
	i += '</script>';
	i += '<td>';
	i += l_salida[LNG_ID];
	i += getDiaSalidaInput();
	i += getMesSalidaInput();
	i += '</td>';
	i += '<td>';
	i += l_habitaciones[LNG_ID];
	i += getHabitaciones();
	i += '</td>';
	i += '<td>';
	i += l_adultos[LNG_ID];
	i += getAdultos(1);
	i += '</td>';
	i += '<td>';
	i += l_ninos[LNG_ID];
	i += getNinos(1);
	i += '</td>';
	i+='<td>';
	i += '<span id="submit">';
	i += getBoton();
	i += '</span>';
	i+='</td>';
	for(en=1;en<=MAXNIN;en++){
		i += '<tr id="edad_ninos1_'+ en +'" style="display: none;">';
		i += '<td colspan="6" style="text-align: right;">'+l_edad[LNG_ID]+' '+ en +'</td>';
		i += '<td>';
		i += getEdadNino(1, en);
		i += '</td>';
		i += '</tr>';
	}
	
	for(h=2;h<=MAXHAB;h++){
		i += '<table id="habitacion_'+ h +'" style="display: none;">';
		i += '<tr>';
		i += '<td class="hab_x" style="width:400px;"> </td>';
		i += '<td class="hab_y" style="width:124px; text-align: center;">Hab. '+ h +'  </td>';
		i += '<td>';
		i += l_adultos[LNG_ID];
		i += getAdultos(h);
		i += '</td>';
		i += '<td>';
		i += l_ninos[LNG_ID];
		i += getNinos(h);
		i += '</td>';
		i += '</tr>';
		for(en=1;en<=MAXNIN;en++){
			i += '<tr id="edad_ninos'+ h +'_'+ en +'" style="display: none;">';
			i += '<td colspan="6" style="text-align: right;">'+l_edad[LNG_ID]+' '+ en +'</td>';
			i += '<td>';
			i += getEdadNino(h, en);
			i += '</td>';
			i += '</tr>';
		}
		i += '</table>';
	}
	i += getOfertaHidden();

	i += '</form>';
	i += '</fieldset>';
	return i;	
}

function getDiaLlegadaInput(){
	i =  '<select id="e_entrada1" onchange="changeDate();" size="1" name="e_DIA_E">';
	var f = new Date();
	for(j=f.getDate();j<=getLastDay(f.getMonth(),f.getFullYear());j++){
		if(j.toString().length==1){t='0'+j.toString();}else{t=j.toString();}
		i += '<option value="'+ j +'">'+ t +'</option>';
	}
	i += '</select>';
	return i;
}

function getMesLlegadaInput(){
	i = '<select id="e_entrada2" onchange="changeDate(null, null, true);" size="1" name="e_MES_E" >';
	miFecha = new Date();
	miFecha.setDate(1);
	for(j=0;j<=12;j++){
		nFecha = new Date();
		nFecha.setDate(1);
		nFecha.setMonth(miFecha.getMonth()+j);
		var m = nFecha.getMonth()+1;
		if(m.toString().length==1){m='0'+m;}
		i += '<option value="'+ nFecha.getMonth() +' - '+ nFecha.getFullYear() +'">'+ m +' - '+ nFecha.getFullYear() +'</option>';
	}
	i += '</select>';
	
	return i;
}

function getNochesInput(){
	i = '<input id="e_noches" type="text" onchange="changeNights();" value="1" name="e_NOCHES" size="1"/>';
	return i;
}

function getDiaSalidaInput(){ 
	i = '<select id="e_salida1" onchange="changeDate();" size="1" name="e_DIA_S">';
	var f = new Date();
	for(j=f.getDate();j<=getLastDay(f.getMonth(),f.getFullYear());j++){
		if(j.toString().length==1){t='0'+j.toString();}else{t=j.toString();}
		i += '<option value="'+ j +'">'+ t +'</option>';
	}
	i += '</select>';
	return i;
}

function getMesSalidaInput(){
	i = '<select id="e_salida2" onchange="changeDate(null, null, true);" size="1" name="e_MES_S">';
	miFecha = new Date();
	miFecha.setDate(1);
	for(j=0;j<=12;j++){
		nFecha = new Date();
		nFecha.setDate(1);
		nFecha.setMonth(miFecha.getMonth()+j);
		var m = nFecha.getMonth()+1;
		if(m.toString().length==1){m='0'+m;}
		i += '<option value="'+ nFecha.getMonth() +' - '+ nFecha.getFullYear() +'">'+ m +' - '+ nFecha.getFullYear() +'</option>';
	}
	i += '</select>';
	return i;
}

function getHabitaciones(){
	i = '<select id="e_habitaciones" name="e_HABITACIONES" onChange="showRooms(this);">';
	for(j=1;j<=MAXHAB;j++){
		i += '<option value="'+ j +'">'+ j +'</option>';
	}
	i += '</select>';
	return i;
}

function getAdultos(hab){
	i = '<select id="e_adultos'+hab+'" name="e_ADULTOS'+hab+'">';
	for(j=1;j<=MAXADS;j++){
		i += '<option value="'+ j +'">'+ j +'</option>';
	}
	i += '</select>';
	return i;
}

function getNinos(hab){
	i = '<select id="ninos'+hab+'" name="e_NINOS'+hab+'" onChange="showChildrenAges(this);" >';
	for(j=0;j<=MAXNIN;j++){
		i += '<option value="'+ j +'">'+ j +'</option>';
	}
	i += '</select>';
	return i;
}

function getEdadNino(hab, nin){
	i = '<select id="edad_ninos_'+hab+'_'+ nin +'" name="e_E'+hab+'N'+nin+'" >';
	for(j=0;j<=MAXEDS;j++){
		i += '<option value="'+ j +'">'+ j +'</option>';
	}
	i += '</select>';
	return i;
}

function getOfertaHidden(){
	i = '<input type="hidden" value="" name="e_OFFER"/>';
	return i;
}

function getBoton(){
	i = '<input id="e_submit" type="image" src="img/disponibilidad_'+LNG+'.jpg" type="submit" onclick="return sendme();" name="commit"/>';
	return i;
}


//** Funciones privadas del js **//
function changeDate (start, end, firstTime) {
	var de = document.getElementById('e_entrada1');
	var me = document.getElementById('e_entrada2');
	var ds = document.getElementById('e_salida1');
	var ms = document.getElementById('e_salida2');
	var e_noches = document.getElementById('e_noches');
	
	var dev = parseInt(de.value);
	var dsv = parseInt(ds.value);
	var mev = me.value;
	var msv = ms.value;	
	var entrada = mev.split(" - ");
	var salida = msv.split(" - ");
	mev = parseInt(entrada[0]);
	msv = parseInt(salida[0]);
	var yev = parseInt(entrada[1]);
	var ysv = parseInt(salida[1]);
	
	var hoy = new Date();
	var ent = new Date(yev, mev, dev,hoy.getHours(),hoy.getMinutes(),59);
	var sal = new Date(ysv, msv, dsv,hoy.getHours(),hoy.getMinutes(),59);

	if (ent.getTime() < hoy.getTime()) {
		if (firstTime) {
			ent = hoy;
		} else {
			ent = new Date(yev, mev + 1, dev,hoy.getHours(),hoy.getMinutes(),59);
			firstTime = true;
		}
	}
	if (sal.getTime() <= ent.getTime()) {
		if (firstTime) {
			sal.setTime(ent.getTime());
			sal.setDate(sal.getDate() + 1);
		} else {
			sal = new Date(ysv, msv + 1, dsv,hoy.getHours(),hoy.getMinutes(),59);
		}
	}
	var nv = Math.floor((sal.getTime() -  ent.getTime()) / (1000 * 60 * 60 * 24)); 
	if (nv > 0) {
		e_noches.value = nv;
	} else {
		sal.setTime(ent.getTime());
		sal.setDate(sal.getDate() + 1);
	}
	
	generateSelects(de, me, ent, start, end);
	generateSelects(ds, ms, sal, start, end);
}

function changeNights () {
	
	var de = document.getElementById('e_entrada1');
	var me = document.getElementById('e_entrada2');
	var ds = document.getElementById('e_salida1');
	var ms = document.getElementById('e_salida2');
	var noches = document.getElementById('e_noches');
	
	if (isNaN(noches.value) || noches.value <= 0)
		noches.value = 1;
	else
		noches.value = parseInt(noches.value);

	var dev = parseInt(de.value);
	var mev = me.value;
	var entrada = mev.split(" - ");
	mev = parseInt(entrada[0]);
	var yev = parseInt(entrada[1]);

	var ent = new Date(yev, mev, dev);
	var sal = new Date();

	var val = Math.floor(ent.getTime() + (noches.value * (1000 * 60 * 60 * 24)));
	sal.setTime(val);

	generateSelects(ds, ms, sal, null, null);
}

function generateSelects(select1, select2, fecha) {
	generateSelects(select1, select2, fecha, null, null);
}

function generateSelects(select1, select2, fecha, start, end) {
	
	var minDate = null;
	var maxDate = null;
	
	if (null != start && null != end) {
		var sDate = start.split("-");
		var eDate = end.split("-");
		if (sDate.length == 3 && eDate.length == 3) {
			minDate = new Date(sDate[0], sDate[1], sDate[2]);
			maxDate = new Date(eDate[0], eDate[1], eDate[2]);
		}
	}
	
	while (select1.options.length > 0) {
		select1.options[0] = null;
	}
	var fDay = 1;
	var lDay = getLastDay(fecha.getMonth(), fecha.getFullYear());
	
	if (null != minDate) {
		if (minDate.getMonth() == fecha.getMonth() && minDate.getFullYear() == fecha.getFullYear()) {
			fDay = minDate.getDate();
		}
	}
	if (null != maxDate) {
		if (maxDate.getMonth() == fecha.getMonth() && maxDate.getFullYear() == fecha.getFullYear()) {
			lDay = maxDate.getDate();
		}
	}
	
	var j = 0;
	for (i = fDay; i <= lDay; i++) {
		var long = (i + '').length;
		var dia;
		if (long > 1) {
			dia = '' + i;
		} else {
			dia = '0' + i;
		}
		var opcion = new Option(dia, i);
		select1.options[j++] = opcion;
	}
	
	var s = fecha.getMonth() + " - " + fecha.getFullYear();
	select1.value = fecha.getDate();
	select2.value = s;
}

function getLastDay(mes, anno) {
	mes = parseInt(mes);
	anno = parseInt(anno);
    switch (mes) {
   		case 0 : case 2 : case 4 : case 6 : case 7 : case 9 : case 11 : return 31;
		case 1 : return (anno % 4 == 0) ? 29 : 28;
 	}
 	return 30;
}

function sendme(){
    window.open('','consulta_disponibilidad','width=1000,height=720,scrollbars=yes');
    window.setTimeout("document.getElementById('form_disponibilidad').submit();",100);
    return false;
}

function showRooms(select) {
	var  ver = select.value;
	var base = parseInt(select.value)+1;
	for(i=2;i<=ver;i++){	
		jQuery("#habitacion_"+i).css('display','');
	} 
	for(i=base;i<=MAXHAB;i++){
		jQuery("#habitacion_"+i).css('display','none');
		for(e=1;e<=MAXNIN;e++){
			jQuery("#edad_ninos"+i+"_"+e).css('display','none');
		}
	}
}
 
function showChildrenAges(select){	
	var id = select.id;
	var cant = parseInt(select.value);
	
	for(i=1;i<=cant;i++){
		jQuery("#edad_"+ id +"_"+i).css('display','');
	}
	for(i=cant+1;i<=MAXNIN;i++){
		jQuery("#edad_"+ id +"_"+i).css('display','none');
	}
}


