/**
 * JSlideshow javascript fallback version for iDevices
 *
 * @module JSlideshow
 */
var window = {};
var log;
var require; //keep jslint happy


/**
 * A slideshow that gets it's images from flickr galleries/albums
 * @namespace JSlideshow
 * @class Main
 */
//var that = this;

/*jslint plusplus: false */

//Could be fun to also integrate this with JSUnit

var JSlideshow = {};


////OR
//
//JSlideshow.Main = function(albumList) {
//    
//}

JSlideshow.Album = function () {
	return {
		data: [],
		currentSlideIndex: 0,
		id: undefined,
		initWithId: function (id) {
			this.id = id;
			JSlideshow.FlickrAccount.getGalleryInfoWithGalleryId(this.id, function (albumInfo) {
				
				var coverURL = JSlideshow.FlickrAccount.getFlickrImageURLFromId(albumInfo.primary, JSlideshow.FlickrAccount.imageSize.SMALL);
			});
		},
		loadInfo: function (callback) {
			
			callback("imaginary json data");
		}
	};
};


JSlideshow.FlickrAccount = (function () {
	
	//singleton this object?
	
	var FLICKR_USER_ID = "51316022@N08",
	FLICKR_API_KEY = "94cdb4674ac66daccda76697d649392d",
	FLICKR_REQUEST_ALBUM_INFO = "flickr.photosets.getInfo",
	FLICKR_REQUEST_GALLERY = "flickr.photosets.getPhotos",
	FLICKR_API_URL_BASE = "http://api.flickr.com/services/",
	FLICKR_REST_API = "rest/",
	IMAGE_SMALL = "SMALL",
	IMAGE_MEDIUM = "MEDIUM",
	IMAGE_LARGE = "LARGE",
	IMAGE_THUMB = "THUMB",
	IMAGE_SQUARE = "SQUARE";
	
	var gallery = {
		title: ""	
	};
	//var that =  this;
	
	return {
		imageSize: (function () {
			return {
				SMALL: IMAGE_SMALL,
				MEDIUM: IMAGE_MEDIUM,
				LARGE: IMAGE_LARGE,
				THUMB: IMAGE_THUMB,
				SQUARE: IMAGE_SQUARE
			};
		}()),
		userId: (function () {
			return FLICKR_USER_ID;
		}()),
		flickrURL: (function () {
			return FLICKR_API_URL_BASE;
		}()),
		getPhotos: (function () {
			return FLICKR_REQUEST_GALLERY;
		}()),
		flickrRestAPI: (function () {
			return FLICKR_REST_API;
		}()),
		getGalleryInfo: (function () {
			return FLICKR_REQUEST_ALBUM_INFO;
		}()),
		apiKey: (function () {
			return FLICKR_API_KEY;
		}()),
		getFlickrImageURLFromId: function (id, size) {
			return "";//cover url
		},
		gallery: (function () {
			return gallery;
		}()),
		processResponse: function (data) {
			var d = data;
			return {
				id: d.photoset.id,
				primary: d.photoset.primary,
				length: d.photoset.photos,
				title: d.photoset.title._content
			};
		},
		getGalleryWithGalleryId: function (id, callback) {
			var f = this;
			//this gets the primary photo url and loads the cover image,
			
			
			callback();
		},
		getGalleryInfoWithGalleryId: function (id, callback) {
			var f = this;
			var gallery = {};
			$['getJSON'](f.flickrURL + f.flickrRestAPI + "?jsoncallback=?",
			{
				"method": f.getGalleryInfo,
				"format": "json",
				"api_key": f.apiKey,
				"photoset_id": id
			}
			,function (data) {
				gallery.title = data.photoset.title._content;
				$("#gallery" + id + " .title")['html'](gallery.title);
			});
			
			$['getJSON'](f.flickrURL + f.flickrRestAPI + "?jsoncallback=?",
			{
				"method": f.getPhotos,
				"format": "json",
				"extras": "url_m",//,url_s,url_t,url_sq
				"api_key": f.apiKey,
				"photoset_id": id
			}
			,function (data) {
				
				//check that the data.photoset.id matches id
				
				var set = data.photoset
				var numPhotos = data.photoset.photo.length;

				gallery.photos = data.photoset.photo;
				gallery.id = data.photoset.id;
				var i, l = gallery.photos.length;
				var coverImage;
		
				for (i = 0; i < l; i++ ) {
					if (gallery.photos[i].isprimary == "1") {
						
						coverImage = gallery.photos[i];
						
						var width = Number(coverImage.width_m);
						var height = Number(coverImage.height_m);
						var dimensions = fitToSize(276, 182, width, height);
			
						var oX = Math.round(dimensions.xOffset);
						var oY = Math.round(dimensions.yOffset);
						var coverImageSrc = "<img style='margin-left:" + oX + "px;margin-top:" + oY + "px;' src='" + coverImage.url_m + "' width='" + dimensions.w + "' height='" + dimensions.h + "' /><span class='title'></span>";
						$("#gallery" + id)['html'](coverImageSrc);
						
						//add caption if it has already been loaded
						if (gallery.title != undefined && gallery.title != "") {
							$("#gallery" + id + " .title")['html'](gallery.title);
						}
						$("#gallery" + id)['click'](function (evt) {
							f.gallery = gallery;
							loadGalleryWithId(id);
							
						});
						//load this into list element with appropriate id.
					}
					
					
					
				}
			});;
			
		}
	};
}());


