//Initialise Google AJAX feed API
init();

function init () {
	try {
		google.load('feeds','1');
	}catch (e) {
	}
}
/***************************** Global variables ***********************/
var _GET = readGet();

var photosize;
if(!photosize){photosize = 800;}//Initialise

var photolist = new Array(); //this is used globally to store the entire list of photos in a given album.

var commentlist = new Array(); //this is used globally to store the entire list of photos in a given album.

var album_name = ""; //this is used globally to store the album name.

var my_numpics = ""; //this is used globally to store the number of items in a particular album.

var prev = ""; //used in the navigation arrows when viewing a single item

var next = "";//used in the navigation arrows when viewing a single item


/***************************** End Global variables ***********************/


/********************************** Functions *****************************/

//Invoke this to show albums. Starting point for showing photos/albums
function showPicasaWebAlbums(username,size,cols) {
	
    if(!size){
		photosize = 800;
    } else {
        photosize = size;
    }
    
	if(_GET['albumid']&&_GET['slideshow_start']) {
		initSlideShow(username);	//view slideshow
	}else if(_GET['photoid']&&_GET['albumid']){
		//Comment on a photo
		$('<script type="text/javascript" src="http://picasaweb.google.com/data/feed/api/user/' 
		  + username + '/albumid/'+_GET['albumid']+'/photoid/'+_GET['photoid']
		  +'?kind=comment&alt=json-in-script&callback=getcommentlist"></script>');

		/*get the list of photos in the album and put it in the global 
		  "photolist" array so we can properly display the navigation arrows; */
		$('<script type="text/javascript" src="http://picasaweb.google.com/data/feed/base/user/' 
		  + username + '/albumid/'+_GET['albumid']+'?kind=photo&alt=json&callback=getphotolist"></script>');

		//get single photo
		$('<script type="text/javascript" src="http://picasaweb.google.com/data/entry/api/user/'
		  + username + '/albumid/'+_GET['albumid']+'/photoid/'
		  +_GET['photoid']+'?kind=photo,comment&alt=json&callback=photo"></script>');

	} else if(_GET['albumid']&&!_GET['photoid']){
		
		$('<script type="text/javascript" src="http://picasaweb.google.com/data/feed/base/user/'+username+'/albumid/'
		  +_GET['albumid']+'?kind=photo&alt=json&callback=albums"></script>');//(All Photos in a Album)
		
    } else{
		
		$('<script type="text/javascript" src="http://picasaweb.google.com/data/feed/api/user/'
		  +username+'?kind=album&alt=json&callback=picasaweb&access=public"></script>');// (All Album)		
    }
}

//View SlideShow
function loadSS(container,albumID,username){
	var feed="http://picasaweb.google.com/data/feed/base/user/jigar.snaps/albumid/"
		+albumID+"?kind=photo&alt=rss&thumbsize=640",default_options={
		displayTime:3000,
		transitionTime:1000,
		fullControlPanel : true,
		fullControlPanelSmallIcons : false,
		pauseOnHover : false,
		transitionCallback : myTransitionHandler
	};
   	new GFslideShow(feed,container,default_options);
}

/**
   * Place the title of the entry under the image
   */
  function myTransitionHandler(entry, transitionTime) {
	  /*var obj = document.getElementById('ss');
	  var sstitle = document.createElement('div');
	  sstitle.id='sstitle';
	  sstitle.className='sstitle';
	  obj.appendChild(sstitle,obj);
	  sstitle.innerHTML = entry.title;*/
  }

//Init SlideShow
function initSlideShow(username) {		
	var objBody = document.getElementById("photos");
	if(objBody){
		var album_base_path = window.location.protocol + "//" + window.location.hostname+window.location.pathname 
			+"?albumid="+ _GET['albumid'];

		var my_fixed_galleryname = "Back to Album";
		//my_fixed_galleryname = album_name;//Ok...right now there is no way in which i can get album name
		$("<div style='margin-left:3px'><a class='standard' href='"+ window.location.protocol + "//" 
		  + window.location.hostname + window.location.pathname+"'>Gallery Home</a> &gt; <a class='standard' href='" 
		  + album_base_path + "'>" + my_fixed_galleryname + "</a></div><br>");

		var ss = document.createElement('div');
		ss.id='ss';
		ss.className='ss';
		objBody.appendChild(ss,objBody);
		google.setOnLoadCallback(function(){loadSS(ss,_GET['albumid'],username);});	
	}
}

