var mc_flickr_gallery_collection_id = '53480120-72157625559532638';

jQuery(document).ready(function() {
	/* Preload the videos in the background */
	loadVideos();
	
	jQuery(window).hashchange(function(){
		/* Hash permalinks */
		var hash = document.location.hash.replace('#','').rtrim('/');
		if(hash) {
			aryHash = hash.split('/');
			switch(aryHash[0]) {
				case 'Photos':
					/* Hide Videos incase hash was changed by the browser back button */
					jQuery('#vbox-wrapper .innertube').html('');
					jQuery('#gallery-wrapper div#videos-wrapper').hide();
					jQuery('#gallery-wrapper #page-tabs').hide();
					
					/* Make sure the Photos button is active */
					activatePhotosButton();
					
					if(aryHash.length>1) {
						jQuery('#gallery-wrapper div.innertube').addClass('slider');
					
						switch(aryHash[1]) {
							case 'Most-Recent':
								galleryClick({'query':'most-recent'});
								break;
							case 'Most-Viewed':
								galleryClick({'query':'most-viewed'});
								break;
							default:
								//id = aryHash[1].replace(new RegExp( "_", "g" ), " " );
								id = hash.replace('Photos/','').replace(new RegExp('_','g'),' ');
								galleryClick({'query':'gallery','title':id});
								break;
						}
					}
					else {
						/* Hash is just #Photos, hide the activity indicator & show photos*/
						hideActivityIndicator();
						jQuery('#slider-wrapper').fadeOut('fast');
						jQuery('#gallery-wrapper #photos-wrapper').fadeIn('fast');
					}
					break;
				case 'Videos':
					activateVideosButton();
		
					if(aryHash.length==1) {
						/* Hash is just #Videos */
						jQuery('#vbox-wrapper .innertube').html('');
						jQuery('#gallery-wrapper #page-tabs').show();
						jQuery('#gallery-wrapper div#photos-wrapper').hide();
						jQuery('#gallery-wrapper div#videos-wrapper').fadeIn('fast');
						jQuery('#vbox-wrapper').fadeOut('fast');
					}
					else {
						/* If hash has a deep permlink and this is a brand new page load, */
						/* loadVideos will automatically show the vbox once the rest have loaded */
						
						/* If the video thumbs have already loaded, call videoClick() now */
						if(typeof(jQuery('#videos-container ul').css('display')) != 'undefined')
							videoClick();
					}
					break;
			}
		}
		else {
			/* No hash, hide activity indicator and display galleries */
			hideActivityIndicator();
			jQuery('#vbox-wrapper').fadeOut('fast');
			jQuery('#slider-wrapper').fadeOut('fast');
			jQuery('#gallery-wrapper #photos-wrapper').fadeIn('fast');
		}
	}) /* end hashchange */
	
	jQuery(window).hashchange();
	
	/* Gallery Navigation */
	jQuery('#left-scroll').click(function(event) {
		event.preventDefault();
		thumbScroll(-1);
	});
	
	jQuery('#right-scroll').click(function(event) {
		event.preventDefault();
		thumbScroll(1);
	});
});

function bindClickOutside() {
	jQuery('#slider-wrapper').bind('clickoutside',function(event){
		hideActivityIndicator();
		jQuery('#gallery-wrapper #photos-wrapper').show();
		jQuery('#slider-wrapper').fadeOut('fast');
		jQuery('#gallery-wrapper #gallery-content').height('auto');
		jQuery('#slider-wrapper #thumbnails').html('');
		jQuery('#slider-wrapper #larger').css({'opacity':0});
		jQuery('#slider-wrapper #larger').html('');
		document.location.hash='Photos';
		
		jQuery('#gallery-wrapper div.innertube').removeClass('slider');
		
		/* Unbind clickoutside */
		jQuery('#slider-wrapper').unbind('clickoutside');
	});
}

function activatePhotosButton() {
	jQuery('#gallery-wrapper #photos-link').addClass('active');
	jQuery('#gallery-wrapper #videos-link').removeClass('active');
	Cufon.refresh('#gallery-wrapper #media-tabs li a');
}

function activateVideosButton() {
	jQuery('#gallery-wrapper #photos-link').removeClass('active');
	jQuery('#gallery-wrapper #videos-link').addClass('active');
	Cufon.refresh('#gallery-wrapper #media-tabs li a');
}

