// JavaScript Document

$(document).ready(function(){


	var $cargando = $('#cargando');
	var $notify = $('#notificaciones');	
	var $ventana_contacto = $ventana_contacta;
	var $ctro = $('#ctro');
	var $reservaweb = $('#reservaweb');
	var $launchpad_img = $('#launchpad_img');
	var $js_news = $("#js-news");
	var $tiempo = $("#tiempo");
	var $emailimg = $("#emailimg");
	var $prueba = $('#prueba');
	var $inicio = $('#inicio');
	var $esquinita = $('#esquinita');
	var $ventana_contacta = $('#ventana_contacta');
	var $boton_enviar = $("#boton_enviar");
	var $open_img = $('#open_img');
	var $open_trip = $('#open_trip');
	var $botones_menu = $('.botones_menu');
	var $galeria = $('#galeria');
	var $contenedor_fuera = $('#contenedor_fuera');
	var $contenedor = $('#contenedor');
	var $info = $("#info");
	
	$.ajaxSetup ({
    	// Disable caching of AJAX responses
   		cache: false
	});
	
	//Arregla problema con ie
	if ($.browser.msie && $.browser.version <= 8) { //Arregla el fallo de ie8 < para el efecto de transparencia
   		$reservaweb.show();
	}
	else {
		$reservaweb.slideDown(500);
		$(document).oneTime(3000, function() { $reservaweb.effect("highlight", {color: "#84c946"}, 500); });
		
	}
	
	//Efecto nieve
	//$().jSnow();

	$(document).everyTime(500, function() {
  		recalcular();
	});
	
	$emailimg.hide();
	$boton_enviar.button();
	
	
	$prueba.click(function() {
  		$prueba.animate({
    		opacity: 0,
    		left: '+=750',
  			}, 1000);
  		$("#promocion").slideUp(500);
      	window.location = "http://www.twitter.com/bellamirador";
	});
	
	
	
	/*$(document).everyTime(3000, function() {
  		$('#promocion').effect("highlight", {color: "red"}, 500);
	});*/

	function relTime(time_value) {
		time_value = time_value.replace(/(\+[0-9]{4}\s)/ig,"");
		var parsed_date = Date.parse(time_value);
		var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
		var timeago = parseInt((relative_to.getTime() - parsed_date) / 1000);
		if (timeago < 60) return _MENOS_1_MIN;
		else if(timeago < 120) return _ALREDEDOR_1_MIN;
		else if(timeago < (45*60)) return (parseInt(timeago / 60)).toString() + _MINUTOS_ANTES;
		else if(timeago < (90*60)) return _HORA_ANTES;
		else if(timeago < (24*60*60)) return (parseInt(timeago / 3600)).toString() + _HORAS_ATRAS;
		else if(timeago < (48*60*60)) return _DIA_ANTES;
		else return (parseInt(timeago / 86400)).toString() + _DIAS_ANTES;
	}
		
	$.getJSON('https://twitter.com/statuses/user_timeline.json?screen_name=bellamirador&count=8&callback=?', function(data) {
		$.each(data, function(i, item) {
				var _date = new Date(item.created_at);
				var created = relTime(item.created_at);
				$js_news.append('<li>'+item.text+' <span class="fecha">'+created+'</span> </li>');
			});
		$js_news.ticker({
			controls: false,        // Whether or not to show the jQuery News Ticker controls
			titleText: _U_TWEETS,   // To remove the title set this to an empty String
			pauseOnItems: 5000,    // The pause on a news item before being replaced
			displayType: 'fade' // Animation type - current options are 'reveal' or 'fade'
		});
		//console.log($('#js-news'));
	});
	
	$ctro.load('inicio.html');
	$ctro.css("width", "890");
	$inicio.css("fontWeight", "bolder");
	$tiempo.hide();
	$cargando.show();
	
	
	$("#form_contacta").validate({
			rules: {
				nombre: {
					required: true
				},
				correo_e: {
					required: true,
					email: true
				},
				mensaje: {
					required: true
				}
			},
			messages: {
				correo_e: _EMAIL_KO,
				nombre: _NAME_KO,
				mensaje: _SUBJECT_KO
			},
			errorLabelContainer: $notify,
			wrapper: "li"
	});
	
	$boton_enviar.click(function() {		
		if($("#form_contacta").valid()) {
			var dataString = 'lang=' + _IDIOMA + '&nombre=' + $('#nombre').val() + '&correo=' + $('#correo_e').val() + '&departamento=' + $('#departamento').val() + '&mensaje=' + $('#mensaje').val(); 
			$.ajax({
				type: "POST",
				url: "sendmail.php",
				data: dataString,
				success: function(msg){
					$notify.css("border-color", "green");
					$notify.html(_MSG_SENT);
					$notify.show();
					$ventana_contacto.delay(2000).slideUp(500);
					$notify.effect("highlight", {color: "green"}, 500);
					$notify.effect("highlight", {color: "green"}, 500);
					$ctro.load('inicio.html');
					$ctro.css("width", "890");
					$botones_menu.css("fontWeight", "normal");
					$inicio.css("fontWeight", "bolder");
					$notify.delay(1000).fadeOut(1000);
					$('.entrada').delay(2000).val("");
					$('#mensaje').delay(2000).val("");
					$cargando.fadeOut(200);
					$esquinita.fadeIn(2000);
					$boton_enviar.fadeIn(100);
				},
				beforeSend: function() {
					$cargando.fadeIn(200);
					$notify.html(_MSG_SEND_NOW);
					$notify.css("border-color", "yellow");
					$notify.show();
					$boton_enviar.fadeOut(100);
				}
			});
		}
		else {
			$('#notificaciones').css("border-color", "red");	
		}
	
	});
	
	$inicio.click(function(){
		$launchpad_img.slideUp(500);
		$open_img.css("background-image", "url(../recursos_comunes/img/camera.png)"); 
		$esquinita.show();
		$open_trip.show();
		$ventana_contacta.slideUp(500);
		$botones_menu.css("fontWeight", "normal");
		$(this).css("fontWeight", "bolder");
		$cargando.fadeIn(100);
		$ctro.load('inicio.html');
		$cargando.fadeOut(100);
		$emailimg.hide();
		//$(document).oneTime(500, function() { recalcular(); });
	}); 
	
	$('#buscavuelo').click(function(){
		$launchpad_img.slideUp(500);
		$open_img.css("background-image", "url(../recursos_comunes/img/camera.png)"); 
		$esquinita.show();
		$open_trip.show();
		$ventana_contacta.slideUp(500);
		$botones_menu.css("fontWeight", "normal");
		$(this).css("fontWeight", "bolder");
		$cargando.fadeIn(100);
		$ctro.load('buscavuelo.html');
		$cargando.fadeOut(100);
		$emailimg.hide();
		//$(document).oneTime(500, function() { recalcular(); });
	});
	
	
	$('#alquilacoche').click(function(){
		$launchpad_img.slideUp(500);
		$open_img.css("background-image", "url(../recursos_comunes/img/camera.png)"); 
		$esquinita.show();
		$open_trip.show();
		$ventana_contacta.slideUp(500);
		$botones_menu.css("fontWeight", "normal");
		$(this).css("fontWeight", "bolder");
		$cargando.fadeIn(100);
		$ctro.load('alquilacoche.html');
		$cargando.fadeOut(100);
		$emailimg.hide();
		//$(document).oneTime(500, function() { recalcular(); });
	});
	
	$('#alojamiento').click(function(){
		$launchpad_img.slideUp(500);
		$open_img.css("background-image", "url(../recursos_comunes/img/camera.png)"); 
		$esquinita.show();
		$open_trip.show();
		$ventana_contacta.slideUp(500);
		$botones_menu.css("fontWeight", "normal");
		$(this).css("fontWeight", "bolder");
		$cargando.fadeIn(100);
		$ctro.load('alojamiento.html');
		$cargando.fadeOut(100);
		$emailimg.hide();
		//$(document).oneTime(500, function() { recalcular(); });
	});
	
	$('#servicios').click(function(){
		$launchpad_img.slideUp(500);
		$open_img.css("background-image", "url(../recursos_comunes/img/camera.png)"); 
		$esquinita.show();
		$open_trip.show();
		$ventana_contacta.slideUp(500);
		$botones_menu.css("fontWeight", "normal");
		$(this).css("fontWeight", "bolder");
		$cargando.fadeIn(100);
		$ctro.load('servicios.html');
		$cargando.fadeOut(100);
		$emailimg.hide();
		//$(document).oneTime(500, function() { recalcular(); });
	});
	
	$('#contacto').click(function(){
		$launchpad_img.slideUp(500);
		$open_img.css("background-image", "url(../recursos_comunes/img/camera.png)"); 
		if($reservaweb.height() != 23) {
			esquinita();
		}
		$botones_menu.css("fontWeight", "normal");
		$(this).css("fontWeight", "bolder");
		$cargando.fadeIn(100);
		$esquinita.hide();
		$open_trip.show();
		$ventana_contacta.slideDown(500);
		$ctro.load('localizacion.html');
		$cargando.fadeOut(100);
		$emailimg.fadeIn(2500);
		//$(document).oneTime(500, function() { recalcular(); });
	});
	
	$esquinita.click(function() { esquinita(); });
	$open_img.click(function(){ $ventana_contacta.slideUp(500); galeria_hs(); });
	$galeria.click(function(){ $ventana_contacta.slideUp(500); galeria_hs(); });
	
	
	function galeria_hs() {
		if($launchpad_img.css("display") === "none") {
			$botones_menu.css("fontWeight", "normal");
			$esquinita.show();
			$galeria.css("fontWeight", "bolder");
			$launchpad_img.slideDown(500);
			$launchpad_img.load("imagenes.html");
			$open_trip.hide();
			$emailimg.hide();
			$open_img.css("background-image", "url(../recursos_comunes/img/bstop.png)"); 
		}
		else {
			$botones_menu.css("fontWeight", "normal");
			$esquinita.show();
			$launchpad_img.slideUp(500);
			$launchpad_img.html("");
			$open_trip.show();
			$emailimg.hide();
			$ctro.load('inicio.html');
			$inicio.css("fontWeight", "bolder");
			$open_img.css("background-image", "url(../recursos_comunes/img/camera.png)"); 
		}
	}
	
	
    $("[title]").mbTooltip({ // also $([domElement]).mbTooltip  >>  in this case only children element are involved
      opacity : .97,       //opacity
      wait:300,           //before show
      cssClass:"default",  // default = default
      timePerWord:70,      //time to show in milliseconds per word
      hasArrow:false,			// if you whant a little arrow on the corner
      hasShadow:true,
      imgPath:"images/",
      ancor:"mouse", //"parent"  you can ancor the tooltip to the mouse position or at the bottom of the element
      shadowColor:"black", //the color of the shadow
      mb_fade:200 //the time to fade-in
    });
	
	$('#imagen').slidy({
		width: 960,
		height: 308,
		animation:  'fade',
		pause:      false
	});
	
	
function esquinita(){
			if($reservaweb.height() === 23) {
				$reservaweb.animate({ backgroundColor: "white" }, 600);
				$('form label').animate({ color: "black" }, 600).css("font-weight", "bold");
				$(_TXT_NORAY).appendTo('#reservaweb').addClass("nota");
				$esquinita.css("background-image", "url(../recursos_comunes/img/bstop.png)"); 
				var altura = $reservaweb.height() + $('#nota').height() + 15;
				$reservaweb.animate({ height: altura }, 500);
			}
			else {
				$reservaweb.animate({ height: 23 }, 500);
				$reservaweb.animate({ backgroundColor: "#000" }, 600);
				$esquinita.css("background-image", "url(../recursos_comunes/img/arrow3_n.png)"); 
				$('form label').animate({ color: "white" }, 600).css("font-weight", "normal");
				$("#nota").remove(":contains('"+ _WORD_FOUND +"')");
			}
}
	$.getJSON('jsontiempo.php', function(data) {
		$("<img/>").attr("src", data.condition.image).attr("alt", "Meteo").appendTo("#icono_t");	
		$info.append("<strong>"+data.location.city+"</strong>");
		$info.append("<br>").append(data.condition.text);
		$info.append("<br>").append("T: " + data.condition.temperature + " º" + data.units.temperature + "  -  " + _VIENTO);
		$info.append(data.wind.speed + " " + data.units.speed);
		$tiempo.fadeIn(1000);
		//$tiempo.show('slide', {direction: 'right'}, 1000);
		$cargando.fadeOut(1000);
	});


	fecha_hoy();
	//obtener_tweets();	
	var dates = $( "#FechaLlegada, #FechaSalida" ).datepicker({
			defaultDate: "+1w",
			closeText: _CLOSE,
			changeMonth: false,
			numberOfMonths: 2,
			dateFormat: 'd/m/yy',
			dayNamesMin: _DIASMIN,
			dayNamesShort: _DIAS,
			monthNames: _MESES,
			firstDay: _FIRSTDAY,
			nextText: _NEXT,
			prevText: _PREV,
			showAnim: 'fade',
			showButtonPanel: true,
			currentText: _TODAY,
			showOptions: {direction: 'down' },
			onSelect: function( selectedDate ) {
				var option = this.id == "FechaLlegada" ? "minDate" : "maxDate",
				instance = $( this ).data( "datepicker" ),
				date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings );
				dates.not( this ).datepicker( "option", option, date );
			}
	});
	
});


