/**
 * @preserve CLIMATE: Weather Application Designed for FirefoxOS
 *
 * @version 2.2.0
 * @copyright Lasyk Networks, Inc. [All Rights Reserved]
 * @dev-team Kirk T Fourniadis - Billy T Fourniadis
 */
var os = "fxos"; // fxos - ios - web
var version = "2.2"; // application version
var appname = "climate";
var locations = {
	index: localStorage.getItem(appname+".locations:index")
};
var ipLookupFailed = 0;
var settings = {
	metric: localStorage.getItem(appname+".settings.metric"),
	cuid: localStorage.getItem(appname+".settings.uuid")
};
var clocation = {
	latitude: localStorage.getItem(appname+".local.latitude"),
	longitude: localStorage.getItem(appname+".local.longitude"),
	city: localStorage.getItem(appname+".local.city"),
	ip: localStorage.getItem(appname+".local.ip")
};
var guid = (function() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
  }
  return function() {
    return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
  };
})();

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

var glblslide = 0;
var mySwiper;

function initWeatherApp(){
	init_FastClick();
	displayDate(glblslide);
	loadUnits();
	
	mySwiper = new Swiper('.swiper-container',{ 
	  	slidesPerView:1,
	    loop:false,
	    pagination: '.pagination',
	    paginationClickable: true,
	    onSlideChangeEnd: function (swiper) {
			console.log("ACTIVE SLIDE: "+swiper.activeIndex);	
			glblslide = swiper.activeIndex;	
			displayDate(glblslide);	  
			if (swiper.activeIndex == 0){ // index 0 is current loc
				
				entry = JSON.parse(localStorage.getItem(appname+".locations:"+(swiper.activeIndex)));
				glblslide = swiper.activeIndex;
				var timestamp = new Date(entry.tempTimestamp);
				var mins = 10; // threshhold for weather update
				var ms = mins*60*1000; // convert to milliseconds
				var diff = getMinutesDiff(timestamp);
				
				if (isNaN(diff))
					diff = ms+1;
				
				if (diff>ms){
					//console.log("GET NEW LOC");
					getCurrentLocation();
					ga('send', 'pageview', {'page': appname+'/'+version+'/'+os+'/local.refetch'});
				} else{
					getWeatherSlide(swiper.activeIndex);
				}
				// check if x amount of time has passed before last check
				//getCurrentLocation();
				// else
				//getWeather(swiper.activeIndex);
			} else{ // get weather for specific index
				getWeather(swiper.activeIndex);
			}
		}
	});
	
	loadLocations();
	getCurrentLocation();
	ga('send', 'pageview', {'page': appname+'/'+version+'/'+os+'/local.launch'});
}

function init_FastClick(){
    window.addEventListener('load', function() {
    	FastClick.attach(document.body);
    }, false);
}


function jumpToWeatherSlide(slide){
	glblslide = slide;
	toggleTransition('#settingspage', '#mainpage', 52, 0);
	displayDate(glblslide);
	getWeather(glblslide);
	mySwiper.swipeTo(glblslide, 0, false);
}


