/**
 * Picasa Webalbum Integration Library
 * This library was inspired and based on pwa by Dieter Raber (http://www.gnu.org/copyleft/lesser.html)
 * @name pwi-0.2.js
 * @author Jeroen Diderik - http://www.multiprof.nl
 * @version 0.4
 * @date October 21, 2008
 * @copyright (c) 2008 Jeroen Diderik(www.multiprof.nl)
 * @license Creative Commons Attribution-Share Alike 3.0 Netherlands License - http://creativecommons.org/licenses/by-sa/3.0/nl/
 * @example Visit http://www.multiprof.nl/ for more informations about this library
 */
 
//Global user variables to set (CHANGE TO WHAT YOU WANT IT TO BE)
var pwi_username = "anhsnhs";
var pwi_photosize = 800; //return maximum size picture (see for supported format:  http://code.google.com/apis/picasaweb/reference.html#Parameters)
var pwi_thumbsize = 160; //size thumb /cropped(see for supported format:  http://code.google.com/apis/picasaweb/reference.html#Parameters)
var pwi_albumcols =4; // distribute thumbs on main page over x collums
var pwi_cols = 5; // distribute thumbs on albumphotos page over x collums
var pwi_maxresults = 10000; //maximum of pictures on albumphotos page
var pwi_maxalbums = 99999; //maximum of pictures on albumphotos page
var pwi_container_div = "#container";

// NEW IN VERSION 0.4 !!!
var pwi_album_only = ""; //setup without a specific alnum, choose an album and take the number from the url between "#" and the last "/1"


//obsolete, untill this will be implemented
var pwi_show_albumtitles = true;
var pwi_show_phototitles = true;


// ****  DONT CHANGE BELOW UNLESS YOU KNOW WHAT YOU ARE DOING ****
//preset globals
var pwi_currAlbum = "";
var pwi_currAlbumTitle = "";
var pwi_currPhoto = "";
var pwi_page = "";
var pwi_si = 1;
var pwi_storage_albums;
var pwi_storage_photos;
var pwi_storage_photo;
var pwi_history = "";

// various functions
//get querytring (for later use to make deeplinks)
function readGet() {
	var _GET = new Array();
	var uriStr = window.location.href.replace(/&amp;/g, '&');
	var paraArr,
	paraSplit;
	if (uriStr.indexOf('?') > -1) {
		var uriArr = uriStr.split('?');
		var paraStr = uriArr[1];
	} else {
		return _GET;
	}
	if (paraStr.indexOf('&') > -1) {
		paraArr = paraStr.split('&');
	} else {
		paraArr = new Array(paraStr);
	}
	for (var i = 0; i < paraArr.length; i++) {
		paraArr[i] = paraArr[i].indexOf('=') > -1 ? paraArr[i] : paraArr[i] + '=';
		paraSplit = paraArr[i].split('=');
		_GET[paraSplit[0]] = decodeURI(paraSplit[1].replace(/\+/g, ' '));
	}
	return _GET;
};
var _GET = readGet();

//fast string concat function ( var.push(x), var.toString() )
function StringCat() {
	var sp;
	var ep;
	var l = 0;
	this.push = function(what) {
		if (typeof(sp) == 'undefined') {
			ep = new Array();
			sp = ep;
		} else {
			var oep = ep;
			ep = new Array();
			oep[1] = ep;
		}
		ep[0] = what; ++l;
	};
	this.toString = function() {
		if (l == 0) return;
		while (l > 1) {
			var ptr = sp;
			var nsp = new Array();
			var nep = nsp;
			var nl = 0;
			while (typeof(ptr) != 'undefined') {
				if (typeof(nep[0]) == 'undefined') {
					nep[0] = ptr[0]; ++nl;
				} else {
					if (typeof(ptr[0]) != 'undefined') nep[0] += ptr[0];
					nep[1] = new Array();
					nep = nep[1];
				};
				ptr = ptr[1];
			};
			sp = nsp;
			ep = nep;
			l = nl;
		};
		return sp[0];
	};
}

function formatDate(dt) {
	var months = new Array(12);
	months[0] = "January";
	months[1] = "February";
	months[2] = "March";
	months[3] = "April";
	months[4] = "May";
	months[5] = "June";
	months[6] = "July";
	months[7] = "August";
	months[8] = "September";
	months[9] = "October";
	months[10] = "November";
	months[11] = "December";
	var today = new Date(Number(dt));
	var year = today.getYear();
	if (year < 1000) {
		year += 1900;
	};
	return (months[(today.getMonth())] + " " + today.getDate() + ", " + year);
}

function formatDateTime(dt) {
	var today = new Date(Number(dt));
	var year = today.getYear();
	if (year < 1000) {
		year += 1900
	};
	return ((today.getMonth() + 1) + "-" + today.getDate() + "-" + year + " " + today.getHours() + ":" + (today.getMinutes() < 10 ? "0" + today.getMinutes() : today.getMinutes()));
}

