var tipos;
var alojamientos;
var tx_gtkhotelsform_codigoalojamiento;
var tx_gtkhotelsform_tipologia ; 
var codigo;
var tipologia;

updateDate = function(e){
	var a =Event.element(e);
	var parent = a.up(0);
	var  dates = $A(parent.getElementsByClassName("date"));
	
	dates.each(function (date){
		var day = parent.getElementsByClassName("day")[0];
		var month = parent.getElementsByClassName("month")[0];
		date.value=day.value+"/"+(parseInt(month.value)+1);

	})
 
}
activateDate= function (input){
	Event.observe(input,"change", updateDate);
}
var formValidate =  function(form) {
 
	 
} 

showValidate=function( validated ,a, value){

	if(!validated){
		
		var advice = a.name;
		var div = $("advice-"+advice+"-"+value);
		if (div != undefined){ 
			Element.show(div);
			return false;
		}


	}

}
submit=function ( e ){
//	validation.validate({onElementValidate : showValidate});
	var a = Event.findElement(e,"form");
	
	var inputs = a.getElements();
	var failed = inputs.findAll(function( input ){
		if (input.hasClassName('validation-failed')) 
			return true;
		else 
			return false;
	});
	
	if (failed.length>0) 
		return false;
	
	
	var iframe=$('iframe');
	var col_central = $('col_central');
	var col_der = $('col_der');
	var td = iframe.up("td")
	
	td.addClassName('oculto');
	if (td.next('td')!=undefined)
		td.next('td').addClassName('oculto');
	if(col_der != undefined)
		col_der.addClassName('oculto');
	if(col_central != undefined)
		col_central.addClassName('oculto');
	
	a.submit();
	iframe.show();
}
ninosChange = function (e){
	var a	=	Event.element( e );
	//alert (a.value);
	var div = $("ninosDiv");
	if ( div==undefined){
		new Insertion.Bottom(	a.up("form"), "<div id='ninosDiv'></div>"); 
		div = $("ninosDiv");
	}
	
	div.innerHTML="";
	
	
	
		
		for (var i=1; i<=a.selectedIndex; i++)
			new Insertion.Bottom(div, "<input type='hidden' name='edad_nino_1_"+i+"' value='11'/>");  
		
		//alert (div.innerHTML);
 
}
fechasChange=function (d){
		

	
	this.input.value = d.format('dd') +"/"+ d.format('mm') +"/"+ d.format('yyyy');
	this.element.hide(); 
	todayDate=new Date();
	//alert(calendarBegin.currentdate<todayDate);
	
//	if (calendarBegin.currentdate<todayDate-86400000){
	if (calendarBegin.currentdate<todayDate){ 

		calendarBegin.setCurrentDate(  new Date(todayDate.getFullYear(),todayDate.getMonth(),todayDate.getDate()+1) );
	}
	
	if(calendarEnd.currentdate < calendarBegin.currentdate){
		//calendarBegin.currentdate+1);
		var dateEnd = new Date(calendarBegin.currentdate.getFullYear(),calendarBegin.currentdate.getMonth(),calendarBegin.currentdate.getDate()+7);
		calendarEnd.setCurrentDate( dateEnd );
	}
	
	//$('noches').value=parseInt( (calendarEnd.currentdate - calendarBegin.currentdate)/86400000 );
	var dummy_total=(calendarEnd.currentdate - calendarBegin.currentdate)/86400000;
  
	var dummy_total2=parseInt(dummy_total);
	//if (dummy_total > dummy_total2) dummy_total2++;
	$('noches').value=dummy_total2;
	
}
nombreChange=function (d){

	var str_articulo= $('codAloja').value;
	var tipo_articulo = str_articulo.substring(str_articulo.length-1,str_articulo.length);
	var nom_articulo = str_articulo.substring(0,str_articulo.length-2);
	//$('id_tipo_articulo_clase').value=tipo_articulo;
	$('nombre_comercial').value=nom_articulo;
}
tipoSelect= function(e){

	var a = Event.element(e);
	var cod_aloja = $('codAloja');
	var suplemento_filtro_1 = $('suplemento_filtro_1');
	
    if(cod_aloja.type=="select-one"){
        cod_aloja.innerHTML =""; 
        var alojamientosxtipo = alojamientos[a.value];
        if (alojamientosxtipo!=undefined){
            if(cod_aloja!=undefined){
                if (tx_gtkhotelsform_codigoalojamiento!=undefined) codigo=tx_gtkhotelsform_codigoalojamiento['tx_gtkhotelsform_codigoalojamiento'];
                    fillSelect(cod_aloja, alojamientosxtipo, codigo);
                cod_aloja.disabled="";
                
                var str_articulo= $('codAloja').value;
                var nom_articulo = str_articulo.substring(0,str_articulo.length-2);
                $('nombre_comercial').value=nom_articulo;
            }
            
            if (suplemento_filtro_1 != undefined && alojamientosxtipo == alojamientos[1]){
                suplemento_filtro_1.disabled="";
                suplemento_filtro_1.selectedIndex=0;
            }else{
                suplemento_filtro_1.disabled="disabled";
            }
        }else{ 
            cod_aloja.disabled="disabled";
            suplemento_filtro_1.disabled="disabled";
            suplemento_filtro_1.selectedIndex=0;
        }
    }
	
}

