Initial commit of V2.

This commit is contained in:
Michael Teeuw
2016-03-24 17:19:32 +01:00
parent c428d6a985
commit 4266c0b279
235 changed files with 31730 additions and 246 deletions

View File

@@ -0,0 +1,139 @@
var calendar = {
eventList: [],
calendarLocation: '.calendar',
updateInterval: 1000,
updateDataInterval: 60000,
fadeInterval: 1000,
intervalId: null,
dataIntervalId: null,
maximumEntries: config.calendar.maximumEntries || 10
}
calendar.updateData = function (callback) {
new ical_parser("controllers/calendar.php" + "?url="+encodeURIComponent(config.calendar.url), function(cal) {
var events = cal.getEvents();
this.eventList = [];
for (var i in events) {
var e = events[i];
for (var key in e) {
var value = e[key];
var seperator = key.search(';');
if (seperator >= 0) {
var mainKey = key.substring(0,seperator);
var subKey = key.substring(seperator+1);
var dt;
if (subKey == 'VALUE=DATE') {
//date
dt = new Date(value.substring(0,4), value.substring(4,6) - 1, value.substring(6,8));
} else {
//time
dt = new Date(value.substring(0,4), value.substring(4,6) - 1, value.substring(6,8), value.substring(9,11), value.substring(11,13), value.substring(13,15));
}
if (mainKey == 'DTSTART') e.startDate = dt;
if (mainKey == 'DTEND') e.endDate = dt;
}
}
if (e.startDate == undefined){
//some old events in Gmail Calendar is "start_date"
//FIXME: problems with Gmail's TimeZone
var days = moment(e.DTSTART).diff(moment(), 'days');
var seconds = moment(e.DTSTART).diff(moment(), 'seconds');
var startDate = moment(e.DTSTART);
} else {
var days = moment(e.startDate).diff(moment(), 'days');
var seconds = moment(e.startDate).diff(moment(), 'seconds');
var startDate = moment(e.startDate);
}
//only add fututre events, days doesn't work, we need to check seconds
if (seconds >= 0) {
if (seconds <= 60*60*5 || seconds >= 60*60*24*2) {
var time_string = moment(startDate).fromNow();
}else {
var time_string = moment(startDate).calendar()
}
if (!e.RRULE) {
this.eventList.push({'description':e.SUMMARY,'seconds':seconds,'days':time_string});
}
e.seconds = seconds;
}
// Special handling for rrule events
if (e.RRULE) {
var options = new RRule.parseString(e.RRULE);
options.dtstart = e.startDate;
var rule = new RRule(options);
var oneYear = new Date();
oneYear.setFullYear(oneYear.getFullYear() + 1);
var dates = rule.between(new Date(), oneYear, true, function (date, i){return i < 10});
for (date in dates) {
var dt = new Date(dates[date]);
var days = moment(dt).diff(moment(), 'days');
var seconds = moment(dt).diff(moment(), 'seconds');
var startDate = moment(dt);
if (seconds >= 0) {
if (seconds <= 60*60*5 || seconds >= 60*60*24*2) {
var time_string = moment(dt).fromNow();
} else {
var time_string = moment(dt).calendar()
}
this.eventList.push({'description':e.SUMMARY,'seconds':seconds,'days':time_string});
}
}
}
};
this.eventList = this.eventList.sort(function(a,b){return a.seconds-b.seconds});
// Limit the number of entries.
this.eventList = this.eventList.slice(0, calendar.maximumEntries);
if (callback !== undefined && Object.prototype.toString.call(callback) === '[object Function]') {
callback(this.eventList);
}
}.bind(this));
}
calendar.updateCalendar = function (eventList) {
table = $('<table/>').addClass('xsmall').addClass('calendar-table');
opacity = 1;
for (var i in eventList) {
var e = eventList[i];
var row = $('<tr/>').css('opacity',opacity);
row.append($('<td/>').html(e.description).addClass('description'));
row.append($('<td/>').html(e.days).addClass('days dimmed'));
table.append(row);
opacity -= 1 / eventList.length;
}
$(this.calendarLocation).updateWithText(table, this.fadeInterval);
}
calendar.init = function () {
this.updateData(this.updateCalendar.bind(this));
this.intervalId = setInterval(function () {
this.updateCalendar(this.eventList)
}.bind(this), this.updateInterval);
this.dataIntervalId = setInterval(function () {
this.updateData(this.updateCalendar.bind(this));
}.bind(this), this.updateDataInterval);
}