function loadLocations(){
	
	if (!locations.index) { // INIT
		localStorage.setItem(appname+".locations:index", 0);
	} else { // we have data
		var lid = parseInt(localStorage.getItem(appname+".locations:index"));
		
		//console.log("Size: " + localStorage.length);
		//console.log("Index Size: " + lid + " items");
		
		var output = "";
		// show new slides too
		$( "#currentloc" ).after("");
		
		for (var i = 0; i < lid; i++){
			
				var cid = i+1;
				
				if (localStorage.getItem(appname+".locations:"+(cid))  === null){
					// Skip empty data
				} else{
						entry = JSON.parse(localStorage.getItem(appname+".locations:"+(cid)));
						
						output += "<li><a onclick=\"jumpToWeatherSlide("+entry.id+")\"><div class=\"left\"><h2>" + entry.area + "</h2><p>" + entry.state + ", " + entry.country + " <!--<span class=\"micro\">( lat.: " + entry.lat + " lon.: " + entry.lon + " )</span>--></p></div></a><div class=\"right\"><a class=\"actionicon remove\" href=\"#\" onclick=\"removeEntry('"+entry.id+"')\"><img src=\"img/icons.png\"></a></div></li>";
						
						var slide = '<div class="page"><div class="weather"><div class="header"><div class="navileft datestamp" id="ds'+cid+'"></div><strong><div class="locstamp" id="loc'+cid+'">loading...</div></strong></div><div class=""><div class="daycast"><div class="temp"><div class="reading" id="temp'+cid+'">-</div><div class="degree">&#176;</div></div><div class="daysum"><div class="weathericon" id="ic'+cid+'"></div><div class="todayinfo"><div class="temprange"><div class="high" id="rdh'+cid+'"></div><div class="low" id="rdl'+cid+'"></div></div><div class="daystamp" id="ts'+cid+'"></div><div class="today">&nbsp;Today</div></div></div></div><div class="forecast"><ul><li><div class="innerheader"><div class="nday" id="d'+cid+'-1">-</div><div class="tomorrow">&nbsp;Tomorrow</div><div class="itemps"><div class="high" ><span id="ih'+cid+'-1">-</span>&#176;</div><div class="low" ><span id="il'+cid+'-1">-</span>&#176;</div><div class="weatherminiicon" id="ic'+cid+'-1"></div></div></div></li><li><div class="innerheader"><div class="nday" id="d'+cid+'-2">-</div><div class="itemps"><div class="high" ><span id="ih'+cid+'-2">-</span>&#176;</div><div class="low" ><span id="il'+cid+'-2">-</span>&#176;</div><div class="weatherminiicon" id="ic'+cid+'-2"></div></div></div></li><li><div class="innerheader"><div class="nday" id="d'+cid+'-3">-</div><div class="itemps"><div class="high" ><span id="ih'+cid+'-3">-</span>&#176;</div><div class="low" ><span id="il'+cid+'-3">-</span>&#176;</div><div class="weatherminiicon" id="ic'+cid+'-3"></div></div></div></li><li class="last"><div class="innerheader"><div class="nday" id="d'+cid+'-4">-</div><div class="itemps"><div class="high" ><span id="ih'+cid+'-4">-</span>&#176;</div><div class="low" ><span id="il'+cid+'-4">-</span>&#176;</div><div class="weatherminiicon" id="ic'+cid+'-4"></div></div></div></li></ul><div class="details"><div class="left" id="ml'+cid+'"></div><div class="right" id="mr'+cid+'"></div><div class="clearboth"></div></div></div> <!-- end forecast --><div class="footercast"></div></div> <!-- empty --></div> <!-- weather --></div> <!-- page -->';
						
						//console.log("Appending slide: " + mySwiper.slides.length + " vs " + cid);
						if (mySwiper.slides.length == cid){
							if (screen.colorDepth > 16) // KEON == 16 so we want more colors to show gradient
								mySwiper.appendSlide(slide, 'swiper-slide '+randomColor()+'-slide night');
							else
								mySwiper.appendSlide(slide, 'swiper-slide '+randomColor()+'-slide');
						}
					
				}
				// here we can check the time of day and show the background accordingly with a gradient according to the timezone
		}
		
		$('#location-list').html(output);
		//mySwiper.reInit();
	}
}
		
function randomColor() {
    var colors = ('blue red green orange pink').split(' ');
    return colors[ Math.floor( Math.random()*colors.length ) ]
}
		
function saveEntry(index, city, state, country, lat, lon, tempTimestamp, weather){
	// weather is an object which stores all the weather data
	var new_index = 1;
	
	if ((index != null) && (parseInt(index) == 0)){ // force index
		new_index = 0; 
	} else if (parseInt(index) > 0){
		new_index = parseInt(index);
	} else{
		new_index = parseInt(localStorage.getItem(appname+".locations:index")) + 1;
		locations.index = new_index;
		localStorage.setItem(appname+".locations:index", new_index);
	}
	
	var entry = {
		id: new_index,
		area: city,
		state: state,
		country: country,
		lat: lat,
		lon: lon,
		tempTimestamp: tempTimestamp,
		localWeather: weather
	};
	
	localStorage.setItem(appname+".locations:"+ entry.id, JSON.stringify(entry));
	//console.log('Climate App is saving ' + entry.area + '...');
	loadLocations();
	//toggleTransition('#searchpage', '#settingspage', 52, 0);
}

