
// bootstrap: loads photosets, tags and latest photos
function bootstrap () {

	// Display the loading gif
	document.getElementById(containerid).innerHTML = '<div class="loading"></div>';
	
	var script = document.createElement('script');
	script.setAttribute('src', url+'photosets/'+config.nsid);
	script.setAttribute('type', 'text/javascript');
	document.documentElement.firstChild.appendChild(script);
	
	var script = document.createElement('script');
	script.setAttribute('src', url+'tag_list/'+config.nsid);
	script.setAttribute('type', 'text/javascript');
	document.documentElement.firstChild.appendChild(script);	

	if(bootstrap_page != '')
	{
		var script = document.createElement('script');
		script.setAttribute('src', url+bootstrap_page);
		script.setAttribute('type', 'text/javascript');
		document.documentElement.firstChild.appendChild(script);
	}
}

//------------------------- LATEST -------------------------//

// Callback handling latest photos retrieval
function latest_callback(json)
{
	if(document.getElementById('title'))
	{
		document.getElementById('title').innerHTML = 'Latest photos:';
		document.getElementById('descr').innerHTML = '';
	}
	config.total = parseInt(json.photos.total);
	config.displayedpages = total(config.total, config.perpage, config.maxpages);
	latest_json = json.photos;
	config.photos = json.photos.photo;
	
	generate_html();
}

// Display the latest photo according to the selected page
function latest () 
{
	highlightMe('latest');
	
	if(typeof latest_json != "undefined")
	{
		document.getElementById('title').innerHTML = 'Latest photos:';
		document.getElementById('descr').innerHTML = '';
		config.page = 1;
		config.total = parseInt(latest_json.total);
		config.displayedpages = total(config.total, config.perpage, config.maxpages);
		config.photos = latest_json.photo;
		generate_html();
	}
	else
	{
		document.getElementById(containerid).innerHTML = '<div class="loading"></div>';
		load('latest/'+config.nsid);
	}
}


//------------------------- PHOTOSET -------------------------//

// Build the photoset list
// called by Flickr with jsoncallback parameter
function photosets_callback(json)
{
	var container = document.getElementById('photosets');
	photosets_json = json.photosets.photoset;
    
    for (var i=0; i < photosets_json.length; i++) {
		var option = document.createElement('option');
    	option.value		= i;
    	option.innerHTML	= photosets_json[i].title._content;
    	container.appendChild(option);
    };
}

// Callback handling  photos from photoset retrieval
// Store the response in an array and call the function to build the html
function photoset_callback (json) {		
	photosets_ids[json.photoset.id] = json.photoset;
	config.total = json.photoset.total;
	if(config.selectedIndex || config.selectedIndex == 0) photoset(config.selectedIndex);
	else photoset(json.photoset.id);
	
}


// Load photos from a selected set
// If not loaded, call Flickr API with jsoncallbac set to photoset_callback
function photoset (selectedIndex) {
	highlightMe('photosets');	
	// Get the corresponding set
	// If an index is passed get the corresponding value, else the photoset_id is directly passed.
	
	
	if(selectedIndex < 100) var photoset_id = photosets_json[selectedIndex].id;
	else 
	{
		var photoset_id = selectedIndex;
		document.getElementById('title').innerHTML = 'Photoset:';
		document.getElementById('descr').innerHTML = '';
	}
	if(photosets_ids[photoset_id]) 
	{   	  
		// Set title and description
		if(selectedIndex < 100)
		{
	    	document.getElementById('title').innerHTML = photosets_json[selectedIndex].title._content+':';
	    	document.getElementById('descr').innerHTML = photosets_json[selectedIndex].description._content;
	    }		
		// Set already retrieved
		config.displayedpages = total(config.total, config.perpage, config.maxpages);			
		config.photos = photosets_ids[photoset_id].photo;
		
		// Display the form
		generate_html();
	}
	else
	{
		config.selectedIndex = selectedIndex;
		config.page = 1;
	    // Load the photos from this set
		// Set title and description
	    document.getElementById('title').innerHTML = photosets_json[selectedIndex].title._content+':';
	    document.getElementById('descr').innerHTML = photosets_json[selectedIndex].description._content;	    
		load('photoset/'+photoset_id);
	}

}


function photoset_get_info (photoset_id)
{
	load('photoset/'+photoset_id);
}

//------------------------- TAG -------------------------//


// Build the tag list
// called by Flickr with jsoncallback parameter
function tags_callback(json)
{
	var container = document.getElementById('tags');
	tags_json = json.who.tags.tag;
    
    for (var i=0; i < tags_json.length; i++) {
		var option = document.createElement('option');
    	option.value		= i;
    	option.innerHTML	= tags_json[i]._content;
    	container.appendChild(option);
    };
}

// Callback handling  photos from photoset retrieval
// Store the response in an array and call the function to build the html
function tag_callback (json) {	
	eval('tags_ids._'+tags_json[config.selectedIndex]._content+' = json.photos.photo');
	config.total = json.photos.total;
	tag(config.selectedIndex);
}

// Load photos from a selected set
// If not loaded, call Flickr API with jsoncallbac set to photoset_callback
function tag (selectedIndex) {
	highlightMe('tags');
	// Get he corresponding tag
	var tag = tags_json[selectedIndex]._content;
	
	if(eval('tags_ids._'+tag)) 
	{
		// Set title and description
		document.getElementById('title').innerHTML = 'Tag:';
		document.getElementById('descr').innerHTML = tags_json[selectedIndex]._content;		
		// tag already retrieved
		config.displayedpages = total(config.total, config.perpage, config.maxpages);			
		config.photos = eval('tags_ids._'+tag);
		
		// Display the form
		generate_html();
	}
	else
	{
		config.selectedIndex = selectedIndex;
		config.page = 1;
		// Set title and description
		document.getElementById('title').innerHTML = 'Tag:';
		document.getElementById('descr').innerHTML = tags_json[selectedIndex]._content;
		// Load the photos tagged with this tag
		load('tag/'+config.nsid+'/'+tag);
	}
}



