$(document).ready(function () {
	var $speed = 1000;
	var pageTitleBase = $('body').attr('data-title');
	
	function ajaxLoad(href) {
		$.address.value(href.replace(/^http:\/\/jobytalbot\.com/, ""));
	}
	
	$.address.change(function(e) {
		if (e.value == "/") {
			$.address.value('/home');
		} else page = e.value;
		
		$('#content').hide();
		$('#sidebar').hide();
		$('#page_loader').show();
		$('#content').load(page +'/', function(response, status, xhr) { // removed +'/'
			if (status == "error") {
				var msg = "Sorry, something went funny. ";
				$("#error").html(msg + xhr.status + " " + xhr.statusText);
			} else {
				var pageTitle = $('#page_title').text();
				var pageID = $('#page_title').attr('data-id');
				var totalSubpages = $('#page_title').attr('data-totalsubpages');
				
				$.address.title(pageTitleBase + " { " + pageTitle + " }");
				
				if ($('#sidebar'+pageID)) var sidebarContent = $('#sidebar'+pageID).html();
				
				$('.scribd').each(function() {
					var t = $(this);
					var scribdId = t.attr('data-id');
					var scribdKey = t.attr('data-key');
					t.attr('href', '/scribd/?id=56593544&key=key-1jpy4rbqbhswvwxqliqv');
					t.fancybox({
						'transitionIn': 'elastic',
						'transitionOut': 'fade',
						'speedIn': 400, 
						'speedOut': 400, 
						'overlayShow': false
					});
				});
				
				$("a.modal").fancybox({
					'transitionIn': 'elastic',
					'transitionOut': 'fade',
					'speedIn': 400, 
					'speedOut': 400, 
					'overlayShow': false
				});
				
				function formatTitle(title, currentArray, currentIndex, currentOpts) {
					return '<div id="gallery_title"><a href="' + currentOpts.href + '" target="_blank">Download Hi-Res Image</a></div>';
				}
				
				$("a.gallery").fancybox({
					'transitionIn': 'elastic',
					'transitionOut': 'fade',
					'speedIn': 400, 
					'speedOut': 400, 
					'overlayShow': false,
					'titleFormat': formatTitle
				});
				
				$(".mp3").each(function() {
					$(this).prepend("<div class=\"button\"></div>");
				});
				
				$('#page_loader').hide();
				
				$.getScript('/media/js/jquery.jscrollpane.min.js', function() {
					$('.horizontal_column').jScrollPane({
						verticalDragMinHeight: 10,
						verticalDragMaxHeight: 30,
						verticalGutter: 20,
						hideFocus: true
					});
				});
				
				$('#content').css({marginLeft: '0px', width: totalSubpages * 770 + 'px'});
				$('#content').fadeIn();
				
				if (sidebarContent) {
					$('#sidebar').html(sidebarContent);
					$('#sidebar').fadeIn(700);
					$('#sidebar a.subpage_link').click(function() {
						var subpage = $(this).attr('id');
						var scrollDistance = subpage * 770;
						$('#content').animate({marginLeft: '-'+scrollDistance+'px'}, $speed+300 );
						return false;
					});
				}
			}
		});
	});
	
	$('a').live('click', function(e) {
		var t = $(this);
		if (t.attr('id') != "fancybox-close" && !t.is('.modal, .mp3, .scribd, .gallery, #fancybox-right, #fancybox-left') && t.attr('target') != "_blank") {
			e.preventDefault();
			var href = t.attr('href');
			ajaxLoad(href);
		}
	});
	
	$('.recording, .media, .thumb').live('mouseenter mouseleave', function(event) {
		if (event.type == "mouseenter") {
			$(this).find('.cover_art').animate({top:'225px'},{queue:false,duration:300});
		} else if (event.type == "mouseleave") {
			$(this).find('.cover_art').animate({top:'0'},{queue:false,duration:300});
		}
	});
	
	/* jPlayer */
	
	/* playlist */
	var Playlist = function(instance, playlist, options) {
		//console.log('playlist function');
		var self = this;
		this.trackTitle = $('#track-title');

		this.instance = instance; // String: To associate specific HTML with this playlist
		this.playlist = playlist; // Array of Objects: The playlist
		this.options = options; // Object: The jPlayer constructor options for this playlist

		this.current = 0;

		this.cssId = {
			jPlayer: "jquery_jplayer_",
			interface: "jp_interface_",
			playlist: "jp_playlist_"
		};
		
		this.cssSelector = {};

		$.each(this.cssId, function(entity, id) {
			self.cssSelector[entity] = "#" + id + self.instance;
		});

		if(!this.options.cssSelectorAncestor) {
			this.options.cssSelectorAncestor = this.cssSelector.interface;
		}

		$(this.cssSelector.jPlayer).jPlayer(this.options);

		$(this.cssSelector.interface + " .jp-previous").click(function() {
			self.playlistPrev();
			$(this).blur();
			return false;
		});

		$(this.cssSelector.interface + " .jp-next").click(function() {
			self.playlistNext();
			$(this).blur();
			return false;
		});
	};

	Playlist.prototype = {
		playlistInit: function(autoplay) {
			//console.log('init');
			if(autoplay) {
				this.playlistChange(this.current);
				this.trackTitle.html(this.playlist[this.current].name);
			} else {
				this.playlistConfig(this.current);
				this.trackTitle.html(this.playlist[this.current].name);
			}
		},
		playlistConfig: function(index) {
			this.current = index;
			$(this.cssSelector.jPlayer).jPlayer("setMedia", this.playlist[this.current]);
		},
		playlistChange: function(index) {
			this.playlistConfig(index);
			$(this.cssSelector.jPlayer).jPlayer("play");
			this.trackTitle.html(this.playlist[this.current].name);
		},
		playlistNext: function() {
			var index = (this.current + 1 < this.playlist.length) ? this.current + 1 : 0;
			this.playlistChange(index);
		},
		playlistPrev: function() {
			var index = (this.current - 1 >= 0) ? this.current - 1 : this.playlist.length - 1;
			this.playlistChange(index);
		}
	};
	
	function loadPlaylist(player, playlist, autoplay) {
		//console.log('loading playlist');
		var audioPlaylist = new Playlist(player, playlist, {
			ready: function() {
				//console.log('ready');
				audioPlaylist.playlistInit(autoplay);
			},
			ended: function() {
				audioPlaylist.playlistNext();
			},
			play: function() {
				//console.log('play');
				$(this).jPlayer("pauseOthers");
				$(".mp3").each(function() {
					$(this).addClass("play");
					$(this).removeClass("pause");
				});
			},
			backgroundColor: "transparent",
			swfPath: "/media/js",
			supplied: "mp3, oga"
		});
	}
	
	// using player name "2" since 1 is used by jplayer 
	// as the default and causes conflict with single player
	loadPlaylist("2", sitePlaylist, false);
	
	/* single */
	
	$("#jp_single_player").jPlayer({
		backgroundColor: "transparent",
		swfPath: "/media/js",
		supplied: "mp3"
	});
	
	$(".mp3").live('click', function() {
		if ($(this).hasClass("pause")) {
			$("#jp_single_player").jPlayer("stop");
			$(this).addClass("play");
			$(this).removeClass("pause");
		} else {
			m($(this).attr("rel"));
			$(".mp3").each(function() {
				$(this).addClass("play");
				$(this).removeClass("pause");
			});
			$(this).addClass("pause");
		}
		return false;
	});
	
	$("#jp_single_player").jPlayer("onSoundComplete", function() {
		$(".mp3").each(function() {
			$(this).addClass("play");
			$(this).removeClass("pause");
		});
	});
	
	function m(h) {
		$("#jp_single_player").jPlayer("pauseOthers");
		$("#jp_single_player").jPlayer("setMedia", {
			mp3: h
		}).jPlayer("play");
	}
});
