/**
 * index.js : Recabar información de usuario (geolocalización huerto, ubicación exterior 
 * 			  o interior y nivel de experiencia)
 */
$(document).ready(function(){ 

//	Inicializamos el histórico de páginas
	var historia = new Array("#location-page");
//	Buttons
	var back = document.querySelector("#back-button");
	var no_current_location = document.querySelector("#no-current-location");
	var current_location = document.querySelector("#current-location");
	var OKLocation = document.querySelector("#OK-location");
	var btn_info = document.querySelector("#info-button");

	var ContinuarLocation = document.querySelector("#continuar-location");
	ContinuarLocation.disabled = true;

	var ContinuarIntExt = document.querySelector("#continuar-int-ext");
	var FinalizarConf = document.querySelector("#finalizar");

	var ratio = window.devicePixelRatio || 1;
	var device_width = screen.width * ratio;




	//Header btn
	if (btn_info){
		btn_info.addEventListener("click", function(){
			window.open("info.html", "info");
		});
	}
	//Current-location btn
	if (current_location){
		current_location.onclick = function(){
			$("#location-page").hide();
			$("#int-ext").show();
			$("#back-button").show();
			historia.push("#int-ext");

			$("label.choice1").click(function(){
				document.querySelector("#radio-choice-1").checked=true;
			});
			$("label.choice2").click(function(){
				document.querySelector("#radio-choice-2").checked=true;
			});
		}
	}





	//Valores por defecto de las variables locales de almacenamiento
	function ValoresDefault(){  
		localStorage.setItem("latlon", "40.42,-3.6888");  //Por defecto, situados en Madrid
		localStorage.setItem("altitud","655"); //Madrid
		localStorage.setItem("alarma", "0");
		localStorage.setItem("estado", "cultivos"); //guarda el estado (content.js)
		localStorage.setItem("influencia_luna", "no");
	}


	//Función de Geolocalización
	function Geolocation(){
		var addressDisplay = document.querySelector("#address-display");
		if (addressDisplay){

			navigator.geolocation.getCurrentPosition(function (position) {  

				var latlon = position.coords.latitude+","+position.coords.longitude;
				var altitude = position.coords.altitude;
				localStorage.setItem("latlon", latlon);
				localStorage.setItem("altitud", altitude);

				//Show address
				var xhr_address = new XMLHttpRequest();
				xhr_address.open("GET","http://maps.googleapis.com/maps/api/geocode/json?latlng="+latlon+"&sensor=true", true);
				xhr_address.overrideMimeType('text/plain; charset=utf-8');
				xhr_address.send(null); 
				xhr_address.onreadystatechange= function () {
					if (xhr_address.status == 200 && xhr_address.readyState == 4) {
						var obj = JSON.parse(xhr_address.responseText);
						addressDisplay.innerHTML = obj.results[0].formatted_address;
					}
				};
			},
			function (position) {
				geoDisplay.innerHTML = "Failed to get your current location";
				geoDisplay.style.display = "block";
			}, {enableHighAccuracy:true, maximumAge: 0, timeout: 57000});
		}	
	}


	// Lista para #no-location (li)
	function CrearListaAddress(address, enganche_ul){
		var new_li = document.createElement("li");
		var new_a = document.createElement("a");
		new_a.setAttribute("href", "#");
		new_li.appendChild(new_a);
		var new_p = document.createElement("p");
		new_p.appendChild(document.createTextNode(address.formatted_address));
		new_p.setAttribute("class", "new_list_address");
		new_p.setAttribute("title", address.geometry.location.lat+","+address.geometry.location.lng);
		new_a.appendChild(new_p);

		enganche_ul.appendChild(new_li);

		new_a.addEventListener("click",  function (){
			localStorage.setItem("latlon", new_a.firstChild.title);
			ContinuarLocation.disabled=false;
		});
	}

	//Lista para #no-location (ul)
	function EligeAddress(JSONobj, write){
		var i;
		var new_section = document.createElement("section");
		new_section.setAttribute("data-type", "list");
		new_section.setAttribute("class", "list-section");
		write.appendChild(new_section);
		//hijo header
		var new_header = document.createElement("header");
		var new_p =document.createElement("p");
		new_p.appendChild(document.createTextNode("Seleccione su dirección"));
		new_p.setAttribute("class", "new_header_address");
		new_header.appendChild(new_p);
		new_section.appendChild(new_header);
		//hijo ul
		var new_ul = document.createElement("ul");
		new_section.appendChild(new_ul);
		for (i=0; i<JSONobj.results.length; i++){
			CrearListaAddress(JSONobj.results[i], new_ul);
		}
	}




	if (localStorage){

		ValoresDefault();
		Geolocation();

		if (no_current_location){
			no_current_location.addEventListener("click", function(){
				$("#location-page").hide();
				$("#no-location").show();
				$("#back-button").show();
				historia.push("#no-location");

				if (OKLocation){
					OKLocation.onclick = function() {
						var address = document.querySelector("#address").value;

						var latlon;
						var bool_elev = 0; 
						var errorLocation = document.querySelector("#error-location");
						var xhr = new XMLHttpRequest();
						xhr.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?address="
								+address+ "&sensor=true");						
						xhr.overrideMimeType('text/plain; charset=utf-8'); 
						xhr.onreadystatechange= function () {
							if (xhr.status == 200 && xhr.readyState == 4) {
								var obj = JSON.parse(xhr.responseText);
								if (obj.status == "OK"){
									//Para al escribir dos veces distinta address, se sobreescriba
									var lista_address = document.querySelector("#lista-address");
									var new_lista = document.createElement("div");
									new_lista.setAttribute("class", "class-lista_address");
									lista_address.appendChild(new_lista);
									EligeAddress(obj, new_lista);
								}
								else if (obj.status =="ZERO_RESULTS")
									errorLocation.innerHTML = "La dirección no es válida";
								else if (obj.status =="OVER_QUERY_LIMIT")
									errorLocation.innerHTML = "Se ha sobrepasado el límite de consultas. Inténtelo de nueva más tarde.";
								else if (obj.status == "REQUEST DENIED")
									errorLocation.innerHTML = "REQUEST_DENIED";
								else if (obj.status == "INVALID_REQUEST")
									errorLocation.innerHTML = "INVALID_REQUEST";
								else if (obj.status == "UNKNOW_ERROR")
									errorLocation.innerHTML = "Error desconocido. Inténtelo de nuevo más tarde";
							}

						};
						xhr.send(null);

						if(ContinuarLocation){
							ContinuarLocation.onclick = function(){
								$("#no-location").hide();
								$("#int-ext").show();
								historia.push("#int-ext");
							}
						}
					}
				}
			});
		}


		if (ContinuarIntExt){
			ContinuarIntExt.onclick = function() {
				localStorage.setItem("intext", $("input:radio[name=radio-choice]:checked").val());

				$("#int-ext").hide();
				$("#experiencia").show();
				historia.push("#experiencia");

				$("label.choice1").click(function(){
					document.querySelector("#radio-exp-1").checked=true;
				});
				$("label.choice2").click(function(){
					document.querySelector("#radio-exp-2").checked=true;
				});
			}
		}


		if (FinalizarConf){
			FinalizarConf.onclick = function() {
				localStorage.setItem("experiencia", $("input:radio[name=experiencia]:checked").val());
				window.location.assign("content.html");
			}
		}

		if (back){
			back.onclick = function() {

				var current_history = historia.pop().toString();
				$(current_history).hide();

				var previous_history = historia.slice(historia.length-1).toString();
				$(previous_history).show();

				if (historia.length == 1)
					$("#back-button").hide();
			}
		}


	}//if localStorage está soportado
	else 
		alert("localStorage no es soportado"); 
});