//Shows the list of all albums for the user
function picasaweb(j){ 
	$("<div style='margin-left:3px'>Gallery Home</div><br>");
	$("<table><tbody><tr><td>");
	for(i=0;i<j.feed.entry.length;i++){
		
		// for each of the albums in the feed, grab its album cover thumbnail and the link to that album,
		// then display them in a table with 4 columns (along with the album title)
		
		var img_base = j.feed.entry[i].media$group.media$content[0].url;
		var id_begin = j.feed.entry[i].id.$t.indexOf('albumid/')+8;
		var id_end = j.feed.entry[i].id.$t.indexOf('?');
		var id_base = j.feed.entry[i].id.$t.slice(id_begin, id_end);
		var album_summary  = j.feed.entry[i].summary.$t;
		if (album_summary) {
			album_summary = album_summary.replace("%20"," ");
			album_summary = album_summary.replace("%22","\"");
			album_summary = album_summary.replace("%27","\'");
		
			var album_base_path = window.location.protocol + "//" + window.location.hostname + window.location.pathname 
				+ "?albumid=" + id_base + "&slideshow_start=0"; //&galleryname=" + j.feed.entry[i].title.$t;
		
			var temp = 'View Album On Picasa' + '<td><a href="'+ album_base_path + '">View Slideshow</a></td>';
			album_summary = album_summary.replace("View Album",temp);
		}
		//alert(album_summary);

		$("<div class='photoframe'>");
		$("<div class='photothumbshadow'>");
		$("<div class='photothumb'>");
		$("<a href='?albumid="+id_base+"' onmouseover='Tip(&#39;" + album_summary 
		  + "&#39;, DELAY,4000,WIDTH, 300, TITLE, &#39;Album Summary&#39;, SHADOW, true, FADEIN, 300, FADEOUT, 200, "
		  +"STICKY, 1, OFFSETX, -20, CLOSEBTN, true, CLICKCLOSE, true)' ><img src='"
		  +img_base+"?imgmax=160&crop=1' class='photothumb'/></a>");
		$("</div>");
		$("</div>");
		$("<p class='phototitle'><a href='?albumid=" +id_base+"'>"
		  + j.feed.entry[i].title.$t +" ("+j.feed.entry[i].gphoto$numphotos.$t+")</a></p>")
		$("</div>");

	}
	$("</td></tr></tbody></table>");
}