function galleryClick(options) {
	/* Set up the lightbox & fade it in */
	jQuery('#slider-wrapper>#slider-content').css({'min-height':jQuery('#gallery-wrapper>#gallery-content').height()});

	jQuery('#slider-wrapper').fadeIn('fast',function(){
		/* Don't bind clickoutside event until slider finishes fading in */
		bindClickOutside();
	});
	
	/* Build JSON query */
	var query = 'http://api.flickr.com/services/rest/';
	var key = '82a9d6317f8ec593c4d7dbad65f0fe0c';
	switch(options['query']) {
		case 'most-recent':
			var photos = jQuery.parseJSON(jQuery('#recent-data script').html());
			var photoset = new Array();
			photoset['photoset'] = new Array();
			photoset['photoset']['photo'] = photos;
			loadPhotosFromArray(photoset,'photoset');
			break;
		
		case 'most-viewed':
			var photos = jQuery.parseJSON(jQuery('#viewed-data script').html());
			var photoset = new Array();
			photoset['photoset'] = new Array();
			photoset['photoset']['photo'] = photos;
			loadPhotosFromArray(photoset,'photoset');
			break;
		
		case 'gallery':
			query += '?format=json&method=flickr.collections.getTree&api_key='+key+'&user_id=53503174@N03&jsoncallback=?';
			findSetInCollection(query,options);
			break;
	}
	
}

function findSetInCollection(query,options) {
	var key = '82a9d6317f8ec593c4d7dbad65f0fe0c';
	var photosInSetQuery = 'http://api.flickr.com/services/rest/';
	jQuery.getJSON(query,function(data){
		for(var collection_index=0;collection_index<data['collections']['collection'].length;collection_index++)  {
			if(data['collections']['collection'][collection_index]['id']==mc_flickr_gallery_collection_id)
				break;
		}
		var sets = data['collections']['collection'][collection_index]['set'];
		var found=0;

		for(var i=0; i<sets.length; i++) {
			if(sets[i]['title']==options['title']) {
				// Found set
				found=1;
				photosInSetQuery += '?format=json&method=flickr.photosets.getPhotos&photoset_id='+sets[i]['id'] + '&api_key='+key+'&extras=tags,description&jsoncallback=?';
				getPhotosInSet(photosInSetQuery,'photoset');
			}
		}
		if(found==0) {
			/* Invalid gallery, go back */
			document.location.hash='#Photos';
		}
	});
}

function getPhotosInSet(query,rootElement) {		
	/* Get my JSON object */
	jQuery.getJSON(query,function(data){
		/* build some thumbnails */
		var thumbnailHTML = '<ul id="thumbs">';
		var i=0;
		for(i=0;i<data[rootElement]['photo'].length;i++) {
			var thumbURL = buildPhotoURL(data[rootElement]['photo'][i],'square');
			
			var id=data[rootElement]['photo'][i]['secret'] + ',' + data[rootElement]['photo'][i]['id'] + ',' + data[rootElement]['photo'][i]['farm'] + ',' + data[rootElement]['photo'][i]['server'];
			
			var li_class='';
			if(i==0)
				li_class='class="active"';
			thumbnailHTML += '<li id="id_'+i+'" '+li_class+'><img  id="id_'+id+'" src="'+thumbURL+'" />';
			var description = data[rootElement]['photo'][i]['description'];
	
			var desc = description._content.split(/credit(s|):/i)[0];
			var credit = '';
			
			var aryDesc = description._content.split(/credit(s|):/i);
		
			if(aryDesc.length>2) {
				credit = aryDesc[2];
			}
		
			if(data[rootElement]['photo'][i]['tags'].search(/credit:/i)>-1) {
				/* Tags contains Credit: */
				credit = data[rootElement]['photo'][i]['tags'].replace(/credit:/gi,'');
				credit = credit.replace(/credit: /gi,'');
			}
		
			thumbnailHTML += '<span class="description">'+desc+'</span>';
			thumbnailHTML += '<span class="credit">'+credit+'</span>';
			thumbnailHTML += '</li>'; 
		}
		thumbnailHTML += '</ul>';
		
		/* update html with thumb list */
		jQuery('#slider-wrapper #slider-content #thumbnails').html(thumbnailHTML);
		
		/* Bind click event */
		jQuery('#thumbnails ul li').click(function(){
			var index = jQuery(this).attr('id');
			index = parseInt(index.replace('id_',''));
			galleryActivateImage(index);
		});
				
		/* resize the thumbs ul to fit */
		jQuery('#slider-wrapper #slider-content #thumbnails ul').width(data[rootElement]['photo'].length * 100);
		jQuery('#slider-wrapper #slider-content #thumbnails ul').fadeIn('fast');
		
		/* Show the first image */
		largeImageURL = buildPhotoURL(data[rootElement]['photo'][0],'medium');
		largeImageHTML = '<a href="javascript:gnext()"><img src="'+largeImageURL+'" /></a>';
		
		/* Is there a description or credit? */
		var description = jQuery('#slider-wrapper #thumbnails ul li.active span.description').html();
		var credit = jQuery('#slider-wrapper #thumbnails ul li.active span.credit').html();

		if(description != '')
			largeImageHTML += '<span class="description">' + description + '</span>';
		if(credit != '')
			largeImageHTML += '<span class="credit">Credit: ' + credit + '</span>'
		jQuery('#slider-wrapper #slider-content #larger').html(largeImageHTML);
		Cufon.refresh('#slider-wrapper #larger span.credit');
		Cufon.refresh('#slider-wrapper #larger span.description');
		jQuery('#slider-wrapper #slider-content #larger img').load(function(){
			jQuery('#slider-wrapper #slider-content #larger').animate({'opacity':1},450);
			ie7ImageFix();
			jQuery('#slider-wrapper span.description').width(jQuery('#slider-wrapper #larger img').width());
		});
	});
	
}


