/*
 * jQuery Slidr Script v1.0
 * http://www.emarketed.com/
 *
 * Made for usage with the Flickr API
 *
 * Copyright (c) 2010 emarketed.
 *
 * PARAMETERS:
 * 	(string) flickrApiKey - your Flickr API Key.
 * 	(string) flickrPhotosetId - your Flickr Photoset ID.
 *  (int) width - a number in pixels of the width of the gallery.
 *  (int) imageWidth - the main photo image width in pixels.
 *  (int) imageHeight - the main photo image height in pixels.
 *  (int) thumbs - the number of thumbnails to show in the slider.
 *  (string) leftArrow - the path to the left arrow image.
 *  (string) rightArrow - the path to the right arrow image.
 *  (string) speed - set the thumbnail slider speed to: "normal", "slow", or "fast".
 *  (string) easing - set the thumbnail slider transition effect to: "linear", or "swing".
 *
 * USAGE/EXAMPLE:
 *
 * <div id="gallery"></div>
 *
 * $(function() {
 *    $("#slidr").slidr({
 *						flickrId : 'jkd2iddj2h8zkxl10a6t56ro',
 *						flickrPhotosetId : '99999999999999999',
 *						width : 300,
 *						imageWidth: 250,
 *						imagehieght: 200,
 *						thumbs: 7,
 * 						speed: 'normal',
 *						easing: 'swing'
 * 						});
 * });
 */
 
