/*
 * @author      Dieter Raber <dieter@dieterraber.net>
 * @copyright   2004-12-27
 * @version     1.0
 * @license     http://www.gnu.org/copyleft/lesser.html
---------------------------------------------------------------------
 * @adaptor      Jeroen Diderik <jdiderik@gmail.com>
 * @source       http://www.jdee.nl/
 * @copyright   2007-08-01
 * @version     1.5
*/
//User variables to set
var photosize = 512; //return maximum size picture (see for supported format:  http://code.google.com/apis/picasaweb/reference.html#Parameters)
var thumbsize = 144; //size thumb /cropped(see for supported format:  http://code.google.com/apis/picasaweb/reference.html#Parameters)
var albumcols = 3; // distribute thumbs on main page over x collums
var cols = 3; // distribute thumbs on albumphotos page over x collums
var maxresults = 15; //maximum of pictures on albumphotos page
var showExif = true; //set to true to show Exif info on the picture page

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();

if(!photosize){
	photosize = 512;
}
var si = _GET['si'];
if(!si){
	si = 1
}
else{
	si=Number(si)
};

function $(a){
	document.write(a);
}

function fraction(decimal){
	var num;
	var whole;
	var z;
	if(!decimal){
		decimal=this;
	}
	whole = String(decimal).split('.')[0];
	decimal = parseFloat("."+String(decimal).split('.')[1]);
	num = "1";
	for(z=0; z<String(decimal).length-2; z++){
		num += "0";
	}
	decimal = parseInt(decimal*num);
	num = parseInt(num);
	for(z=2; z<decimal+1; z++){
		if(decimal%z==0 && num%z==0){
			decimal = decimal/z;
			num = num/z;
			z=2;
		}
	}
	return ((whole==0)?"" : whole+" ")+decimal+"/"+num;
}

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.getDate() + "-" + (today.getMonth()+1) + "-" + year + " " + today.getHours() + ":" + (today.getMinutes()<10 ? "0"+today.getMinutes() : today.getMinutes()) );
}

function picasaweb(j){ //returns the list of all albums for the user
	if(j.feed.entry){
		$("<table><tr>");
		for(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);
	
			$("<td valign='top' align='center'><a href='?page="+_GET['page']+"&albumid="+id_base+"'><img src='"+j.feed.entry[i].media$group.media$thumbnail[0].url+"?imgmax="+thumbsize+"&crop=1' alt='"+ j.feed.entry[i].title.$t + "' class='imgShadow'/></a>");
			$("<div class='albumCaption'><a href='?page="+_GET['page']+"&albumid="+id_base+"'>"+ j.feed.entry[i].title.$t +"</a><br/>"+album_date+"<br/>"+j.feed.entry[i].gphoto$numphotos.$t+" photos</div></td>");
			if (i % albumcols == (albumcols-1)) {
				$("</tr><tr><td colspan='"+albumcols+"'><hr/></td></tr><tr>");
			}
		}
		$("</tr></table><div id='exifInfo'></div>");
	}
	else{
		$("<p class='contentTxt'>There are currently no photos in the photo gallery.</p>");
	}
}