function reIndex(){
	var x = 0;
	var adjust_index = 0;
	var lid = parseInt(localStorage.getItem(appname+".locations:index"));
	// using an array would be more efficient, but not needed now
	console.log("Re-Indexing...");
	
	if (lid == 0){
		localStorage.setItem(appname+".locations:index",0);
	} else{
		for (var i = 0; i < lid; i++){
			x++;
			adjust_index++;
			if (localStorage.getItem(appname+".locations:"+(x)) === null){ // skip null entry
				adjust_index--;
				localStorage.removeItem(appname+".locations:"+ x);
				localStorage.setItem(appname+".locations:index", adjust_index);
			} else{
				//console.log('WeatherZila App is setting ' + x + '...');
				var entry = JSON.parse(localStorage.getItem(appname+".locations:"+(x)));
				entry.id = adjust_index;
				localStorage.setItem(appname+".locations:"+ adjust_index, JSON.stringify(entry));
				localStorage.setItem(appname+".locations:index", adjust_index);
			}
		}
		
		if (adjust_index<x) // forcefully remove last item if we have reIndexed after delete
			localStorage.removeItem(appname+".locations:"+ x);
	}
}

function removeEntry(id){
	// remove results in having one more location, nevertheless we do not reach it because of the index being lower
	console.log('Climate is removing ' + id + '...');
	localStorage.removeItem(appname+".locations:"+ id);
	reIndex();
	mySwiper.swipeTo(0, 0, false);
	mySwiper.removeSlide(id);
	loadLocations();
}

function loadUnits(){
	settings.metric = parseInt(localStorage.getItem(appname+".settings.metric"));
	if (settings.metric == 0){ // Show Imperial
		//imperial
		//°F (selected)
		$('#units').html("<div class=\"btnSettings selected\">°F</div><a class=\"\" onclick=\"setUnits(1)\"><div class=\"btnSettings\">°C</div></a>");
	} else{ // Show Metric
		//metric
		//°C (selected)
		$('#units').html("<a class=\"\" onclick=\"setUnits(0)\"><div class=\"btnSettings\">°F</div></a><div class=\"btnSettings selected\">°C</div>");
		settings.metric = 1;
	}
}

function setUnits(metric){
	if (!settings.metric) { // INIT
		localStorage.setItem(appname+".settings.metric", metric);
	} else{
		localStorage.setItem(appname+".settings.metric", metric);
	}
	
	settings.metric = metric;
	if (metric == 0){ // Show Imperial
		//imperial
		//°F (selected)
		$('#units').html("<div class=\"btnSettings selected\">°F</div><a class=\"\" onclick=\"setUnits(1)\"><div class=\"btnSettings\">°C</div></a>");
	} else{ // Show Metric
		//metric
		//°C (selected)
		$('#units').html("<a class=\"\" onclick=\"setUnits(0)\"><div class=\"btnSettings\">°F</div></a><div class=\"btnSettings selected\">°C</div>");
		settings.metric = 1;
	}
	getWeatherSlide(glblslide);
}

function displayDate(slide){
	var d = new Date();
	var weekday = new Array(7);
	weekday[0]=  '<span data-l10n-id="sunday">Sunday</span>';
	weekday[1] = '<span data-l10n-id="monday">Monday</span>';
	weekday[2] = '<span data-l10n-id="tuesday">Tuesday</span>';
	weekday[3] = '<span data-l10n-id="wednesday">Wednesday</span>';
	weekday[4] = '<span data-l10n-id="thursday">Thursday</span>';
	weekday[5] = '<span data-l10n-id="friday">Friday</span>';
	weekday[6] = '<span data-l10n-id="saturday">Saturday</span>';
	
	var month = new Array();
	month[0] = '<span data-l10n-id="january">January</span>';
	month[1] = '<span data-l10n-id="february">February</span>';
	month[2] = '<span data-l10n-id="march">March</span>';
	month[3] = '<span data-l10n-id="april">April</span>';
	month[4] = '<span data-l10n-id="may">May</span>';
	month[5] = '<span data-l10n-id="june">June</span>';
	month[6] = '<span data-l10n-id="july">July</span>';
	month[7] = '<span data-l10n-id="august">August</span>';
	month[8] = '<span data-l10n-id="september">September</span>';
	month[9] = '<span data-l10n-id="october">October</span>';
	month[10] = '<span data-l10n-id="november">November</span>';
	month[11] = '<span data-l10n-id="december">December</span>';
	var m = month[d.getMonth()];
	
	var strd = m + " " + d.getDate(); //+ ", " + d.getFullYear();
	
	$('#ds'+slide).html(strd);
	$('#ts'+slide).html(weekday[d.getDay()]);
	
	d.setDate(d.getDate()+1);
	$('#d'+slide+'-1').html(weekday[d.getDay()]);
	//$('#d1-1').text("Tomorrow");
	d.setDate(d.getDate()+1);
	$('#d'+slide+'-2').html(weekday[d.getDay()]);
	d.setDate(d.getDate()+1);
	$('#d'+slide+'-3').html(weekday[d.getDay()]);
	d.setDate(d.getDate()+1);
	$('#d'+slide+'-4').html(weekday[d.getDay()]);
	
	//navigator.mozL10n.localize(myElement, 'label3'{ arg: "myarg" });
}