(function($) {

	//FUNCTIONS
	function scrollSlider(imageSelector,newPos,speed,easing) {
		imageSelector.animate({scrollLeft: newPos},speed,easing);
	}

	$.fn.slidr = function(options) {
		//DEFAULT SETTINGS
		var settings = $.extend({
			flickrApiKey : '',
			flickrPhotosetId : '',
			width : 600,
			imageWidth : 490,
			imageHeight: 330,
			thumbs : 7,
			leftArrow : '',
			rightArrow : '',
			playButton : '',
			pauseButton : '',
			speed : 'normal',
			easing : 'swing',
			autoPlay : false,
			autoPlayDelay : 5000
		},options);

		//PROPERTIES
		var originalHTML = '';
		var mainDivId = '';
		var leftArrowImage = settings.leftArrow;
		var rightArrowImage = settings.rightArrow;
		var currPhoto = {
			title : '',
			url : ''
		};
		var photoSize = Math.ceil(settings.width-20);
		var thumbSize = Math.ceil((settings.width-40)/settings.thumbs);
		var sliderWidth = 0;
		var currentPhotoIndex = 0;
		var allPhotos = new Array();
		var autoPlayStatus = false;

		//START CONSTRUCT
		return this.each(function() {
			obj = $(this);
			var originalHTML = obj.html();
			obj.html("");
			mainDivId = obj.attr('id');
			obj.css('width',settings.width + 'px');
			var requestUrl = 'http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=' + settings.flickrApiKey + '&photoset_id=' + settings.flickrPhotosetId + '&extras=url_t,url_m,url_o&format=json&jsoncallback=?';
			$.getJSON(requestUrl,function(data) {
				$.each(data.photoset.photo, function(i,image) {
					if(i==0) { //if it's first image, set as default
						currPhoto = {
							photo_id : image.id,
							title : image.title,
							description : image.title,
							fullUrl : image.url_m,
							thumbUrl : image.url_t
						}
					}
					allPhotos.push({
						photo_id : image.id,
						title : image.title,
						description : image.title,
						fullUrl : image.url_m,
						thumbUrl : image.url_t
					});
				});
				sliderWidth = thumbSize * allPhotos.length;
				if(allPhotos.length==0) { obj.html(originalHTML); }
				else { //photos.length exists
					var imageTop = $("<div />")
									.attr('id',mainDivId + '-image-top')
									.css({
										 'clear' : 'both',
										 'height' : settings.imageHeight + 'px',
										 'overflow' : 'hidden',
										 'margin-bottom' : '15px'
									})
									.appendTo(obj);
					var playPauseImage = $("<img />")
						.attr('id',mainDivId + '-play-pause')
						.css({
							'display' : 'block',
							'width' : settings.imageWidth,
							'height' : settings.imageHeight,
							'position' : 'absolute',
							'z-index' : '2'
						});
					var imagePhoto = $("<div />")
									.attr('id',mainDivId + '-image-photo')
									.css({
										 'float' : 'left',
										 'width' : settings.imageWidth,
										 'height' : settings.imageHeight
									})
									.append('<img src="' + currPhoto['fullUrl'] + '" width="' + settings.imageWidth + '" height="' + settings.imageHeight + '" alt="' + currPhoto['title'] + '" />')
									.mouseover(function() {
										var thisPhotoDiv = $(this);
										playPauseImage
											.css('cursor','pointer')
											.attr('src',(autoPlayStatus) ? settings.pauseButton : settings.playButton)
											.mouseout(function() {
												$(this)
													.css('cursor','default')
													.remove();
											})
											.click(function() {
												if(autoPlayStatus) {
													playPauseImage.attr('src',settings.playButton);
													$(imageSelector).stopTime('autoPlayControl');
													autoPlayStatus = false;
												}
												else {
													playPauseImage.attr('src',settings.pauseButton);
													$(imageSelector).everyTime(settings.autoPlayDelay,'autoPlayControl',function() {
														if(currentPhotoIndex==allPhotos.length-1) { currentPhotoIndex = 0; }
														else { currentPhotoIndex++; }
														photo = allPhotos[currentPhotoIndex];
														var fullPhoto = new Image();
														$(fullPhoto)
															.load(function() {
																$(this).hide();
																imagePhoto.html(this);
																$(this).fadeIn();
															})
															.attr('width',settings.imageWidth)
															.attr('height',settings.imageHeight)
															.attr('alt',photo['title'])
															.attr('src',photo['fullUrl'])
															.css('display','inline');
														imageTitle.html(photo['title']);
														var infoRequestUrl = 'http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=' + settings.flickrApiKey + '&photo_id=' + photo['photo_id'] + '&extras=url_m&format=json&jsoncallback=?';
														$.getJSON(infoRequestUrl,function(data) {
															imageDescription.html(data.photo.description._content);
														});
														if(currentPhotoIndex+(settings.thumbs)<=allPhotos.length) {
															var newPos = (currentPhotoIndex) * (thumbSize);
															scrollSlider($(this),newPos,settings.speed,settings.easing);
														}
													});
													autoPlayStatus = true;
												}
											})
											.prependTo(imageTop);
									})
									.appendTo(imageTop);
					var imageInfo = $("<div />")
									.attr('id',mainDivId + '-image-info')
									.css({
										 'float' : 'left',
										 'width' : ((settings.width-settings.imageWidth)-50) + 'px',
										 'height' : settings.imageHeight + 'px',
										 'margin-left' : '50px'
									})
									.appendTo(imageTop);
					var imageTitle = $("<div />")
									.attr('id',mainDivId + '-image-title')
									.css({
										 'margin-bottom' : '10px',
										 'font-weight' : 'bold',
										 'font-size' : '2em'
									})
									.html(currPhoto['title'])
									.appendTo(imageInfo);
					var imageDescription = $("<div />")
									.attr('id',mainDivId + '-image-description')
									.appendTo(imageInfo);
						var infoRequestUrl = 'http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=' + settings.flickrApiKey + '&photo_id=' + currPhoto['photo_id'] + '&extras=url_m&format=json&jsoncallback=?';
						$.getJSON(infoRequestUrl,function(data) {
							imageDescription.html(data.photo.description._content);
						});
					var imageNavigation = $("<div />")
									.attr('id',mainDivId + '-image-navigation')
									.css({
										 'height' : thumbSize-10 + 'px',
										 'overflow' : 'hidden'
									})
									.appendTo(obj);
					var leftArrow = $("<div />")
									.attr('id',mainDivId + '-left-arrow')
									.css({
										 'float' : 'left',
										 'width' : '15px',
										 'padding-top' : '18px'
									})
									.click(
										   function() {
											   newPos = imageSelector.scrollLeft() - (settings.width-40);
											   scrollSlider(imageSelector,newPos,settings.speed,settings.easing);
											   return false;
										   }
									)
									.append('<a href="#"><img src="' + leftArrowImage + '" alt="Previous" /></a>')
									.appendTo(imageNavigation);
					var imageSelector = $("<div />")
									.attr('id',mainDivId + '-selector')
									.css({
										 'float' : 'left',
										 'width' : (settings.width-40) + 'px', //arrow div width and margin left/right
										 'height' : thumbSize-10 + 'px',
										 'position' : 'relative',
										 'overflow' : 'hidden',
										 'margin-left' : '5px',
										 'margin-right' : '5px'
									})
									.appendTo(imageNavigation);
					var rightArrow = $("<div />")
									.attr('id',mainDivId + '-right-arrow')
									.css({
										 'float' : 'left',
										 'width' : '15px',
										 'padding-top' : '18px'
									})
									.click(
										   function() {
											   newPos = imageSelector.scrollLeft() + (settings.width-40);
											   scrollSlider(imageSelector,newPos,settings.speed,settings.easing);
											   return false;
										   }
									)
									.append('<a href="#"><img src="' + rightArrowImage + '" alt="Next" /></a>')
									.appendTo(imageNavigation);
					var imageSlider = $("<div />")
									.attr('id',mainDivId + '-slider')
									.css({
										 'width' : sliderWidth + 'px',
										 'height' : thumbSize-10 + 'px',
										 'margin' : '0px'
									})
									.appendTo(imageSelector);
					$.each(allPhotos, function(i, photo) {
						var newImage = $("<div />")
										.css({
											 'float' : 'left',
											 'width' : thumbSize-10 + 'px',
											 'height' : thumbSize-10 + 'px',
											 'margin-left' : '5px',
											 'margin-right' : '5px',
											 'opacity' : '0.5'
										})
										.click(function() {
											currentPhotoIndex = i;
											var fullPhoto = new Image();
											$(fullPhoto)
												.load(function() {
													$(this).hide();
													imagePhoto.html(this);
													$(this).fadeIn();
												})
												.attr('width',settings.imageWidth)
												.attr('height',settings.imageHeight)
												.attr('alt',photo['title'])
												.attr('src',photo['fullUrl'])
												.css('display','inline');
											imageTitle.html(photo['title']);
											var infoRequestUrl = 'http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=' + settings.flickrApiKey + '&photo_id=' + photo['photo_id'] + '&extras=url_m&format=json&jsoncallback=?';
											$.getJSON(infoRequestUrl,function(data) {
												imageDescription.html(data.photo.description._content);
											});
											return false;
										})
										.hover(function() {
											$(this).css('opacity','1.0');
										},
									   	function() {
									   		$(this).css('opacity','0.5');
									   	})
										.append('<a href="#"><img src="' + photo['thumbUrl'] + '" width="' + (thumbSize-10) + '" height="' + (thumbSize-10) + '" alt="' + photo['title'] + '" /></a>')
										.appendTo(imageSlider);
					}); //$.each(allPhotos)
				} //else photos.length exists
				if(settings.autoPlay) {
					$(imageSelector).everyTime(settings.autoPlayDelay,'autoPlayControl',function() {
						if(currentPhotoIndex==allPhotos.length-1) { currentPhotoIndex = 0; }
						else { currentPhotoIndex++; }
						photo = allPhotos[currentPhotoIndex];
						var fullPhoto = new Image();
						$(fullPhoto)
							.load(function() {
								$(this).hide();
								imagePhoto.html(this);
								$(this).fadeIn();
							})
							.attr('width',settings.imageWidth)
							.attr('height',settings.imageHeight)
							.attr('alt',photo['title'])
							.attr('src',photo['fullUrl'])
							.css('display','inline');
						imageTitle.html(photo['title']);
						var infoRequestUrl = 'http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=' + settings.flickrApiKey + '&photo_id=' + photo['photo_id'] + '&extras=url_m&format=json&jsoncallback=?';
						$.getJSON(infoRequestUrl,function(data) {
							imageDescription.html(data.photo.description._content);
						});
						if(currentPhotoIndex+(settings.thumbs)<=allPhotos.length) {
							var newPos = (currentPhotoIndex) * (thumbSize);
							scrollSlider($(this),newPos,settings.speed,settings.easing);
						}
					});
					autoPlayStatus = true;
				}
			}); //$.getJSON(requestUrl)
		}); //return this.each()
	};

}) (jQuery);