View File

@@ -0,0 +1,70 @@
var compliments = {
complimentLocation: '.compliment',
currentCompliment: '',
complimentList: {
'morning': config.compliments.morning,
'afternoon': config.compliments.afternoon,
'evening': config.compliments.evening
},
updateInterval: config.compliments.interval || 30000,
fadeInterval: config.compliments.fadeInterval || 4000,
intervalId: null
};
/**
* Changes the compliment visible on the screen
*/
compliments.updateCompliment = function () {
var _list = [];
var hour = moment().hour();
// In the followign if statement we use .slice() on the
// compliments array to make a copy by value.
// This way the original array of compliments stays in tact.
if (hour >= 3 && hour < 12) {
// Morning compliments
_list = compliments.complimentList['morning'].slice();
} else if (hour >= 12 && hour < 17) {
// Afternoon compliments
_list = compliments.complimentList['afternoon'].slice();
} else if (hour >= 17 || hour < 3) {
// Evening compliments
_list = compliments.complimentList['evening'].slice();
} else {
// Edge case in case something weird happens
// This will select a compliment from all times of day
Object.keys(compliments.complimentList).forEach(function (_curr) {
_list = _list.concat(compliments.complimentList[_curr]).slice();
});
}
// Search for the location of the current compliment in the list
var _spliceIndex = _list.indexOf(compliments.currentCompliment);
// If it exists, remove it so we don't see it again
if (_spliceIndex !== -1) {
_list.splice(_spliceIndex, 1);
}
// Randomly select a location
var _randomIndex = Math.floor(Math.random() * _list.length);
compliments.currentCompliment = _list[_randomIndex];
$('.compliment').updateWithText(compliments.currentCompliment, compliments.fadeInterval);
}
compliments.init = function () {
this.updateCompliment();
this.intervalId = setInterval(function () {
this.updateCompliment();
}.bind(this), this.updateInterval)
}

43
old_version/js/config.js Executable file
View File

@@ -0,0 +1,43 @@
var config = {
lang: 'nl',
time: {
timeFormat: 12
},
weather: {
//change weather params here:
//units: metric or imperial
params: {
q: 'Baarn,Netherlands',
units: 'metric',
// if you want a different lang for the weather that what is set above, change it here
lang: 'nl',
APPID: '38f485725346a5f0fd84a3567f91f490'
}
},
compliments: {
interval: 30000,
fadeInterval: 4000,
morning: [
'Good morning, handsome!',
'Enjoy your day!',
'How was your sleep?'
],
afternoon: [
'Hello, beauty!',
'You look sexy!',
'Looking good today!'
],
evening: [
'Wow, you look hot!',
'You look nice!',
'Hi, sexy!'
]
},
calendar: {
maximumEntries: 10,
url: "https://p01-calendarws.icloud.com/ca/subscribe/1/n6x7Farxpt7m9S8bHg1TGArSj7J6kanm_2KEoJPL5YIAk3y70FpRo4GyWwO-6QfHSY5mXtHcRGVxYZUf7U3HPDOTG5x0qYnno1Zr_VuKH2M"
},
news: {
feed: 'http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml'
}
}

View File

