forked from joshwnj/flickr-photos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathphotos.js
118 lines (100 loc) · 3.15 KB
/
photos.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/*global jQuery*/
var setupPhotos = (function ($) {
function each (items, callback) {
var i;
for (i = 0; i < items.length; i += 1) {
setTimeout(callback.bind(this, items[i]), 0);
}
}
function flatten (items) {
return items.reduce(function (a, b) {
return a.concat(b);
});
}
function loadPhotosByTag (tag, max, callback) {
var photos = [];
var callback_name = 'callback_' + Math.floor(Math.random() * 100000);
window[callback_name] = function (data) {
delete window[callback_name];
var i;
for (i = 0; i < max; i += 1) {
photos.push(data.items[i].media.m);
}
callback(null, photos);
};
$.ajax({
url: 'http://api.flickr.com/services/feeds/photos_public.gne',
data: {
tags: tag,
lang: 'en-us',
format: 'json',
jsoncallback: callback_name
},
dataType: 'jsonp'
});
}
function loadAllPhotos (tags, max, callback) {
var results = [];
function handleResult (err, photos) {
if (err) { return callback(err); }
results.push(photos);
if (results.length === tags.length) {
callback(null, flatten(results));
}
}
each(tags, function (tag) {
loadPhotosByTag(tag, max, handleResult);
});
}
function renderPhoto (photo) {
var img = new Image();
img.src = photo;
return img;
}
function imageAppender (id) {
var holder = document.getElementById(id);
var icon = favoriteIcon();
return function (img) {
var elm = document.createElement('div');
elm.className = 'photo';
elm.appendChild(img);
elm.appendChild( icon(img) );
holder.appendChild(elm);
};
}
function favoriteIcon() {
var favorites = [];
if (localStorage.favorites)
favorites = JSON.parse(localStorage.favorites);
return function (img) {
var favIcon = document.createElement('a');
favIcon.href = '#';
if ( favorites.indexOf(img.src) >= 0 ) {
favIcon.className = 'icon-heart';
} else {
favIcon.className = 'icon-heart-empty';
}
favIcon.onclick = function () {
if ( favorites.indexOf(img.src) >= 0 ) {
favorites.splice( favorites.indexOf(img.src), 1 );
favIcon.className = 'icon-heart-empty';
} else {
favorites.push(img.src);
favIcon.className = 'icon-heart';
}
localStorage.favorites = JSON.stringify(favorites);
return false;
};
return favIcon;
}
}
// ----
var max_per_tag = 5;
return function setup (tags, callback) {
loadAllPhotos(tags, max_per_tag, function (err, items) {
if (err) { return callback(err); }
each(items.map(renderPhoto), imageAppender('photos'));
callback();
});
};
}(jQuery));