function loadPhotosFromArray(data,rootElement) {		
		/* build some thumbnails */
		var thumbnailHTML = '<ul id="thumbs">';
		var i=0;
		for(i=0;i<data[rootElement]['photo'].length;i++) {
			var thumbURL = buildPhotoURL(data[rootElement]['photo'][i],'square');
			
			var id=data[rootElement]['photo'][i]['secret'] + ',' + data[rootElement]['photo'][i]['id'] + ',' + data[rootElement]['photo'][i]['farm'] + ',' + data[rootElement]['photo'][i]['server'];
			
			var li_class='';
			if(i==0)
				li_class='class="active"';
			thumbnailHTML += '<li id="id_'+i+'" '+li_class+'><img  id="id_'+id+'" src="'+thumbURL+'" />';
			var description = data[rootElement]['photo'][i]['description'];
			var desc = description;
			var credit = '';
			if(data[rootElement]['photo'][i]['tags'].search(/credit:/i)>-1) {
				/* Tags contains Credit: */
				credit = data[rootElement]['photo'][i]['tags'].replace(/credit:/gi,'');
				credit = credit.replace(/credit: /gi,'');
			}
		
			thumbnailHTML += '<span class="description">'+desc+'</span>';
			thumbnailHTML += '<span class="credit">'+credit+'</span>';
			thumbnailHTML += '</li>'; 
		}
		thumbnailHTML += '</ul>';
		
		/* update html with thumb list */
		jQuery('#slider-wrapper #slider-content #thumbnails').html(thumbnailHTML);
		
		/* Bind click event */
		jQuery('#thumbnails ul li').click(function(){
			var index = jQuery(this).attr('id');
			index = parseInt(index.replace('id_',''));
			galleryActivateImage(index);
		});
				
		/* resize the thumbs ul to fit */
		jQuery('#slider-wrapper #slider-content #thumbnails ul').width(data[rootElement]['photo'].length * 100);
		jQuery('#slider-wrapper #slider-content #thumbnails ul').fadeIn('fast');
		
		/* Show the first image */
		largeImageURL = buildPhotoURL(data[rootElement]['photo'][0],'medium');
		largeImageHTML = '<a href="javascript:gnext()"><img src="'+largeImageURL+'" /></a>';
		
		/* Is there a description or credit? */
		var description = jQuery('#slider-wrapper #thumbnails ul li.active span.description').html();
		var credit = jQuery('#slider-wrapper #thumbnails ul li.active span.credit').html();

		if(description != '')
			largeImageHTML += '<span class="description">' + description + '</span>';
		if(credit != '')
			largeImageHTML += '<span class="credit">Credit: ' + credit + '</span>'
		jQuery('#slider-wrapper #slider-content #larger').html(largeImageHTML);
		Cufon.refresh('#slider-wrapper #larger span.credit');
		Cufon.refresh('#slider-wrapper #larger span.description');
		jQuery('#slider-wrapper #slider-content #larger img').load(function(){
			jQuery('#slider-wrapper #slider-content #larger').animate({'opacity':1},450);
			ie7ImageFix();
			jQuery('#slider-wrapper span.description').css('min-width','200px');
			jQuery('#slider-wrapper span.description').width(jQuery('#slider-wrapper #larger img').width());
		});

	
}

function bindLargerClickHandler() {
	jQuery('#slider-wrapper #larger img').click(function(){
		thumbScroll(1);
	});
}

