Event.observe(window,'load',init);

// Storage
var containerName = 'photoContainer';
var albums = [];

// ---- RSH ----
    
function init() {
	// initialize the DHTML History framework
	dhtmlHistory.initialize();
	
	// if this is the first time we have loaded the page...
	if (dhtmlHistory.isFirstLoad()) {
		loadAlbums('/ajax/photo');
	} else {
		albums = historyStorage.get("albums");
		showAlbums( );
	}
	
}


/** Our callback to receive history change events. */
function handleHistoryChange(newLocation, historyData) {
  if (newLocation == "") {
      newLocation = "view:albums";
  }
  
  newLocation = newLocation.replace(/view\:/, "");
  
  displayLocation(newLocation, historyData);
}

function displayLocation( newLocation, historyData) {
	if( newLocation == "albums" ) {
		showAlbums();
	} else if( newLocation.indexOf(':') == -1) {
		// No albumlist, and no picture, must be an album
		loadAlbum(newLocation);
	} else {
		// Show picture, use split char :
		var temp = newLocation.split(':');
		printImage(temp[0],temp[1]);
	}
}



// Some Ajax related scripts used in the photoalbum


function loadAlbums(uri)
{
	
	// check for history
	if( !historyStorage.hasKey("albums") )
	{
		new Ajax.Request(uri,
	  {
	    method:'get',
	    onLoading:function(request){
	    	Effect.Appear('spinner');
	    },
	    onSuccess: function(transport){
	    	Effect.Fade('spinner',{ duration: 1.0 });
	      //var albums = transport.headerJSON;
	      var albums = transport.responseText.evalJSON(true);
	      
	      historyStorage.put("albums", albums );
	      
	      showAlbums();
	      Effect.BlindDown(containerName, {delay: 1.0 });
	    },
	    onFailure: function(){ alert('Something went wrong...') }
	  });
	}	else {
		albums = historyStorage.get("albums");
	  showAlbums( );
	}
}

function showAlbums()
{
	// Show options
	if($('photo-options')) {
		$('photo-options').show();
	}
	var albums = historyStorage.get("albums");
	
	var container = $(containerName);
	clearContainer();
	
	var table = Builder.node('table', {cellspacing:'4'});
	
	albums.each(function(elem){

		var row = table.insertRow(table.rows.length);
		
		var cell1 = Builder.node('td',{className:'medium'},elem.date);
		var cell2 = Builder.node('td',{className:'medium'},[ Builder.node('a',{href:'/photos#view:'+elem.id},elem.title) ]);
		
		row.appendChild(cell1);
		row.appendChild(cell2);
  });
	container.appendChild(table);
	
	dhtmlHistory.addListener(handleHistoryChange);
	dhtmlHistory.add("view:albums", albums);
}






function loadAlbum(albumName)
{
	
	if( !historyStorage.hasKey(albumName) )
	{
		var uri = '/ajax/photo/'+albumName;
		new Ajax.Request(uri,
	  {
	    method:'get',
	    onLoading:function(request){
	    	Effect.Appear('spinner');
	    },
	    onSuccess: function(transport){
	    	Effect.Fade('spinner');
			var json = transport.responseText.evalJSON(true);
	      var album = json;
	      historyStorage.put(albumName, album );
	
	      showAlbum( album, albumName, true );
	    },
	    onFailure: function(){ alert('Something went wrong...') }
	  });
  }	else {
  	var album = historyStorage.get(albumName);
	  showAlbum( album, albumName, false );
	}
}

function showAlbum(album, albumid, effect)
{
	// Hide options
	if($('photo-options')) {$('photo-options').hide();}

	var effect = effect ? true : false;
	
	var container = $(containerName);
	clearContainer();
	container.show();
	
	// Back button
	var back = Builder.node('p',[Builder.node('a',{href:'/photos#view:albums'},'Terug')]);
	container.appendChild( back );
	
	album.each(function(elem, index){
		
		var thumbnail = document.createElement('p');
		thumbnail.className = 'thumbnail';
		
		//link.href = '/photos/' + album + '/' + id;
		var style = '';
		if( effect ) { style ='display: none;'; }
		
		var image = Builder.node('a',{className:'lightview',rel:'gallery[set]',title:':: '+elem.caption,'href':elem.imgurl+'?imgmax=800'},[
			Builder.node('img',{id:'thumbnail'+index,style:style,className:'thumbnail',src:elem.imgurl+'?imgmax=144'})
		]);

		thumbnail.appendChild( image );
		container.appendChild( thumbnail );

		if( effect ) { var delay = index > 40 ? 3 : 1+(index/20); Effect.Appear('thumbnail'+index,{delay: delay}); }
		
	});
	var terminator = document.createElement('div');
	terminator.style.clear = "both";
	container.appendChild( terminator );
	
	dhtmlHistory.add("view:"+albumid, album);
	
	Lightview.updateViews();
}