function recalcular() {
	
	var tam = $('#contenedor').height();
	var tam_new = tam + 40;
	$('#contenedor_fuera').height(tam_new);
	
}

function fecha_hoy() {

	var fecha = new Date();
	
	var dia = fecha.getDate();
	var diadespues = fecha.getDate() + 1;
	var mes = fecha.getMonth() + 1;
	var anio = fecha.getFullYear();
	
	$('#FechaLlegada').val(dia + '/' + mes + '/' + anio);
	$('#FechaSalida').val(diadespues + '/' + mes + '/' + anio);
	
	$('#fecha').html(_DIAS[fecha.getDay()] + " " + dia + ", " + _MESES[mes-1]);
	//$('#fecha').html("Miercoles" + ", " + dia + " " + "Septiembre" + ", " + anio);
}


/*function updateBackground() {
	screenWidth = $(window).width();
	screenHeight = $(window).height();
	
	//alert(screenWidth + " " + screenHeight);
	
	// Proporcion horizontal/vertical. En este caso la imagen es cuadrada
	ratio = 1.6;
	
	if (screenWidth/screenHeight > ratio) {
		$("#bg").height("auto");
		$("#bg").width("100%");
	} else {
		$("#bg").width("auto");
		$("#bg").height("100%");
	}
	
	// Si a la imagen le sobra anchura, la centramos a mano
	if ($("#bg").width() > 0) {
		$("#bg").css('left', (screenWidth - $("#bg").width()) / 2);
	}
}*/

