/*
 * jQuery Postr 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) thumbRows - the number of thumbnails to rows show in the slider.
 *  (int) thumbCols - the number of thumbnail columns to show in the slider.
 *  (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>
 *
 * $(document).ready(function() {
 *    $("div#gallery").gallery({
 *							   flickrApiKey : 'jkd2iddj2h8zkxl10a6t56ro',
 *							   flickrPhotosetId : '99999999999999999',
 *							   width : 485,
 *							   height : 400,
 *							   imageWidth: 320,
 *							   imageHeight: 450,
 *							   thumbRows: 3,
 *							   thumbCols: 3,
 * 							   speed: 'normal',
 *							   easing: 'swing'
 * 							   });
 * });
 */

var CURRENT_PHOTO_INDEX = 0;

(function($) {

	//FUNCTIONS
	function changePage(perPage,currPage,settings,mainDivId,imageSlider,imageColumn,thumbWidth,thumbHeight) {
		var allPhotos = new Array();
		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&per_page=' + perPage + '&page=' + currPage + '&format=json&jsoncallback=?';
		$.getJSON(requestUrl,function(data) {
		  if(data.stat!="fail") {
			  $.each(data.photoset.photo, function(i,image) {
				  allPhotos.push({
					  photo_id : image.id,
					  title : image.title,
					  description : image.title,
					  fullUrl : image.url_m,
					  thumbUrl : image.url_t
				  });
			  });
		  }
		  if(allPhotos.length) {
			  imageSlider.animate({'opacity':'0'},settings.speed,settings.easing,function() {
					imageSlider.empty();
			  });
			  imageSlider.animate({'opacity':'1'},settings.speed,settings.easing,function() {
				  $.each(allPhotos, function(i, photo) {
					  var newImage = $("<div />")
									  .css({
										   'float' : 'left',
										   'width' : thumbWidth + 'px',
										   'height' : thumbHeight + 'px',
										   'margin' : '2px',
										   'opacity' : '0.5'
									  })
									  .click(function() {
										  if($("div#" + mainDivId + "-image-share-popup").size()) {
										  	   $("div#" + mainDivId + "-image-share-popup").remove();
										  }
										  var fullPhoto = new Image();
										  $(fullPhoto)
											  .load(function() {
												  $(this).hide();
												  imageColumn.html(this);
												  $(this).fadeIn();
											  })
											  .attr('width',settings.imageWidth)
											  .attr('height',settings.imageHeight)
											  .attr('alt',photo['title'])
											  .attr('src',photo['fullUrl'])
											  .css('display','inline')
										  CURRENT_PHOTO_INDEX = i;
										  return false;
									  })
									  .append('<a href="#"><img src="' + photo['thumbUrl'] + '" width="' + (thumbWidth) + '" height="' + (thumbHeight) + '" alt="' + photo['title'] + '" /></a>')
									  .appendTo(imageSlider);
				  });
			  });
		  }
		});
		return allPhotos;
	}

	$.fn.postr = function(options) {
		//DEFAULT SETTINGS
		var settings = $.extend({
			flickrApiKey : '',
			flickrPhotosetId : '',
			width : 485,
			height : null,
			imageWidth : 320,
			imageHeight: 450,
			thumbRows : 3,
			thumbCols : 3,
			speed : 'normal',
			easing : 'swing',
			prevButton : '',
			prevOverButton : '',
			nextButton : '',
			nextOverButton : '',
			playButton : '',
			pauseButton : '',
			downloadFilePath : '',
			autoPlay : false,
			autoPlayDelay : 5000
		},options);

		//PROPERTIES
		var imageNavigationHeight = (settings.height) ? settings.height : Math.ceil(settings.imageHeight*0.6);
		var originalHTML = '';
		var mainDivId = '';
		var previousImage = settings.prevButton;
		var previousOverImage = settings.prevOverButton;
		var nextImage = settings.nextButton;
		var nextOverImage = settings.nextOverButton;
		var downloadURL = settings.downloadFilePath;
		var currPhoto = {
			title : '',
			url : ''
		};
		//CALCULATIONS
		var totalPhotos = 0;
		var perPage = settings.thumbCols * settings.thumbRows;
		var totalPages = 1;
		var currPage = 1;
		var frameWidth = (settings.width-settings.imageWidth)-20;
		var thumbWidth = Math.floor(frameWidth/(settings.thumbCols)-4);
		var thumbHeight = Math.ceil((imageNavigationHeight-14)/settings.thumbRows)-4;
		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&per_page=' + perPage + '&page=' + currPage + '&format=json&jsoncallback=?';
			$.getJSON(requestUrl,function(data) {
				totalPhotos = data.photoset.total;
				totalPages = Math.ceil(totalPhotos/perPage);
				$.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
					});
				});
				if(allPhotos.length==0) { obj.html(originalHTML); }
				else {
					obj.css({
							'height' : settings.imageHeight
					});
					var controlsColumn = $("<div />")
									.attr('id',mainDivId + '-controls-column')
									.css({
										 'float' : 'left',
										 'width' : frameWidth + 'px',
										 'height' : settings.imageHeight,
										 'margin-right' : '20px'
									})
									.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 allowMouseOver = true;
					var imageColumn = $("<div />")
									.attr('id',mainDivId + '-image-column')
									.css({
										 'float' : 'left',
										 'width' : settings.imageWidth + 'px',
										 'height' : settings.imageHeight + 'px'
									})
									.append('<img src="' + currPhoto['fullUrl'] + '" width="' + settings.imageWidth + '" height="' + settings.imageHeight + '" alt="' + currPhoto['title'] + '" />')
									.mouseover(function() {
										if(!allowMouseOver) return 1;
										var thisPhotoDiv = $(this);
										playPauseImage
											.css('cursor','pointer')
											.attr('src',(autoPlayStatus) ? settings.pauseButton : settings.playButton)
											.mouseout(function() {
												allowMouseOver = true;
												$(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($("div#" + mainDivId + "-image-share-popup").size()) {
															$("div#" + mainDivId + "-image-share-popup").remove();
														}
														if(CURRENT_PHOTO_INDEX==allPhotos.length-1) { CURRENT_PHOTO_INDEX = 0; }
														else { CURRENT_PHOTO_INDEX++; }
														photo = allPhotos[CURRENT_PHOTO_INDEX];
														var fullPhoto = new Image();
														$(fullPhoto)
															.load(function() {
																$(this).hide();
																imageColumn.html(this);
																$(this).fadeIn();
															})
															.attr('width',settings.imageWidth)
															.attr('height',settings.imageHeight)
															.attr('alt',photo['title'])
															.attr('src',photo['fullUrl'])
															.css('display','inline');
													});
													autoPlayStatus = true;
												}
											})
											.prependTo(imageColumn);
											allowMouseOver = false;
									})
									.appendTo(obj);
					var imageNavigation = $("<div />")
									.attr('id',mainDivId + '-image-navigation')
									.css({
										 'height' : imageNavigationHeight + 'px',
										 'overflow' : 'hidden',
										 'margin-top' : ((settings.imageHeight-imageNavigationHeight)-0) + 'px'
									})
									.appendTo(controlsColumn);
					if(totalPages>1) {
						var imageSwitcher = $("<div />")
										.attr('id',mainDivId + 'image-switcher')
										.css({
											 'height' : '14px',
											 'margin-bottom' : '5px'
										})
										.appendTo(imageNavigation);
						var imagePagination = $("<div />")
										.attr('id',mainDivId + 'image-pagination')
										.css({
											 'float' : 'left',
											 'width' : (frameWidth-76) + 'px',
											 'height' : '14px'
										})
										.appendTo(imageSwitcher);
						for(var x=1;x<=totalPages;x++) {
							var pageNum = $("<div />")
											.attr('title',x)
											.css({
												 'float' : 'left',
												 'margin-right' : '3px'
											})
											.click(function() {
												currPage = $(this).attr('title');
												allPhotos = changePage(perPage,currPage,settings,mainDivId,imageSlider,imageColumn,thumbWidth,thumbHeight)
												return false;
											})
											.append("<a href=\"#\">" + x + "</a>")
											.appendTo(imagePagination);
						}
					}
					var imageSelector = $("<div />")
									.attr('id',mainDivId + '-selector')
									.css({
										 'width' : frameWidth + 'px',
										 'height' : imageNavigationHeight-14 + 'px',
										 'position' : 'relative',
										 'overflow' : 'hidden'
									})
									.appendTo(imageNavigation);
					var imageButtons = $("<div />")
									.attr('id',mainDivId + 'image-buttons')
									.css({
										 'float' : 'left',
										 'width' : '76px',
										 'height' : '14px'
									})
									.appendTo(imageSwitcher);
					var previousButton = $("<div />")
									.attr('id',mainDivId + '-previous-button')
									.css({
										 'float' : 'left',
										 'width' : '37px',
										 'height' : '14px'
									})
									.click(
											function() {
												if(currPage>1) {
													currPage--;
													allPhotos = changePage(perPage,currPage,settings,mainDivId,imageSlider,imageColumn,thumbWidth,thumbHeight);
													CURRENT_PHOTO_INDEX = allPhotos.length-1;
												}
												return false;
											}
									)
									.append('<a href="#"><img src="' + previousImage + '" alt="Previous" onmouseover="this.src=\'' + previousOverImage + '\'" onmouseout="this.src=\'' + previousImage + '\'" /></a>')
									.appendTo(imageButtons);
					var nextButton = $("<div />")
									.attr('id',mainDivId + '-next-button')
									.css({
										 'float' : 'left',
										 'width' : '39px',
										 'height' : '14px'
									})
									.click(
											function() {
												if(currPage<totalPages) {
													currPage++;
													allPhotos = changePage(perPage,currPage,settings,mainDivId,imageSlider,imageColumn,thumbWidth,thumbHeight);
													CURRENT_PHOTO_INDEX = allPhotos.length-1;
												}
												return false;
											}
									)
									.append('<a href="#"><img src="' + nextImage + '" alt="Next" onmouseover="this.src=\'' + nextOverImage + '\'" onmouseout="this.src=\'' + nextImage + '\'" /></a>')
									.appendTo(imageButtons);
					var imageSlider = $("<div />")
									.attr('id',mainDivId + '-slider')
									.css({
										 'width' : frameWidth + 'px',
										 'height' : imageNavigationHeight-14 + 'px',
										 'margin' : '0px'
									})
									.appendTo(imageSelector);
					$.each(allPhotos, function(i, photo) {
						var newImage = $("<div />")
										.css({
											 'float' : 'left',
											 'width' : thumbWidth + 'px',
											 'height' : thumbHeight + 'px',
											 'margin' : '2px',
											 'opacity' : '0.5'
										})
										.click(function() {
											if($("div#" + mainDivId + "-image-share-popup").size()) {
												$("div#" + mainDivId + "-image-share-popup").remove();
											}
											var fullPhoto = new Image(settings.imageWidth,settings.imageHeight);
											$(fullPhoto)
												.load(function() {
													$(this).hide();
													imageColumn.html(this);
													$(this).fadeIn();
												})
												.attr('alt',photo['title'])
												.attr('src',photo['fullUrl'])
												.css('display','inline');
											allowMouseOver = true;
											CURRENT_PHOTO_INDEX = i;
											return false;
										})
										.append('<a href="#"><img src="' + photo['thumbUrl'] + '" width="' + (thumbWidth) + '" height="' + (thumbHeight) + '" alt="' + photo['title'] + '" /></a>')
										.appendTo(imageSlider);
						newImage.hover(function() {
											newImage.css('opacity','1.0')
									   },
									   function() {
									   		newImage.css('opacity','0.5')
									   }
						);
					});
					/*var shareButton = $("<div />")
									.attr('id',mainDivId + '-image-share')
									.css({
										 'height' : '18px',
										 'text-align' : 'center',
										 'font-weight' : 'bold',
										 'background-color' : '#f1f1f1',
										 'margin' : '2px 2px 0px 2px'
									})
									.appendTo(controlsColumn);
					var shareLink = $("<a />")
									.attr('href','#')
									.css({
										 'display' : 'block'
									})
									.html("Share")
									.click(function() {
										if($("div#" + mainDivId + "-image-share-popup").size()) {
											$("div#" + mainDivId + "-image-share-popup").remove();
										}
										else {
												imageUrl = $("div#" + mainDivId + "-image-column > img").attr('src');
												$("<div />")
													.attr('id',mainDivId + '-image-share-popup')
													.css({
														 'width' : settings.imageWidth,
														 'height' : '33px',
														 'background-color' : shareButton.css('background-color'),
														 'padding' : '3px',
														 'position' : 'relative',
														 'top' : '-15px',
														 'left' : '208px'
													})
													.html("<input id=\"shareUrl\" type=\"text\" name=\"shareUrl\" value=\"" + imageUrl + "\" style=\"width:" + (settings.imageWidth-20) + "px;\" onfocus=\"this.select()\"/>")
													.appendTo(shareButton);
										}
										return false;
													})
									.appendTo(shareButton);*/
					/*var downloadButton = $("<div />")
									.attr('id',mainDivId + '-image-download')
									.css({
										 'height' : '18px',
										 'text-align' : 'center',
										 'font-weight' : 'bold',
										 'background-color' : '#f1f1f1',
										 'margin' : '2px 2px 0px 2px'
									})
									.appendTo(controlsColumn);
					var downloadLink = $("<a />")
									.attr('href','#')
									.css({
										 'display' : 'block'
									})
									.html("Download")
									.click(function() {
										imageUrl = $("div#" + mainDivId + "-image-column > img").attr('src');
										$("<form />")
											.attr('action',downloadURL)
											.attr('method','post')
											.append("<input type=\"hidden\" name=\"file\" value=\"" + imageUrl + "\" />")
											.appendTo('body')
											.submit()
											.remove();
										return false;
									})
									.appendTo(downloadButton);*/
				}
				if(settings.autoPlay) {
					$(imageSelector).everyTime(settings.autoPlayDelay,'autoPlayControl',function() {
						if($("div#" + mainDivId + "-image-share-popup").size()) {
							$("div#" + mainDivId + "-image-share-popup").remove();
						}
						if(CURRENT_PHOTO_INDEX==allPhotos.length-1) { CURRENT_PHOTO_INDEX = 0; }
						else { CURRENT_PHOTO_INDEX++; }
						photo = allPhotos[CURRENT_PHOTO_INDEX];
						var fullPhoto = new Image(settings.imageWidth,settings.imageHeight);
						$(fullPhoto)
							.load(function() {
								$(this).hide();
								imageColumn.html(this);
								$(this).fadeIn();
							})
							.attr('width',settings.imageWidth)
							.attr('height',settings.imageHeight)
							.attr('alt',photo['title'])
							.attr('src',photo['fullUrl'])
							.css('display','inline');
						allowMouseOver = true;
					});
					autoPlayStatus = true;
				}
			}); //$.getJSON(requestUrl)
		}); //return this.each
	};

}) (jQuery);
