var obj = {error:false, errorString:null};
////////////////////////////////////////////////////////////////////////////////////////////////////////////

function convertWeatherIcon(iconString, mainIcon){

iconCount = iconString.indexOf("/i/c/a/") + 7;

iconName = iconString.substring(iconCount, iconString.length);

//if it is night then add the prefix nt_
if (isNight(obj.sunset, obj.sunrise, obj.localtime) && mainIcon == true){

iconName = "nt_" + iconName;

}

	switch (iconName)
		{
		case "chanceflurries.gif":
			return 13;                       // 13 Mostly Cloudy with Flurries
			break;
		case "chancerain.gif":
			return 9;                        // 9 showers (am/pm)
			break;
		case "chancesleet.gif":
			return 16;                       // 16 Sleet (am/pm)
			break;
		case "chancesnow.gif":
			return 13;                       // 13 Mostly Cloudy with Flurries
			break;
		case "chancetstorms.gif":
			return 11;                       // 11 Partly Sunnty with Thunder Showers
			break;
		case "clear.gif":
			return 0;                        // 0 Sunny
			break;
		case "cloudy.gif":
			return 6;                        // 6 Cloudy (am/pm)
			break;
		case "flurries.gif":
			return 13;                       // 13 Mostly Cloudy with Flurries
			break;
		case "fog.gif":
			return 8;                       // 8 Fog
			break;            
		case "hazy.gif":
			return 4;                        // 4 Hazy Sunshine
			break;
		case "mostlycloudy.gif":
			return 5;                        // 5 Mostly Cloudy
			break;
		case "mostlysunny.gif":
			return 1;                        // 1 Mostly Sunny
			break;
		case "partlycloudy.gif":                    
			return 3;                        // 3 Intermittent Clouds
			break;
		case "partlysunny.gif":
			return 2;                        //2 Partly Sunny
			break;
		case "rain.gif":
			return 12;                       // 12 Rain (am/pm)
			break;
       case "sleet.gif":
			return 16;                       // 16 Sleet (am/pm)
			break;
		case "snow.gif":
			return 14;                       // 14 Snow (am/pm)
			break;
		case "sunny.gif":
			return 0;                        // 0 Sunny
			break;
		case "tstorms.gif":                         
			return 10;                       // 10 Thunderstorms (am/pm)
			break;
		case "unknown.gif":
			return 7;                        // 7 retired
			break;
		case "nt_chanceflurries.gif":
			return 23;                       // 23 Night Mostly Cloudy with Flurries
			break;
		case "nt_chancerain.gif":
			return 21;                       // 21 Night Partly Cloudy with Showers
			break;
		case "nt_chancesleet.gif":
			return 24;                       // 24 Night Light snow
			break;
		case "nt_chancesnow.gif":
			return 24;                       // 25 Night Snow Fog
			break;
		case "nt_chancetstorms.gif":
			return 22;                       // 22 Night Partly Cloudy with Thunder Showers
			break;
		case "nt_clear.gif":
			return 17;                       //  17 Night Clear
			break;
		case "nt_cloudy.gif":
			return 19;                       // 19 Night Intermittent Clouds
			break;
		case "nt_flurries.gif":
			return 23;                       // 23 Night Mostly Cloudy with Flurries
			break;
		case "nt_fog.gif":
			return 20;                       // 20 Night Hazy
			break;  
		case "nt_hazy.gif":
			return 20;                       // 20 Night Hazy
			break;
		case "nt_mostlycloudy.gif":
			return 19;                       // 19 Night Intermittent Clouds
			break;
		case "nt_mostlysunny.gif":
			return 18;                       // 18 Night Mostly Clear
			break;
		case "nt_partlycloudy.gif":
			return 19;                       //19 Night Intermittent Clouds
			break;		
		case "nt_partlysunny.gif":
			return 18;                        // 18 Night Mostly Clear
			break;		
		case "nt_rain.gif":
			return 21;                       // 21 Night Partly Cloudy with Showers
			break;
		case "nt_sleet.gif":
			return 24;                       // 24 Night Light snow
			break;
		case "nt_snow.gif":
			return 24;                       // 25 Night Snow Fog
			break;
		case "nt_sunny.gif":
			return 17;                       //  17 Night Clear
			break;
		case "nt_tstorms.gif":
			return 22;                       // 22 Night Partly Cloudy with Thunder Showers
			break;
		case "nt_unknown.gif":
			return 7;                        // 7 Unknown
			break;
		default:
			return 7;		                 //	7 Unknown
			break;
    }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////

var MiniIcons = //Fix Up for weatherParser.js but also enables standardisation of sorts
[
["sunny", "flurries22"],     // 0 Sunny
["cloudy1", "flurries22"],     // 1 Mostly Sunny
["cloudy2", "cloudy62"],     //2 Partly Sunny
["cloudy6", "cloudy62"],     // 3 Intermittent Clouds
["hazysunshine", "hazysunshine2"],     // 4 Hazy Sunshine
["cloudy2", "cloudy62"],     // 5 Mostly Cloudy
["cloudy3", "cloudy32"],     // 6 Cloudy (am/pm)
["dunno", "dunno"],	// 7 retired
["fog", "cloudy62"],	 // 8 fog (am/pm)
["shower1", "shower12"],     // 9 showers (am/pm)
["tstorm3", "cloudy32"],     // 10 Thunderstorms (am/pm)
["tstorm1", "tstorm12"],     // 11 Partly Sunnty with Thunder Showers
["light_rain", "cloudy32"],	// 12 Rain (am/pm)
["flurries1", "cloudy62"],     // 13 Mostly Cloudy with Flurries
["snow3", "sleet2"],	 // 14 Snow (am/pm)
["snow5", "snow52"],	 // 15 Mostly Cloudy with Snow
["sleet", "sleet2"],	 // 16 Sleet (am/pm)
// Night only Icons;
["sunny_night", "cloudy1_night2"],     //  17 Night Clear
["cloudy1_night", "cloudy1_night2"],	 // 18 Night Mostly Clear
["cloudy4_night", "cloudy1_night2"],	 // 19 Night Intermittent Clouds
["cloudy6_night", "cloudy1_night2"],	 // 20 Night Hazy
["shower2_night", "shower3_night2"],	 // 21 Night Partly Cloudy with Showers
["tstorm1_night", "cloudy1_night2"],	 // 22 Night Partly Cloudy with Thunder Showers
["snow3", "cloudy1_night2"],	         // 23 Night Mostly Cloudy with Flurries
["cloudy1_nightls", "cloudy1_night2"],	 // 24 Night Light snow
];

////////////////////////////////////////////////////////////////////////////////////////////////////////////


function trimWhiteSpace (string)
{
	return string.replace(/^\s*/, '').replace(/\s*$/, '');
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////

function constructError (string)
{
	return {error:true, errorString:string};
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////

// parses string of the form nn:nn
function parseTimeString(string)
{
	var obj = null;
	try {
		var array = string.match (/\d{1,2}/g);
		
		obj = {hour:parseInt(array[0], 10), minute:parseInt(array[1],10)};
	}
	catch (ex)
	{
		// ignore
	}
	
	return obj;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////

// parses string of the form nn:nn
function parsehour(string)
{
	var obj = null;
	try {
		var array = string.match (/\d{1,2}/g);
		
		obj = {hour:parseInt(array[0], 10)};
	}
	catch (ex)
	{
		// ignore
	}
	
	return obj;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////

function parseDayCode (dayCode)
{
	return trimWhiteSpace(dayCode).substr (0, 3).toUpperCase();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//This function looks at the passed sunrise and sunset variables to see if it is day or night
        function isNight(sunset, sunrise, localTime)
        {
            sunrise = sunrise.replace(/^\s+|\s+$/g, "").toUpperCase();
            sunriselen = sunrise.length;
            sunriseColPos = sunrise.search(":");
            sunriseHours = parseInt(sunrise.substring(0, sunriseColPos), 10) * 60;
            sunriseMinutes = parseInt(sunrise.substring(sunriseColPos + 1, sunriselen - sunriseColPos + 2));
            sunriseMinutes = sunriseHours + sunriseMinutes;

            sunset = sunset.replace(/^\s+|\s+$/g, "").toUpperCase();
            sunsetlen = sunset.length;
            sunsetColPos = sunset.search(":");
            sunsetHours = parseInt(sunset.substring(0, sunsetColPos), 10) * 60;
            sunsetMinutes = parseInt(sunset.substring(sunsetColPos + 1, sunsetlen - sunsetColPos + 2));
            sunsetMinutes = sunsetHours + sunsetMinutes;

            localTimeColPos = localTime.search(":");            
            currentHours = parseInt(localTime.substr(localTimeColPos-2,2));
            currentMinutes = parseInt(localTime.substr(localTimeColPos+1,2));

            localTimeAMPMString = localTime.substr(localTimeColPos+3,localTime.length);
            
            if ((localTimeAMPMString.search("PM") == 1 && currentHours != 12) || (localTimeAMPMString.search("AM") == 1 && currentHours == 12)){
            currentHours = currentHours + 12;                                                                                                                                                    
            }
            currentMinutes = (currentHours * 60) + currentMinutes            

            if (currentMinutes >= sunriseMinutes && currentMinutes < sunsetMinutes)
            {
                //set image to sun
                return false;
            }
            else
            {
                //set image to moon
                return true;
            }
        }
        
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        
function fetchWeatherData (callback, location, metric)
{
url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fapi.wunderground.com%2Fauto%2Fwui%2Fgeo%2FWXCurrentObXML%2Findex.xml%3Fquery%3D" + location + "'&format=json";

$.getJSON(url, 
function(jsondata) {xml_loaded(jsondata, callback, metric, location);})

url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fapi.wunderground.com%2Fauto%2Fwui%2Fgeo%2FForecastXML%2Findex.xml%3Fquery%3D" + location + "'&format=json";

$.getJSON(url, 
function(jsondata) {Weather_xml_loaded(jsondata, callback, metric, location);})
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////

function xml_loaded (request, callback, metric, location)
{
      

	if (request.query.results.current_observation.display_location.city == undefined){
		callback({error:true, errorString:"Invalid Location"});  } 


	obj.localtime = request.query.results.current_observation.local_time;
            
	obj.city = request.query.results.current_observation.display_location.city;
	
	obj.observationLocation = request.query.results.current_observation.display_location.full
	
	obj.humidity = request.query.results.current_observation.relative_humidity;
    
	obj.description = request.query.results.current_observation.weather;	
    
	obj.observationTime = request.query.results.current_observation.observation_time;   
	
	obj.windDirection = request.query.results.current_observation.wind_degrees;
	
	obj.windspeed = request.query.results.current_observation.wind_mph;

	obj.icon = request.query.results.current_observation.icons.icon_set[0].icon_url.toLowerCase();

    if (metric == "false"){
    
	obj.temp = request.query.results.current_observation.temp_f + "&deg;F";
    
	obj.pressure = request.query.results.current_observation.pressure_in + " inHg";
	
	obj.dewpoint = request.query.results.current_observation.dewpoint_f + "&deg;F";	

	obj.windchill = request.query.results.current_observation.windchill_f + "&deg;F";  

	obj.visibility = request.query.results.current_observation.visibility_mi + " miles";  
    
    }else{
     
	obj.temp = request.query.results.current_observation.temp_c + "&deg;C";
    
	obj.pressure = request.query.results.current_observation.pressure_mb + " kPa";
	  
	obj.dewpoint = request.query.results.current_observation.dewpoint_c + "&deg;C";
	
	obj.windchill = request.query.results.current_observation.windchill_c + "&deg;C";  
	
	obj.visibility = request.query.results.current_observation.visibility_km + " km"; 
   
    }
    
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
function Weather_xml_loaded(request, callback, metric, location)
{
    obj.moonPhase = request.query.results.forecast.moon_phase.ageOfMoon
    
	hour = request.query.results.forecast.moon_phase.sunset.hour;
	
	minute = request.query.results.forecast.moon_phase.sunset.minute;
	
	obj.sunset = hour + ":" + minute;

	hour = request.query.results.forecast.moon_phase.sunrise.hour;
	
	minute = request.query.results.forecast.moon_phase.sunrise.minute;
	
	obj.sunrise = hour + ":" + minute;
    
    obj.icon = convertWeatherIcon(obj.icon, true)	
    
    obj.forecast = new Array;
	
for(j=0;j<5;j++){
		
var foreobj = {daycode:null, hi:0, lo:0, icon:-1};	
					
if (metric == "false"){
	obj.hi = request.query.results.forecast.simpleforecast.forecastday[j].high.fahrenheit + "&deg;F";
	obj.lo = request.query.results.forecast.simpleforecast.forecastday[j].low.fahrenheit + "&deg;F";
	foreobj.hi = obj.hi
	foreobj.lo = obj.lo
	} else {
	obj.hi = request.query.results.forecast.simpleforecast.forecastday[j].high.celsius + "&deg;C";
	obj.lo = request.query.results.forecast.simpleforecast.forecastday[j].low.celsius + "&deg;C";
	foreobj.hi = obj.hi
	foreobj.lo = obj.lo
      }
	
	foreobj.daycode = request.query.results.forecast.simpleforecast.forecastday[j].date.weekday;

	foreobj.desc = request.query.results.forecast.simpleforecast.forecastday[j].conditions;

	foreobj.icon = convertWeatherIcon(request.query.results.forecast.simpleforecast.forecastday[j].icons.icon_set[0].icon_url.toLowerCase(), false);
	foreobj.ouricon = MiniIcons[foreobj.icon];
		
	obj.forecast[j]=foreobj;

	obj.forecast[j].desc=request.query.results.forecast.txt_forecast.forecastday[j].fcttext

    	}
		
weatherData = JSON.stringify(obj);

myDB.transaction(function (transaction)
 {
	transaction.executeSql("UPDATE files SET weatherData = ?, lastUpdated = ?",
	    [weatherData, timeNow()],
	    function (transaction, results) {callback(weatherData);},
		function (transaction, error) {});
});

}