function loadGalleryWithId(id) {
	
	
	var gals = $("#galleries");
	gals['css']("opacity", 0);
	gals['css']("top", "-500px");
	
	var gal = $("#gallery");
	
	gal['css']('display', 'block');
	gal['animate']({'opacity': 1},1000);

	
	
	//create slides
	var gallery = JSlideshow.FlickrAccount.gallery;
	gallery.currentSlide = 0;
	
	
	imageOne = $("#img1");
	imageTwo = $("#img2");
	photoTitle = $('#photoTitle');
	imageOne['css']('opacity', 0);
	imageTwo['css']('opacity', 0);
	gallery.currentImage = imageTwo;
	timer = setInterval(setImage, 6000);
	setImage();
}
var timer;
var imageOne;
var imageTwo;
var photoTitle;

function setImage() {
	
	var gallery = JSlideshow.FlickrAccount.gallery;
	var photo = gallery.photos[gallery.currentSlide];
	
	var oldImage;
	var imageEl;
	
	//need to do check for image loaded, preload next image

	
	if (gallery.currentImage == imageTwo) {
		imageEl = imageOne;
		oldImage = imageTwo;
	}
	else {
		imageEl = imageTwo;
		oldImage = imageOne;
	}
	gallery.currentImage = imageEl;

	
	//oldImage.attr('src', '');
	imageEl['attr']('src', photo.url_m);
	

	var caption = '<strong>' + (gallery.currentSlide + 1) + " of " + gallery.photos.length + '</strong> ' + photo.title;
	var size = fitToSize(594, 370, Number(photo.width_m), Number(photo.height_m));

	imageEl['attr']("width", size.w);
	imageEl['attr']("height", size.h);
	imageEl['css']("marginLeft", size.xOffset + "px");
	imageEl['css']("marginTop", size.yOffset + "px");
	if (gallery.currentSlide + 1 < gallery.photos.length) {
		gallery.currentSlide++;
	}
	else {
		gallery.currentSlide = 0;
	}
	
	/*$(imageEl).animate({
		opacity: 1
	}, 500);
	$(oldImage).animate({
		opacity: 0
	}, 500);*/
	imageEl['css']('opacity', 1);
	//do caption transition.

	
	photoTitle['html'](caption);
	photoTitle['css']('top', '-' + (photoTitle['height']() + 10) + 'px');
	
	oldImage['css']('opacity', 0);
	
		//preload next image:
	setTimeout(function() {
		oldImage['attr']('src', gallery.photos[gallery.currentSlide].url_m);
		
		photoTitle['css']('top', 0);
		
	}, 1000);
	setTimeout(function() {
		photoTitle['css']('top', '-' + (photoTitle['height']() + 10) + 'px');
	}, 5000)
}

function returnToGallerySelection () {
	var gals = $("#galleries");

	gals['css']("opacity", 1);
	gals['css']("top", 0);
	
	//animate in thumbnails section and load first image.
	var gallery = $("#gallery");
	gallery['animate']({'opacity': 0},1000);
	setTimeout(function() {
		gallery['css']("display", "none");
	}, 1000);
	clearInterval(timer);
}

function fitToSize(tW, tH, aW, aH) {
	var rH, rW, ratio;
	ratio = aW / aH;
	
	rH = tH;
	rW = rH * ratio;
	
	
	return {
		h: Math.ceil(rH)
		, w: Math.ceil(rW)
		, xOffset: Math.round((tW - rW) * 0.5)
		, yOffet: Math.round((tH - rH) * 0.5)
	}
}

JSlideshow.Main = ({
    
    /**
     * @method initWithGalleryIds
     * @param {Array} Array of Strings which are Flickr album ids
     * @return {Boolean} on success
     */
	
    initWithGalleryIds: function (albumList) {
		var i = 0,
		l = albumList.length,
		album;
		
		var galleryList = "";
		
		for (i = 0; i < l; i++) {
		
			album = new JSlideshow.Album();
		
			galleryList += "<li id='gallery" + albumList[i] + "'></li>";
			album.initWithId(albumList[i]);
			//init album
		}
		
		$("#galleries")['html'](galleryList);
		
		//setup gallery nav:
		$("#backButton")['click']( function (evt) {
			evt.preventDefault();
			returnToGallerySelection();
		});
    }
});