nightsChange=function(e){
	var a = Event.element(e);
	if( !isNaN(a.value) && a.value!=""){
		var date = new Date(calendarBegin.currentdate.getFullYear(), calendarBegin.currentdate.getMonth(), calendarBegin.currentdate.getDate()+parseInt(a.value));
		calendarEnd.input.value=date.format("dd")+"/"+date.format('mm')+"/"+date.format("yyyy");
		//.format('dd') +"/"+ d.format('mm') +"/"+ d.format('yyyy');
	}
}

formConstruct = function ( e){
	
	var days = $A($$("form.reserve .day"));
	var months = $A($$("form.reserve .month"));
	
	var validation = new Validation($('hotels-form') );
	validation.options.focusOnError=false;
	
	Event.observe('hotels-form','submit',validation.onSubmit.bind(validation))

	Event.observe('hotels-form', 'submit', submit);
	
	
	var options = Object.extend({
			 
            titleformat:'mm yyyy', 
			updateformat:'dd/mm/yyyy', 
            dayheadlength:4,
            weekdaystart:1,
            tabular: true
			});	 
	
	calendarBegin = new scal('calendarBegin', fechasChange, options);
	calendarBegin.input = $("fechaEntrada");
	
	$('calendarBegin').hide();
	calendarBegin.input.calendar=calendarBegin;
	Event.observe (calendarBegin.input ,"change", calendarInputChange );
	

	
	calendarEnd = new scal('calendarEnd', fechasChange, options);
	calendarEnd.input = $("fechaSalida");
	$('calendarEnd').hide();
	calendarEnd.input.calendar=calendarEnd;
	Event.observe (calendarEnd.input ,"change", calendarInputChange );
	
	
	Event.observe($("noches"),"keyup",nightsChange);
	
		
	var codAloja = $('codAloja');
	if(codAloja!=undefined)
		Event.observe(codAloja,"change",nombreChange); 
	
	
	
	//tipologias de alojamiento
	var id_tipo_articulo_clase= $('id_tipo_articulo_clase');
	
	if (tx_gtkhotelsform_tipologia!=undefined) tipologia =tx_gtkhotelsform_tipologia['tx_gtkhotelsform_tipologia'];
	
	if (tipos!=undefined)
        if(id_tipo_articulo_clase.type=="select-one"){
            fillSelect(id_tipo_articulo_clase, tipos, tipologia);
        }
	
	
	
	if( id_tipo_articulo_clase != undefined )
		Event.observe(id_tipo_articulo_clase,"change",tipoSelect); 
	
	if (tipologia!=undefined){
		document.observe("tipo:changed", tipoSelect);
		id_tipo_articulo_clase.fire("tipo:changed");
		
	}

	var ninos = $("ninos");
	if (ninos!=undefined){ 
		Event.observe(ninos,"change",ninosChange);
	}
	if ($('primera')!=undefined){
		var columna = $("primera").next();
		new Insertion.Top(columna,"<iframe name='iframe' id='iframe' src='' frameborder='0' style='width:100%; height:500px;display:none;' >   </iframe>");
	}
		calendarBegin.setCurrentDate(new Date());
}	
function calendarInputChange(e){
	var  a =Event.element( e );
	var re = new RegExp("[^0-9]+", "g");
	a.value = a.value.replace(re, "/"); 
	var arr = a.value.split("/");
	this.calendar.setCurrentDate(	new Date(arr[2], arr[1]-1, arr[0])	);
}
function formatOption(val){ return "<option value='"+val.key+"'>"+val.value+"</option>";}

function optionSelect(sel,selectedValue){

	
	if (selectedValue==undefined){ 
		var opt  = sel.down('option');
		
		if (document.all==undefined){ opt.selected=true;return} 
		opt.setAttribute('selected','selected'); 
		
		return ;} 
	
	var options = sel.select("option");
	options.each(function (option){		 if(option.value==selectedValue){ 
		if (document.all==undefined){option.selected=true; return;} 
		option.setAttribute('selected','selected');
		
	}	})
}
function fillSelect(select, values, selectedValue){
	values=$H(values);
	
	var arr=new Array();
	values.each(function (val){
		if( !Object.isFunction(val.value) ) 
			arr.push(formatOption(val));
	});	
	var str=arr.join("");
	new Insertion.Bottom(select,str);
	
	optionSelect(select,selectedValue)
} 
var calendarBegin;
var calendarEnd; 
Event.observe(window,"load", formConstruct);
