Function.prototype.method=function(name,fn){this.prototype[name]=fn;return this;};if(!Array.prototype.forEach){Array. method('forEach',function(fn,thisObj){var scope=thisObj||window;for(var i=0,j=this.length;i<j;++i){fn.call(scope,this[i],i,this);}}). method('every',function(fn,thisObj){var scope=thisObj||window;for(var i=0,j=this.length;i<j;++i){if(!fn.call(scope,this[i],i,this)){return false;}}return true;}). method('some',function(fn,thisObj){var scope=thisObj||window;for(var i=0,j=this.length;i<j;++i){if(fn.call(scope,this[i],i,this)){return true;}}return false;}). method('map',function(fn,thisObj){var scope=thisObj||window;var a=[];for(var i=0,j=this.length;i<j;++i){a.push(fn.call(scope,this[i],i,this));}return a;}). method('filter',function(fn,thisObj){var scope=thisObj||window;var a=[];for(var i=0,j=this.length;i<j;++i){if(!fn.call(scope,this[i],i,this)){continue;}a.push(this[i]);}return a;}). method('indexOf',function(el,start){var start=start||0;for(var i=start,j=this.length;i<j;++i){if(this[i]===el){return i;}}return-1;}). method('lastIndexOf',function(el,start){var start=start||this.length;if(start>=this.length){start=this.length;}if(start<0){start=this.length+start;}for(var i=start;i>=0;--i){if(this[i]===el){return i;}}return-1;});}
function Observer() {
    this.fns = [];
	this.obj ="";
}

Observer.prototype = {
    subscribe : function(fn) {
        this.fns.push(fn);
    },
    unsubscribe : function(fn) {
        this.fns = this.fns.filter(
            function(el) {
                if ( el !== fn ) {
                    return el;
                }
            }
        );
    },
    fire : function(o) {
        var scope = this.obj || window;
        this.fns.forEach(
            function(el) {
                el.call(scope, o);
            }
        );
    }
};

var Crono = Class.create({
	
	initialize: function (){
		this.start_at = 0;
		this.end_at = 0;
		this.wait_time = 0;
		this.current_timer =  0;
		this.class_name = 'Crono';
		this.observer = new Observer();
		
	},
			startCron: function (){
				this.start_at = new Date();
			},
			
			stopCron: function (){
				this.end_at = new Date();
				this.wait_time = this.end_at - this.start_at ;
				return  ( this.wait_time / 1000 );
			},
			startTimeOut: function  ( segundos ) {
				this.current_timer = setInterval( this.closeTimeOutError.bindAsEventListener( this ) , segundos * 1000 );
				
			},
			clearTimeOut: function  (){
				clearInterval( this.current_timer );
			},
			closeTimeOutError: function (){
				clearInterval( this.current_timer );
				this.observer.fire ( "TimeOut" );
				
				
			},
			listen: function ( fn, obj ){
				this.observer.subscribe (fn);
				this.observer.obj = obj;
			}
	
});


