/**
 * 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! 
 */
  
var scripts = document.getElementsByTagName("script");
var host = "";
for (i=0;i<scripts.length;i++){
    if (scripts[i].src.match(/:\/\/(.[^/]+)/)!=null && scripts[i].src.match(/:\/\/(.[^/]+)/).length>0){
     temp = scripts[i].src.match(/:\/\/(.[^/]+)/)[1];
     if (temp.indexOf('bookinweb')>-1 || temp.indexOf('restauranteaptc')){
        host = temp;   
      }
    }
        
}
/* ------  CONFIGURACIONES ------ */
var CUSTOMER = 2222;		// Numero de Customer Core.
var CHANNEL = 2;		// Canal de venta.
var LNG = 'es';			// Lenguaje.
var LNG_ID = 1;			// Posicion del idioma en locales.
var GETHOTELES = 1;	// Si queremos mostrar hoteles o solo destinos. 
var MAXHAB = 3;			// Numero de habitaciones.
var MAXADS = 3;			// Numero maximo de adultos por habitacion. 
var MAXNIN = 2;			// Numero maximo de niños por habitacion.
var MINEDS = 1;			// 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://hotelplayagolf.bookinweb.es';	//Url base para las llamadas AJAX.
var URL_ACTION = 'http://hotelplayagolf.bookinweb.es/index_external.xhtml';
/* --------  FIN CFG  ----------  */
var VISIBILIDAD = "_blank";
var ANALITICS = "";

/* ------ FUNCIONES MODIFICADORAS ------  */
function visibilidad(vis){alert(vis);VISIBILIDAD = vis;alert(VISIBILIDAD);}
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&auml;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_habitacion	= new Array('','Habitacion',	'Room',	    'Zimmer',		'Chambre',			'Camere');
var l_adultos		= new Array('','Adultos',		'Adults',	'Erwachsene',	'Adultes',			'Adulti');
var l_ninos 		= new Array('','Ni&ntilde;os',			'Children',	'Kinder',		'Enfants',			'Bambini');
var l_promocode		= new Array('','Promocode',		'Promocode','Promocode',	'Promocode',		'Promocode');
var l_edad			= new Array('','Edad ni&ntilde;o',	'Ages',		'Jahre',		'Âges',				'età');
var l_reservas			= new Array('','Reservas Online',	'Bookings',		'Reservierungen',		'Bookings',				'Bookings');
var l_reservar			= new Array('','Reservar',	'Book',		'Buchen',		'Bookings',				'Bookings');

/* ------------  FIN LOCALES ------------  */

/* Y se pinta el cajetin */
/* Y se pinta el cajetin */


$(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{
	   getVisibilidad();
	   	$('#'+DIV).html("");
		$('#'+DIV).append(getForm());
		getDestinos();
		if(GETHOTELES)getHoteles();
	}
});

