var gallery = (function() {
	var userId = "60151302@N04"; //ANZ Netball
	var apiKey = "8ef560b7d84abd070614e2700af331ad";
	var apiSecret = "3201e8615bf6bfc1";
	var apiUrl = "http://www.flickr.com/services/rest/";
	var photoExtras = "url_sq,url_t,url_s,url_m,url_o";
	var photoPageSize = 10;
	var setPageSize = 3;
	var setPageCount = 1;
	var photosetData = {
		api_key: apiKey,
		user_id: userId,
		format: "json",
		jsoncallback: "gallery.handlePhotosetList",
		method: "flickr.photosets.getList"
	};
	var timer;
	
	/*
		photosets - 
		key: photosetId
		contains: title, description, photoCount, currentPage, pageCount, photoList
		
		photoList - 
		key: photoId
		contains: thumb(object), full(object), title, description
		
		thumb - 
		contains: width, height, url
		
		full -
		contains: width, height, url
		
		original - 
		contains: width, height, url
	*/
	var photosets = {};
	
	//keeps list of photosets in order
	var setList = [];
	
	var currentPage = 0;
	var setPageCount = 0;
	
	var prettyPhotoMarkup = '<div class="pp_pic_holder"> \
	  <div class="ppt">&nbsp;</div> \
    <div class="pp_top"> \
      <div class="pp_left"></div> \
      <div class="pp_middle"></div> \
      <div class="pp_right"></div> \
	  </div> \
    <div class="pp_content_container"> \
      <div class="pp_left"> \
        <div class="pp_right"> \
          <div class="pp_content"> \
            <div class="pp_loaderIcon"></div> \
            <div class="pp_fade"> \
              <div id="pp_full_res"></div> \
              <div class="pp_details clearfix"> \
                <p class="pp_description"></p> \
                <a id="pp_fullsize" href="#" title="Opens new window" target="_blank">View full size image</a> \
								<div class="clearfix"></div> \
                <a class="pp_close" href="#">Close</a> \
                <div class="pp_nav"> \
                <a href="#" class="pp_arrow_previous">Previous</a> \
                <p class="currentTextHolder">0/0</p> \
                <a href="#" class="pp_arrow_next">Next</a> \
              </div> \
            </div> \
          </div> \
        </div> \
      </div> \
    </div> \
  </div> \
  <div class="pp_bottom"> \
    <div class="pp_left"></div> \
    <div class="pp_middle"></div> \
    <div class="pp_right"></div> \
  </div> \
</div> \
<div class="pp_overlay"></div>';
	
	var curPhotoId;
	
	// calls flickr api for list of photosets
	var getPhotoSetList = function() {
			jQuery.ajax( { data: photosetData });
	}
	
	// calls flickr api for list of photos for set
	var getPhotosForSet = function(photosetId) {
		jQuery.ajax( {
			data: {
				api_key: apiKey,
				user_id: userId,
				format: "json",
				jsoncallback: "gallery.handlePhotosForSet",
				method: "flickr.photosets.getPhotos",
				photoset_id:photosetId,
				extras: photoExtras,
				media: "photo"
			}
		});
	}
	
	// gets extended info for individual photo
	var getPhotoDetails = function(photoId) {
		jQuery.ajax({
			data: {
				api_key: apiKey,
				user_id: userId,
				format:"json",
				jsoncallback: "gallery.handlePhotoDetails",
				method: "flickr.photos.getInfo",
				photo_id:photoId
			}
		});
	}
	
	// creates gallery for set, returns HTML for div
	var createPhotosetDiv = function(photoset) {
		var htmlString = '<div class="photoset" id="photoset_' + photoset.id + '"><h2>' + photoset.title + '</h2><p>' + photoset.description + '</p><ul class="gallery">';
		var photo;
		for(var i in photoset.photoList) {
			photo = photoset.photos[photoset.photoList[i]];
			htmlString += '<li><a href="' + photo.full.url + '" rel="prettyPhoto[set_'+ photoset.id + ']">' +
				'<img src="' + photo.thumb.url + '" width="' + photo.thumb.width + '" height="' + photo.thumb.height + '" alt="' +
				photo.title + '" /></a></li>';
		}
		htmlString += "</ul></div>";
		jQuery("#gallery").append(htmlString);
	}
	
	// once all photo details have been returned from flickr, show galleries
	var showGallery = function() {
		// make sure #gallery is empty
		jQuery("#gallery").empty();
		var start = currentPage * setPageSize;
		var end = setPageSize * currentPage + setPageSize;
		end = (end > setList.length) ? setList.length : end;
		for(var i = start; i < end; i++) {
			createPhotosetDiv(photosets[setList[i]]);
		}
		if(setPageCount > 1) {
			htmlString = '<ul class="pagination">';
			if(currentPage > 0) {
				htmlString += '<li class="setBack"><a href="#prev">Prev</a></li>';
			} else {
				htmlString += '<li class="setBack">Prev</li>';
			}
			for(i = 0; i < setPageCount; i++) {
				htmlString += '<li class="setPage';
				if(i == currentPage) {
					htmlString += ' currentPage">' + (i + 1) + '</li>';
				} else {
					htmlString += '"><a href="#set_' + (i+1) + '">' + (i + 1) + '</a></li>';
				}
			}
			if(currentPage < (setPageCount- 1)) {
				htmlString += '<li class="setForward"><a href="#next">Next</a></li>';
			} else {
				htmlString += '<li class="setForward">Next</li>';
			}
			jQuery("#gallery").append(htmlString);
			jQuery("#gallery ul.pagination li.setBack").click(prevGallery);
			jQuery("#gallery ul.pagination li.setPage a").click(showGalleryPage);
			jQuery("#gallery ul.pagination li.setForward a").click(nextGallery);
		}
		jQuery("a[rel^='prettyPhoto']").prettyPhoto({theme: 'light_rounded', overlay_gallery:false, animation_speet:'normal', allow_resize: false, markup: prettyPhotoMarkup, changepicturecallback: setOriginalUrl, show_title:false});
		jQuery("ul.gallery").prettyGallery({itemsPerPage : 10, navigation : 'bottom', previous_label: "Prev", next_label: "Next"});
		jQuery("#loading").hide();
		jQuery("#gallery").fadeIn("slow");
	}
	
	
	var nextGallery = function(e) {
		e.preventDefault();
		currentPage++;
		displayPage();
	}
	
	var prevGallery = function(e) {
		e.preventDefault();
		currentPage--;
		displayPage();
	}
	
	var showGalleryPage = function(e) {
		e.preventDefault();
		currentPage = parseInt(e.currentTarget.hash.substr(5), 10) - 1;
		displayPage();
	}
	
	displayPage = function() {
		jQuery("#gallery").fadeOut("slow", function() {
			showGallery();
		});
	}
	
	var setOriginalUrl = function() {
		var url = jQuery("#fullResImage").get(0).src;
		// find image by the URL
		for(var x in photosets) {
			for(var y in photosets[x].photos) {
				//found image
				if(photosets[x].photos[y].full.url == url) {
					if(photosets[x].photos[y].original.url) {
						jQuery("#pp_fullsize").get(0).href = photosets[x].photos[y].original.url;
						return ;
					}
					else {
						jQuery("#pp_fullsize").get(0).href = url;
						return;
					}
				}
			}
			jQuery("#pp_fullsize").get(0).href = url;
			return;
		}
		jQuery("#pp_fullsize").get(0).href = jQuery("#fullResImage").get(0).src;
	}
	
	return {
		
		// sets up gallery on page load
		init: function() {
			// set up common ajax variables
			jQuery.ajaxSetup({
				url: apiUrl,
				dataType: "script"
			});
			
			getPhotoSetList();
		},
		
		// called when photoset list returned
		handlePhotosetList: function(rsp) {
			if(rsp.stat == "ok") {
				ps = rsp.photosets.photoset;
				var len = rsp.photosets.photoset.length;
				if(len > setPageSize) {
					setPageCount = Math.ceil(len / setPageSize);
				}
				currentPage = 0;
				for( var i in ps) {
					var id = ps[i].id;
					setList.push(id);
					photosets[id] = {
						id: id,
						title: ps[i].title._content,
						description: ps[i].description._content,
						photoCount: parseInt(ps[i].photos, 10),
						pageCount: Math.ceil(parseInt(ps[i].photos, 10) / photoPageSize),
						currentPage: 1,
						photos: {},
						photoList: []
					};
					getPhotosForSet(id);
				}
			} else {
				jQuery("#loading").empty().append("<div class=\"error\">" + rsp.message + "</div>");
			}
		},
		
		
		// called when list of photos retuned from flickr
		handlePhotosForSet: function(rsp) {
			if(rsp.stat == "ok") {
				photoset = photosets[rsp.photoset.id];
				arrPhotos = rsp.photoset.photo;
				
				//handle all photos in set
				for(var i in arrPhotos) {
					var photo = arrPhotos[i];
					photoset.photos[photo.id] = {
						thumb: {
							width: photo.width_sq,
							height: photo.height_sq,
							url: photo.url_sq
						},
						full: {
							width: photo.width_m,
							height: photo.height_m,
							url: photo.url_m
						},
						original: {
							width: photo.width_o,
							height: photo.height_o,
							url: photo.url_o
						},
						title: photo.title
					};
					photoset.photoList.push(photo.id);
					//getPhotoDetails(photo.id);
					
				// clear the timer if it's been set to delay showGallery
				if(timer) {
					clearTimeout(timer);
				}
				
				// set a timer to 3 seconds to give enough time to be sure all photos have returned, then show gallery
				timer = setTimeout(showGallery, 1000);
				}
			} else {
				jQuery("#loading").empty().append("<div class=\"error\">" + rsp.message + "</div>");
			}
		},
		
		// called when an individual photo's details returned
		handlePhotoDetails: function(rsp) {
			if(rsp.stat == "ok") {
				// go through all photos and find the one that was returned;
				for(var i in photosets) {
					for(var j in photosets[i].photos) {
						// only set the details if it hasn't been already (if photo used in more than 1 set)
						if(j == rsp.photo.id && ! photosets[i].photos[j].description) {
							photosets[i].photos[j].description = rsp.photo.description._content;
						}
					}
				}
				
				// clear the timer if it's been set to delay showGallery
				if(timer) {
					clearTimeout(timer);
				}
				
				// set a timer to 3 seconds to give enough time to be sure all photos have returned, then show gallery
				timer = setTimeout(showGallery, 1000);
			} else {
				jQuery("#loading").empty().append("<div class=\"error\">" + rsp.message + "</div>");
			}
		}
	}
})();
