1/**
2 * Picasa Webalbum Integration jQuery plugin
3 * This library was inspired aon pwa by Dieter Raber
4 * @name jquery.pwi.js
5 * @author Jeroen Diderik - http://www.multiprof.nl/
6 * @revision 1.1.13
7 * @date November 02, 2009
8 * @copyright (c) 2009 Jeroen Diderik(www.multiprof.nl)
9 * @license Creative Commons Attribution-Share Alike 3.0 Netherlands License - http://creativecommons.org/licenses/by-sa/3.0/nl/
10 * @Visit http://pwi.googlecode.com/ for more informations, duscussions etc about this library
11 */
12(function ($) {
13	var elem, opts = {};
14	$.fn.pwi = function (opts) {
15		var $self, settings = {};
16		opts = $.extend({},	$.fn.pwi.defaults, opts);
17		elem = this;
18		function _initialize() {
19			settings = opts;
20			ts = new Date().getTime();
21			settings.id = ts;
22			$self = $("<div id='pwi_" + ts + "'/>").appendTo(elem);
23			$self.addClass('pwi_container');
24			_start();
25			return false;
26		}
27		function _start() {
28			if (settings.username === '') {
29				alert('Make sure you specify at least your username.' + '\n' + 'See http://pwi.googlecode.com for more info');
30				return;
31			}
32			switch (settings.mode) {
33			case 'latest':
34				getLatest();
35				break;
36			case 'album':
37				getAlbum();
38				break;
39			case 'keyword':
40				getAlbum();
41				break;
42			default:
43				getAlbums();
44				break;
45			}
46		}
47		function formatDate($dt) {
48			var $today = new Date(Number($dt)),
49			$year = $today.getUTCFullYear();
50			if ($year < 1000) {
51				$year += 1900;
52			}
53			return (settings.months[($today.getUTCMonth())] + " " + $today.getUTCDate() + ", " + $year);
54		}
55		function formatDateTime($dt) {
56			var $today = new Date(Number($dt));
57			$year = $today.getUTCFullYear();
58			if ($year < 1000) {
59				$year += 1900;
60			}
61			if($today == "Invalid Date"){
62				return $dt;
63			}else{
64				return ($today.getUTCDate() + "-" + ($today.getUTCMonth() + 1) + "-" + $year + " " + $today.getUTCHours() + ":" + ($today.getUTCMinutes() < 10 ? "0" + $today.getUTCMinutes() : $today.getUTCMinutes()));
65			}
66		}
67
68		function photo(photo){
69				var $html, $dt, $d, $img_base = photo.content.src,
70				$id_base = photo.gphoto$id.$t,
71				$c = (photo.summary ? photo.summary.$t : "");
72				if(settings.showPhotoDate){
73					if( photo.exif$tags.exif$time ){
74						$dt = formatDateTime(photo.exif$tags.exif$time.$t);
75					}else if( photo.gphoto$timestamp ){
76						$dt = formatDateTime(photo.gphoto$timestamp.$t);
77					}else{
78						$dt = formatDateTime(photo.published.$t);
79					}
80				}
81				$d = $dt + " " + $c.replace(new RegExp("'", "g"), "&#39;");
82				$html = $("<div class='pwi_photo' style='height:" + (settings.thumbSize + 1) + "px;cursor: pointer;'/>");
83				$html.append("<a href='" + $img_base + "?imgmax=" + settings.photoSize + "' rel='lb-" + settings.username + "' title='" + $d + "'><img src='" + $img_base + "?imgmax=" + settings.thumbSize + "&crop=" + settings.thumbCrop + "'/></a>");
84				if(settings.showPhotoDownload){$c += "download";}
85				if (settings.showPhotoCaption){ $html.append("<br/>" + $c);}
86				return $html;
87
88		}
89
90		function albums(j) {
91			var $scAlbums = $("<div/>"), i=0;
92			while(i < settings.albumMaxResults && i< j.feed.entry.length){
93				var $id_base = j.feed.entry[i].gphoto$name.$t,
94				$album_date = formatDate(j.feed.entry[i].gphoto$timestamp.$t),
95				$thumb = j.feed.entry[i].media$group.media$thumbnail[0].url.replace(new RegExp("/s160-c/", "g"), "/");
96				if ($.inArray($id_base, settings.albums) > -1 || settings.albums.length === 0) {
97					$scAlbum = $("<div class='pwi_album'/>");
98					$scAlbum.bind('click.pwi',  $id_base, function(e){
99						e.stopPropagation();
100						settings.page = 1;
101						settings.album = e.data;
102						if(typeof(settings.onclickAlbumThumb) === "function"){
103							settings.onclickAlbumThumb(e, settings);
104							return false;
105						}else{
106							getAlbum();
107							return false;
108						}
109					});
110					$scAlbum.append("<img src='" + $thumb + "?imgmax=" + settings.albumThumbSize + "&crop=" + settings.albumCrop + "'/>");
111					settings.showAlbumTitles ? $scAlbum.append("<br/>" + j.feed.entry[i].title.$t + "<br/>" + (settings.showAlbumdate ? $album_date : "") + (settings.showAlbumPhotoCount ? "&nbsp;&nbsp;&nbsp;&nbsp;" + j.feed.entry[i].gphoto$numphotos.$t + " " + settings.labels.photos : "")) : false;
112					$scAlbums.append($scAlbum);
113				}
114				i++;
115			}
116			$scAlbums.append("<div style='clear: both;height:0px;'/>");
117			settings.albumstore = j;
118			show(false, $scAlbums);
119		}
120
121		function album(j) {
122			var $scPhotos, $scPhotosDesc,
123			$np = j.feed.openSearch$totalResults.$t,
124			$loc = j.feed.gphoto$location === undefined ? "" : j.feed.gphoto$location.$t,
125			$ad = j.feed.subtitle === undefined ? "" : j.feed.subtitle.$t,
126			$album_date = formatDate(j.feed.gphoto$timestamp === undefined ? '' : j.feed.gphoto$timestamp.$t),
127			$item_plural = ($np == "1") ? false : true;
128
129			settings.albumTitle = (j.feed.title === "undefined" || settings.albumTitle.length > 0) ? settings.albumTitle : j.feed.title.$t;
130			$scPhotos = $("<div/>");
131			$scPhotosDesc = $("<div class='pwi_album_description'/>");
132			if (settings.mode != 'album') {
133				var tmp = $("<div class='pwi_album_backlink'>" + settings.labels.albums + "</div>").bind('click.pwi', function (e) {
134					e.stopPropagation();
135					getAlbums();
136					return false;
137				});
138				$scPhotosDesc.append(tmp);
139			}
140			if (settings.showAlbumDescription) {
141				$scPhotosDesc.append("<div class='title'>" + settings.albumTitle + "</div>");
142				$scPhotosDesc.append("<div class='details'>" + $np + " " + ($item_plural ? settings.labels.photos : settings.labels.photo) + (settings.showAlbumdate ? ", " + $album_date : "") + (settings.showAlbumLocation && $loc ? ", " + $loc : "") + "</div>");
143				$scPhotosDesc.append("<div class='description'>" + $ad + "</div>");
144				if (settings.showSlideshowLink) {
145					if(settings.mode === 'keyword'){
146						//alert("currently not supported");
147					}else{
148						$scPhotosDesc.append("<div><a href='http://picasaweb.google.com/" + settings.username + "/" + j.feed.gphoto$name.$t + "" + ((settings.authKey != "") ? "?authkey=" + settings.authKey : "") + "#slideshow/" + j.feed.entry[0].gphoto$id.$t + "' rel='gb_page_fs[]' target='_new' class='sslink'>" + settings.labels.slideshow + "</a></div>");
149					}
150				}
151			}
152			$scPhotos.append($scPhotosDesc);
153
154			if ($np > settings.maxResults) {
155				$pageCount = ($np / settings.maxResults);
156				var $ppage = $("<div class='pwi_prevpage'/>").text(settings.labels.prev),
157				$npage = $("<div class='pwi_nextpage'/>").text(settings.labels.next),
158				$navRow = $("<div class='pwi_pager'/>");
159				if (settings.page > 1) {
160					$ppage.addClass('link').bind('click.pwi', function (e) {
161						e.stopPropagation();
162						settings.page = (parseInt(settings.page) - 1);
163						getAlbum();
164						return false;
165					});
166				}
167				$navRow.append($ppage);
168				for (var p = 1; p < $pageCount + 1; p++) {
169					if (p == settings.page) {
170						tmp = "<div class='pwi_pager_current'>" + p + "</div> ";
171					} else {
172						tmp = $("<div class='pwi_pager_page'>" + p + "</div>").bind('click.pwi', p, function (e) {
173							e.stopPropagation();
174							settings.page = e.data;
175							getAlbum();
176							return false
177						});
178					}
179					$navRow.append(tmp);
180				}
181				if (settings.page < $pageCount) {
182					$npage.addClass('link').bind('click.pwi', function (e) {
183						e.stopPropagation();
184						settings.page = (parseInt(settings.page) + 1);
185						getAlbum();
186						return false
187					});
188				}
189				$navRow.append($npage);
190				$scPhotos.append($navRow);
191			}
192			var i = ((settings.page-1)*settings.maxResults);
193			while(i < (settings.maxResults*settings.page) && i < $np) {
194				var $scPhoto = photo(j.feed.entry[i]);
195				$scPhotos.append($scPhoto);
196				i++;
197			}
198			$scPhotos.append($navRow);
199			$scPhotos.append("<div style='clear: both;height:0px;'/>");
200			//settings.photostore = $scPhotos;
201			settings.photostore[settings.album] = j;
202			var $s = $(".pwi_photo", $scPhotos).css(settings.thumbCss);
203			if (typeof(settings.popupExt) === "function") {
204				settings.popupExt($s.find("a[rel='lb-" + settings.username + "']"));
205			} else if (typeof(settings.onclickThumb) === "function") {
206				$s.find("a[rel='lb-" + settings.username + "']").bind('click.pwi', clickThumb);
207			} else if (typeof(settings.onclickThumb) != "function" && $.slimbox) {
208				$s.find("a[rel='lb-" + settings.username + "']").slimbox(settings.slimbox_config);
209			}
210			show(false, $scPhotos);
211		}
212
213		function latest(j) {
214			var $scPhotos = $("<div/>"),
215			$len = j.feed ? j.feed.entry.length : 0,
216			i = 0;
217			while (i < settings.maxResults && i < $len) {
218				var $scPhoto = photo(j.feed.entry[i]);
219				$scPhotos.append($scPhoto);
220				i++;
221			}
222			$scPhotos.append("<div style='clear: both;height:0px;'> </div>");
223			var $s = $("div.pwi_photo", $scPhotos).css(settings.thumbCss);
224			if (typeof(settings.popupExt) === "function") {
225				settings.popupExt($s.find("a[rel='lb-" + settings.username + "']"));
226			} else if (typeof(settings.onclickThumb) === "function") {
227				$s.find("a[rel='lb-" + settings.username + "']").bind('click', clickThumb);
228			} else if (typeof(settings.onclickThumb) != "function" && $.slimbox) {
229				$s.find("a[rel='lb-" + settings.username + "']").slimbox(settings.slimbox_config);
230			}
231			show(false, $scPhotos);
232		}
233
234		function clickAlbumThumb(ref){
235			settings.onclickAlbumThumb(ref);
236			return false;
237		}
238		function clickThumb() {
239			settings.onclickThumb.call(this);
240			return false;
241		}
242		function getAlbums() {
243			if (settings.albumstore.feed) {
244				albums(settings.albumstore);
245			} else {
246				show(true, '');
247				var $url = 'http://picasaweb.google.com/data/feed/api/user/' + settings.username + '?kind=album&access=' + settings.albumTypes + '&alt=json';
248				$.getJSON($url, 'callback=?', albums);
249			}
250			return $self;
251		}
252		function getAlbum() {
253			if (settings.photostore[settings.album]) {
254				album(settings.photostore[settings.album]);
255			} else {
256				var $si = ((settings.page - 1) * settings.maxResults) + 1;
257				if(settings.mode === 'keyword'){
258					var $url = 'http://picasaweb.google.com/data/feed/api/user/' +settings.username + '?alt=json&kind=photo&tag=' + settings.keyword +'&max-results=' + settings.maxResults + '&start-index=' + $si +((settings.authKey != "") ? "&authkey=" + settings.authKey : "");
259				}else{
260					var $url = 'http://picasaweb.google.com/data/feed/api/user/' + settings.username + '/album/' + settings.album + '?kind=photo&alt=json' + ((settings.authKey != "") ? "&authkey=" + settings.authKey : "");
261				}
262				show(true, '');
263				$.getJSON($url, 'callback=?', album);
264			}
265			return $self;
266		}
267		function getLatest() {
268			show(true, '');
269			var $url = 'http://picasaweb.google.com/data/feed/api/user/' + settings.username + (settings.album != "" ? '/album/' + settings.album : '') + '?kind=photo&max-results='+settings.maxResults+'&alt=json&q=' + ((settings.authKey != "") ? "&authkey=" + settings.authKey : "");
270			$.getJSON($url, 'callback=?', latest);
271			return $self;
272		}
273		function show(loading, data) {
274			if (loading) {
275				document.body.style.cursor = "wait";
276				//if ($.blockUI){ $self.block(settings.blockUIConfig);}
277			} else {
278				document.body.style.cursor = "default";
279				//if ($.blockUI){ $self.unblock(); }
280				$self.html(data);
281			}
282		}
283		_initialize();
284	}
285	$.fn.pwi.defaults = {
286		mode: 'albums',
287		username: '',
288		album: "",
289		authKey: "",
290		albums: [],
291		albumCrop: 1,
292		albumTitle: "",
293		albumThumbSize: 160,
294		albumMaxResults: 999,
295		albumStartIndex: 1,
296		albumTypes: "public",
297		page: 1,
298		photoSize: 800,
299		maxResults: 50,
300		thumbSize: 72,
301		thumbCrop: 0,
302		thumbCss: {
303			'margin': '5px'
304		},
305		onclickThumb: "",
306		onclickAlbumThumb: "",
307		popupExt: "",
308		showAlbumTitles: true,
309		showAlbumdate: true,
310		showAlbumPhotoCount: true,
311		showAlbumDescription: true,
312		showAlbumLocation: true,
313		showSlideshowLink: true,
314		showPhotoCaption: false,
315		showPhotoDownload: true,
316		showPhotoDate: true,
317		labels: {
318			photo: "photo",
319			photos: "photos",
320			albums: "Back to albums",
321			slideshow: "Display slideshow",
322			loading: "PWI fetching data...",
323			page: "Page",
324			prev: "Previous",
325			next: "Next",
326			devider: "|"
327		},
328		months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
329		slimbox_config: {
330			loop: false,
331			overlayOpacity: 0.6,
332			overlayFadeDuration: 400,
333			resizeDuration: 400,
334			resizeEasing: "swing",
335			initialWidth: 250,
336			initlaHeight: 250,
337			imageFadeDuration: 400,
338			captionAnimationDuration: 400,
339			counterText: "{x}/{y}",
340			closeKeys: [27, 88, 67, 70],
341			prevKeys: [37, 80],
342			nextKeys: [39, 83]
343		},
344		blockUIConfig: {
345			message: "<div class='lbLoading pwi_loader'>loading...</div>",
346			css: "pwi_loader"
347		},
348		albumstore: {},
349		photostore: {},
350		token: ""
351	}
352})(jQuery);