function albums(j){  //returns all photos in a specific album

	//get the number of photos in the album
	var np = j.feed.openSearch$totalResults.$t;
	var loc = j.feed.gphoto$location.$t;
	var desc = j.feed.subtitle.$t;
	var album_date = formatDate(j.feed.gphoto$timestamp.$t);
	var item_plural = "s";
	if (np == "1") { item_plural = ""; }
	var photoids = new Array();
	var len = j.feed.entry.length;

	$("<table border='0'><tr>");
	$("<tr><td colspan='"+cols+"'>");
	$("<p class='albumTitle'>"+ j.feed.title.$t +"</p>");
	$("<p class='albumInfo'>"+np+" photo"+item_plural+", "+album_date+", "+loc+"</p>");
	$("<p class='albumDesc'>"+desc+"</p>");
	$("<a class='albumSlideshow' href='http://picasaweb.google.com/"+username+"/"+j.feed.gphoto$name.$t+"/photo#s"+j.feed.entry[0].gphoto$id.$t+"' rel='gb_page_center[520,400]' target='_new' title='View as a slideshow'>View as a slideshow</a>");
	$("</td></tr><tr>");

	for(i=0;i<len;i++){
		// get the list of all photos referenced in the album and display;
		// also stored in an array (photoids) for navigation in the photo view (passed via the URL)
		var id_base = j.feed.entry[i].gphoto$id.$t;
		photoids[i]=id_base; //must be pre-loaded before the URLs are generated. That's why we need to run the loop twice.
	}
 
	//create paging navigation
	pageCount = (np/maxresults);
	var ppage = "previous | ", npage = "| next";
	if(si>1){
		ppage = "<a href='?page="+_GET['page']+"&albumid="+_GET['albumid']+"&si="+(si-maxresults)+"' title='Previous page'>previous</a> | "
	};
	if((si+maxresults)<np){
		npage = "| <a href='?page="+_GET['page']+"&albumid="+_GET['albumid']+"&si="+(si+maxresults)+"' title='Next page'>next</a>"
	};

	var navRow = "<tr><td colspan='"+cols+"'><p class='albumNav'>" + ppage + "Page ";
	for(i=0;i<=pageCount;i++){
		if(si == ((i*maxresults)+1)){
			navRow += "<b>["+(i+1)+"]</b> ";
		}
		else{
			navRow += "<a href='?page="+_GET['page']+"&albumid="+_GET['albumid']+"&si="+((i*maxresults)+1)+"' title='Goto page " + (i+1) + "'>"+(i+1)+"</a> "
		};
	};
	navRow += npage + "</p></td></tr>"
	$(navRow); 
	for(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 photoDate = j.feed.entry[i].exif$tags.exif$time ? formatDateTime(j.feed.entry[i].exif$tags.exif$time.$t) : "";
		photoids[i]=id_base;
		if (i>0){ var prev = j.feed.entry[i-1].gphoto$id.$t; }
		if (i<len-1){ var next = j.feed.entry[i+1].gphoto$id.$t; }

		//photo page
		$("<td valign='top'><a href='?page="+_GET['page']+"&albumid="+_GET['albumid']+"&photoid="+id_base+"&galleryname={"+j.feed.title.$t+"}&np="+np+"&prev="+prev+"&next="+next+"&photoids="+photoids+"&si="+si+"'><img src='"+img_base+"?imgmax="+thumbsize+"&crop=1' alt='"+ j.feed.entry[i].title.$t + "' class='imgShadow'/></a>");
  
		if (i % cols == (cols-1)) {$("</tr><tr><td colspan='"+cols+"'><hr/></td></tr><tr>");}
	}
	$("</tr>");
	$(navRow); 
	$("</table><div id='exifInfo'></div>");
}