function getForm(){
	
	i = '<h2 style="margin:5px;">'+l_reservas[LNG_ID]+'</h2>';
	i += '<span style="margin:5px;"><img src="/img/df_ln2.gif" width="95%;" height="4px;"/></span>';
	i += '<fieldset>';
	i += '<form action="'+ URL_ACTION +'?customer='+CUSTOMER+'&lng='+LNG+'&e_channel='+CHANNEL+'" id="form_disponibilidad" method="post" target="_blank">';
	i += '<input type="hidden"   id="customer" name="customer" value="'+CUSTOMER+'" >';

	i += getHotelesInput();
	i += '</p>';
	i += '<table >';
	i += '<tr>';
	i += '<td nowrap="nowrap">';
	i += l_entrada[LNG_ID]+': <br/>';
	i += '<input name="from" id="from" value="from" maxlength="5" style="width:70px;" />';
	i += getDiaLlegadaInput();
	i += getMesLlegadaInput();
	i += '</td>';
	i += '<td style="width:100px; text-align:right;" >';
	i += l_noches[LNG_ID]+'<br/>';
	i += getNochesInput();
	i += '<input name="nights" id="nights"  value="1" maxlength="3" style="width:20px; "/>';
	i += '</td>';
	i += '</tr>';
	i += '</table>';
	i += '<script type="text/javascript">';
	i += 'changeDate(null, null, true);';
	i += '</script>';
	i += '<table>';
	i += '<tr>';
	i += '<td>';
	i += l_salida[LNG_ID]+': <br/>';
	i += '<input name="to" id="to" value="" maxlength="10" style="width:70px;"/>';
	i += getDiaSalidaInput();
	i += getMesSalidaInput();
	i += '</td>';
	i += '</tr>';
	i += '</table>';
	
	i += '<table id="paxes">';
	i += '<tr>';
	i += '<td class="hab_0">';
	i += l_habitaciones[LNG_ID]+'<br/>';
	i += getHabitaciones();
	i += '</td>';
	i += '<td style="width:60px; text-align:right;" >';
	i += l_adultos[LNG_ID]+'<br/>';
	i += getAdultos(1);
	i += '</td>';
	i += '<td style="width:60px; text-align:right;" >';
	i += l_ninos[LNG_ID]+'<br/>';
	i += getNinos(1);
	i += '</td>';
	i += '</tr>';
	for(en=1;en<=MAXNIN;en++){
		i += '<tr id="edad_ninos1_'+ en +'" style="display: none;">';
		i += '<td colspan="2">'+l_edad[LNG_ID]+' '+ en +'</td>';
		i += '<td style="width:60px; text-align:right;">';
		i += getEdadNino(1, en);
		i += '</td>';
		i += '</tr>';
	}
	i += '</table>';
	for(h=2;h<=MAXHAB;h++){
		i += '<table id="habitacion_'+ h +'" style="display: none;">';
		i += '<tr>';
		i += '<td class="hab_x"> </td>';
		i += '<td class="hab_y">'+ l_habitacion[LNG_ID]+ ' '+ h +'  </td>';
		i += '<td style="width:60px; text-align:right;">';
		i += l_adultos[LNG_ID]+'<br/>';
		i += getAdultos(h);
		i += '</td>';
		i += '<td style="width:60px; text-align:right;">';
		i += l_ninos[LNG_ID]+'<br/>';
		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></td>";
			i += '<td colspan="2">'+l_edad[LNG_ID]+' '+ en +'</td>';
			i += '<td style="width:60px; text-align:right;">';
			i += getEdadNino(h, en);
			i += '</td>';
			i += '</tr>';
		}
		i += '</table>';
	}
	i += '<p id="promo">';
	i += l_promocode[LNG_ID]+'';
	i += '<br/>';
	i += getPromoInput();
	i += '</p>';
	i += getOfertaHidden();
	i += '</fieldset>';
	i +='<blockquote>';
	i += '<fieldset  class="button">';
	i += getBoton();
	i += '</fieldset >';
	i +='</blockquote>';
	i += '</form>';
	return i;	
}

function getDestinosInput(){
	i  = '<select id="e_destinos" size="1" name="e_DESTINO" ';
	if(GETHOTELES) i += 'onchange="getHoteles();" ';
	i += '>';
	i += '</select>';
	return i;
}

function getHotelesInput(){
	i = '<input id="e_hoteles" type="hidden" value="HPG" name="e_HOTEL"  />';
	return i;
}