//returns all photos in a specific album
function albums(j){  

	//get the number of photos in the album
	var np = j.feed.openSearch$totalResults.$t;
	var item_plural = "s";
	if (np == "1") { item_plural = ""; }

	//var album_begin = j.feed.entry[0].summary.$t.indexOf('href="')+6;
	//var album_end = j.feed.entry[0].summary.$t.indexOf('/photo#');
	//var album_link = j.feed.entry[0].summary.$t.slice(album_begin, album_end);
	var photoids = new Array();


	var album_base_path = window.location.protocol + "//" + window.location.hostname + window.location.pathname 
		+ "?albumid=" + _GET['albumid'] + "&slideshow_start=0"; //&galleryname=" + j.feed.entry[i].title.$t;
	
	var slide_show_link = '<a class="standard" href="'+ album_base_path + '">Watch Slideshow</a>';
	var view_on_picasa = '<a class="standard" href="'+j.feed.link[1].href+'">View On PicasaWeb</a>'
	//alert(slide_show_link);

	$("<div style='margin-left:3px'><a class='standard' href='" + window.location.protocol + "//" 
	  + window.location.hostname+window.location.pathname+"'>Gallery Home</a> &gt; "
	  + j.feed.title.$t +"&nbsp;&nbsp;["+np+" item"+item_plural+"]"
	  //	  + "&nbsp;&nbsp; | &nbsp;&nbsp; " + slide_show_link
	  +"</div><br>");

	$("<table><tbody><tr><td>");



	for(i=0;i<j.feed.entry.length;i++){
		
		var img_base = j.feed.entry[i].media$group.media$content[0].url;
		// var img_base = j.feed.entry[i].media$group.media$thumbnail.url;
		var id_begin = j.feed.entry[i].id.$t.indexOf('photoid/')+8;
		var id_end = j.feed.entry[i].id.$t.indexOf('?');
		var id_base = j.feed.entry[i].id.$t.slice(id_begin, id_end);
		//var photo_description = j.feed.entry[i].media$group.media$description.$t;
		var photo_summary = j.feed.entry[i].summary.$t;
		if (photo_summary) {
			photo_summary = photo_summary.replace("%20"," ");
			photo_summary = photo_summary.replace("%22","\"");
			photo_summary = photo_summary.replace("%27","\'");
			photo_summary = photo_summary.replace("View Photo","View Photo On Picasa");
		}
		photoids[i]=id_base;
  
		/* display the thumbnail (in a table) and make the link to the photo page, 
		   including the gallery name so it can be displayed.*/

		var link_url = "?albumid="+_GET['albumid']+"&photoid="+id_base; 
		/* disable the navigation entirely for really long URLs so we don't hit against the URL length limit.
		   note: this is probably not necessary now that we're no longer passing the photoarray inside the URL. 7/17/2007
		   Not a bad idea to leave it in, though, 
		   in case something goes seriously wrong and we need to revert to that method.*/
		if (link_url.length > 2048) { 
			link_url = link_url.slice(0, link_url.indexOf('&photoids=')+10)+id_base;
			
		}

		$("<div class='photoframe'>");
		$("<div class='photothumbshadow'>");
		$("<div class='photothumb'>");
		$("<a href='"+link_url+"' onmouseover='Tip(&#39;" + photo_summary 
		  + "&#39;, DELAY,4000,WIDTH, 300, TITLE, &#39;Photo Summary&#39;, SHADOW, true, FADEIN, 300, FADEOUT, 200, "
		  +"STICKY, 1, OFFSETX, -20, CLOSEBTN, true, CLICKCLOSE, true)' ><img src='"
		  +img_base+"?imgmax=160&crop=1' class='photothumb'/></a>");
		$("</div>");
		$("</div>");
		$("</div>");
	}

	$("</td></tr></tbody></table>");
	$("<div id='infobox'>");
	$("<h2 class='heading'>Album Information</h2>");
	$("<div class='albuminfo'><span class='title'>" + j.feed.title.$t + "</span>");
	$("<span class='albumdetails'>" + j.feed.subtitle.$t + "</span>");
	$("<span class='updated'>Last Updated : " + j.feed.updated.$t + "</span>");
	$("<span class='icon slideshow'><b>" + slide_show_link + "</b></span>");
	$("<span class='icon picasa-small'><b>" + view_on_picasa + "</b></span>");
	var rec = getRecommendIt(_GET['albumid']);
	$(rec);
	$("</div>");
	$("</div>");

}

