var directionsService;
var marker;
var latlng;
var map;
var infowindow;
var time;
var browserSupportFlag =  new Boolean();
function googleMaps(){
	var initialLocation;
	var userLocation;
	var geocoder = new google.maps.Geocoder();
	directionsService = new google.maps.DirectionsService();
	latlng = new google.maps.LatLng(lat, long);
	
    var myOptions = {
      zoom: 10,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
	directionsDisplay = new google.maps.DirectionsRenderer({draggable:true});
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	directionsDisplay.setMap(map);
	directionsDisplay.setPanel(document.getElementById("directions"));

	
	
	// Try W3C Geolocation (Preferred)
	  if(navigator.geolocation) {
		browserSupportFlag = true;
		navigator.geolocation.getCurrentPosition(function(position) {
		  	userLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
			var latlng2 = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
			geocoder.geocode({'latLng': latlng2, "language": document.getElementById("locale").value }, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
			  if (results[0]) {
					$('#fromAddress').val(results[0].formatted_address);
				//calcRoute();
			  }
			} 
		  });
		});
	 
	  // Browser doesn't support Geolocation
	  } else {
		browserSupportFlag = false;
	  }

	
	marker = new google.maps.Marker({
      position: latlng, 
      map: map, 
      title:hotel_name
  	}); 
	infowindow = new google.maps.InfoWindow({
		content: hotel_name
	});
	google.maps.event.addListener(marker, 'click', function() {
	  infowindow.open(map,marker);
	});
}
function calcRoute() {
  var start = document.getElementById("fromAddress").value;
  var end = document.getElementById("toAddress").value;
  var request = {
    origin:start, 
    destination:end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
	  directionsDisplay.setMap(map);
      directionsDisplay.setDirections(response);
    }
	else{
		directionsDisplay.setMap(null);
		$('#directions').html('');
		marker = new google.maps.Marker({
		  position: latlng, 
		  map: map, 
		  title:hotel_name
		}); 
		map.setCenter(latlng);
		map.setZoom(10);
		infowindow = new google.maps.InfoWindow({
			content: hotel_name
		});
	}
  });
  marker.setMap(null);
}