function day_name(a) {
    return new Date(day[a].date).getDayName()
}

function getCurrentLocation() {// COORDINATES first IP second
    navigator.geolocation.getCurrentPosition(getGeoLocation, getGeoLocationError, options);
}

function getGeoLocation(a) {// GEOLOCATED
	
	// we need to get the city name	
	
	if ((a.coords.latitude == clocation.latitude) && (a.coords.longitude == clocation.longitude)){
		
	}
	
	clocation.latitude = a.coords.latitude;
	clocation.longitude = a.coords.longitude;
	clocation.city = "";
	clocation.ip = a.ip;
	
	localStorage.setItem(appname+".local", JSON.stringify(clocation));
	
	console.log("Coordinates detected: lat(" + clocation.latitude + ") lon(" + clocation.longitude + ")");
	
	GetLocalWeather(clocation.latitude + "," + clocation.longitude);
}
function getGeoLocationError() {
	// If IP fails we get location from IP
	getIpLocation("http://api.hostip.info/get_json.php");
}

function getIpLocation(a) {
    $.ajax({
        type: "get",
        dataType: "json",
        url: a,
        success: function (a) {
            loc = clocation.ip = a.ip, GetLocalWeather(loc)
            if ((a.city != "(Unknown city)") || (a.city != "(Unknown City?)"))
            	$('#loc0').text(a.city);
        },
        error: function (e) {
            // this can lead to the hang we experienced so
            //ipLookupFailed || (ipLookupFailed = !0, getIpLocation("http://jsonip.appspot.com/"))
            // log the error and do the following
            console.log("Loc Error: " + e.message);
            $( "#preloader" ).removeClass( "show");
			jQuery('#loadaction').unload("img/loading-bubbles.svg", null, function(){});
        }
    })
}

//api.worldweatheronline.com
var _ApiBaseURL = 'http://weather.lasyk.net/free/v2/';
var _ApiKey = 'aedc2c270736bec24d80863dd6e95';
	
//------------ LOCAL WEATHER ----------------	
function JSONP_LocalWeather(input) {
    var url = _ApiBaseURL + 'weather.ashx?q=' + input.query + '&format=' + input.format + '&extra=' + input.extra + '&num_of_days=' + input.num_of_days + '&date=' + input.date + '&fx=' + input.fx + '&cc=' + input.cc + '&includelocation=' + input.includelocation + '&show_comments=' + input.show_comments + '&key=' + _ApiKey;
    jsonP(url, input.callback);
}
// Helper Method
function jsonP(url, callback) {
    $.ajax({
        type: 'GET',
        url: url,
        async: false,
        contentType: "application/json",
        jsonpCallback: callback,
        dataType: 'jsonp',
        success: function (json) {
            //console.log('success');
            $( "#preloader" ).removeClass( "show");
			jQuery('#loadaction').unload("img/loading-bubbles.svg", null, function(){});
        },
        error: function (e) {
            console.log("API Error: " + e.message);
            $( "#preloader" ).removeClass( "show");
			jQuery('#loadaction').unload("img/loading-bubbles.svg", null, function(){});
            
        }
    });
}
	
function getWeather(index){
	//GetLocalWeather(loc);
	entry = JSON.parse(localStorage.getItem(appname+".locations:"+(index)));
	if (entry.area != "(Unknown city)");
		$('#loc'+glblslide).text(entry.area);
		
	glblslide = index;
	// HERE WE SHOULD CHECK IF WE SHOULD FETCH JSON OR LOCAL STORAGE
	
	var timestamp = new Date(entry.tempTimestamp);
	var mins = 120; // threshhold for weather update
	var ms = mins*60*1000; // convert to milliseconds
	var diff = getMinutesDiff(timestamp);
	
	if (isNaN(diff))
		diff = ms+1;
	
	if (diff>ms){
		console.log("Data is old (" + diff + ")");
		GetLocalWeather(entry.lat+","+entry.lon);
		
		if (parseInt(entry.id) > 0)
			ga('send', 'pageview', {'page': appname+'/'+version+'/'+os+'/'+entry.id+'/'+entry.country+','+entry.state+','+entry.area});
		else
			ga('send', 'pageview', {'page': appname+'/'+version+'/'+os+'/local.fetch'});
	} else{
		console.log("Data is fresh fetched " + diff + " ms ago");
		//console.log(timestamp.toString());
		getWeatherSlide(index);
	}
}
	
