/*var locationCode;
var useGPS;
var lastUpdated;
var isMetric;
var showRealFeel;
var enabled = true;
var useTrueAnimations;
var cityOrientation;
var DBVersion;
var weatherDataObj;
var theme;
var xmlReq = new XMLHttpRequest();
var iconWeather;
self = this;
self.weatherObject = ''; // Initialize the systemDB global variable. */
var animationComplete = false;

var shortName = 'WeatherElements';
var version = '1.0';
var displayName = 'Weather Elements';
var maxSize = 65536; // in bytes
var myDB = openDatabase(shortName, version, displayName, maxSize);

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

function getLocationData(callback) {

    myDB.transaction(function (transaction) {
        transaction.executeSql("SELECT * from files;", [], function (transaction, results) {

            for (var i = 0; i < results.rows.length; i++) {
                var row = results.rows.item(i);
                locationCode = row['zipcodefield'];
                gpsCode = row['gpsCords'];

                if (row['isMetric'] == "true") {
                    isMetric = "true";
                } else {
                    isMetric = "false";
                };

                if (row['useGPS'] == "true") {
                    useGPS = true;
                } else {
                    useGPS = false;
                };
                if (row['use24hour'] == "true") {
                    use24hour = true;
                } else {
                    use24hour = false;
                };

                cityOrientation = row['cityOrientation'];

                theme = row['theme'];

                language = row['language'];

                updateInterval = row['updateInterval'];

                weatherDataObj = row['weatherData'];

                lastUpdated = row['lastUpdated'];

                useTrueAnimations = row['useTrueAnimations'];

                DBVersion = row['DBVersion]'];
                callback();

            }

        }, function (transaction, error) {});
    });
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

(function ($) {
    //Attach this new method to jQuery
    $.fn.extend({

        divFill: function () {

            var minFontSize = .5
            var step = .1

            //Iterate over the current set of matched elements
            return this.each(function () {

                maxWidth = $(this).width();
                maxFont = parseInt($(this).css("font-size")); // use current font-size by default
                $(this).css('width', '');
                fontSize = maxFont;
                do {
                    $(this).css('font-size', fontSize + 'em');
                    innerWidth = $(this).width();
                    fontSize = fontSize - step;
                    maxFontff = parseInt($(this).css("font-size"));
                } while (innerWidth > maxWidth && fontSize > minFontSize && fontSize <= maxFont);
                $(this).css('width', maxWidth);

            });
        }
    });

    //pass jQuery to the function, 
    //So that we will able to use any valid Javascript variable name 
    //to replace "$" SIGN. But, we'll stick to $ (I like dollar sign: ) )       
})(jQuery);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function convertMPH(speed) {
    if (isMetric == "true") {
        speed = speed * 1.609344;
        speed = Math.round((speed * 10) / 10)
        return speed + " kph";
    } else {
        return speed + " mph";
    }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function convertTime(originaltime) {

    if (!use24hour) {
        originaltime = originaltime.replace(/^\s+|\s+$/g, "");
        originaltimelen = originaltime.length;
        originaltimeColPos = originaltime.search(":");
        originaltimeHours = originaltime.substring(0, originaltimeColPos);

        originaltimeMinutes = originaltime.substring(originaltimeColPos + 1, originaltimelen - originaltimeColPos + 2);

        if (originaltimeHours >= 12) {
            originaltimeHours = originaltimeHours - 12;
            originaltime = originaltimeHours + ":" + originaltimeMinutes + " PM";

        } else {
            originaltime = originaltimeHours + ":" + originaltimeMinutes + " AM";

        }
    }

    return originaltime;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function forecastTemp() {

    if ($('#forecastdiv').css('display') == 'none') {
        $('#forecastdiv').fadeIn(1000);
        $('#desc,#slice,#alltemp,#temp,#minago,#city').css('display', 'none');
        $('#animationFrame').css('width', '0')
    } else {
        $('#forecastdiv').fadeOut(1000);
        $('#desc,#slice,#alltemp,#temp,#minago,#city').css('display', 'block');
        $('#animationFrame').css('width', '100%')
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//shows and hides the more info page

function moreInfo() {

    if ($('#moreinfodiv').css('display') == 'none') {
        $('#moreinfodiv').fadeIn(1000);
        $('#desc,#slice,#alltemp,#temp,#minago,#city').css('display', 'block');
        $('#animationFrame').css('width', '0')
    } else {
        $('#moreinfodiv').fadeOut(1000);
        $('#desc,#slice,#alltemp,#temp,#minago,#city').fadeIn('1000');
        $('#animationFrame').css('width', '100%')
    }

}

////////////////////////////////////////////////////////////////////////////////////////////////////
//changes the details on the forecast page when you click on a different day

function changeDetail(index) {
    $('#forecaststr').html(self.weatherObject.forecast[index].daycode);
    $('#forecastDetail').html(self.weatherObject.forecast[index].desc);
    $('.iconday').css('background-color', 'transparent');
    $('#iconday' + (index + 1)).css('background-color', 'rgba(244, 244, 244, 0.6)');
    str = self.weatherObject.humidity;
    var sections = str.split("%");
    $('#daytext1').html(translateObj.humidity + ": " + parseInt(sections[0]) + "%");
}
////////////////////////////////////////////////////////////////////////////////////////////////////

function getWeather() {

    // Spinning wheel while loading
    $('#alltemp').css('display', 'block');
    $('#alltemp').html("Retrieving Weather");
    if (useGPS) {
        locationCode = gpsCode
    }
    fetchWeatherData(dealWithWeather, locationCode, isMetric);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////

function dealWithWeather(weatherDataObj) {
    if (weatherDataObj.error != true) {
        $('#alltemp').css('display', 'none');
        var str;
        var dummy = "";
        var forecastNumber;

        var obj = JSON.parse(weatherDataObj)
        // Set global var
        self = this;
        self.weatherObject = obj;

        //Enter path of images to be preloaded inside parenthesis. Extend list as desired.
        // Mini icons
        iconWeather = obj.icon;
        var img1 = 'images/moonphases/moon' + obj.moonPhase + '.png'
        var img2 = 'images/themes/' + theme + '/' + MiniIcons[iconWeather][1] + '.png'
        var img3 = 'images/themes/' + theme + '/' + MiniIcons[iconWeather][0] + '.png'

        // Bottom divider image
        $('#slice').html('<img src="images/slice.png" border=0>');

        var Conditions = ["sun", "sun", "sun", "cloud", "cloud", "cloud", "cloud", "blank", "fog", "rain", "thunderstorm", "thunderstorm", "rain", "snow", "snow", "snow", "rainsnow", "blank", "blank", "cloud", "cloud", "rain", "thunderstorm", "snow", "snow", "frostandsnow"];

        if (useTrueAnimations == "true") {
            $('#animationFrame').attr('src', 'Animations/' + Conditions[obj.icon] + '.html')
        }

        // *******     TRANSLATE EVERYTHING   ***************************
        if (language != 'en') {
            eval("translate_" + language + "();");
            obj = self.weatherObject;

        }

        // *******   END   TRANSLATE EVERYTHING  ***************************
        // Set the weather description
        $('#desc').html(obj.description.toLowerCase());

        // City from location code
        if (cityOrientation == "horizontal") {
            $('#cityHorizontal').html(obj.city);
        } else if (cityOrientation == "vertical") {
            $('#cityVertical').html(obj.city);
        }


        // Show big temperature
        $('#temp').html(obj.temp);
        // Show Sunrise
        $('#sunrise').html(translateObj.sunrise + ": " + convertTime(obj.sunrise));
        // Show sunset
        $('#sunset').html(translateObj.sunset + ": " + convertTime(obj.sunset));
        // Show Observation Time
        $('#observationTime').html(obj.observationTime);
        // Show pressure
        $('#pressure').html(translateObj.pressure + ": " + obj.pressure);
        // Show wind speed
        $('#windspeed').html(translateObj.windspeed + ": " + convertMPH(obj.windspeed));
        // Show humidity
        $('#humidity').html(translateObj.humidity + ": " + obj.humidity);
        //Observation Location
        $('#observationLocation').html("Observation Location: " + obj.observationLocation);
        //Setup compass direction
        if (obj.windspeed != 0) {

            $('#compasshand').show();
            $('#compasshand').css("webkitTransform", "rotate(" + obj.windDirection + "deg)");

        }

        // Show visibility
        $('#visibility').html(translateObj.visibility + ": " + obj.visibility);
        // Show dewpoint
        $('#dewpoint').html(translateObj.dewpoint + ": " + obj.dewpoint);
        //Show Moon Phase
        $('#moonPhaseImg').attr('src', 'images/moonphases/moon' + obj.moonPhase + ".png");
        // Show all temps in main view
        $('#alltemp').html(translateObj.hi + ": " + obj.hi + "&nbsp;&nbsp;&nbsp;&nbsp;" + translateObj.lo + ": " + obj.lo);


        // Set high and low temps in forecast view
        $('#day1').html(forecast(obj.forecast[0].hi, obj.forecast[0].lo));
        $('#day2').html(forecast(obj.forecast[1].hi, obj.forecast[1].lo));
        $('#day3').html(forecast(obj.forecast[2].hi, obj.forecast[2].lo));
        $('#day4').html(forecast(obj.forecast[3].hi, obj.forecast[3].lo));
        $('#day5').html(forecast(obj.forecast[4].hi, obj.forecast[4].lo));


        // Today's day title
        $('#forecaststr').html(obj.forecast[0].daycode);

        // Day names in forecast view
        $('#daycode1').html(obj.forecast[0].daycode);
        $('#daycode2').html(obj.forecast[1].daycode);
        $('#daycode3').html(obj.forecast[2].daycode);
        $('#daycode4').html(obj.forecast[3].daycode);
        $('#daycode5').html(obj.forecast[4].daycode);

        // Forecast icons for forecast view
        $('#iconday1').html("<img src=\"images/forecast/" + obj.forecast[0].ouricon[0] + "small.png\" border=0 onclick=\"changeDetail(0);\">");
        $('#iconday2').html("<img src=\"images/forecast/" + obj.forecast[1].ouricon[0] + "small.png\" border=0 onclick=\"changeDetail(1);\">");
        $('#iconday3').html("<img src=\"images/forecast/" + obj.forecast[2].ouricon[0] + "small.png\" border=0 onclick=\"changeDetail(2);\">");
        $('#iconday4').html("<img src=\"images/forecast/" + obj.forecast[3].ouricon[0] + "small.png\" border=0 onclick=\"changeDetail(3);\">");
        $('#iconday5').html("<img src=\"images/forecast/" + obj.forecast[4].ouricon[0] + "small.png\" border=0 onclick=\"changeDetail(4);\">");

        // Set detailed description for today's forecast in forecast view
        $('#forecastDetail').html(obj.forecast[0].desc);

        //sunMoon();
        animation();

    } else {
	$('#desc').html(weatherDataObj.errorString);
	$('#alltemp').fadeOut(1500);
	$('#desc').fadeIn(1500);
    }

}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


function animation() {

    $('#fading').attr('src', "images/themes/" + theme + "/" + MiniIcons[iconWeather][1] + ".png");
    $('#weatherIcon').attr('src', "images/themes/" + theme + "/" + MiniIcons[iconWeather][0] + ".png");
    $('#desc,#cityHorizontal,#cityVertical').divFill();
    $('#fading').delay(1000).fadeIn(1500);
    $('#weatherIcon').delay(1000).fadeIn(1500);
    $('#desc,#slice,#alltemp,#temp,#minago,#refreshButton').delay(1500).fadeIn('1500');
    $('#cityHorizontal,#cityVertical, #rightarrow, #leftarrow').delay(1500).fadeIn('1500');

    animationComplete = true;
    getLocationData(checkMinAgo);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


function forecast(temp, templo) {
    var dummy;
    dummy = temp + "&nbsp;&nbsp;<font color=\"#BEBEBE\">" + templo;
    "</font>";
    return dummy;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Get the current time


function timeNow() {

    var currentTime = new Date();

    var currentHours = currentTime.getHours();
    var currentMinutes = currentTime.getMinutes();

    // Pad the minutes and seconds with leading zeros, if required
    currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
    // Pad the minutes and seconds with leading zeros, if required
    currentHours = (currentHours < 10 ? "0" : "") + currentHours;

    // Compose the string for display
    var Day = currentTime.getDate();
    Day = (Day < 10 ? "0" : "") + Day;
    var month = currentTime.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;
    var Year = currentTime.getFullYear();


    var currentTimeString = month + "/" + Day + "/" + Year + " " + currentHours + ":" + currentMinutes + ":00";

    return currentTimeString;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Check how many minutes it has been since the last update


function checkMinAgo() {
    date1 = new Date();
    date2 = new Date();
    diff = new Date();

    date1temp = new Date(lastUpdated);
    date1.setTime(date1temp.getTime());

    date2temp = new Date(timeNow());
    date2.setTime(date2temp.getTime());

    // sets difference date to difference of first date and second date
    diff.setTime(Math.abs(date1.getTime() - date2.getTime()));

    timediff = diff.getTime();

    weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
    timediff -= weeks * (1000 * 60 * 60 * 24 * 7);

    days = Math.floor(timediff / (1000 * 60 * 60 * 24));
    timediff -= days * (1000 * 60 * 60 * 24);

    hours = Math.floor(timediff / (1000 * 60 * 60));
    timediff -= hours * (1000 * 60 * 60);

    mins = Math.floor(timediff / (1000 * 60));
    timediff -= mins * (1000 * 60);

    secs = Math.floor(timediff / 1000);
    timediff -= secs * 1000;

    if (!lastUpdated) {
        getWeather();
    } else if (((hours * 60) + mins) >= updateInterval) {
        myDB.transaction(function (transaction) {
            transaction.executeSql("UPDATE files SET weatherData = ?, lastUpdated = ?", [null, null], function (transaction, results) {}, function (transaction, error) {});
        });
        animationComplete = false;
        getWeather();
        getLocationData(checkMinAgo);
        $('#minago').html();
    } else if (animationComplete == false) {
        $('#minago').html();
        dealWithWeather(weatherDataObj);
    }

//    if (!weatherDataObj) {
//        setTimeout(checkMinAgo, 300000);
//    } else {
//        $('#minago').html(mins + " " + translateObj.minAgo);
//        setTimeout(checkMinAgo, 60000);
//    }
}