var Gadget = function (  ){
	this.class_name = 'Gadget'
	this.crono = new Crono();
	this.url = '/es/rprocessor.php';
	this.state_machine_only = false;
	this.actual_request = false;
	
	this.conect_to = function ( URL){
		this.url = URL
	}
	
	this.inicia = function ( newNombre ){
		
		this.nombre = newNombre;
		
		this.crono.listen ( this.crono_time_out_hook, this );
		this.contenedor = $(this.nombre);
		this.form_name = this.nombre + "_form";
		this.observer = new Observer();
	}
	this.destroy = function (){
		
	}
	this.submit_gadget = function (  ){
			
			this.crono.startCron();
			this.crono.startTimeOut( 50 );
			var formulario = $(this.form_name);
			var params = formulario.serialize(true);
			params.action = this.nombre;
			this.before_submit();
			this.request = new Ajax.Request('/es/rprocessor.php',
					  {
					    method:'post',
						parameters: params,
						onSuccess: this.on_validate.bindAsEventListener( this ),
					    onFailure: this.on_invalidate.bindAsEventListener( this )
						}
					  )
			this.after_submit();
			return false;
		
	}
	this.before_submit = function (){
		
	}

	this.after_submit = function(){
	}
	

	this.stop_request = function (  ){
		Event.stop( this.actual_request ); 
		this.actual_request = false;
	}
	this.crono_time_out_hook = function ( response ){
		this.request.transport.abort();
		this.request = false;
		this.observer.fire("ko");
		this.timeout();
	}
	
	this.on_validate = function ( Response ){
		this.crono.clearTimeOut();
		this.request = false;
		this.validate( Response );
		this.observer.fire("ok");
		
	}
	this.on_invalidate = function ( Response ){
		this.crono.clearTimeOut();
		this.request = false;
		this.invalidate( Response );
		this.observer.fire("ko");
	}
	
	this.validate = function ( Response ){
		
	}
	this.invalidate = function( Response ){
		// Invalid Comunication Response
		
	} 
	this.timeout = function (){
		
	}
	
	
	this.regenerate = function (){
		
	}
	
	this.consolidate = function (){
		
	}
	
	this.listen = function ( fn, obj ){
		this.observer.subscribe (fn);
		this.observer.obj = obj;
	}
	
	this.destroy = function (){
		$( this.nombre + "_box").update('');
	}
	
	this.timeout_server_log = function (){
		
	}
	this.redirect_to = function (event,  place ){
		window.location = place
	}
	
	this.choseYearOptionSelect = function ( select, fecha ){
		var someNodeList = $(select).getElementsByTagName('option');
		var nodes = $A(someNodeList);
		var re = 0;
		nodes.each(function(node){
				if ( node.value == fecha ){
					re = node.index;
				}
			});
		return(re);
	}
	
	this.date_object_to_human_date = function ( date ) {
		return ( date.getDate() + " / " + date.getMonth() + " / " + date.getFullYear()  )
	}
	
	this.date_object_to_date_calendar = function  ( date_combo ){
		return ( date_combo.getDate() + "-" + date_combo.getMonth() + "-" + date_combo.getFullYear()  )
	}
	
	this.date_string_to_date_object = function ( date_combo ){
		return ( new Date ( parseInt(date_combo.substr(6,4)), parseInt (date_combo.substr(3,2)) - 1 , parseInt (date_combo.substr(0,2)) ) ) ;
	}
	
	this.date_gateway_to_date_object = function ( date_gateway ) {
		return ( new Date ( parseInt (date_gateway.substr(0,4)) , parseInt (date_gateway.substr(4,2)) - 1 , parseInt(date_gateway.substr(6,2)) ) ) ;
	}
	this.date_gateway_to_date_human = function ( date_gateway ) {
		return ( date_gateway.substr(6,2) + " / " + date_gateway.substr(4,2)   + " / " + date_gateway.substr(0,4) ) ;
	}
	
	this.extract_date = function  ( date_combo ){
		var f = new Date ( parseInt(date_combo.substr(6,4)), parseInt (date_combo.substr(3,2)) - 1 , parseInt (date_combo.substr(0,2))  );
		return f;
	}
	
	this.get_languaje = function (){
		var url = window.location.href;
		this.languaje = (url.match(/\/[a-z][a-z]\//)).toString().replace('/', '').replace('/', '') ;
	}
	this.get_vip = function (){
		if ( $("viphomeformulario") ){
			this.session_vip = true;
		}else {
			this.session_vip = false;
		}
	}
	this.transalate_month = function ( month , lg){
		var temp = new Array();
		temp['es'] = new Array
		("Enero",
		 "Febrero",
		 "Marzo",
		 "Abril",
		 "Mayo",
		 "Junio",
		 "Julio",
		 "Agosto",
		 "Septiembre",
		 "Octubre",
		 "Noviembre",
		 "Diciembre");
		temp['en'] = new Array
		("January", 
		"February", 
		"March", 
		"April",
        "May", 
		"June", 
		"July", 
		"August", 
		"September",
        "October", 
		"November", 
		"December");
		 temp['pt'] = new Array
		("Enero",
		 "Febrero",
		 "Marzo",
		 "Abril",
		 "Mayo",
		 "Junio",
		 "Julio",
		 "Agosto",
		 "Septiembre",
		 "Octubre",
		 "Noviembre",
		 "Diciembre");
		return temp[ lg ][ month ];
		
	}	
	
	this.transalate = function( text, lg){
		var temp = new Hash();
		temp['en'] = new Hash();
		temp['en']['enviando'] = 'Checking availability for selected dates. Please wait, this could take a few seconds to be completed';
		temp['en']['timeout'] = 'This query took too long, Plaese try again.';
		temp['en']['no_response'] = 'The booking server has not response, please try again in a minute. We apologize for the inconvenience';
		temp['en']['reintentar'] = 'Retry';
		temp['en']['volver'] = 'Back'; 
		
		temp['es'] = new Hash();
		temp['es']['enviando'] = 'Estamos enviando su petici&oacute;n de disponibilidad. Espere por favor, este proceso podr&aacute; durar unos minutos';
		temp['es']['timeout'] = 'Se ha excedido el tiempo seguro de respuesta. Por favor, int&eacute;ntelo de nuevo.';
		temp['es']['no_response'] = 'La conexi&oacute;n con el servidor de reservas no emite respuesta, le rogamos lo intente pasados unos minutos. Disculpe las molestias.';
		temp['es']['reintentar'] = 'Reintentar'
		temp['es']['volver'] = 'Volver';
		
		temp['pt'] = new Hash();
		temp['pt']['enviando'] = 'Estamos enviando su petici&oacute;n de disponibilidad para las fechas solicitadas. Espere por favor, este proceso pouede durar unos minutos';
		temp['pt']['timeout'] = 'Se ha excedido el tiempo seguro de respuesta. Por favor, int&eacute;ntelo de nuevo.';
		temp['pt']['no_response'] = 'La conexi&oacute;n con el servidor de reservas no emite respuesta, le rogamos lo intente pasados unos minutos. Disculpe las molestias.';
		temp['pt']['reintentar'] = 'Reintentar'; 
		temp['pt']['volver'] = 'Volver';
		
		return (temp[lg][text]);
	}

}

var lkh = new Gadget ();

