$(document).ready(function() {	
	// Get hermesite tweets
	$(".tweethermesite").tweet({
		username: "sanfollower",
		join_text: "auto",
		avatar_size: false,
		count: 1,
		auto_join_text_default: ": ",
		auto_join_text_ed: "we",
		auto_join_text_ing: "we were",
		auto_join_text_reply: "we replied to",
		auto_join_text_url: "we were checking out",
		loading_text: "loading tweets..."
	});
	
	//	Contact
	$("#mensaje").hide();
	$("#frmContact").validate({
		event: "blur",rules: {'nombre': "required",'email': "required email",'consulta': "required"},
		messages: {'nombre': "Falta tu nombre",'email': "Escribe una direcci&oacute;n de e-mail v&aacute;lida",'consulta': "Escribe algo"},
		debug: true,errorElement: "label",
		submitHandler: function(form){
			$("#mensaje").show();
			$("#mensaje").html("<img src='ajax-loader.gif' style='vertical-align:middle;margin:0 10px 0 0' /><strong>Enviando mensaje...</strong>");
			$.ajax({
				type: "POST",
				url:"envio.php",
				contentType: "application/x-www-form-urlencoded",
				processData: true,
				data: "nombre="+escape($('#ContactName').val())+"&email="+escape($('#ContactRecipient').val())+"&mensaje="+escape($('#ContactMessage').val()),
				success: function(msg){
					$("#mensaje").html("Mensaje enviado");
					document.getElementById("ContactName").value="";
					document.getElementById("ContactRecipient").value="";
					document.getElementById("ContactMessage").value="";
					setTimeout(function() {$('#mensaje').fadeOut('fast');}, 3000);

				}
			});
		}
	});
	//whereAreYou();
	$('#sniff').append(BrowserDetect.browser +""+ BrowserDetect.version);
	$('#sniff2').append(BrowserDetect.OS);
	$('#window').append(window.innerWidth +"x"+ window.innerHeight);
});
function whereAreYou() {
	if (navigator.geolocation) {
	    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
	}
    else {
	    alert('Tu navegador no soporta la geolocalizacion.');
	}
		
	function successFunction(position) {
		var lat = position.coords.latitude;
		var lon = position.coords.longitude;
		$("#geolocation").append('latitud : '+lat+' longitud : '+lon+'</p');		
	}
	
	function errorFunction(position) {
		$("#geolocation").append('<span class="error">No se ha podido recuperar la geolocalizacion.</span>');
	}	
}

window.onload = function() {
  var startPos;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      startPos = position;
      document.getElementById("startLat").innerHTML = startPos.coords.latitude;
      document.getElementById("startLon").innerHTML = startPos.coords.longitude;
    }, function(error) {
      alert("Error occurred. Error code: " + error.code);
      // error.code can be:
      //   0: unknown error
      //   1: permission denied
      //   2: position unavailable (error response from locaton provider)
      //   3: timed out
    });

    navigator.geolocation.watchPosition(function(position) {
      document.getElementById("currentLat").innerHTML = position.coords.latitude;
      document.getElementById("currentLon").innerHTML = position.coords.longitude;
      document.getElementById("distance").innerHTML =
        //calculateDistance(startPos.coords.latitude, startPos.coords.longitude,
        (calculateDistance(41.3738623, 2.1324822, position.coords.latitude, position.coords.longitude)).toFixed(0);
    });
  }
};

// Reused code - copyright Moveable Type Scripts - retrieved May 4, 2010.
// http://www.movable-type.co.uk/scripts/latlong.html
// Under Creative Commons License http://creativecommons.org/licenses/by/3.0/
function calculateDistance(lat1, lon1, lat2, lon2) {
  var R = 6371; // km
  var dLat = (lat2-lat1).toRad();
  var dLon = (lon2-lon1).toRad();
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
          Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
          Math.sin(dLon/2) * Math.sin(dLon/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;
  return d;
}
Number.prototype.toRad = function() {
  return this * Math.PI / 180;
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera",
			versionSearch: "Version"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
