
jQuery(document).ready(function($) {

	jQuery.noConflict();
	
	
/**
 * Sidebar hide/show content
 * ------------------------------------------- */
 
	// Remove About link if JS is enabled since it is in sidebar
	$('#primary-nav #menu-item-149').hide();
	
	// Sidebar page content
	sidebar_page_content();
	function sidebar_page_content() {
		$('.sidebar .page-content p.more a').click(function(e){
			e.preventDefault();
			$(this).parent().parent().slideToggle(100);
			$(this).parent().parent().siblings().filter('.content').slideToggle(500);
		});
		$('.sidebar .page-content p.less a').click(function(e){
			e.preventDefault();
			$(this).parent().parent().slideToggle(500, function(){
				$(this).siblings().filter('.excerpt').slideToggle(300);
			});
		});
	}
	
/**
 * Ajax content loading.
 * ------------------------------------------- */
	
	// remove trailing slashes
	String.prototype.unSlash = function() {
		return (this.lastIndexOf('/') === this.length-1) ? this.substr(0, this.length-1) : this.toString();
	};
	// Unhash, convert hashed to normal url
	String.prototype.unHash = function() {
		return (this.indexOf("#") != -1) ? this.split("/#").join("") : this;
		//return (this.lastIndexOf('/') === this.length-1) ? this.substr(0, this.length-1) : this.toString();
	};
	
	addAjaxToLinks();
	function addAjaxToLinks() {
		ajaxPostNav();
		ajaxPrimaryNav();
		ajaxPosts();
		ajaxMeta();
	};
	function ajaxPostNav() {
		ajaxNav($('.content .navigation a'));
	};
	function ajaxPrimaryNav() {
		ajaxNav($('#primary-nav a'));
	};
	function ajaxPosts() {
		ajaxNav($('.post h2 a'));
	};
	function ajaxMeta() {
		ajaxNav($('.post .postmetadata a'));
	};
	function ajaxNav($target) {
		$target.click(function(e){
			e.preventDefault();
			var url = $(this).attr('href');
			//var url_array = url.unSlash().split('/');
			//var hash = '/'+ url_array[url_array.length-2] +'/'+ url_array[url_array.length-1];
			var hash = url.unSlash().split(homeUrl).join("");
			
			loadContent(url);
			reloadHeader(url);
			
			window.location.hash = hash;
			$(this).blur();
		});
	};
	
	function loadContent(url) {
		var fadeTime = 500;
		$('#main .content').stop()
			.animate({opacity: 0.0}, fadeTime, function(){ 
				//$(this).html('Loading...');
				//$('.content .loader').show();
				$(this)
					.html($('div.loader').html())
					.css({opacity: 1.0})
					.load(url +' #main .content > *', function(){ 
						//$('.content .loader').hide();
						//$(this).css({'opacity':0}).animate({opacity: 1.0}, fadeTime); 
						$(this).animate({opacity: 1.0}, fadeTime); 
						addAjaxToLinks();
					});
			});
	};
	
	function reloadHeader(url) {
		//$('head title').load(url +' head title', function(){
		//	document.title = $(this).text();
		//});
		$.ajax({
		  url: url,
		  success: function(text) {
			var newPage = $(text);
			
			//var updatedPage = newPage.filter('#page, #wpadminbar').remove();
			document.title = newPage.filter('title').text();
			//$('head').html(newPage);
		  }
		});

	};
	
	manageHash();
	function manageHash() {
		forceHash();
		loadHash();
	}
	
	function loadHash() {
		var currentUrl 	= window.location;
		
		//if (currentUrl.hash.length > 0) {
		//	var _hash = currentUrl.hash.split("#")[1];
		//	var _path = currentUrl.protocol +'//'+ currentUrl.hostname +'/'+ currentUrl.pathname;
		//}
		
		if (currentUrl.hash.length > 0) {
			loadContent(currentUrl.href.unHash());
			reloadHeader(currentUrl.href.unHash());
			//$('.content h1').text(currentUrl.href.unHash());
		}
	};
	function forceHash() {
		var currentUrl 	= window.location;
		var pathname 	= currentUrl.pathname.unSlash();
		var query 		= currentUrl.href.split("?");
		
		// if page not docroot, then bump to hash page
		if ( pathname && pathname != "/" ) { 
			if ( query.length < 2 ) {	// no querystring
				window.location = currentUrl.protocol +'//'+ currentUrl.hostname +'/#'+ pathname;
			} else { 					// add qs to location
				window.location = currentUrl.protocol +'//'+ currentUrl.hostname +'/#'+ pathname +"?"+ query[1]; 
			}
		}  
	};
	
/**
 * Setup mp3 player
 * ------------------------------------------- */
 
	//var playStatus = ($.cookie('playstatus')) ? 1 : 0;
	//var trackTime = (!$.cookie('tracktime')) ? 0 : parseInt($.cookie('tracktime'));
	//var trackId = (!$.cookie('trackid')) ? 0 : parseInt($.cookie('trackid'));
	//var sessionId = $.cookie('music_id');
	
	//$('.track-album').html(trackTime+", playStatus="+playStatus);

	var trackId = 0;
	
	var Playlist = function(instance, playlist, options) {
		var self = this;

		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 = trackId;
		
		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 = {
		displayPlaylist: function() {
			var self = this;
			$(this.cssSelector.playlist + " ul").empty();
			for (i=0; i < this.playlist.length; i++) {
				var listItem = (i === this.playlist.length-1) ? "<li class='jp-playlist-last'>" : "<li>";
				listItem += "<a href='#' id='" + this.cssId.playlist + this.instance + "_item_" + i +"' tabindex='1'>"+ this.playlist[i].name +"</a>";
				
				// Create links to free media
				if(this.playlist[i].free) {
					var first = true;
					listItem += "<div class='jp-free-media'>(";
					$.each(this.playlist[i], function(property,value) {
						if($.jPlayer.prototype.format[property]) { // Check property is a media format.
							if(first) {
								first = false;
							} else {
								listItem += " | ";
							}
							listItem += "<a id='" + self.cssId.playlist + self.instance + "_item_" + i + "_" + property + "' href='" + value + "' tabindex='1'>" + property + "</a>";
						}
					});
					listItem += ")</span>";
				}
				
				listItem += "</li>";
				
				// Associate playlist items with their media
				$(this.cssSelector.playlist + " ul").append(listItem);
				$(this.cssSelector.playlist + "_item_" + i).data("index", i).click(function() {
					var index = $(this).data("index");
					if(self.current !== index) {
						self.playlistChange(index);
					} else {
						$(self.cssSelector.jPlayer).jPlayer("play");
					}
					$(this).blur();
					return false;
				});
				
				// Disable free media links to force access via right click
				if(this.playlist[i].free) {
					$.each(this.playlist[i], function(property,value) {
						if($.jPlayer.prototype.format[property]) { // Check property is a media format.
							$(self.cssSelector.playlist + "_item_" + i + "_" + property).data("index", i).click(function() {
								var index = $(this).data("index");
								$(self.cssSelector.playlist + "_item_" + index).click();
								$(this).blur();
								return false;
							});
						}
					});
				}
			}
			$('.track-count .track-connect').html("of");
			$('.track-count .track-total-items').html(this.playlist.length);
			$('.track-count').after(" <div class=\"track-show-playlist\"><a href=\"#\" title=\"See full playlist\">see song list</a></div>");
			
			$(".track-show-playlist").click(function() {
				if ($('a', this).text().indexOf('hide') > -1) {
					$('a', this).text($('a', this).text().replace(/hide/, "see"));
				} else {
					$('a', this).text($('a', this).text().replace(/see/, "hide"));
				}
				$('.jp-playlist').slideToggle();
				return false;
			});
		},
		playlistInit: function(autoplay) {
			if (autoplay) {
				this.playlistChange(this.current);
			} else {
				this.playlistConfig(this.current);
			}
			//$("#jquery_jplayer_1").jPlayer("playHead", trackTime);
			/*.bind($.jPlayer.event.progress, function(event) { // Add a listener to report the time play began
				$.cookie('tracktime', event.jPlayer.status.currentPercentAbsolute, { expires: 7, path: '/', domain: 'lukewesley.com' });
			});*/
		},
		playlistConfig: function(index) {
			$(this.cssSelector.playlist + "_item_" + this.current).removeClass("jp-playlist-current").parent().removeClass("jp-playlist-current");
			$(this.cssSelector.playlist + "_item_" + index).addClass("jp-playlist-current").parent().addClass("jp-playlist-current");
			this.current = index;
			//$.cookie('trackid', index, { expires: 7, path: '/', domain: 'lukewesley.com' });
			
			this.playlist[this.current]['mp3'] = this.playlist[this.current]['mp3'].replace(/cd\//, "").replace(/tracks\//, "");
			this.playlist[this.current]['oga'] = this.playlist[this.current]['oga'].replace(/cd\//, "").replace(/tracks\//, "");
			//$('.track-name').text(this.playlist[this.current]['name']);
			$('.track-name').html(this.playlist[this.current]['name'] +" <span class=\"buy-link\"><a href=\""+this.playlist[this.current]['buy']+"\" title=\"Buy this song on iTunes\">buy song</a></span>");
			$('.track-count .track-current-item').html(index+1);
			$(this.cssSelector.jPlayer).jPlayer("setMedia", this.playlist[this.current]);
		},
		playlistChange: function(index) {
			this.playlistConfig(index);
			$(this.cssSelector.jPlayer).jPlayer("play");
			
			this.current = index;
			
			var date = new Date();
			expireTime = date.setMinutes(date.getMinutes()+15);
		},
		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);
		}
	};
	/**/
	var audioPlaylist = new Playlist("1", [
		{
			name:"I Hope You Like This Song",
			buy:"http://itunes.apple.com/us/album/i-hope-you-like-this-song/id366155064?i=366155123",
			mp3:"http://lukewesley.com/cd/music/tracks/track_01.mp3",
			oga:"http://lukewesley.com/cd/music/tracks/track_01.ogg"

		},
		{
			name:"Keep it to Yourself",
			buy:"http://itunes.apple.com/us/album/keep-it-to-yourself/id366155064?i=366155101",
			mp3:"http://lukewesley.com/cd/music/tracks/track_02.mp3",
			oga:"http://lukewesley.com/cd/music/tracks/track_02.ogg"
		},
		{
			name:"Suburbia",
			buy:"http://itunes.apple.com/us/album/suburbia/id366155064?i=366155102",
			mp3:"http://lukewesley.com/cd/music/tracks/track_03.mp3",
			oga:"http://lukewesley.com/cd/music/tracks/track_03.ogg"
		},
		{
			name:"Pretty Boy",
			buy:"http://itunes.apple.com/us/album/pretty-boy/id366155064?i=366155068",
			mp3:"http://lukewesley.com/cd/music/tracks/track_04.mp3",
			oga:"http://lukewesley.com/cd/music/tracks/track_04.ogg"
		},
		{
			name:"The Story",
			buy:"http://itunes.apple.com/us/album/the-story/id366155064?i=366155111",
			mp3:"http://lukewesley.com/cd/music/tracks/track_05.mp3",
			oga:"http://lukewesley.com/cd/music/tracks/track_05.ogg"
		},
		{
			name:"Here is Your Ballad",
			buy:"http://itunes.apple.com/us/album/here-is-your-ballad/id366155064?i=366155110",
			mp3:"http://lukewesley.com/cd/music/tracks/track_06.mp3",
			oga:"http://lukewesley.com/cd/music/tracks/track_06.ogg"
		},
		{
			name:"Ohio",
			buy:"http://itunes.apple.com/us/album/ohio/id366155064?i=366155119",
			mp3:"http://lukewesley.com/cd/music/tracks/track_07.mp3",
			oga:"http://lukewesley.com/cd/music/tracks/track_07.ogg"
		},
		{
			name:"Fool's Gold",
			buy:"http://itunes.apple.com/us/album/fools-gold/id366155064?i=366155121",
			mp3:"http://lukewesley.com/cd/music/tracks/track_08.mp3",
			oga:"http://lukewesley.com/cd/music/tracks/track_08.ogg"
		},
		{
			name:"Sorry I'm Not Hotter",
			buy:"http://itunes.apple.com/us/album/sorry-im-not-hotter/id366155064?i=366155122",
			mp3:"http://lukewesley.com/cd/music/tracks/track_09.mp3",
			oga:"http://lukewesley.com/cd/music/tracks/track_09.ogg"
		},
		{
			name:"Battered Apartments",
			buy:"http://itunes.apple.com/us/album/battered-apartments/id366155064?i=366155124",
			mp3:"http://lukewesley.com/cd/music/tracks/track_10.mp3",
			oga:"http://lukewesley.com/cd/music/tracks/track_10.ogg"
		}

	], {
		ready: function() {
			audioPlaylist.displayPlaylist();
			audioPlaylist.playlistInit(false); // Parameter is a boolean for autoplay. playStatus
		},
		ended: function() {
			audioPlaylist.playlistNext();
		},
		play: function() {
			$(this).jPlayer("pauseOthers");
		},
		swfPath: "/inc/themes/ohiowesleyan_2.0/js",
		supplied: "oga, mp3"
	});
	/**/
	
});