function getMinutesDiff(date){
	var now = new Date();
	var diffMs = (now - date); // milliseconds between now & date
	
	return diffMs;
	/*
	var diffDays = Math.round(diffMs / 86400000); // days
	var diffHrs = Math.round((diffMs % 86400000) / 3600000); // hours
	var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
	return diffMins;
	*/
}
	
function timeSince(date) {
    var seconds = Math.floor((new Date() - date) / 1000);
    var interval = Math.floor(seconds / 31536000);
    if (interval > 1) {
        return interval + " years";
    }
    interval = Math.floor(seconds / 2592000);
    if (interval > 1) {
        return interval + " months";
    }
    interval = Math.floor(seconds / 86400);
    if (interval > 1) {
        return interval + " days";
    }
    interval = Math.floor(seconds / 3600);
    if (interval > 1) {
        return interval + " hours";
    }
    interval = Math.floor(seconds / 60);
    if (interval > 1) {
        return interval + " minutes";
    }
    return Math.floor(seconds) + " seconds";
}
	
function GetLocalWeather(loc) {
	
	// show SVG animation improves lag when you load and unload
	//console.log("Fetching for: " + loc);
	// show loader
	$( "#preloader" ).addClass( "show");
	jQuery('#loadaction').load("img/loading-bubbles.svg", null, function(){});
	
    var slideWeatherInput = {
        query: loc,
        format: 'JSON',
        num_of_days: '5',
        date: '',
        fx: '',
        cc: '',
        includelocation: '',
        show_comments: '',
        callback: 'weatherCallback'
    };
	JSONP_LocalWeather(slideWeatherInput);
	 
	 // HANDLE A FALLBACK IF JSON REQ HANGS
}

function weatherCallback(slideWeather) {
	var slide = glblslide;
	var utcDate = new Date();
	
	if (parseInt(slide)>0){
    	var entry = JSON.parse(localStorage.getItem(appname+".locations:"+(slide)));
		console.log(entry.tempTimestamp);
		entry.tempTimestamp = utcDate.toString();
		saveEntry(entry.id, entry.area, entry.state, entry.country, entry.lat, entry.lon, entry.tempTimestamp, JSON.stringify(slideWeather));
	} else { // slide is 0 = current location
		// if we already have data dont empty it out!
		// else
		saveEntry(0, '', '', '', '', '', utcDate.toString(), JSON.stringify(slideWeather));
	}
	//console.log("Loading Weather Slide: " + slide);
	getWeatherSlide(slide);
}
	