var photoids = new Array();

function albums(j) { //returns the list of all albums for the user
	var scAlbums = new StringCat();
	
	scAlbums.push("<h1 class=\"pagetitle\" style=\"text-align:center;\"><img src=\"/images/icon/photocamera.png\">Photo Albums</h1><center><table><tr>");
	for (var i = 0; i < j.feed.entry.length; i++) {
		var id_base = j.feed.entry[i].gphoto$id.$t;
		var album_date = formatDate(j.feed.entry[i].gphoto$timestamp.$t);
		scAlbums.push("<td valign=top align=center><a class='standard' href='javascript:void(0)' onclick='javascript:$.historyLoad(\"" + id_base + "/1\")'><img src='" + j.feed.entry[i].media$group.media$thumbnail[0].url + "?imgmax=" + pwi_thumbsize + "&crop=1' class='pwimages' /></a>");
		//edited to change from # Photos on a separate line to Album Name ([#photos])
		scAlbums.push("<br><a class='thumbtitle' href='javascript:void(0)' onclick='javascript:$.historyLoad(\"" + id_base + "/1\")'>" + j.feed.entry[i].title.$t + " (" + j.feed.entry[i].gphoto$numphotos.$t + ")</a><br/><span class='date'><b>" + album_date + "</b></span></td>");
		if (i % pwi_albumcols == (pwi_albumcols - 1)) {
			scAlbums.push("</tr><tr><td colspan='" + pwi_albumcols + "'></td></tr><tr>");
		}
	}
	scAlbums.push("</tr></table></center>");
	pwi_storage_albums = scAlbums.toString();
	
	if(pwi_album_only.length > 0){
			getAlbum(pwi_album_only,1);
	}else{
		show(false, pwi_storage_albums);
	}
}

function album(j) { //returns all photos in a specific album
	var scPhotos = new StringCat();
	 //get the number of photos in the album
	var np = j.feed.openSearch$totalResults.$t;
	var loc = j.feed.gphoto$location.$t;
	var desc = makehtml(j.feed.subtitle.$t);
	var album_date = formatDate(j.feed.gphoto$timestamp.$t);
	var item_plural = "s";
	if (np == "1") {
		item_plural = "";
	}
	var len = j.feed.entry.length;
	pwi_currAlbumTitle = j.feed.title.$t;

	if(!pwi_album_only.length>0){
		scPhotos.push("<div id='albums_top'><a class='standard' href='javascript:void(0)' onclick='$.historyLoad(\"\");'>Go Back to Albums</a> > ");
	};
	scPhotos.push(j.feed.title.$t);
	//scPhotos.push("(" + np + " photo" + item_plural + ", " + album_date + ", " + loc + ")");
	//scPhotos.push("<div style='margin-left:3px'><b>" + desc + "</b></div>");
	//scPhotos.push(" > <a href='http://picasaweb.google.com/" + pwi_username + "/" + j.feed.gphoto$name.$t + "/photo#s" + j.feed.entry[0].gphoto$id.$t + "' rel='gb_page_fs[]' target='_new'>View as slideshow</a>&nbsp;&nbsp;&nbsp;");

	//Currently paging navigation is disabled!
	 //create paging navigation
	pageCount = (np / pwi_maxresults);
	var ppage = "&#9664;previous | ",
	npage //= "| next&#9654;";
	//if (pwi_page > 1) {
	//	ppage = "<a href='javascript:void(0)' onclick='$.historyLoad(\"" + pwi_currAlbum + "/" + (parseInt(pwi_page) - 1) + "\")'>&#9664;previous</a> | "
	//};
	//if (pwi_page < pageCount) {
	//	npage = "| <a href='javascript:void(0)' onclick='$.historyLoad(\"" + pwi_currAlbum + "/" + (parseInt(pwi_page) + 1) + "\")'>next&#9654;</a>"
	//};

	var navRow = new StringCat();
	//navRow.push(ppage + "Page ");
	//for (var i = 1; i < pageCount + 1; i++) {
	//	if (i == pwi_page) {
	//		navRow.push("<b>[" + (i) + "] </b> ");
	//	} else {
	//		navRow.push("<a href='javascript:void(0)' onclick='$.historyLoad(\"" + pwi_currAlbum + "/" + i + "\")'>" + (i) + " </a>");
	//	};
	//};
	navRow.push(/*npage + */"</div><div class=\"gallery\"><ul>");
	scPhotos.push(navRow.toString());
	for (var i = 0; i < len; i++) {
		var img_base = j.feed.entry[i].content.src;
		var id_base = j.feed.entry[i].gphoto$id.$t;
		var desc = makehtml(j.feed.entry[i].summary.$t);

		var photoDate = j.feed.entry[i].exif$tags.exif$time ? formatDateTime(j.feed.entry[i].exif$tags.exif$time.$t) : j.feed.entry[i].published.$t;
		//desc = "<p style=\"font-size: 12pt;text-align:center;\">" + desc + "</p>";
		scPhotos.push("<li><span class=\"hotspot\" onmouseover=\"tooltip.show('"+ desc+"');\" onmouseout=\"tooltip.hide();\"><a href='" + img_base + "?imgmax=" + pwi_photosize + "&crop=0' class='lightbox' alt='"+desc+"'><img src='" + img_base + "?imgmax=" + pwi_thumbsize + "&crop=1' class='pwimages'/></a></span>");
		
		/***********************************************
		next line modified to get rid of pesky date, we just want thumbnails!, no extra info!
		original: scPhotos.push("<small>" + photoDate + "</small></center></td>"); 
		***********************************************/
		
		scPhotos.push("</li>");
		if (i % pwi_cols == (pwi_cols - 1)) {
			//scPhotos.push("</tr><tr>");
		}
	}
	//disable nav bar
	//scPhotos.push("</ul><div id=\"albums_top\">"+navRow+"</div>");
	pwi_storage_photos = scPhotos.toString();
	show(false, pwi_storage_photos);
}

