$(function(){
	pg.init();
});

var pg = {
	/*user defined*/
	randomAlbum: true, /*boolean: Start with a random image for each gallery*/
	randomImg: false, /*boolean: Start with a random image for each gallery*/
	userId: 'jeremiahjmartin', /*string: Picaca user id*/
	slideDelay: 6000,	/*integer: delay between slides in milliseconds*/
	autoPlay: true, /*boolean: play slideshow when gallery loads*/
	
	/*don't touch*/
	t: '', //timer
	idx: 0,
	imgCount: 0,
	imgTotal: 0,
	detailHeight: 458,
	init: function(){
		
		//check for touch device
		if ("ontouchstart" in document.documentElement) {
			window.scrollTo(0, 1);
			pg.touch = true;
		}
		
		
		pg.writeHTML();
		
		pg.loadAlbums();
		//attach loadGallery to the album links
		$('.pglink').live('click',function(){
			$('.pglink').removeClass('active');
			$(this).addClass('active');
			var galleryURL = this.href;
			var galleryTitle = $(this).children('strong').html();
			pg.loadGallery(galleryURL,galleryTitle);
			if(pg.touch == true) {
				pg.toggleAlbums();
			}
			
			return false;
		});
		
		
		
		if(pg.touch == true) {
			$('#gallerynavtitle').live('click',function(){		
				pg.toggleAlbums();
			});
		} 
		else {
			$('#pgnavalbums').live('hover',function(){		
				pg.toggleAlbums();
			});
		}
		
		
		pg.prevNextInit();
		pg.playPauseInit();
		pg.toggleThumbs();
	}, //End Init
	
	/*--------------------------
	
		Set up all the HTML for the gallery
	
	----------------------------*/
	writeHTML: function(){
		$('#plusgallery').append(
			'<ul id="pgnav">' + 
				'<li id="pgimgtoggle" class="pgcontrols"><a href="#" title="Show Thumbnails"><span>View Thumbnails</span></a></li>' + 
				'<li id="pgplaypause" class="pgcontrols"><a href="#" class="play" title="Play Slideshow"><span>Play Slideshow</span></a></li>' + 
				'<li id="pgnavalbums"><a href="#" id="gallerynavtitle">Loading Albums</a>' + 
					'<ul id="pgsubnavalbums"></ul>' + 
				'</li>' + 
				'<li id="pgimgtitle"></li>' + 
			'</ul>' + 
			'<div id="pgdetail">' + 
				'<div class="loading"><img src="/images/plusgallery/loader.gif"></div>' + 
				'<a href="#" id="pgprev" class="hide pgprevnext">&laquo;</a>' + 
				'<a href="#" id="pgnext" class="hide pgprevnext">&raquo;</a>' + 
			'</div>' + 
			'<div id="pgimages" class="clearfix">' + 
				'<ul>' + 
				'</ul>' + 
			'</div>' + 
			'<div id="pgcredits">' + 
				'<a href="http://www.plusgallery.net" target="_blank">+Gallery</a>' + 
			'</div>' 
		)
	
	
	},
	
	
	/*--------------------------
	
		Load all albums to the page
	
	----------------------------*/
	loadAlbums: function() {
		var albumURL = 'https://picasaweb.google.com/data/feed/base/user/' + pg.userId + '?alt=json&kind=album&hl=en_US&callback=?';
		
		
		$.getJSON(albumURL,function(json) {
			//Successfully Loaded Albums
			var objPath = json.feed.entry;
			
			//Generate a random start index for the album
			var albumTotal = objPath.length;
			var albumStart = Math.random() * (albumTotal - 1);
					albumStart = Math.round(albumStart);	
			
			
			$.each(objPath,function(i,obj){	
				
				//obj is entry
				var galleryTotal = obj.length;
				var galleryTitle = obj.title.$t;
				var galleryImage = obj.media$group.media$thumbnail[0].url;
				var galleryJSON = obj.link[0].href;
				
				//Set a Random Start Album
				if(i == albumStart){
					pg.loadGallery(galleryJSON,galleryTitle);
					
					var activeLink = ' active';
				} 
				else {
					var activeLink = '';
				}
				
				//console.log('i:' + i + '  | albumStart: ' + albumStart + ' | galleryTotal: ' + obj.length);
				//Set up the Subnav
				$('#pgsubnavalbums').append('<li><a href="' + galleryJSON + '" class="pglink' + activeLink + '"><img src="' + galleryImage + '" alt="' + galleryTitle + '"><strong>' + galleryTitle + '</strong></a></li>');
			});
		});
		
	}, //End loadAlbums
	
	/*--------------------------
	
		Load all the images within
		a specific gallery
	
	----------------------------*/
	loadGallery: function(url,title){
		$('#pgnavalbums').blur();//Hide menus for mobile
		$('#gallerynavtitle').html(title);
		
		//Set the height of #photodetail to 60% of the window height. Why 60? becuase it works well on mobile and fine for desktop
		var winHeight = $(window).height();
		var detailHeight = winHeight * .6;

		$('#pgdetail').height(detailHeight);
		
		//set up the top pos for the loading image
		pg.loadingMargin();
		$.getJSON(url,function(json) {
			$('#pgimages ul').empty();
			var objPath = json.feed.entry;	
			
			pg.imgTotal = objPath.length;

			//Generate a random start index for the Image
			if(pg.randomImg == true) {
				
				var imgStart = Math.random() * (pg.imgTotal - 1);
						imgStart = Math.round(imgStart);	
			} 
			else {
				imgStart = 0;
			}
						
			$.each(objPath,function(i,obj){
				var imgTitle = obj.title.$t;
				var imgSrc = obj.media$group.media$content[0].url;
				var imgTh = obj.media$group.media$thumbnail[1].url;
				
				//Set a Random Start Album
					if(i == imgStart){
						pg.imgCount = i + 1;
						pg.loadImage(imgSrc,imgTitle);
						var activeClass = ' active';
					} else {
						var activeClass = '';
					}
				
				$('#pgimages ul').append('<li><a href="' + imgSrc + '" class="detaillink' + activeClass + '" title="' + imgTitle + '" data-count="' + parseInt(i + 1) + '"><img src="/images/plusgallery/blank-90.gif" alt="' + imgTitle + '" style="background: url(' + imgTh + ') no-repeat 50% 50%"></a></li>');
			});
		});
		
		//attach links load detail image
		$('.detaillink').live('click',function(){
			var winPos = 	$(window).scrollTop();				 
			
			var scrollPos = $("#plusgallery").offset().top - 10;
			
			//scroll the window to the top of the gallery
			
			if(winPos > scrollPos) {
				$('body').stop().animate({
					scrollTop: scrollPos
				}, 350);	
			}
																				 
			//stop slideshow
			pg.playPauseToggle(false);																		 
																					 
			$('.detaillink').removeClass('active');		
			$(this).addClass('active');
			pg.imgCount = $(this).attr('data-count');
			pg.imgCount = parseInt(pg.imgCount);
			var imgURL = this.href;
			var imgTitle = this.title;
			pg.loadImage(imgURL,imgTitle);
			return false;
		});
	}, //End loadGallery
	
	/*--------------------------
	
		Function that loads the
		detail image
	
	----------------------------*/
	loadImage: function(src,title){
		
		$('#pgdetail .loading').fadeIn(200);
		
		
		//console.log('pg.imgCount: ' + pg.imgCount);
		//Show/hide the previous/next buttons
		switch(pg.imgCount)
		{
		case 1:
			//Hide prev
			$('#pgprev').fadeOut(300,function(){
				$(this).addClass('hide');																																						
			});
			
			$('#pgnext').fadeIn(300);
			//console.log('1: hide prev');
			break;
		case pg.imgTotal:
			//Hide Next
			$('#pgnext').fadeOut(300,function(){
				$(this).addClass('hide');																																						
			});
			
			
			$('#pgprev').fadeIn(300);
			//console.log('2: hide next');
			break;
		default:
			//show them both
			if($('#pgprev').hasClass('hide')){
				$('#pgprev').fadeIn(300,function(){
					$(this).removeClass('hide');																																						
				});															
			}
			
			if($('#pgnext').hasClass('hide')){
				$('#pgnext').fadeIn(300,function(){
					$(this).removeClass('hide');																																						
				});															
			}
			//console.log('3: show all');
		}
		
		$("#pgdetail div.detailimg").addClass('back');
		$("#pgdetail div.detailimg").removeClass('front');
		$("#pgdetail").append('<div class="front detailimg"><div class="centerer"></div></div>');
		$('.centerer').height($('#pgdetail').height());
		$('.centerer').width($('#pgdetail').width());
		var galleryImg = new Image();
		
		$(galleryImg).load(function(){
			$('#pgdetail .loading').fadeOut(200);
			//Happens once the image is loaded.		
			$("#pgdetail .front .centerer").html(this);
			$("#pgdetail .front").fadeIn(function(){
				pg.detailHeight = $('#pgdetail').height();
				
				$("#pgdetail .back").remove();
			});
			$("#pgdetail .back").fadeOut();
		
			
		}).attr('src',src).attr('title',title);
		
		$('#pgimgtitle').html('<span>' + title + '</span>');
	},//End loadImage
	
	/*--------------------------
	
		Function that loas the prev 
		or next slide and 
		accepts a "+" 
		or "-" argument.
	
	----------------------------*/
	prevNext: function(dir){
		$('.detaillink').removeClass('active');
				
		if(dir == '+'){
			var nextCount = pg.imgCount + 1;
			var nextIdx = pg.imgCount;
			var nextThumb = $('.detaillink:eq(' + nextIdx + ')');
			nextThumb.addClass('active');
			pg.imgCount = nextThumb.attr('data-count');
			pg.imgCount = parseInt(pg.imgCount);
			var imgURL = nextThumb.attr('href');
			var imgTitle = nextThumb.attr('title');
		}
		else {
			var prevCount = pg.imgCount - 1;
			var prevIdx = pg.imgCount - 2;
			var prevThumb = $('.detaillink:eq(' + prevIdx + ')');
			
			prevThumb.addClass('active');
			pg.imgCount = prevThumb.attr('data-count');
			pg.imgCount = parseInt(pg.imgCount);
			var imgURL = prevThumb.attr('href');
			var imgTitle = prevThumb.attr('title');
		}
		pg.loadImage(imgURL,imgTitle);
	},
	
	/*--------------------------
	
		attaches previous/next
		functionality to buttons
	
	----------------------------*/
	prevNextInit: function(){
		$('#pgprev').live('click',function(){
			pg.prevNext('-');
			
			//stop slideshow
			pg.playPauseToggle(false);
			
			return false;
		});
		
		$('#pgnext').live('click',function(){
			pg.prevNext('+');
			
			//stop slideshow
			pg.playPauseToggle(false);
			
			return false;
		});
	},
	
	/*--------------------------
	
		Function attaches clicks to 
		thumb toggle and creates 
		action
	
	----------------------------*/
	toggleThumbs: function(){
			
		
		
		$('#pgimgtoggle a').click(function(){
			$(this).toggleClass('active');
			$('#pgimages').animate(
				{
					height: 'toggle',
					opacity: 'toggle'
				}
			);
			
			
			var winPos = 	$(window).scrollTop();	
			var bottomOfWin = winPos + $(window).height();
			var scrollPos = $("#plusgallery").offset().top - 10;
			var thumbPos = $("#pgdetail").offset().top  + $("#pgdetail").height();
			console.log(thumbPos);
			console.log(bottomOfWin);
			//scroll the window to the top of the gallery
			
			if(thumbPos > bottomOfWin) {
				$('body').stop().animate({
					scrollTop: scrollPos
				}, 350);	
			}		
			
			
			return false;
		});	
		
		
	},
	
	
	/*--------------------------
	
		Function to show and 
		hide album subnav menus
	
	----------------------------*/
	toggleAlbums: function(){
		
		
		$('#pgsubnavalbums').stop(false,true).animate({
				opacity: 'toggle',
				height: 'toggle'
			}, 250, 
			function(){
				
			}
		);
	},
	
	
	
	
	/*--------------------------
	
		Function sets the top 
		position for the loading 
		animation and the prev/next
		buttons
	
	----------------------------*/
	loadingMargin: function() {
		var detailHeight = $('#pgdetail').height();
		var loadMargin = (detailHeight - 54)/2;
		$('#pgdetail .loading').css('top',loadMargin + 'px');
		
		var prevNextMargin = (detailHeight - 38)/2;
		$('.pgprevnext').css('top',prevNextMargin + 'px');
		
	}, 
	
	/*--------------------------
	
		set up play/pause functionality
	
	----------------------------*/
	
	playPauseTimer: function(play){
		var playButton = $('#pgplaypause a');
		var playTitle = playButton.attr('title');
			if(play == true){
			pg.t = setTimeout(function(){
				pg.prevNext('+');
				if(pg.imgCount == pg.imgTotal) {
					pg.imgCount = 0;
				}
				pg.playPauseTimer(pg.autoPlay);
			},pg.slideDelay);
		}
	},
	playPauseToggle: function(play){
		var playButton = $('#pgplaypause a');
		var playTitle = playButton.attr('title');
		if(play == true) {
			playButton.removeClass('play');
			playButton.addClass('pause');
			playButton.attr('title',playTitle.replace('Play','Pause'));
			pg.playPauseTimer(true);
			pg.autoPlay = true;
		}
		else {
			playButton.removeClass('pause');
			playButton.addClass('play');
			playButton.attr('title',playTitle.replace('Pause','Play'));	
			clearTimeout(pg.t);	
			pg.autoPlay = false;
		}
	},
	
	playPauseInit: function(){
		
		var playButton = $('#pgplaypause a');
		var playTitle = playButton.attr('title');
		
		pg.playPauseToggle(pg.autoPlay);
		
		playButton.click(function(){
			if(playButton.hasClass('play')) {
				pg.playPauseToggle(true);
				
			}
			else {
				pg.playPauseToggle(false);
			}
			return false;
		
		});
	}
}