function getWeatherSlide(slide){
	
	var entry = JSON.parse(localStorage.getItem(appname+".locations:"+(slide)));
	if (entry.localWeather != ""){
		var weather = JSON.parse(entry.localWeather);
		
		var humidity =  weather.data.current_condition[0].humidity;
		var precipitation = weather.data.current_condition[0].precipMM;
		var pressure = weather.data.current_condition[0].pressure;
		var visibility = weather.data.current_condition[0].visibility;
		var cloudcover = weather.data.current_condition[0].cloudcover;
		var windspeedKmph = weather.data.current_condition[0].windspeedKmph;
		
		if (settings.metric == 1){
			precipitation = weather.data.current_condition[0].precipMM + " cm";
			pressure = numberWithCommas(pressure) + " mb";
			visibility = visibility + " km";
			windspeedKmph = windspeedKmph + " km/h";
			
		} else{
			precipitation = toInches(weather.data.current_condition[0].precipMM) + " in";
			pressure = toInchesOfMercury(pressure) + " in";
			visibility = toMiles(visibility) + " mi";
			windspeedKmph = toMiles(windspeedKmph) + " mi/h";
		}
		
		
		var d = new Date(new Date().toUTCString()),
		    s = weather.data.current_condition[0].observation_time,
		    parts = s.match(/(\d+)\:(\d+) (\w+)/),
		    hours = /am/i.test(parts[3]) ? parseInt(parts[1], 10) : parseInt(parts[1], 10) + 12,
		    minutes = parseInt(parts[2], 10);
		
		d.setUTCHours(hours);
		d.setUTCMinutes(minutes);
		
		var loutput = '<span data-l10n-id="observed">Observed</span>: ' + formatAMPM(d);
		loutput += '<br/><span data-l10n-id="humidity">Humidity</span>: ' + humidity + '%';
		loutput += '<br/><span data-l10n-id="precipitation">Precipitation</span>: ' + precipitation;
		loutput += '<br/><span data-l10n-id="pressure">Pressure</span>: ' + pressure;
		
		var routput = '<span data-l10n-id="visibility">Visibility</span>: ' + visibility;
		routput += '<br/><span data-l10n-id="cloud-cover">Cloud Cover</span>: ' + cloudcover + '%';
		routput += '<br/><span data-l10n-id="wind">Wind</span>: <span class="nsew">' + weather.data.current_condition[0].winddir16Point + '</span> ' + windspeedKmph;
		
		rotation = weather.data.current_condition[0].winddirDegree;
		routput += '<br/><span data-l10n-id="wind-direction">Wind Direction</span>: <img src="img/arrow-up.svg" id="wdirection'+slide+'" class="wdirection"> ' + rotation + '&#176;';
		
		$('#ml'+slide).html(loutput);
		$('#mr'+slide).html(routput);
		
		// refresh localization
		document.webL10n.setLanguage(document.webL10n.getLanguage());
		
		//document.webL10n.setLanguage("es");
		
		$('#wdirection'+slide).css('-moz-transform', 'rotate(' + rotation + 'deg)');
		//$('#wdirection.'+slide).css('-webkit-transform', 'rotate(' + rotation + 'deg)');
		
		var UTC = weather.data.current_condition[0].observation_time;
		UTC = UTC.slice(0,5);
		var date = new Date();
		date.setDate(date.getFullYear()+"-"+date.getMonth()+"-"+date.getDay()+" "+UTC+":00 UTC");
		
		// TIME IN UTC convert to local
		if (settings.metric == 1){
			$('#temp'+slide).text(weather.data.current_condition[0].temp_C);
		} else{
			$('#temp'+slide).text(weather.data.current_condition[0].temp_F);	
		}
		// Set the icon here...
		jQuery('#ic'+slide).load("img/weather/"+getWeatherIcon(weather.data.current_condition[0].weatherCode), null, function(){});
		//$('#ic1').html("<img src=\"img/weather/"+getWeatherIcon(localWeather.data.current_condition[0].weatherCode)+"\" class=\"icnweather\"/>");
		
		console.log("Temp + 1 - " + weather.data.weather[1].maxtempC);
		
		
		// TODAY HIGH/LOW is index 0 i.e. weather.data.weather[0]
		// we need to show this also
		
		if (settings.metric == 1){
			$('#rdh'+slide).html(weather.data.weather[0].maxtempC + "&#176;");
			$('#ih'+slide+'-1').text(weather.data.weather[1].maxtempC);
			$('#ih'+slide+'-2').text(weather.data.weather[2].maxtempC);
			$('#ih'+slide+'-3').text(weather.data.weather[3].maxtempC);
			$('#ih'+slide+'-4').text(weather.data.weather[4].maxtempC);
			
			$('#rdl'+slide).html(weather.data.weather[0].mintempC + "&#176;");
			$('#il'+slide+'-1').text(weather.data.weather[1].mintempC);
			$('#il'+slide+'-2').text(weather.data.weather[2].mintempC);
			$('#il'+slide+'-3').text(weather.data.weather[3].mintempC);
			$('#il'+slide+'-4').text(weather.data.weather[4].mintempC);
		} else {
			$('#rdh'+slide).html(weather.data.weather[0].maxtempF + "&#176;");
			$('#ih'+slide+'-1').text(weather.data.weather[1].maxtempF);
			$('#ih'+slide+'-2').text(weather.data.weather[2].maxtempF);
			$('#ih'+slide+'-3').text(weather.data.weather[3].maxtempF);
			$('#ih'+slide+'-4').text(weather.data.weather[4].maxtempF);
			
			$('#rdl'+slide).html(weather.data.weather[0].mintempF + "&#176;");
			$('#il'+slide+'-1').text(weather.data.weather[1].mintempF);
			$('#il'+slide+'-2').text(weather.data.weather[2].mintempF);
			$('#il'+slide+'-3').text(weather.data.weather[3].mintempF);
			$('#il'+slide+'-4').text(weather.data.weather[4].mintempF);
		}
		
		jQuery('#ic'+slide+'-1').load("img/weather/"+getWeatherIcon(weather.data.weather[1].hourly[3].weatherCode), null, function(){});
		jQuery('#ic'+slide+'-2').load("img/weather/"+getWeatherIcon(weather.data.weather[2].hourly[3].weatherCode), null, function(){});
		jQuery('#ic'+slide+'-3').load("img/weather/"+getWeatherIcon(weather.data.weather[3].hourly[3].weatherCode), null, function(){});
		jQuery('#ic'+slide+'-4').load("img/weather/"+getWeatherIcon(weather.data.weather[4].hourly[3].weatherCode), null, function(){});
		/*
		console.log("WCode: " + weather.data.weather[1].hourly[3].weatherCode);
		console.log("WCode: " + weather.data.weather[2].hourly[3].weatherCode);
		console.log("WCode: " + weather.data.weather[3].hourly[3].weatherCode);
		console.log("WCode: " + weather.data.weather[4].hourly[3].weatherCode);
		*/
		if (slide == 0){
			if (screen.colorDepth>16){
				// Display custom day/night screen according to time of day
				if ((d.getHours()<6) || (d.getHours()>19)){ //night
					$('#currentloc0').removeClass('day');
					$('#currentloc0').addClass('night');
				}else{ // day
					$('#currentloc0').removeClass('night');
					$('#currentloc0').addClass('day');
				}
			}
		}
	} else{
		// Null weather!!!
		console.log("No weather data!");
	}
}
    
    
function toMiles(km){
    return (km*0.62137).toFixed(1);
}