function photo(j){//returns exactly one photo

	var img_title = j.entry.title.$t;

	//get the dimensions of the photo we're grabbing; if it's smaller than our max width, there's no need to scale it up.
	var img_width = j.entry.media$group.media$content[0].width;
	var img_height = j.entry.media$group.media$content[0].height;
	var img_base = j.entry.media$group.media$content[0].url;
	
	var photo_id = _GET['photoid'];
	var album_id = _GET['albumid'];
	var my_next = _GET['next'];
	var my_prev = _GET['prev'];
	var my_photoids = _GET['photoids'];
	var my_numpics = _GET['np'];
	var my_galleryname = _GET['galleryname'];
	var my_fixed_galleryname = my_galleryname.slice(1, my_galleryname.length-1);
	var album_base_path = window.location.protocol + "//" + window.location.host+window.location.pathname +"?page="+_GET['page']+"&si="+si+"&albumid="+ _GET['albumid'];

	//Collect Exif info if available
	if(j.entry.exif$tags){
		var photo_exif = "<table><tr><td colspan='2' class='exifHeader'>Exchangeable Image File Data (Exif)</td></tr>";
		var title;
		var val;
		var skip;
		for(var exif in j.entry.exif$tags){
			skip=false;
			switch(exif){
				case "exif$fstop":
					title="Aperture";
					val="f/"+j.entry.exif$tags[exif].$t;
					break;
					
				case "exif$focallength":
					title="Focal Length";
					val=Math.round(j.entry.exif$tags[exif].$t*Math.pow(10,1))/Math.pow(10,1)+"mm";
					break;
				
				case "exif$flash":
					title="Flash Used";
					if(j.entry.exif$tags[exif].$t=="true") {
						val="Yes";
					}
					else {
						val="No";
					}
					break;
					
				case "exif$make":
					title="Make";
					val=j.entry.exif$tags[exif].$t;
					break;
				
				case "exif$model":
					title="Model";
					val=j.entry.exif$tags[exif].$t;
					break;
					
				case "exif$exposure":
					title="Exposure";
					switch(parseFloat(j.entry.exif$tags[exif].$t)){
						case 0.016666668:
							val="1/60 sec";
							break;
						
						default:
							val=fraction(parseFloat(j.entry.exif$tags[exif].$t))+" sec";
							break;
					}
					break;
					
				case "exif$time":
					title="Date and Time";
					var theDate=new Date(parseFloat(j.entry.exif$tags[exif].$t));
					var minutes=theDate.getMinutes()+theDate.getTimezoneOffset();
					theDate.setMinutes(minutes);					
					val=theDate.toLocaleString();
					break;
				
				case "exif$imageUniqueID":
					skip=true;
					break;
				
				default:
					title=exif.replace("exif$","");
					val=j.entry.exif$tags[exif].$t;
					break;
			}
			if(!skip) photo_exif += "<tr><td class='exifTitle'>"+title+":</td><td class='exifValue'>"+val+"</td></tr>";
		}
		photo_exif += "</table>";
	}

	// Get the filename for display in the breadcrumbs
	var LastSlash = 0;
	var img_filename = img_title;
	var photo_array = my_photoids.split(",");

	//find preceding two and following two pictures in the array; used for the navigation arrows.
	//the arrows are already linked to the previous and next pics, which were passed in with the URL.
	//however, we need the ones that are two behind and two ahead so that we can pass that info along when we link to another photo.
	//"pretty sneaky, sis."
	for(i=0;i<photo_array.length;i++){
		if (photo_array[i]==photo_id){
			var p2 = photo_array[i-2]; //ID of the picture two behind this one
			var p1 = photo_array[i-1]; //ID of the picture one behind this one; if null, we're at the beginning of the album
			var current_index = i + 1; //this is the count of the current photo
			var n1 = photo_array[i+1]; //ID of the picture one ahead of this one; if null, we're at the end of the album
			var n2 = photo_array[i+2]; //ID of the picture two ahead of this one
		}
	}
	//these will be passed along if we move to the next or previous photo
	var prev = album_base_path + "&photoid=" + p1 + "&np=" + my_numpics + "&galleryname=" + my_galleryname + "&next="+photo_id+ "&prev="+p2+"&photoids="+my_photoids;
	var next = album_base_path + "&photoid=" + n1 + "&np=" + my_numpics + "&galleryname=" + my_galleryname + "&prev="+photo_id+ "&next="+n2+"&photoids="+my_photoids;

	//Display the breadcrumbs
	$("<p class='imgTitle'>" + img_filename + " (" + (current_index+si-1) + " of " + my_numpics + ")</p>");


	if (p1 == null){ var prev = album_base_path } //we're at the first picture in the album; going back takes us to the album index
	if (n1 == null){ var next = album_base_path } //we're at the last picture in the album; going forward takes us to the album index

	//the navigation panel: back, home, and next.
	$("<p class='imgNav'><a href='"+prev+"' title='Previous photo'>previous photo</a> | <a href='"+album_base_path+"' title='Return to the " + my_fixed_galleryname.replace("'","") + " album'>" + my_fixed_galleryname + " album</a> | <a href='"+next+"' title='Next photo'>next photo</a></p>");

	if (img_width < photosize){ display_width = img_width; } //don't scale up photos that are narrower than our max width; disable this to set all photos to max width

	//at long last, displayed the image and its description. photos larger than max_width are scaled down; smaller ones are left alone
	$("<img class='imgShadow center' id='picture' alt='" + img_filename + "' src='"+img_base+"?imgmax="+photosize+"'/>");
	$("<p class='imgDesc'>"+j.entry.media$group.media$description.$t+"</p>");
	if(showExif){
		$("<a class='exifLink' href=\"javascript:toggleLayer('exifInfo');\" title='View additional information'>View additional information</a>")
		$("<div id='exifInfo'>" + photo_exif + "</div>");
	}
}

if(_GET['photoid']&&_GET['albumid']){
	$('<script type="text/javascript" src="http://picasaweb.google.com/data/entry/api/user/'+username+'/albumid/'+_GET['albumid']+'/photoid/'+_GET['photoid']+'?alt=json&callback=photo"></script>');//photo
}else if(_GET['albumid']&&!_GET['photoid']){
	$('<script type="text/javascript" src="http://picasaweb.google.com/data/feed/api/user/'+username+'/albumid/'+_GET['albumid']+'?category=photo&alt=json&callback=albums&max-results='+maxresults+'&start-index='+si+'"></script>');//albums
}else{
	$('<script type="text/javascript" src="http://picasaweb.google.com/data/feed/api/user/'+username+'?category=album&alt=json&callback=picasaweb&access=public"></script>');//picasaweb
}
//$Update: May 10, 2007$
//$Update: July 31, 2007, Jeroen Diderik$
//$Update: Januari 31, 2008, Jeroen Diderik$