// Call a custom function through the Flickr API
// options: - source: photoset|tag|latest 
//          - additionnal params according to the source (photoset id|tag name)  
function load (src) {
	
	// Display the loading gif
	document.getElementById(containerid).innerHTML = '<div class="loading"></div>';
	
	var src = url + src;

	// for (option_name in options) {	
	// 	//var option_val = "" + options[option_name] + "";
	// 	//src += option_name + "=" + option_val + "&";
	// }
	
	var script = document.createElement('script');
	script.setAttribute('src', src);
	script.setAttribute('type', 'text/javascript');
	document.documentElement.firstChild.appendChild(script);		
}

// Generate the html of a photo array
function generate_html () {

	var i = 0;
	var start = (config.page - 1) * config.perpage;
	var end = start + config.perpage - 1;
	end = config.total <= end ? config.total -1 : end;
	
	var photos = config.photos;
	var container = document.getElementById(containerid);
	container.innerHTML = '';
	
	//var group = (new Date()).getTime();
	
	for (var p = start; p <= end; p++)
	{

        var photo = photos[p];
        var href = '';

		// --------- SRCs of the photo
        // A photo which original is not accessible can have a _b format
        href = getImageUrl(photo, '');
        
        if (config.quality == 'hd')
        {
            if(photo.o_width)
            {
                if (photo.o_width > 1280 || photo.o_height > 1280)
                	href = getImageUrl(photo, '_b');
                else 
                	href = getOriginalImageUrl(photo);
            }
        }

		build_photo(container, photo, href, i/*, group*/);
             
        i++;   
	}
    
	build_pagination(container);
	
	overlay_callback();
}

// Build the pagination links
function build_pagination (container) {
	// --------- pagination HTML
    var div 	= document.createElement('div');
    div.id		= 'pagination';

    for (var p = 1; p <= config.displayedpages; p++)
    {
        // var a = document.createElement('a');
        // a.href			= '';
        // a.innerHTML		= p;
        // a.setAttribute('onclick', 'config.page = '+p+'; generate_html(); return false;');
        // if (p == config.page) 
        // 	a.className = 'selected';
        // div.appendChild(a);
		
        var theclass = '';
		if (p == config.page) 
			theclass = 'selected';
		var a ='<a href="" onclick="config.page='+p+'; generate_html(); return false" class="'+theclass+'">'+p+'</a>';
		div.innerHTML += a;        


    }
    
    container.appendChild(div);		
}


// handy functions to build the url of an image according to its size
function getImageUrl (photo, format) {
	return "http://farm" + photo.farm + ".static.flickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + format + ".jpg";
}

// handy function to retrieve the original photo if available
function getOriginalImageUrl (photo) {
	return "http://farm" + photo.farm + ".static.flickr.com/" + photo.server + "/" + photo.id + "_" + photo.originalsecret + "_" + "o."+photo.originalformat;
}	

// Compute the total page to display according to total photos, perpage and maxpages wanted
function total (total, perpage, maxpages)
{
	 reste = total % perpage == 0 ? 0 : 1;
	 if (total <= perpage) 
	 	return 1;
	 else if (Math.floor(total / perpage) > maxpages) 
	 	return maxpages;
	 	
	 return Math.floor(total / perpage) + reste; 
}

// Highlight the selected photo source (latest|photosets|tag)
function highlightMe(source) {
    switch (source)
    {
      case 'photosets':
        document.getElementById('photosets').style.background = "#fdd1d1";
        document.getElementById('tags').style.background = "#FFFFFF";
        document.getElementById('latest').style.textDecoration = "none";
       break;
      case 'tags':
        document.getElementById('photosets').style.background = "#FFFFFF";
        document.getElementById('tags').style.background = "#fdd1d1";
        document.getElementById('latest').style.textDecoration = "none";
       break;
      case 'latest':
        document.getElementById('photosets').style.background = "#FFFFFF";
        document.getElementById('tags').style.background = "#FFFFFF";
        document.getElementById('latest').style.textDecoration = "underline";
       break;       
    }
}

// parse the DOM and enable triptracker
function triptracker () {
    var viewer = new PhotoViewer();
	var anchors = document.getElementsByTagName('a');
	triptracker_index = 0;
	for (var i = 0; i < anchors.length; i++) {
		var anchor = anchors[i];
		var relAttribute = String(anchor.getAttribute('rel'));
		if (anchor.getAttribute('href')) {
			if (relAttribute.toLowerCase().match('triptracker')) {
				viewer.add(anchor.getAttribute('href'));
                anchor.onclick = function () { viewer.show(this.getAttribute('num')); };
                triptracker_index = triptracker_index + 1;
		    }
        }
	}    
}

// get a cookie
function getCookie(c_name, default_value)
{
	if (document.cookie.length>0)
		{
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
			{ 
			    c_start=c_start + c_name.length+1; 
			    c_end=document.cookie.indexOf(";",c_start);
			    if (c_end==-1) c_end=document.cookie.length;
			    return unescape(document.cookie.substring(c_start,c_end));
			} 
	}
	return default_value;
}

// set a cookie
function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+"; path=/";
}