/**
 * Picasa Webalbum Integration Library
 * This library was inspired and based on pwa by Dieter Raber (http://www.gnu.org/copyleft/lesser.html)
 * @name pwi-1.0.js
 * @author Jeroen Diderik - http://www.multiprof.nl/
 * @version 1.0
 * @date March 27, 2009
 * @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://pwi.googlecode.com/ for more informations, duscussions etc about this library
 */

i=0;
configAlbumData = new Array();

configAlbumData_jsonData_rel = new Array();

tmp = new Array();
tmp["url"]="http://picasaweb.google.dk/data/feed/base/user/Mathiasrw/album/BafoFest?alt=json&kind=photo&authkey=Gv1sRgCLOhsJucpZWMTg";
tmp["hashId"]="RaWu.dk";
tmp["hashName"]="bafofest";
configAlbumData[i]=tmp

configAlbumData_jsonData_rel["Mathiasrw/BafoFest"]=configAlbumData[i]

i++

tmp = new Array();
tmp["url"]="http://picasaweb.google.dk/data/feed/base/user/Mathiasrw/album/BrasilianClash?alt=json&kind=photo";
tmp["hashId"]="RaWu.dk";
tmp["hashName"]="brasilianClash";
configAlbumData[i]=tmp

configAlbumData_jsonData_rel["Mathiasrw/BrasilianClash"]=configAlbumData[i]

i++



//Global user variables to set (CHANGE TO WHAT YOU WANT IT TO BE)
var pwi_username = "mathiasrw"; 			//Your username at Picasa WebAlbums
var pwi_container_div = "container"; 	//Specifiy the id of the div in which the albums should be loaded inside your HTML/template/...
var pwi_album_only = "";				//setup with ONE specific album only, choose an album and take the name from the url between "#" and the last "/1"
var pwi_album_thumbsize = 72;			//supported sizes: 32, 48, 64, 72, 144, 160 (http://code.google.com/apis/picasaweb/reference.html#Parameters)
var pwi_album_crop = 1;					// 1 = crop to thumbsize, making them square, or 0 = keep original aspect ratio making the thumbsize the max width and height
var pwi_photosize = 800; 				//Supported sizes: 200, 288, 320, 400, 512, 576, 640, 720, 800 (http://code.google.com/apis/picasaweb/reference.html#Parameters)
var pwi_thumbsize = 144; 				//supported sizes: 32, 48, 64, 72, 144, 160 (http://code.google.com/apis/picasaweb/reference.html#Parameters)
var pwi_photo_crop = 1; 				// 1 = crop to thumbsize, making them square, or 0 = keep original aspect ratio making the thumbsize the max width and height
var pwi_maxresults = 9999; 				//pictures per page

//Album and Photo details to show or not
var pwi_show_albumtitles = true;
var pwi_show_albumdate = true;
var pwi_show_albumphotocount = true;
var pwi_show_albumdescription = true;
var pwi_show_albumlocation = true;
var pwi_show_slideshowlink = true;
var pwi_show_photocaption = true;
var pwi_show_photodate = true;

// LABELS, translate ON THE RIGHT SIDE OF THE = if you want
var pwi_labels = new Array();
pwi_labels["photo"] 	= "billede";
pwi_labels["photos"] 	= "Billeder";
pwi_labels["albums"] 	= "Tilbage til oversigt";
pwi_labels["slideshow"] = "Vis som slideshow";
pwi_labels["loading"] 	= "Loader lige billederne";
pwi_labels["page"] 		= "Side";
pwi_labels["prev"] 		= "TIlbage";
pwi_labels["next"] 		= "Neste";
pwi_labels["devider"] 	= "|";


//SLIMBOX settings, making the single photo view personal to your likings (http://www.digitalia.be/software/slimbox2)
var pwi_slimbox_config = {
	loop: false,
	overlayOpacity: 0.6,
	overlayFadeDuration: 400,
	resizeDuration: 200,
	resizeEasing: "swing",
	initialWidth: 250,
	initlaHeight: 250,
	imageFadeDuration: 400,
	captionAnimationDuration: 400,
	counterText: "Billede {x} af {y}",
	closeKeys: [27, 88, 67, 70],
	nextKeys: [37, 80],
	nextKeys: [39, 83]
}


var pwi_maxalbums = 0; //maximum of pictures on albumphotos page

var pwi_currAlbum = "";
var pwi_currAlbumTitle = "";
var pwi_currPhoto = "";
var pwi_page = 1;
var pwi_si = 1;
var pwi_storage_albums;
var pwi_storage_photos;
var pwi_storage_photo;
var pwi_history = "";