function unbindLargerClickHandler() {
	jQuery('#slider-wrapper #larger img').unbind();
}

function gnext() {
	thumbScroll(1);
}

function thumbScroll(direction) {
	/* What image is currently selected? */
	var index = jQuery('#slider-wrapper #slider-content #thumbnails ul li.active').attr('id');
	index = parseInt(index.replace('id_',''));
	
	/* At the end and trying to advance? Go to beginning */
	if(direction==1 && index == jQuery('#thumbnails ul>li').size()-1) {
		direction=1;
		index=-1;
	}
	
	/* Make sure we can't step out of bounds */
	if(index==0 && direction==-1)
		return;
	
	/* What's the next image? */
	var next = index + direction;

	/* Activate image */
	galleryActivateImage(next);	
	
	/* Preload next image */
	preloadImage(next++);
}

function galleryActivateImage(id) {
	/* Stop animations */
	jQuery('#slider-wrapper #larger').stop();
	
	/* Activate activity indicator */
	showSliderActivityIndicator();
	
	/* Hide the current image */
	jQuery('#slider-wrapper #slider-content #larger').css({'opacity':0});

	/* Remove active class from current */
	jQuery('#slider-wrapper #slider-content #thumbnails ul li.active').removeClass('active');
	
	/* Add selected class to new thumb */
	jQuery('#slider-wrapper #slider-content #thumbnails ul li#id_'+id).addClass('active');
	
	id -= 4;
	if(id<0)
		id=0;

	//if(id>0 || jQuery('#slider-wrapper #thumbnails').scrollLeft() != 0)
		jQuery('#slider-wrapper #slider-content #thumbnails').scrollTo(jQuery('#slider-wrapper #slider-content #thumbnails ul li#id_'+id),500, {onAfter:function(id){showLargerImage(id)}});
	//else
	//	showLargerImage(id);
	
}

function preloadImage(id) {
	var idString = jQuery('#slider-wrapper #slider-content #thumbnails ul li.active img').attr('id');
	idString = idString.replace('id_','');
	var aryId = idString.split(',');
	
	var photo = {
		'id':aryId[1],
		'secret':aryId[0],
		'farm':aryId[2],
		'server':aryId[3] };
		
	var largeImageURL = buildPhotoURL(photo,'medium');
	
	jQuery('#slider-wrapper #preloader img').attr('src',largeImageURL);
}

function showLargerImage(id) {
	
	var idString = jQuery('#slider-wrapper #slider-content #thumbnails ul li.active img').attr('id');
	idString = idString.replace('id_','');
	var aryId = idString.split(',');
	
	var photo = {
		'id':aryId[1],
		'secret':aryId[0],
		'farm':aryId[2],
		'server':aryId[3] };
		
	var largeImageURL = buildPhotoURL(photo,'medium');
	largeImageHTML = '<a href="javascript:gnext()"><img src="'+largeImageURL+'" /></a>';
	
	/* Is there a description or credit? */
	var description = jQuery('#slider-wrapper #thumbnails ul li.active span.description').html();
	var credit = jQuery('#slider-wrapper #thumbnails ul li.active span.credit').html();
	//description = 'Test Description';
	//credit = 'Test Credit';
	if(description != '')
		largeImageHTML += '<span class="description">' + description + '</span>';
	if(credit != '')
		largeImageHTML += '<span class="credit">Credit: ' + credit + '</span>'
		
	jQuery('#slider-wrapper #slider-content #larger').html(largeImageHTML);
	Cufon.refresh('#slider-wrapper #larger span.credit');
	Cufon.refresh('#slider-wrapper #larger span.description');
	
	
	/* Resize the description */
	jQuery('#slider-wrapper #larger img').load(function() {
		hideSliderActivityIndicator();
		jQuery('#slider-wrapper #slider-content #larger').animate({'opacity':1},500);
		ie7ImageFix();
		jQuery('#slider-wrapper span.description').width(jQuery('#slider-wrapper #larger img').width());
	});
	
}

function ie7ImageFix() {
	if(document.all && !window.opera && window.XMLHttpRequest) {
		jQuery('#slider-wrapper #larger').width(jQuery('#slider-wrapper #larger img').width() + 20);
	}
}