function loadImageInfo(albumid,imageid)
{
	var imageobj;
	
	var uri = '/ajax/photo/'+albumid + '/' + imageid;
	
	//debug
	//$('extra').appendChild(Builder.node('p',{className:'medium'},uri));
	
	new Ajax.Request(uri,
	{
	  method:'get',
	  onSuccess: function(transport){
	    var response = transport.responseXML || "";
	    imageobj = imageXMLToArray(response);
	    
	    if( imageobj != null )
			{
				$('downloadPhoto').removeChild($('downloadPhoto').firstChild);
				$('downloadPhoto').appendChild(Builder.node('a',{href:imageobj,target:"_blank"},'Download Foto') );
			}
	  },
	  onFailure: function(){ alert('Something went wrong...') }
	});
	
}

function printImage(albumid,imageid)
{	
	var album = historyStorage.get(albumid);
	
	var container = $(containerName);
	
	clearContainer();
	
	var photoContainer = Builder.node('div',{id:'photo'});
	var optionsContainer = Builder.node('div',{id:'photooptions'});
	var extraContainer = Builder.node('div',{id:'extra'});
	
	var backToAlbum = Builder.node('span',{className:'medium link',onclick:'window.location.href = \'/photos#view:'+albumid+'\''},'Terug');
	var imageNode, captionNode, videoNode;
	var firstId, lastId, prevTmpId, prevId, nextId;
	
	var albumTitle = album[0].albumname;
	var realAlbumId = album[0].albumid;
	var numPhotos = album.length;
	var curPhoto;
		
	album.each(function(elem, i){
		var id = elem.id;
		
		// Remember the first and the last
		if( i==0 ){ firstId=id }
		if( i==album.length-1 ){ lastId=id }
		
		// Determine next image (if there is one)
		if( imageNode != null && nextId == null )
		{
			if( i<album.length ){ nextId=id }
		}
		
		// Image found
		if( imageid == id )
		{
			imageWidth = elem.width;
			imageHeight = elem.height;
			
			imageNode = Builder.node('img',{className:'photo',src:elem.imgurl+'?imgmax=400',onclick:'showLargeImage(this);'});
			if( elem.vidurl != null ) {
				var videoUrl=encodeURIComponent(unescape(elem.vidurl));
				videoNode = Builder.node('embed',{style:'width:400px; height:326px;',id:'VideoPlayback', type:'application/x-shockwave-flash', src:'http://video.google.com/googleplayer.swf?videoUrl='+videoUrl+'&hl=nl&autoplay=yes', allowscriptaccess:'always', swliveconnect:'true', quality:'best'},'');
			}
			
			captionNode = Builder.node('p',{className:'medium'},elem.caption);
			if( i>0 ){ prevId = prevTmpId }
			curPhoto = i+1;
		}		
		
		// remember this one for the next loop.
		prevTmpId=id;
	}); // End each
	
	var prevImageNode = (prevId != null) 
		? Builder.node('span',{className:'medium link',onclick:'window.location.href = \'/photos#view:'+albumid+':'+prevId+'\''},'Vorige')
		: Builder.node('span',{className:'medium'},'Vorige');
	var nextImageNode = (nextId != null )
		? Builder.node('span',{className:'medium link',onclick:'window.location.href = \'/photos#view:'+albumid+':'+nextId+'\''},'Volgende')
		: Builder.node('span',{className:'medium'},'Volgende');
		
	var photoNumberNode = Builder.node('p',{className:'medium'},'Foto '+curPhoto+' van '+numPhotos );
	var albumTitleNode  = Builder.node('p',{className:'medium'},albumTitle );
	var photoSizeNode   = Builder.node('p',{className:'medium dark'},imageWidth + ' x ' + imageHeight );
	var downloadNode    = Builder.node('p',{id:'downloadPhoto',className:'medium dark'},[ Builder.node('a',{href:'/ajax/photo/download/'+realAlbumId+'/'+imageid},'Download Foto')] );
	
	videoNode != null ? photoContainer.appendChild(videoNode) : photoContainer.appendChild(imageNode);
	photoContainer.appendChild(captionNode);
	
	optionsContainer.appendChild( backToAlbum );
	optionsContainer.appendChild( prevImageNode );
	optionsContainer.appendChild( nextImageNode );
	
	extraContainer.appendChild(albumTitleNode);
	extraContainer.appendChild(photoNumberNode);
	extraContainer.appendChild(photoSizeNode);
	extraContainer.appendChild(downloadNode);
	
	container.appendChild( optionsContainer );
	container.appendChild( photoContainer );
	container.appendChild( extraContainer );
	
	historyStorage.put(albumid, album);
	dhtmlHistory.add("view:"+albumid+":"+imageid);
	
	// Downloadlink zoeken:
	//loadImageInfo(realAlbumId,imageid);
}

function clearContainer()
{
	var container = $(containerName);
	while (container.firstChild) 
	{
		container.removeChild(container.firstChild);
	}
}