var photoids = new Array();


$(document).ready(function() {
	if (pwi_username == "YOUR_PICASA_NAME") {
		alert('Open the pwi js-file and change content \nof the variable pwi_username in the top of the file\nto your Picasa Webalbum username');
	} else {
		$.extend($.blockUI.defaults.overlayCSS, {
			backgroundColor: '#000'
		});
		$.ajaxSetup({
			cache: false	//true
		});
		$("#" + pwi_container_div).addClass("pwi_container");
		$.historyInit(navigate);
		
		$(".pwi_album_description").fadeIn(1000);		

	}
});

function navigate(hash) {
	var params, user, folder;
	params = hash.split("/");
	if(2<params.length){
		user = params[0];
		folder = params[0];
		showSelectedAlbum(user, folder);
	} else {
		showAlbums();
	}
}

var thisAlbum;
function showAlbums(){
	for (var i = 0; i < configAlbumData.length; i++) {
		show(true, '');
		var url = configAlbumData[i]['url'];
		thisAlbum = configAlbumData[i];
		$.getJSON(url, 'callback=?', saveAlbumData);
	}
}

var albumData = new Array();
var imageData = new Array();

function saveAlbumData(album){
		
		var album_tmp = ''+album.feed.id.$t;
		var album_tmp = album_tmp.split("/user/")[1];
		var album_tmp = album_tmp.split("/album/");
		var album_rel = album_tmp[0]+'/'+album_tmp[1];
		var thisAlbum = {
			title	:	album.feed.title.$t	,
			user	:	configAlbumData_jsonData_rel[album_rel]['user'] 	,
			folder	:	configAlbumData_jsonData_rel[album_rel]['folder']	, 
			configAlbumData	:	configAlbumData_jsonData_rel[album_rel] 
		}
		
		var thisImages = new Array();

		
		for (var i = 0; i < album.feed.entry.length; i++) {
			var thisImage = {
				imgUrl 	:	album.feed.entry[i].content.src,
				album 	:	thisAlbum,
			}
			imageData[imageData.length] = thisImage;
			thisImages[thisImages.length] = thisImage;
			
		}
		
		thisAlbum.images = thisImages;
		
		albumData[albumData.length] = thisAlbum;
	
		var showAlbumsHTML = new StringCat();
	
	
		showAlbumsHTML.push(makeAlbumHTML(thisAlbum));
		
		
		$('#menu').append(showAlbumsHTML);
}



function makeAlbumHTML(album){
	return "<hr>Dette er albummet: " + album.title;
}

function showSelectedAlbum(user, folder){
	for (var i = 0; i < albumData.length; i++) {
		if(albumData[i].user == user && albumData[i].folder == folder ){
			show(true, makeSelectedAlbumHTML(albumData[i]));
			break;
		}
	}
}

function makeSelectedAlbumHTML(album){
	var albumHTML = new StringCat();
	for (var i = 0; i < album.images.length; i++) {
		
	}
}

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 + '/album/' + albumid + '?category=photo&max-results=' + pwi_maxresults + '&start-index=' + pwi_si + '&alt=json';
		 url = 'http://picasaweb.google.dk/Mathiasrw/SandraLorisFDselsdag?authkey=Gv1sRgCNuDzMms1_XZ4QE&category=photo&alt=json';
		 url = 'http://picasaweb.google.dk/data/feed/base/user/Mathiasrw/albumid/5102248724536188465?alt=json&kind=photo&authkey=Gv1sRgCNuDzMms1_XZ4QE&hl=en_US';
		 url = 'http://picasaweb.google.com/data/feed/api/user/mathiasrw/album/MDK?category=photo&max-results=' + pwi_maxresults + '&start-index=' + pwi_si + '&alt=json';
				    
		show(true, '');
		//$.getJSON(url, 'callback=?', album);
		$.getJSON(url, 'callback=?', saveAlbumData);
	} else {
		show(false, pwi_storage_photos);
	}
}


//Open images
function show(loading, data) {
	if (loading) {
		//$("#"+pwi_container_div).fadeOut('slow');
		$("#" + pwi_container_div).block({
			message: "<div class='lbLoading pwi_loader'>" + pwi_labels["loading"] + "</div>",
			css: "pwi_loader"
		});
	} else {
		$("#" + pwi_container_div).unblock();
		$("#" + pwi_container_div).html(''+data); //.fadeIn('fast');
		$("a[rel^='lightbox']").slimbox(pwi_slimbox_config, null,
		function(el) {
			return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
		});
	}
}