/*fixes pesky bug when single quotes are used and not properly escaped*/

function makehtml(text) {
/*add the "g" after / / to replace every instance, not only the first one. g = global expression*/
var textneu = text.replace(/&/g,"&amp;");
textneu = textneu.replace(/\'/g,"&#146;");
textneu = textneu.replace(/</g,"&lt;");
textneu = textneu.replace(/>/g,"&gt;");
textneu = textneu.replace(/\r\n/g,"<br>");
textneu = textneu.replace(/\n/g,"<br>");
textneu = textneu.replace(/\r/g,"<br>");
return(textneu);
}

function getAlbums() {
	if (pwi_storage_albums) {
		show(false, pwi_storage_albums);
	} else {
		show(true, '');
		var url = 'http://picasaweb.google.com/data/feed/api/user/' + pwi_username + '?category=album&max-results=' + pwi_maxalbums + '&access=public&alt=json';
		$.getJSON(url, 'callback=?', albums);
	}
}

function getAlbum(albumid, newPage) {
	if (albumid != pwi_currAlbum || pwi_page != newPage) {
		pwi_page = newPage;
		pwi_currAlbum = albumid;
		pwi_si = ((pwi_page - 1) * pwi_maxresults) + 1;
		var url = 'http://picasaweb.google.com/data/feed/api/user/' + pwi_username + '/albumid/' + albumid + '?category=photo&max-results=' + pwi_maxresults + '&start-index=' + pwi_si + '&alt=json';
		show(true, '');
		$.getJSON(url, 'callback=?', album);
	} else {
		show(false, pwi_storage_photos);
	}
}

function fromHistory(hash) {
	if (hash) {
		var a,p;
		if (hash.indexOf("/") > 0) {
			a = hash.split("/")[0];
			p = hash.split("/")[1];
			getAlbum(a, p);
		}
	} else {
		getAlbums();
	}
}

function show(loading, data) {
	if (loading) {
		$(pwi_container_div).fadeOut('slow');
		$("#maincontent").block("<img src=\"http://www.anhs-nhs.com/pwi/images/lightbox-ico-loading.gif\"> <span style=\"color:#009999;font-size:14pt; font-weight:bold;\">Loading ...</span>", {
			border: '5px solid #009999'
		});
	} else {
		$("#maincontent").unblock();
		$(pwi_container_div).html(data).fadeIn('fast');
		$('a.lightbox').lightBox();
	}
}

$(document).ready(function() {
	if(pwi_username == "your_picasa_username"){
		alert('Open the pwi-0.2.js and change content \nof the variable pwi_username in the top of the file\nto your Picasa Webalbum name');
	}else{
		$.extend($.blockUI.defaults.overlayCSS, {
			backgroundColor: '#000'
		});
		$.ajaxSetup({
			cache: true
		});
			$.historyInit(fromHistory);
	}
});


//$Update: May 10, 2007$
//$Update: July 31, 2007, Jeroen Diderik$
//$Update: September 23, 2007, Jeroen Diderik, Mootools conversion$
//$Update: November 19, 2007, Jeroen Diderik, PWI vars update$
//$Update: March 25, 2008, Jeroen Diderik, rewrite to replace MOOTools with  jQuery$
//$Update: April 05, 2008, Jeroen Diderik, rewrite for early release$
//$update: October 21, 2008, Jeroen Diderik, added ALBUM_ONLY option


/*
TOD0: photo details
function getPhoto(photoid){
	pwi_currPhoto = photoid;
	url = 'http://picasaweb.google.com/data/entry/api/user/'+pwi_username+'/albumid/'+pwi_currAlbum+'/photoid/'+photoid+'?alt=json';
	show(true,'');
	$.getJSON(url, 'callback=?',photo);
}
*/