function getDiaLlegadaInput(){
	i = '<input id="e_entrada1" type="hidden" onchange="changeDate();" value="" name="e_DIA_E"  />';


/*<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= i = '<input id="e_entrada2" type="hidden" onchange="changeDate();" value="" name="e_MES_E" />';
	/*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="hidden" onchange="changeNights();" value="1" name="e_NOCHES" size="1" style="width:20px; text-align:right;" />';
	return i;
}

function getDiaSalidaInput(){ 
	i= i = '<input id="e_salida1" type="hidden" onchange="changeDate();" value="" name="e_DIA_S" />';
	/*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= i = '<input id="e_salida2" type="hidden" onchange="changeDate();" value="" name="e_MES_S" />';
	/*
	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+'" >';
	i += '<option value="'+ 0 +'"><'+MINEDS+'</option>';
	for(j=MINEDS;j<=MAXEDS;j++){
		if (j==5){
		  i += '<option value="'+ j +'" selected="selected">'+ j +'</option>';
        } else {
         i += '<option value="'+ j +'">'+ j +'</option>';
        }
	}
	i += '</select>';
	return i;
}

function getPromoInput(){
	i = '<input id="promo" type="text" value="" name="promocode"/>';
	return i;
}

function getOfertaHidden(){
	i = '<input type="hidden" value="" name="e_OFFER"/>';
	return i;
}


function getBoton(){
	i = '<a href="#"  onclick="sendme();" id="book_button" class="sandos_b1_'+LNG+'"><span style="">'+l_reservar[LNG_ID]+'</span></a>'
	
	'//<input id="e_submit" class="sandos_b1" type="submit" onclick="return sendme();" value="Buscar" 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(){
	try{
	   $('#form_disponibilidad').submit();
    } catch (err){
        $j('#form_disponibilidad').submit();
    }
	//document.getElementById('form_disponibilidad').submit();
}

function showRooms(select) {
	var  ver = select.value;
	var base = parseInt(select.value)+1;
	for(i=2;i<=ver;i++){	
		try{
		  $("#habitacion_"+i).css('display','');
        } catch (err){
          $j("#habitacion_"+i).css('display','');
        }
	} 
	for(i=base;i<=MAXHAB;i++){
		try{
		  $("#habitacion_"+i).css('display','none');
		  for(e=1;e<=MAXNIN;e++){
		  	$("#edad_ninos"+i+"_"+e).css('display','none');
		  }
         } catch (err){
            $j("#habitacion_"+i).css('display','none');
		      for(e=1;e<=MAXNIN;e++){
		  	   $j("#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++){
		try{
		  $("#edad_"+ id +"_"+i).css('display','');
        } catch (err){
          $j("#edad_"+ id +"_"+i).css('display','');
        }
	}
	for(i=cant+1;i<=MAXNIN;i++){
		try{
		  $("#edad_"+ id +"_"+i).css('display','none');
        } catch (err){
          $j("#edad_"+ id +"_"+i).css('display','none');
        }
	}
}

function getDestinos(){
	var url = URL+"./xmenu?action=destinos&customer="+CUSTOMER+"&lng="+LNG+"&jsoncallback=?";
	$.getJSON(url);
}

function BookingCoreJsonDestinos(data){
	try{
	   $.each(data.destinos, function(i,item){
	   	$("#e_destinos").append('<option value="'+ item.id +'">'+ item.nombre +'</option>');
	   });
    } catch (err){
      $j.each(data.destinos, function(i,item){
	   	$j("#e_destinos").append('<option value="'+ item.id +'">'+ item.nombre +'</option>');
	   });
    }
}

function getHoteles(){
	var val = '--';
	if(null!=$("#e_destinos").val())val = $("#e_destinos").val();	
	var url = URL+"/xmenu?lng="+LNG+"&action=hoteles&customer="+CUSTOMER+"&destino="+val+"&jsoncallback=?";
	$.getJSON(url);
}

function BookingCoreJsonHoteles(data){
	try{
	   $("#e_hoteles").html('');
	   $.each(data.hoteles, function(i,item){
	       	$("#e_hoteles").append('<option value="'+ item.id +'">'+ item.nombre +'</option>');
	   });
	   
    } catch (err){
        $j("#e_hoteles").html('');
	   $j.each(data.hoteles, function(i,item){
	       	$j("#e_hoteles").append('<option value="'+ item.id +'">'+ item.nombre +'</option>');
	   });
    }
}
	
function getVisibilidad(){
	var url = URL+"/xmenu?lng="+LNG+"&action=visibilidad&customer="+CUSTOMER+"&jsoncallback=?";
	$.getJSON(url);
    }
function BookingCoreJsonCaracteristicas(data){
	try{
	$.each(data.caracteristicas, function(i,item){
		if (item.id=='popup') {document.getElementById('form_disponibilidad').target='_blank';}
		if (item.id=='iframe') {document.getElementById('form_disponibilidad').target='reservas';}
		if (item.id=='analitics') {	$('#form_disponibilidad').submit(function() {
										_gaq.push(['_linkByPost',this,true]);
									});}
	});
	} catch (err){
	$j.each(data.caracteristicas, function(i,item){
		if (item.id=='popup') {document.getElementById('form_disponibilidad').target='_blank';}
		if (item.id=='iframe') {document.getElementById('form_disponibilidad').target='reservas';}
		if (item.id=='analitics') {	$j('#form_disponibilidad').submit(function() {
										_gaq.push(['_linkByPost',this,true]);
									});}
	});
	}
}