$(document).ready(function(){
	$("a[rel^='prettyPhoto']").prettyPhoto({
		showTitle: true, /* true/false */
		theme: 'facebook' /* light_rounded / dark_rounded / light_square / dark_square / facebook */
	});
	if((!navigator.userAgent.match(/iPhone/i)) && (!navigator.userAgent.match(/iPod/i))) { 
		$('#destinoid').selectmenu({
			style:'dropdown',
			width: 157
		});
	}
	$("#desplegarListaIdioma").bind("click",function(e){
		e.preventDefault();
		if($("#desplegable_idiomas:hidden").length){
			$("#desplegable_idiomas").slideDown();
			var timeIdioma=setTimeout(" $(\"#desplegable_idiomas\").slideUp()",2000,function(){clearTimeout(timeIdioma);});
			$("#desplegarListaIdioma").mouseout(function(){
				//
			});
			$("#desplegable_idiomas").hover(function(){
				clearTimeout(timeIdioma);
			},function(){
				clearTimeout(timeIdioma);
				$("#desplegable_idiomas").slideUp()
			});
		}
		else{
			$("#desplegable_idiomas").slideUp();
		}
	});
	//Labels interiores del formulario de boletin
	$('#frmSS1 :input[title]').each(function() {
	  var $this = $(this);
	  if($this.val() === '' || $this.val() === $this.attr('title')) {
		$this.val($this.attr('title'));
		$this.css('color','#999');
	  }
	  $this.focus(function() {
		if($this.val() === $this.attr('title')) {
		  $this.val('');
		  $this.css('color','#000');
		}
	  });
	  $this.blur(function() {
		if($this.val() === '') {
		  $this.val($this.attr('title'));
		  $this.css('color','#999');
		}
	  });
	});
	$("form.validar").validationEngine({
		promptPosition: "topRight" // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft,  centerRight, bottomRight 
	});
	
	/*Desplegables FAQS
	$('div.faqs a:not(.no-desplegable)').click(function(event){
		event.preventDefault();
		$(this).parents('li').toggleClass('on');	
		$(this).parents('li').children('ul, p').slideToggle();
	});*/
	//Desplegables Localizacion
	$('ul.como-llegar h4 a, ul.como-llegar a.cerrar').click(function(event){
		event.preventDefault();
		$(this).parents('li').toggleClass('on');	
		$(this).parents('li').children('div.wrapper').slideToggle();
	});
});
function setDates(){
	if(typeof(id)!='undefined'){
		if(id == 73){
			if($('#form_reservar input.hasta').val() == 0){
				$('#form_reservar input.desde').datepicker('option','maxDate',new Date(2010,11,30));
			}
			$('#form_reservar input.hasta').datepicker('option','maxDate',new Date(2010,11,30));
		}
	}
}
function setEndDate(dateText, inst){
	var fecha = dateText.split('/');
	$('input.hasta').datepicker('option','minDate',new Date(fecha[2],fecha[1]-1,fecha[0]));
	$('input.desde').val(dateText);
}
function setStartDate(dateText, inst){
	var fecha = dateText.split('/');
	$('input.desde').datepicker('option','maxDate',new Date(fecha[2],fecha[1]-1,fecha[0]));
	$('input.hasta').val(dateText);
}
$(document).ready(function(){
	$('input.desde').datepicker({dateFormat: 'dd/mm/yy',minDate:0,buttonImage:'/im/common/ico_calendario.jpg',showOn: 'both',buttonImageOnly: true,firstDay:1,onSelect:setEndDate,showAnim: 'fadeIn', beforeShow:setDates});
	$('input.hasta').datepicker({dateFormat: 'dd/mm/yy',minDate:0,buttonImage:'/im/common/ico_calendario.jpg',showOn: 'both',buttonImageOnly: true,firstDay:1,onSelect:setStartDate,showAnim: 'fadeIn', beforeShow:setDates});						   	
	var iFecha;
	var fFecha;
	var iYear;
	var iMonth;
	var iDay;
	var fYear;
	var fMonth;
	var fDay;
	var queryString = location.search.substring(1);
	var querys = queryString.split("&");
	for(i=0;i<querys.length;i++) {
		temp = querys[i].split("=");
		if(temp[0]=="desde"){
			iFecha = temp[1];
		}
		else if(temp[0]=="hasta"){
			fFecha = temp[1];
		}
	}
	if(iFecha && fFecha){
		temp = iFecha.split("%2F");
		iDay = temp[0];
		iMonth = temp[1]-1;
		iYear = temp[2];
		temp = fFecha.split("%2F");
		fDay = temp[0];
		fMonth = temp[1]-1;
		fYear = temp[2];
	}
	if(iFecha && fFecha){
		$('input.desde').datepicker('setDate',new Date(iYear,iMonth,iDay));
		$('input.hasta').datepicker('setDate', new Date(fYear,fMonth,fDay));
	}
});
var v = 2;
var first_run = true;
function bucleCabecera(){
	var carpeta = "/im/headerbucle/";
	var cabecera = jQuery('img.bucle');
	if($(cabecera).length != 0){
		if($('img.afterbucle').length == 0){
			$(cabecera).before('<img src="'+carpeta+v+'_'+ll+'.jpg'+'" class="afterbucle" />');
		}
		else{
			$('img.afterbucle').attr('src',carpeta+v+'_'+ll+".jpg");
		}
		$(cabecera).attr('alt','');
		if(first_run){
			//Esperamos a que cargue la imagen, luego hacemos efecto de desvanecer sustituimos el src y volvemos a mostrar la img original para el bucle
			$('img.afterbucle').load(function() {
				$(cabecera).fadeOut(function(){
					$(cabecera).attr('src',$('img.afterbucle').attr('src')).show();
					clearTimeout(time);
					time = window.setTimeout('bucleCabecera()', 4000);
				});
			});
		}
		else{
			$(cabecera).fadeOut(function(){
				$(cabecera).attr('src',$('img.afterbucle').attr('src')).show();
				clearTimeout(time);
				time = window.setTimeout('bucleCabecera()', 4000);
			});
		}
		
		
		v++;
		if(v>5){
			v=1;
			first_run = false;	
		}
	}
}
//Bucle de la cabecera
$(document).ready(function(){
	//window.setInterval('bucleCabecera()', 4000);
	//time = window.setTimeout('bucleCabecera()', 4000);
	$('ul.bucle').innerfade({
		speed: 'normal',
		timeout: 4000,
		type: 'sequence'
	});
	//Bucle del banner de la home
	$('ul.flash_home').innerfade({
		speed: 'normal',
		timeout: 4000,
		type: 'sequence'
	});
});
function CheckForm1(f) {
var email_re = /[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/i;
if (!email_re.test(f.email.value)) {
	alert("Please enter your email address.");
	f.email.focus();
	return false;
}

	return true;
}
function dni() {
	  var dni = $("#dni").val();
	  numero = dni.substr(0,dni.length-1);
	  let = dni.substr(dni.length-1,1).toUpperCase();
	  numero = numero % 23;
	  letra='TRWAGMYFPDXBNJZSQVHLCKET';
	  letra=letra.substring(numero,numero+1);
	  if (letra!=let) 
		return true;
	  else
		return false;
}
$(document).ready(function(){
	var username='sidorme'; // set user name
	var format='json'; // set format, you really don't have an option on this one
	var url= ('https:' == document.location.protocol ? 'https://' : 'http://') + 'twitter.com/statuses/user_timeline/'+username+'.'+format+'?count=1&callback=?'; // make the url
	$.getJSON(url,function(tweet){ // get the tweets
		var text = tweet[0].text; // get the first tweet in the response
		var regexp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
  		var text = text.replace(regexp,"<a href='$1' target='_blank'>$1</a>"); //Enlaces normales
		var text = text.replace(/(^|\s)@(\w+)/g, "$1<a href='http://twitter.com/$2' target='_blank'>@$2</a>"); //Usuarios de twitter
		var text = text.replace(/(^|\s)#(\w+)/g, "$1<a href='http://twitter.com/search?q=%23$2' target='_blank'>#$2</a>"); //Hashtags de twitter
		$("#last_tweet #tweet_text").html(text); // place the text inside the div
	});
});