function buildPhotoURL(photo,size) {
	//receives an array (can use the individual photo data returned
	//from an API call) and returns a URL (doesn't mean that the
	//file size exists)
	var url='';
	var sizes = {
		'square':'_s',
		'thumbnail':'_t',
		'small':'_m',
		'medium':'',
		'large':'_b',
		'original':'_o' };
	
	size = size.toLowerCase();
	
	if (size == 'original') {
		url = 'http://farm' + photo['farm'] + '.static.flickr.com/' + photo['server'] + '/' + photo['id'] + '_' + photo['secret'] + '_o' + '.' + photo['format'];
	} else {
		url = 'http://farm' + photo['farm'] + '.static.flickr.com/' + photo['server'] + '/' + photo['id'] + "_" + photo['secret'] + sizes[size] + '.jpg';
	}
	return url;
}

function loadVideos() {
	jQuery.ajax({url:'../vimeo/vimeo_gallery.php',success:function(data){
		/* Hide the activity indicator */
		hideActivityIndicator();
		
		jQuery('#videos-wrapper').html(data);
		
		/* Resize vbox */
		jQuery('#vbox-content').height(jQuery('#gallery-content').height()+2);
		
		/* Position the tabs */
		jQuery('#gallery-wrapper #page-tabs').html(jQuery('#gallery-wrapper #page-tabs-hidden').html());
		
		/* Video page tabs */
		jQuery('#gallery-wrapper #page-tabs li').click(function(event) {
			jQuery(document).scrollTo(jQuery('div.yui-gc'));
			event.preventDefault();
			jQuery('#gallery-wrapper #page-tabs li a').removeClass('active');
			jQuery(this).children('a').addClass('active');
			var pageNumber = jQuery('#gallery-wrapper #page-tabs li a.active').html();
			/* Switch */
			jQuery('#videos-wrapper div.page').hide();
			jQuery('#videos-wrapper div#page'+pageNumber).show();
		});
		
		Cufon.refresh('#videos-container span.title');
		Cufon.refresh('#videos-wrapper ul.callout span.caption');
		
		/* Once the photos have loaded, display the frames */
		jQuery('#videos-container ul li img').load(function() {
			jQuery('#videos-container ul li div.frame').show();
		});
		
		/* Is there a deep permalink / should we load a video? */
		var hash = document.location.hash.replace('#','').rtrim('/');
		var aryHash = hash.split('/');

		if(aryHash.length != 1 && aryHash[0]=='Videos') {
			videoClick();
		}	
	}});
}

function videoClick() {
	/* Display the vbox */
	jQuery('#vbox-content').height(jQuery('#gallery-content').height()+2);
	jQuery('#vbox-wrapper').fadeIn('fast',function() {
		/* Don't bind clickoutside event until fadeIn completes */
		jQuery('#vbox-wrapper').bind('clickoutside',function(event){
			/* Destroy the video player */
			jQuery('#vbox-wrapper div.innertube').html('');
			jQuery('#vbox-wrapper').fadeOut('fast');
			jQuery('#vbox-wrapper').unbind('clickoutside');
			document.location.hash='#Videos';
		});
		
		/* Find the video ID based on the hash */
		jQuery('#videos-wrapper div.frame a').each(function() {
			var deepHash = decodeURIComponent(document.location.hash.replace('#Videos/',''));

			if(jQuery(this).attr('href').indexOf(deepHash,0)>-1) {
				var id = jQuery(this).parent().parent().attr('id');
				id = id.replace('id_','');
				var url = 'http://www.vimeo.com/'+id;
				
				/* Embed the Vimeo player */
				jQuery.getJSON('http://vimeo.com/api/oembed.json?url='+encodeURIComponent(url)+'&autoplay=true&maxwidth=830&callback=?',function(json){
					var titleBox = '<div class="title-box">'+json.title+'</div>';
					jQuery('#vbox-content div.innertube').html(json.html + titleBox);
					jQuery('#vbox-content div.title-box').width(json.width);
			
					Cufon.refresh('#vbox-wrapper div.title-box');
				});
			}
		});
	});
}

function hideActivityIndicator() {
	jQuery('#gallery-wrapper #gallery-content>div.innertube').css('background-image','none');
}

function showActivityIndicator() {
	jQuery('#gallery-wrapper #gallery-content>div.innertube').css('background-image','url(../images/gallery/activity.gif)');
}

function hideSliderActivityIndicator() {
	jQuery('#slider-wrapper div.innertube').css('background-image','none');
}

function showSliderActivityIndicator() {
	jQuery('#slider-wrapper div.innertube').css('background-image','url(../images/gallery/activity-black-background.gif)');
}
/* Helper Functions */

// Easing equation, borrowed from jQuery easing plugin
// http://gsgd.co.uk/sandbox/jquery/easing/
jQuery.easing.easeOutQuart = function (x, t, b, c, d) {
	return -c * ((t=t/d-1)*t*t*t - 1) + b;
};

String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