//returns exactly one photo
function photo(j){
	//var album_begin = j.entry.summary.$t.indexOf('href="')+6;
	//var album_end = j.entry.summary.$t.indexOf('/photo#');
	//var album_link = j.entry.summary.$t.slice(album_begin, album_end);
	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;


	// is this a video? If so, we will display that in the breadcrumbs below.
	var is_video = 0;
	if (j.entry.media$group.media$content.length > 1) {
		//$('This is a '+j.entry.media$group.media$content[1].medium+'.<br>');
		if (j.entry.media$group.media$content[1].medium == "video")	{
			is_video = 1;
		}
	}

 
	//var photo_begin = j.entry.summary.$t.indexOf('href="')+6;
	//var photo_end = j.entry.summary.$t.indexOf('"><img');
	//var photo_link = j.entry.summary.$t.slice(photo_begin, photo_end);
	var photo_id = _GET['photoid'];
	
	var album_id = _GET['albumid'];
	var my_next = next;
	var my_prev = prev;
	var photo_array = photolist;
	var my_galleryname = album_name;
	var my_fixed_galleryname = album_name;
	var album_base_path = window.location.protocol + "//" + window.location.hostname+window.location.pathname 
		+"?albumid="+ _GET['albumid'];

	// Get the filename for display in the breadcrumbs
	var LastSlash = 0;
	var img_filename = img_title;
	for(i=0;i<img_base.length-1;i++){
		if (img_base.charAt(i)=="/") {
			LastSlash = i;
		}
	}
	if (LastSlash != 0)	{
		img_filename = img_base.slice(LastSlash+1, img_base.length);
	}
	// replace some commonly-used URL characters like %20
	img_filename = img_filename.replace("%20"," ");
	img_filename = img_filename.replace("%22","\"");
	img_filename = img_filename.replace("%27","\'");


	/*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.

	NOTE: as of 7/16/2007, the photo array is taken from global photolist 
	(loaded in the getphotolist function) rather than from the URL.
	//This has eliminated the need for really long URLs, which were hitting up against 
	the URL length limit in some extreme cases.*/

	for(i=0;i<photo_array.length;i++){
		if (photo_array[i]==photo_id) {
			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 prev = album_base_path + "&photoid=" + p1; //+"&photoids="+photo_array;
	var next = album_base_path + "&photoid=" + n1; //+"&photoids="+photo_array;


	//Display the breadcrumbs
	var my_item_plural = "";
	if (my_numpics != 1) {
		my_item_plural = "s";
	}
	var item_label = "picture";
	var item_label_caps = "Picture";
	if (is_video == 1) {//if it's a video, don't say it's a picture, say it's an "item" instead
		item_label = "item";
		item_label_caps = "Item";
	}

	var current_index_text = item_label_caps + " " + current_index + " of " + my_numpics;
	if (is_video == 1) { 
		current_index_text = current_index_text + "&nbsp;&nbsp;[VIDEO]"; 
	}  //show in the breadcrumbs that the item is a video

	$("<div style='margin-left:3px'><a class='standard' href='"+ window.location.protocol + "//" 
	  + window.location.hostname + window.location.pathname+"'>Gallery Home</a> &gt; <a class='standard' href='" 
	  + album_base_path + "'>" + my_fixed_galleryname + "</a> &gt;" + current_index_text + "</div><br>");

	if (p1 == null) {//we're at the first picture in the album; going back takes us to the album index
		var prev = album_base_path ;
	}
	
	if (n1 == null) {//we're at the last picture in the album; going forward takes us to the album index
		var next = album_base_path ;
	}

	//the navigation panel: back, home, and next.
	$("<table border=0><tr valign=right>");
	if (photo_array.length > 1) { 
		$("<td><a class='standard' href='"+prev
		  +"'><img border=0 alt='Previous item' src='images/prev_gray.gif'></a> </td><td></td>");
	}

	$("<td><a class='standard' href='"+album_base_path
	  +"'><img border=0 alt='Back to album index' src='images/home_gray.gif'></a> </td>");

	if (photo_array.length > 1) { 
		$("<td></td><td> <a class='standard' href='"+next
		  +"'><img border=0 alt='Next item' src='images/next_gray.gif'></a></td>"); 
	}
	if((current_index % 3) == 0 || current_index == 1) {
		$("<td class='navtip'><span class='tip icon' ><b>Tip : </b>"
		  +"You can use <img src='images/prev_key.png'> and <img src='images/next_key.png'> keys to navigate </span></td>");
	}

	$("</tr></table><br>");
	
	var max_width = 658; //max width for our photos
	var display_width = max_width;
	if (img_width < display_width) { 
		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, display the image and its description. photos larger than 
	  max_width are scaled down; smaller ones are left alone*/
	$("<img id='picture' width="+display_width+" src='"+img_base+"?imgmax="+photosize+"' class='loading' />");

	$("<div id='infobox'>");
	$("<h2 class='heading'>Photo Information</h2>");
	$("<div class='albuminfo'>");
	if (j.entry.media$group.media$description.$t != "") {
		$("<span class='description'>"+j.entry.media$group.media$description.$t+"</span>");
	}
	$("<span class='filename'>Filename : "+j.entry.title.$t+"</span>");
	$("<span class='updated'>Last Updated : "+j.entry.updated.$t+"</span>");
	$("<span class='comments icon'><a href='#comments'>Comments("
	  + j.entry.gphoto$commentCount.$t + ")</a></span>");

	if (j.entry.media$group.media$keywords.$t != "") {
		$("<span class='tags icon'>"+j.entry.media$group.media$keywords.$t+"</span>");
	}
	//	$("<p><span class='icon slideshow'><b>"+slide_show_link+"</b></span></p>");
	var album_base_path = window.location.protocol + "//" + window.location.hostname + window.location.pathname 
		+ "?albumid=" + _GET['albumid'] + "&slideshow_start=0"; //&galleryname=" + j.feed.entry[i].title.$t;	
	var slide_show_link = '<a class="standard" href="'+ album_base_path + '">Watch Slideshow</a>';
	//alert(slide_show_link);
	$("<span class='icon slideshow'><b>" + slide_show_link + "</b></span>");
	var rec = getRecommendIt(_GET['photoid']);
	$(rec);	
	$("</div>");
	$("</div>");
	$("<h2 id='comments' class='heading'>Photo Comments</h2>");
	var comment_list = commentlist;
	for(i=0;i < comment_list.length;i++) {
		$(comment_list[i]);
	}
	$("<h3><span class='addcomment icon heading2'><a href='"+j.entry.link[1].href+"'>Add Comment</a></span></h3>");
	//	$("</div>");

	//now we will trap left and right arrow keys so we can scroll through the photos with a single keypress ;-) JMB 7/5/2007
	$('<script type="text/javascript"> function testKeyCode( evt, intKeyCode ) { if ( window.createPopup ) ' 
	  + 'return evt.keyCode == intKeyCode; else return evt.which == intKeyCode; } document.onkeydown = function ' 
	  + '( evt ) { if ( evt == null ) evt = event; if ( testKeyCode( evt, 37 ) ) { window.location = "' 
	  + prev + '"; return false; } if ( testKeyCode( evt, 39 ) ) { window.location = "' 
	  + next + '"; return false; } } </script>');


}

function getcommentlist(j) {
	if (j.feed.entry != null){
		commentlist[0] = "<div class='usercomment'></div>"; 
		for (i = 0; i < j.feed.entry.length; i++ ) {
		var auth_pic = j.feed.entry[i].author[0].gphoto$thumbnail.$t;
		var auth_nick = j.feed.entry[i].author[0].gphoto$nickname.$t;
		var auth_url = j.feed.entry[i].author[0].uri.$t;
		var comment = j.feed.entry[i].content.$t;

		commentlist[i+1] = "<div class='usercomment'>"
			+ "<span class='authimg'><img src='"+auth_pic+"' /></span>"
			+ "<span class='authname'><a href='"+auth_url+"'>"+auth_nick+"</a></span>"
 			+ "<span class='comment_item'>"+comment+"</span>" 
			+ "</div>";

		}
	}
}
/* This function is called just before displaying an item; it returns info about the item's 
   current state within its parent album, such as the name of the album it's in,
   the index of the photo in that album, and the IDs of the previous and next
   photos in that album (so we can link to them using navigation arrows).  
   This way we don't have to pass state information
   around in the URL, which was resulting in hellishly long URLs 
   (sometimes causing "URI too long" errors on some servers).
*/

function getphotolist(j){
	// Get the number of pictures in the album.  
	my_numpics = j.feed.openSearch$totalResults.$t;

	// Also get the name of the album
	album_name = j.feed.title.$t;
 
	for(i=0;i<j.feed.entry.length;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_begin = j.feed.entry[i].id.$t.indexOf('photoid/')+8;
		var id_end = j.feed.entry[i].id.$t.indexOf('?');
		var id_base = j.feed.entry[i].id.$t.slice(id_begin, id_end);
		photolist[i]=id_base;
		
		// now get previous and next photos relative to the photo we're currently viewing
		if (i>0) {
			var prev_begin = j.feed.entry[i-1].id.$t.indexOf('photoid/')+8;
			var prev_end = j.feed.entry[i-1].id.$t.indexOf('?');
			prev = j.feed.entry[i-1].id.$t.slice(id_begin, id_end);
		}
		if (i<j.feed.entry.length-1) {
			var next_begin = j.feed.entry[i+1].id.$t.indexOf('photoid/')+8;
			var next_end = j.feed.entry[i+1].id.$t.indexOf('?');
			next = j.feed.entry[i+1].id.$t.slice(id_begin, id_end);
		}
	}
}


//requestVars - parse GET request
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;
}

function getRecommendIt(divid){
var testRecommend = "<div id='div-"+divid+"' style='width:100%;'></div>" 
	+ "<!-- Render the gadget into a div. -->"
	+ "<script type='text/javascript'>"
	+ "var skin = {};"
	+ "skin['HEIGHT'] = '21';"
	+ "skin['BUTTON_STYLE'] = 'compact';"
	+ "skin['BUTTON_TEXT'] = 'Recommend it!';"
	+ "skin['BUTTON_ICON'] = 'default';"
	+ "google.friendconnect.container.setParentUrl('/' /* location of rpc_relay.html and canvas.html */);"
	+ "google.friendconnect.container.renderOpenSocialGadget("
	+ " { id: 'div-"+divid+"',"
	+ "   url:'http://www.google.com/friendconnect/gadgets/recommended_pages.xml',"
	+ "   height: 21,"
	+ "   site: '08794474466032456174',"
	+ "   'view-params':{\"pageUrl\":location.href,\"pageTitle\":(document.title ? document.title : location.href),\"docId\":\"recommendedPages\"}"
	+ " },"
	+ "  skin);"
	+ "</script>";
return testRecommend;
}


//To print values on the page
function $(a) {
    document.write(a);
}