function toInchesOfMercury(mb){
    return (mb/33.3).toFixed(2);
}

function toInches(mm){
    return (mm/2.54).toFixed(1);
    
}

function formatAMPM(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'PM' : 'AM';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + '' + ampm;
  return strTime;
}

function numberWithCommas(x) {
	return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
    
    function getWeatherIcon(a) {
	    // Check if day or night for the current icon
	    
	    switch (parseInt(a, 10)) {
	        case 113:
		        return "sun.svg"; // moon.svg //"Clear";
		    case 116:
		        return "cloudSun.svg"; // cloudMoon.svg //"Partly Cloudy";
		    case 119:
		        return "cloud.svg"; // cloud.svg // "Cloudy";
		    case 122:
		        return "cloud.svg"; // "Overcast";
		    case 143:
		        return "cloudFog.svg"; // "Mist";
		    case 176:
		        return "cloudDrizzleSun.svg"; // cloudDrizzleMoon.svg  // "Patchy Rain";
		    case 179:
		        return "cloudSnowSunAlt.svg"; // cloudSnowMoonAlt.svg // "Patchy Snow";
		    case 182:
		        return "cloudSnowSun.svg"; // cloudSnowMoon.svg // "Patchy Sleet";
		    case 185:
		        return "cloudSnowSun.svg"; // cloudSnowMoon.svg // "Freezing Drizzle";
		    case 200:
		        return "cloudLightning.svg"; // "Thundery Outbreaks";
		    case 227:
		        return "wind.svg"; // "Blowing Snow";
		    case 230:
		        return "wind.svg"; // "Blizzard";
		    case 248:
		        return "cloudFog.svg"; // "Fog";
		    case 260:
		        return "cloudFog.svg"; // "Freezing Fog";
		    case 263:
		        return "cloudRainSunAlt.svg"; // "cloudRainAltMoon.svg" // "Light Drizzle";
		    case 266:
		        return "cloudRainSunAlt.svg"; // "cloudRainAltMoon.svg" // "Light Drizzle";
		    case 281:
		        return "cloudSnowSunAlt.svg"; // "cloudSnowMoonAlt.svg" // "Freezing Drizzle";
		    case 284:
		        return "cloudDrizzleAlt.svg"; // "Heavy Freezing Drizzle";
		    case 293:
		        return "cloudRainAlt.svg"; // "Light Rain";
		    case 296:
		        return "cloudRainAlt.svg"; // "Light Rain";
		    case 299:
		        return "cloudRain.svg"; // "Moderate rain";
		    case 302:
		        return "cloudRain.svg"; // "Moderate rain";
		    case 305:
		        return "cloudRain.svg"; // "Heavy Rain";
		    case 308:
		        return "cloudRain.svg"; // "Heavy Rain";
		    case 311:
		        return "cloudDrizzle.svg"; // "Light Freezing Rain";
		    case 314:
		        return "cloudDrizzle.svg"; // "Heavy Freezing Rain";
		    case 317:
		        return "cloudHailAlt.svg"; // "Light Sleet";
		    case 320:
		        return "cloudHailAlt.svg"; // "Heavy Sleet";
		    case 323:
		        return "cloudSnowSunAlt.svg"; // cloudSnowMoon.svg // "Light Snow";
		    case 326:
		        return "cloudSnowSunAlt.svg"; // cloudSnowMoon.svg // "Light Snow";
		    case 329:
		        return "cloudSnowSunAlt.svg"; // cloudSnowMoon.svg // "Moderate Snow";
		    case 332:
		        return "cloudSnowSunAlt.svg"; // cloudSnowMoon.svg // "Moderate Snow";
		    case 335:
		        return "snowflake.svg"; // "Heavy Snow";
		    case 338:
		        return "snowflake.svg"; // "Heavy Snow";
		    case 350:
		        return "snowflake.svg"; // "Ice Pellets";
		    case 353:
		        return "cloudRainAlt.svg"; // "Light Rain Shower";
		    case 356:
		        return "cloudRain.svg"; //"Heavy Rain Shower";
		    case 359:
		        return "cloudRain.svg"; // "Torrential Rain Shower";
		    case 362:
		        return "cloudSnow.svg"; // "Light Sleet Showers";
		    case 365:
		        return "cloudSnow.svg"; // "Heavy Sleet Showers";
		    case 368:
		        return "cloudSnowAlt.svg"; // "Light Snow Showers";
		    case 371:
		        return "cloudSnow.svg"; // "Heavy Snow Showers";
		    case 374:
		        return "cloudSnowAlt.svg"; // "Light Showers of Ice Pellets";
		    case 377:
		        return "cloudLightning.svg"; // "Heavy Showers of Ice Pellets";
		    case 386:
		        return "cloudRainAlt.svg"; // "Light Rain with Thunder";
		    case 389:
		        return "cloudLightning.svg"; // "Heavy Rain with Thunder";
		    case 392:
		        return "cloudSnowAlt.svg"; // "Light Snow with Thunder";
		    case 395:
		        return "cloudLightning.svg"; // "Heavy Snow with Thunder";
		    default:
		        return "sun.svg"; // default
		}
	}
	
	function setWeatherBG(){ // show background according to time and weather condition
		
	}
	
var timer = null;
$("#location").keyup(function (a) {
    if (clearTimeout(timer), timer = setTimeout(searchSuggestion, 1e3), 13 === a.keyCode) {
        var b = document.getElementById("location").value;
        searchLocation(b);
	}
});


function searchLocation(a) {
    var b = _ApiBaseURL + "search.ashx?q=" + a + "&format=json&key=" + _ApiKey;
    
    $.ajax({
        type: "get",
        dataType: "jsonp",
        url: b,
        success: function (a) {
            a.search_api ? showResults(a) : (document.getElementById("results").innerHTML = "<li class='no-results'>Nothing found</li>", 
            document.getElementById("results").style.display = "block")
        },
        error: function () {
            document.getElementById("results").innerHTML = "<li class='no-results'>Error, it must be the weather</li>", 
            document.getElementById("results").style.display = "block"
        }
    })
}

function searchSuggestion() {
    var a = document.getElementById("location").value;
    searchLocation(a), clearTimeout(timer)
}

function showResults(a) {
	
	var output = "";
	
	for (x=0;x<a.search_api.result.length;x++){
		output += "<li><div class=\"left\"><h2>" + a.search_api.result[x].areaName[0].value + "</h2><p>" + a.search_api.result[x].region[0].value + ", " + a.search_api.result[x].country[0].value + " <!--<span class=\"micro\">( lat.: " + a.search_api.result[x].latitude + " lon.: " + a.search_api.result[x].longitude + " )--></span></p></div><div class=\"right\"><a class=\"actionicon add\" href=\"#\" onclick=\"saveEntry('','"+ a.search_api.result[x].areaName[0].value + "', '" + a.search_api.result[x].region[0].value + "', '" + a.search_api.result[x].country[0].value + "', '" + a.search_api.result[x].latitude + "', '" + a.search_api.result[x].longitude + "','','');toggleTransition('#searchpage', '#settingspage', 52, 0);$('#location').val('');$('#results').html('');\"><img src=\"img/icons.png\"></a></li>";  
	}
	
	document.getElementById("results").innerHTML = output;
	document.getElementById("results").style.display = "block";
}