@@ -0,0 +1,224 @@
/**
* Javascript ical Parser
* Proof of concept method of reading icalendar (.ics) files with javascript.
*
* @author: Carl Saggs
* @source: https://github.com/thybag/
* @version: 0.2
*/
function ical_parser(feed_url, callback){
//store of unproccesed data.
this.raw_data = null;
//Store of proccessed data.
this.events = [];
/**
* loadFile
* Using AJAX to load the requested .ics file, passing it to the callback when completed.
* @param url URL of .ics file
* @param callback Function to call on completion.
*/
this.loadFile = function(url, callback){
//Create request object
try {xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");} catch (e) { }
//Grab file
xmlhttp.onreadystatechange = function(){
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
//On success, run callback.
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
/**
* makeDate
* Convert the dateformat used by ICalendar in to one more suitable for javascript.
* @param String ical_date
* @return dt object, includes javascript Date + day name, hour/minutes/day/month/year etc.
*/
this.makeDate = function(ical_date){
//break date apart
var dtutc = {
year: ical_date.substr(0,4),
month: ical_date.substr(4,2),
day: ical_date.substr(6,2),
hour: ical_date.substr(9,2),
minute: ical_date.substr(11,2)
}
//Create JS date (months start at 0 in JS - don't ask)
var utcdatems = Date.UTC(dtutc.year, (dtutc.month-1), dtutc.day, dtutc.hour, dtutc.minute);
var dt = {};
dt.date = new Date(utcdatems);
dt.year = dt.date.getFullYear();
dt.month = ('0' + (dt.date.getMonth()+1)).slice(-2);
dt.day = ('0' + dt.date.getDate()).slice(-2);
dt.hour = ('0' + dt.date.getHours()).slice(-2);
dt.minute = ('0' + dt.date.getMinutes()).slice(-2);
//Get the full name of the given day
dt.dayname =["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][dt.date.getDay()];
dt.monthname = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ][dt.date.getMonth()] ;
return dt;
}
/**
* parseICAL
* Convert the ICAL format in to a number of javascript objects (Each representing a date)
*
* @param data Raw ICAL data
*/
this.parseICAL = function(data){
//Ensure cal is empty
this.events = [];
//Clean string and split the file so we can handle it (line by line)
cal_array = data.replace(new RegExp( "\\r", "g" ), "").replace(/\n /g,"").split("\n");
//Keep track of when we are activly parsing an event
var in_event = false;
//Use as a holder for the current event being proccessed.
var cur_event = null;
for(var i=0;i<cal_array.length;i++){
ln = cal_array[i];
//If we encounted a new Event, create a blank event object + set in event options.
if(!in_event && ln == 'BEGIN:VEVENT'){
in_event = true;
cur_event = {};
}
//If we encounter end event, complete the object and add it to our events array then clear it for reuse.
if(in_event && ln == 'END:VEVENT'){
in_event = false;
this.events.push(cur_event);
cur_event = null;
}
//If we are in an event
else if(in_event){
//var lntrim = ln.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
//var lnsplit = lntrim.split(':');
//type = lnsplit[0];
//val = lnsplit[1];
//Split the item based on the first ":"
idx = ln.indexOf(':');
//Apply trimming to values to reduce risks of badly formatted ical files.
type = ln.substr(0,idx).replace(/^\s\s*/, '').replace(/\s\s*$/, '');//Trim
val = ln.substr(idx+1).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
//If the type is a start date, proccess it and store details
if(type =='DTSTART'){
dt = this.makeDate(val);
val = dt.date;
//These are helpful for display
cur_event.start_time = dt.hour+':'+dt.minute;
cur_event.start_date = dt.day+'/'+dt.month+'/'+dt.year;
cur_event.day = dt.dayname;
cur_event.start_date_long = dt.day+'. '+dt.monthname+' '+dt.year ;
}
//If the type is an end date, do the same as above
else if(type =='DTEND'){
dt = this.makeDate(val);
val = dt.date;
//These are helpful for display
cur_event.end_time = dt.hour+':'+dt.minute;
cur_event.end_date = dt.day+'/'+dt.month+'/'+dt.year;
cur_event.day = dt.dayname;
}
//Convert timestamp
else if(type =='DTSTAMP'){
val = this.makeDate(val).date;
}
else {
val = val
.replace(/\\r\\n/g,'<br />')
.replace(/\\n/g,'<br />')
.replace(/\\,/g,',');
}
//Add the value to our event object.
cur_event[type] = val;
}
}
//Run this to finish proccessing our Events.
this.complete();
}
/**
* complete
* Sort all events in to a sensible order and run the original callback
*/
this.complete = function(){
//Sort the data so its in date order.
this.events.sort(function(a,b){
return a.DTSTART-b.DTSTART;
});
//Run callback method, if was defined. (return self)
if(typeof callback == 'function') callback(this);
}
/**
* getEvents
* return all events found in the ical file.
*
* @return list of events objects
*/
this.getEvents = function(){
return this.events;
}
/**
* getFutureEvents
* return all events sheduled to take place after the current date.
*
* @return list of events objects
*/
this.getFutureEvents = function(){
var future_events = [], current_date = new Date();
this.events.forEach(function(itm){
//If the event ends after the current time, add it to the array to return.
if(itm.DTEND > current_date) future_events.push(itm);
});
return future_events;
}
/**
* getPastEvents
* return all events sheduled to take place before the current date.
*
* @return list of events objects
*/
this.getPastEvents = function(){
var past_events = [], current_date = new Date();
this.events.forEach(function(itm){
//If the event ended before the current time, add it to the array to return.
if(itm.DTEND <= current_date) past_events.push(itm);
});
return past_events.reverse();
}
/**
* load
* load a new ICAL file.
*
* @param ical file url
*/
this.load = function(ical_file){
var tmp_this = this;
this.raw_data = null;
this.loadFile(ical_file, function(data){
//if the file loads, store the data and invoke the parser
tmp_this.raw_data = data;
tmp_this.parseICAL(data);
});
}
//Store this so we can use it in the callback from the load function.
var tmp_this = this;
//Store the feed url
this.feed_url = feed_url;
//Load the file
this.load(this.feed_url);
}

View File

@@ -0,0 +1,32 @@
//jQuery extension to fetch an rss feed and return it as json via YQL
//created by dboz@airshp.com
(function($) {
$.extend({
feedToJson: function(options, callback) {
if ($.isFunction(options)) {
callback = options;
options = null;
}
options = $.extend($.feedToJson.defaults,options);
var url = options.yqlURL + options.yqlQS + "'" + encodeURIComponent(options.feed) + "'" + "&_nocache=" + options.cacheBuster;
return $.getJSON(url, function(data){
//console.log(data.query.results);
data = data.query.results;
$.isFunction(callback) && callback(data); //allows the callback function to be the only option
$.isFunction(options.success) && options.success(data);
});
}
});
//defaults
$.feedToJson.defaults = {
yqlURL : 'https://query.yahooapis.com/v1/public/yql', //yql
yqlQS : '?format=json&callback=?&q=select%20*%20from%20rss%20where%20url%3D', //yql query string
feed:'http://instagr.am/tags/tacos/feed/recent.rss', //instagram recent posts tagged 'tacos'
cachebuster: Math.floor((new Date().getTime()) / 1200 / 1000), //yql caches feeds, so we change the feed url every 20min
success:null //success callback
};
})(jQuery);
// eo feedToJson

4
old_version/js/jquery.js vendored Normal file

File diff suppressed because one or more lines are too long

60
old_version/js/main.js Executable file
View File

@@ -0,0 +1,60 @@
jQuery.fn.updateWithText = function(text, speed)
{
var dummy = $('<div/>').html(text);
if ($(this).html() != dummy.html())
{
$(this).fadeOut(speed/2, function() {
$(this).html(text);
$(this).fadeIn(speed/2, function() {
//done
});
});
}
}
jQuery.fn.outerHTML = function(s) {
return s
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
};
function roundVal(temp)
{
return Math.round(temp * 10) / 10;
}
jQuery(document).ready(function($) {
var eventList = [];
var lastCompliment;
var compliment;
moment.locale(config.lang);
//connect do Xbee monitor
// var socket = io.connect('http://rpi-alarm.local:8082');
// socket.on('dishwasher', function (dishwasherReady) {
// if (dishwasherReady) {
// $('.dishwasher').fadeIn(2000);
// $('.lower-third').fadeOut(2000);
// } else {
// $('.dishwasher').fadeOut(2000);
// $('.lower-third').fadeIn(2000);
// }
// });
version.init();
time.init();
calendar.init();
compliments.init();
weather.init();
news.init();
});

File diff suppressed because one or more lines are too long

152
old_version/js/news/news.js Normal file
View File

@@ -0,0 +1,152 @@
// A lot of this code is from the original feedToJson function that was included with this project
// The new code allows for multiple feeds to be used but a bunch of variables and such have literally been copied and pasted into this code and some help from here: http://jsfiddle.net/BDK46/
// The original version can be found here: http://airshp.com/2011/jquery-plugin-feed-to-json/
var news = {
feed: config.news.feed || null,
newsLocation: '.news',
newsItems: [],
seenNewsItem: [],
_yqURL: 'https://query.yahooapis.com/v1/public/yql',
_yqlQS: '?format=json&q=select%20*%20from%20rss%20where%20url%3D',
_cacheBuster: Math.floor((new Date().getTime()) / 1200 / 1000),
_failedAttempts: 0,
fetchInterval: config.news.fetchInterval || 60000,
updateInterval: config.news.interval || 5500,
fadeInterval: 2000,
intervalId: null,
fetchNewsIntervalId: null
}
/**
* Creates the query string that will be used to grab a converted RSS feed into a JSON object via Yahoo
* @param {string} feed The original location of the RSS feed
* @return {string} The new location of the RSS feed provided by Yahoo
*/
news.buildQueryString = function (feed) {
return this._yqURL + this._yqlQS + '\'' + encodeURIComponent(feed) + '\'';
}
/**
* Fetches the news for each feed provided in the config file
*/
news.fetchNews = function () {
// Reset the news feed
this.newsItems = [];
this.feed.forEach(function (_curr) {
var _yqUrlString = this.buildQueryString(_curr);
this.fetchFeed(_yqUrlString);
}.bind(this));
}
/**
* Runs a GET request to Yahoo's service
* @param {string} yqUrl The URL being used to grab the RSS feed (in JSON format)
*/
news.fetchFeed = function (yqUrl) {
$.ajax({
type: 'GET',
datatype:'jsonp',
url: yqUrl,
success: function (data) {
if (data.query.count > 0) {
this.parseFeed(data.query.results.item);
} else {
console.error('No feed results for: ' + yqUrl);
}
}.bind(this),
error: function () {
// non-specific error message that should be updated
console.error('No feed results for: ' + yqUrl);
}
});
}
/**
* Parses each item in a single news feed
* @param {Object} data The news feed that was returned by Yahoo
* @return {boolean} Confirms that the feed was parsed correctly
*/
news.parseFeed = function (data) {
var _rssItems = [];
for (var i = 0, count = data.length; i < count; i++) {
_rssItems.push(data[i].title);
}
this.newsItems = this.newsItems.concat(_rssItems);
return true;
}
/**
* Loops through each available and unseen news feed after it has been retrieved from Yahoo and shows it on the screen
* When all news titles have been exhausted, the list resets and randomly chooses from the original set of items
* @return {boolean} Confirms that there is a list of news items to loop through and that one has been shown on the screen
*/
news.showNews = function () {
// If all items have been seen, swap seen to unseen
if (this.newsItems.length === 0 && this.seenNewsItem.length !== 0) {
if (this._failedAttempts === 20) {
console.error('Failed to show a news story 20 times, stopping any attempts');
return false;
}
this._failedAttempts++;
setTimeout(function () {
this.showNews();
}.bind(this), 3000);
} else if (this.newsItems.length === 0 && this.seenNewsItem.length !== 0) {
this.newsItems = this.seenNewsItem.splice(0);
}
var _location = Math.floor(Math.random() * this.newsItems.length);
var _item = news.newsItems.splice(_location, 1)[0];
this.seenNewsItem.push(_item);
$(this.newsLocation).updateWithText(_item, this.fadeInterval);
return true;
}
news.init = function () {
if (this.feed === null || (this.feed instanceof Array === false && typeof this.feed !== 'string')) {
return false;
} else if (typeof this.feed === 'string') {
this.feed = [this.feed];
}
this.fetchNews();
this.showNews();
this.fetchNewsIntervalId = setInterval(function () {
this.fetchNews()
}.bind(this), this.fetchInterval)
this.intervalId = setInterval(function () {
this.showNews();
}.bind(this), this.updateInterval);
}

1910
old_version/js/rrule.js Normal file

File diff suppressed because it is too large Load Diff

2
old_version/js/socket.io.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,34 @@
var time = {
timeFormat: config.time.timeFormat || 24,
dateLocation: '.date',
timeLocation: '.time',
updateInterval: 1000,
intervalId: null
};
/**
* Updates the time that is shown on the screen
*/
time.updateTime = function () {
var _now = moment(),
_date = _now.format('dddd, LL');
$(this.dateLocation).html(_date);
$(this.timeLocation).html(_now.format(this._timeFormat+':mm[<span class="sec">]ss[</span>]'));
}
time.init = function () {
if (parseInt(time.timeFormat) === 12) {
time._timeFormat = 'hh'
} else {
time._timeFormat = 'HH';
}
this.intervalId = setInterval(function () {
this.updateTime();
}.bind(this), 1000);
}

View File

@@ -0,0 +1,34 @@
var version = {
updateInterval: 600000,
intervalId: null
}
/**
* Checks the version and refreshes the page if a new version has been pulled
*/
version.checkVersion = function () {
$.ajax({
type: 'GET',
url: 'controllers/hash.php',
success: function (data) {
// The githash variable is located in index.php
if (data && data.gitHash !== gitHash) {
window.location.reload();
window.location.href = window.location.href;
}
},
error: function () {
}
});
}
version.init = function () {
this.intervalId = setInterval(function () {
this.checkVersion();
}.bind(this), this.updateInterval);
}

View File

@@ -0,0 +1,169 @@
var weather = {
// Default language is Dutch because that is what the original author used
lang: config.lang || 'nl',
params: config.weather.params || null,
iconTable: {
'01d':'wi-day-sunny',
'02d':'wi-day-cloudy',
'03d':'wi-cloudy',
'04d':'wi-cloudy-windy',
'09d':'wi-showers',
'10d':'wi-rain',
'11d':'wi-thunderstorm',
'13d':'wi-snow',
'50d':'wi-fog',
'01n':'wi-night-clear',
'02n':'wi-night-cloudy',
'03n':'wi-night-cloudy',
'04n':'wi-night-cloudy',
'09n':'wi-night-showers',
'10n':'wi-night-rain',
'11n':'wi-night-thunderstorm',
'13n':'wi-night-snow',
'50n':'wi-night-alt-cloudy-windy'
},
temperatureLocation: '.temp',
windSunLocation: '.windsun',
forecastLocation: '.forecast',
apiVersion: '2.5',
apiBase: 'http://api.openweathermap.org/data/',
weatherEndpoint: 'weather',
forecastEndpoint: 'forecast/daily',
updateInterval: config.weather.interval || 6000,
fadeInterval: config.weather.fadeInterval || 1000,
intervalId: null
}
/**
* Rounds a float to one decimal place
* @param {float} temperature The temperature to be rounded
* @return {float} The new floating point value
*/
weather.roundValue = function (temperature) {
return parseFloat(temperature).toFixed(1);
}
/**
* Converts the wind speed (km/h) into the values given by the Beaufort Wind Scale
* @see http://www.spc.noaa.gov/faq/tornado/beaufort.html
* @param {int} kmh The wind speed in Kilometers Per Hour
* @return {int} The wind speed converted into its corresponding Beaufort number
*/
weather.ms2Beaufort = function(ms) {
var kmh = ms * 60 * 60 / 1000;
var speeds = [1, 5, 11, 19, 28, 38, 49, 61, 74, 88, 102, 117, 1000];
for (var beaufort in speeds) {
var speed = speeds[beaufort];
if (speed > kmh) {
return beaufort;
}
}
return 12;
}
/**
* Retrieves the current temperature and weather patter from the OpenWeatherMap API
*/
weather.updateCurrentWeather = function () {
$.ajax({
type: 'GET',
url: weather.apiBase + '/' + weather.apiVersion + '/' + weather.weatherEndpoint,
dataType: 'json',
data: weather.params,
success: function (data) {
var _temperature = this.roundValue(data.main.temp),
_temperatureMin = this.roundValue(data.main.temp_min),
_temperatureMax = this.roundValue(data.main.temp_max),
_wind = this.roundValue(data.wind.speed),
_iconClass = this.iconTable[data.weather[0].icon];
var _icon = '<span class="icon ' + _iconClass + ' dimmed wi"></span>';
var _newTempHtml = _icon + '' + _temperature + '&deg;';
$(this.temperatureLocation).updateWithText(_newTempHtml, this.fadeInterval);
var _now = moment().format('HH:mm'),
_sunrise = moment(data.sys.sunrise*1000).format('HH:mm'),
_sunset = moment(data.sys.sunset*1000).format('HH:mm');
var _newWindHtml = '<span class="wi wi-strong-wind xdimmed"></span> ' + this.ms2Beaufort(_wind),
_newSunHtml = '<span class="wi wi-sunrise xdimmed"></span> ' + _sunrise;
if (_sunrise < _now && _sunset > _now) {
_newSunHtml = '<span class="wi wi-sunset xdimmed"></span> ' + _sunset;
}
$(this.windSunLocation).updateWithText(_newWindHtml + ' ' + _newSunHtml, this.fadeInterval);
}.bind(this),
error: function () {
}
});
}
/**
* Updates the 5 Day Forecast from the OpenWeatherMap API
*/
weather.updateWeatherForecast = function () {
$.ajax({
type: 'GET',
url: weather.apiBase + '/' + weather.apiVersion + '/' + weather.forecastEndpoint,
data: weather.params,
success: function (data) {
var _opacity = 1,
_forecastHtml = '';
_forecastHtml += '<table class="forecast-table">';
for (var i = 0, count = data.list.length; i < count; i++) {
var _forecast = data.list[i];
_forecastHtml += '<tr style="opacity:' + _opacity + '">';
_forecastHtml += '<td class="day">' + moment(_forecast.dt, 'X').format('ddd') + '</td>';
_forecastHtml += '<td class="icon-small ' + this.iconTable[_forecast.weather[0].icon] + '"></td>';
_forecastHtml += '<td class="temp-max">' + this.roundValue(_forecast.temp.max) + '</td>';
_forecastHtml += '<td class="temp-min">' + this.roundValue(_forecast.temp.min) + '</td>';
_forecastHtml += '</tr>';
_opacity -= 0.155;
}
_forecastHtml += '</table>';
$(this.forecastLocation).updateWithText(_forecastHtml, this.fadeInterval);
}.bind(this),
error: function () {
}
});
}
weather.init = function () {
if (this.params.lang === undefined) {
this.params.lang = this.lang;
}
if (this.params.cnt === undefined) {
this.params.cnt = 5;
}
this.intervalId = setInterval(function () {
this.updateCurrentWeather();
this.updateWeatherForecast();
}.bind(this), this.updateInterval);
}