var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	}, 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	}

}


//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] = "Januar";
	months[1] = "Februar";
	months[2] = "Marts";
	months[3] = "April";
	months[4] = "Maj";
	months[5] = "Juni";
	months[6] = "Juli";
	months[7] = "August";
	months[8] = "September";
	months[9] = "Oktober";
	months[10] = "November";
	months[11] = "December";
	var today = new Date(Number(dt));
	var year = today.getYear();
	if (year < 1000) {
		year += 1900;
	};
	return (today.getDate() +". " + months[(today.getMonth())] + " "  + 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 Xalbums(j) { //returns the list of all albums for the user
	var scAlbums = new StringCat();
	//scAlbums.push("<div class='pwi_albums'>Albums</div>");
	for (var i = 0; i < j.feed.entry.length; i++) {
		var id_base = j.feed.entry[i].gphoto$name.$t;
		var album_date = formatDate(j.feed.entry[i].gphoto$timestamp.$t);
		var thumb = j.feed.entry[i].media$group.media$thumbnail[0].url.replace(new RegExp("/s160-c/", "g"), "/");
		scAlbums.push("<div class='pwi_album'><a class='standard' href='#" + id_base + "' onclick='javascript:parent.$.historyLoad(\"" + id_base + "/\"); return false;' title='"+j.feed.entry[i].title.$t+"'>");
		scAlbums.push("<img src='" + thumb + "?imgmax=" + pwi_album_thumbsize + "&crop=" + pwi_album_crop + "'/></a><br>");
		pwi_show_albumtitles ? scAlbums.push("<a href='#" + id_base + "' onclick='javascript:$.historyLoad(\"" + id_base + "\");return false;'>" + j.feed.entry[i].title.$t + "</a><br/>" + (pwi_show_albumdate ? album_date : "") + ( pwi_show_albumphotocount ? " | " + j.feed.entry[i].gphoto$numphotos.$t + " "+ pwi_labels["photos"] : "")) : false;
		scAlbums.push("</div>");
	}
	scAlbums.push("<div style='clear: both;height:0px;'> </div>");
	pwi_storage_albums = scAlbums.toString();

	if (pwi_album_only.length > 0) {
		getAlbum(pwi_album_only, 1);
	} else {
		show(false, pwi_storage_albums);
	}
}









*/



function Xalbum(j) { //returns all photos in a specific album
	
	
	var scPhotos = new StringCat();
	
	
	for(att in j){
	scPhotos.push(j[att]);
	}
	
	var scPhotosDescription = new StringCat();
	//get the number of photos in the album
	var np = j.feed.openSearch$totalResults.$t;
	
	var ad = j.feed.subtitle.$t;
	var album_date = formatDate(j.feed.gphoto$timestamp.$t);
	var item_plural = true;
	if (np == "1") item_plural = false;
	var len = j.feed.entry.length;
	pwi_currAlbumTitle = j.feed.title.$t;
	
	scPhotosDescription.push("<div class='pwi_album_description'>");
	scPhotosDescription.push("<div class='pwi_album_description_container'>");
	if (!pwi_album_only.length > 0) {
		//scPhotosDescription.push("<a href='javascript:void(0)' onclick='$.historyLoad(\"\");'>" + pwi_labels["albums"] + "</a> &gt; " + j.feed.title.$t + "<br/>");
	};
	
	loc = 0;
	
	if (pwi_show_albumdescription) {
		scPhotosDescription.push("<div class='title'>" + j.feed.title.$t + "</div>");
		scPhotosDescription.push("<div class='details'>" + np + " " + (item_plural ? pwi_labels["photos"] : pwi_labels["photo"]) + (pwi_show_albumdate ? ", " + album_date: "") + (pwi_show_albumlocation && loc ? ", " + loc: "") + "</div>");
		scPhotosDescription.push("<div class='description'>" + (ad ? ad: "") + "</div>");
		if (pwi_show_slideshowlink) scPhotosDescription.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' class='sslink'>" + pwi_labels["slideshow"] + "</a>");
	}
	scPhotosDescription.push('<span style="font-size:8px;position:fixed;top:2px;left:2px;font-family:arial;">M<br>E<br>N<br>U</span>');
	scPhotosDescription.push('<br><iframe src="?" width="100%" onload="this.height=contentDocument.body.scrollHeight+50" ALLOWTRANSPARENCY="true" FRAMEBORDER="0" MARGINWIDTH="0" MARGINHEIGHT="0" SCROLLING="no">');
	scPhotosDescription.push('</iframe>');
	scPhotosDescription.push('</div>');
	scPhotosDescription.push('</div>');
	scPhotosDescription.push('<script>');
	scPhotosDescription.push('$(".pwi_album_description").hover(function(){');
	scPhotosDescription.push('$(this).stop().animate( { width:"400px"}, 1000 )');
	scPhotosDescription.push('},function(){');
	scPhotosDescription.push('        $(this).stop().animate( { width:"10px"}, 1000 )');
	scPhotosDescription.push('}).hide().fadeIn(4000).animate( { width:"10px"}, 1000 );');
	scPhotosDescription.push('</script>');
	//create paging navigation
	if (np > pwi_maxresults) {
		pageCount = (np / pwi_maxresults);
		var ppage = pwi_labels["prev"] + " " + pwi_labels["devider"] + " ",
		npage = pwi_labels["devider"] + " " + pwi_labels["next"];
		if (pwi_page > 1) {
			ppage = "<a href='javascript:void(0)' onclick='$.historyLoad(\"" + pwi_currAlbum + "/" + (parseInt(pwi_page) - 1) + "\")'>previous</a> | "
		};
		if (pwi_page < pageCount) {
			npage = "| <a href='javascript:void(0)' onclick='$.historyLoad(\"" + pwi_currAlbum + "/" + (parseInt(pwi_page) + 1) + "\")'>next</a>"
		};
		var navRow = new StringCat();
		navRow.push("<div class='pwi_pager'>" + ppage + pwi_labels["page"] + " ");
		for (var i = 1; i < pageCount + 1; i++) {
			if (i == pwi_page) {
				navRow.push("<span class='pwi_pager_current'>" + i + "</span> ");
			} else {
				navRow.push("<a href='javascript:void(0)' onclick='$.historyLoad(\"" + pwi_currAlbum + "/" + i + "\")'>" + i + "</a> ");
			};
		};
		navRow.push(npage + "</div>");
		scPhotosDescription.push(navRow.toString());
	}
	scPhotos.push('<div class="images">');
	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 c = pwi_show_photocaption ? (j.feed.entry[i].summary.$t ? j.feed.entry[i].summary.$t: "") : "";
		var dt = pwi_show_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) : "";
		var d = dt + " " + c.replace(new RegExp("'", "g"), "&#39;");
		
		/*
		scPhotos.push("<div class='pwi_photo' style='height:" + pwi_thumbsize + "px;'>");
		scPhotos.push("<a href='" + img_base + "?imgmax=" + pwi_photosize + "' rel='lightbox-photo' title='" + d + "'>");
		scPhotos.push("<img src='" + img_base + "?imgmax=" + pwi_thumbsize + "&crop=" + pwi_photo_crop + "'/></a>");
		scPhotos.push("</div>");
		*/
		
		/* KArnecalsbilleder-dk MRW 09 */
		scPhotos.push("<div class='pwi_photo'>");
		scPhotos.push("<a href='" + img_base + "?imgmax=" + pwi_photosize + "' rel='lightbox-photo' title='" + d + "'>");
		scPhotos.push("<img src='" + img_base + "?imgmax=" + pwi_thumbsize + "&crop=" + pwi_photo_crop + "'/></a>");
		//scPhotos.push("<a href='" + img_base + "?imgmax=" + pwi_photosize + "' rel='lightbox-cats' style='display:none;' >Dette er bare fantastisk " + img_base + " !</a>");
		scPhotos.push("</div>");
		
		
	}
	scPhotos.push('</div>');
	scPhotos.push(navRow);
	scPhotos.push('<script>');
	scPhotos.push('	$(".pwi_photo img").hover(');
	scPhotos.push('function(){');
	scPhotos.push('$(this).stop( ).fadeTo(300, 1, "swing");');
	scPhotos.push('},function(){');
	scPhotos.push('$(this).fadeTo(2000, 0.5).fadeTo(2000, 0.7);');
	scPhotos.push('});');
	scPhotos.push('</script>');
	scPhotos.push(scPhotosDescription);
	pwi_storage_photos = scPhotos.toString();
	show(false, pwi_storage_photos);
}


function XgetAlbums() {
	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' + (pwi_maxalbums > 0 ? '&max-results=' + pwi_maxalbums: "") + '&access=public&alt=json';
		$.getJSON(url, 'callback=?', albums);
	}
}


//$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
//$update: March 27, 2009, Jeroen Diderik, added many option and rewrote to using DIVs

