$( '#jplayer_pause' ).css('opacity','0');

$(document).ready(function(){

	// TWITTER stuff
	if ($( '#tweets' ).length){
		
		$('#tweets').append('<div id="loader_icon"><img src="assets/img/ajax-loader.gif" alt="Loading..." width="16" height="16"> Loading</div>');
		
		var tweets = $.getJSON('http://twitter.com/statuses/user_timeline/pipas4thepeople.json?count=8&callback=?'),
			template = "<li><small>{created_at}, {year} @ {timeposted} </small><p>{text}</p></li>",
			container = $("#tweets ul");
			
			tweets.success(function( data ){
				$('#loader_icon').hide();

				$.each(data, function(i,item)
				{
					// format twitter text
					item.year = item.created_at.substr(26, 29);
					item.timeposted = item.created_at.substr(11, 5);
					item.created_at = item.created_at.substr(0,10);
					item.text = item.text.replace(/#(.*?)(\s|$)/g,'<span class="hash">#$1 </span>').replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,'<a href="$&">$&</a> ').replace(/@(.*?)(\s|\(|\)|$)/g,'<a href="http://twitter.com/$1">@$1 </a>$2');
					
					container.append($.nano(template, item));
				});
				
			});
			
			tweets.fail(function ( response) {
				$('#loader_icon').hide();
				container.html('<p class="error">Twitter seems to be not responding...</p>');
			});
		
	}
	
	// AUDIOPLAYER stuff
	if ($( '#songs' ).length){
		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 = 0;
			this.cssId = {
				jPlayer: 'jquery_jplayer_',
				jpInterface: '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.jpInterface;
			}
			$(this.cssSelector.jPlayer).jPlayer(this.options);
			$(this.cssSelector.jpInterface + " .jp-previous").click(function()
			{
				self.playlistPrev();
				$(this).blur();
				return false;
			});
			$(this.cssSelector.jpInterface + " .jp-next").click(function()
			{
				self.playlistNext();
				$(this).blur();
				return false;
			});
		};

		Playlist.prototype = {
			displayPlaylist: function() {
				var self = this;
				$(this.cssSelector.playlist + " ol").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 + " ol").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;
								});
							}
						});
					}
				}
			},
			playlistInit: function(autoplay) {
				if(autoplay) {
					this.playlistChange(this.current);
				} else {
					this.playlistConfig(this.current);
				}
			},
			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;
				$(this.cssSelector.jPlayer).jPlayer("setMedia", this.playlist[this.current]);
			},
			playlistChange: function(index) {
				this.playlistConfig(index);
				$(this.cssSelector.jPlayer).jPlayer("play");
			},
			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:"3, 2, 1 &amp; None",
				mp3:"/assets/audio/pipas-321andNone.mp3"
				// oga:"/assets/audio/pipas-321andNone.ogg"
			},
			{
				name:"Seldom Dream",
				mp3:"/assets/audio/pipas-seldomdream.mp3"
				// oga:"/assets/audio/pipas-seldomdream.ogg"
			}
		], {
			ready: function() {
				audioPlaylist.displayPlaylist();
				audioPlaylist.playlistInit(false); // Parameter is a boolean for autoplay.
			},
			ended: function() {
				audioPlaylist.playlistNext();
			},
			play: function() {
				$(this).jPlayer("pauseOthers");
			},
			swfPath: "/assets/swf/",
			supplied: "mp3"
		});
			// $.jPlayer.defaults.oggSupport = true;
			// $.jPlayer.defaults.graphicsFix = false;
			// 
			// 		$( '#jquery_jplayer' ).jPlayer( {
			// 		    
			// 			ready: function () 
			// 			{
			// 				$( '#jplayer_pause' ).css('opacity','1');
			// 				this.element.jPlayer("setFile", "/assets/audio/pipas-321andNone.mp3","/assets/audio/pipas-321andNone.ogg");
			// 			},
			// 			swfPath: "/assets/flash"
			// 			
			// 		}).jPlayer("onProgressChange", function(lp,ppr,ppa,pt,tt) {
			// 			$( '#runningTime' ).text($.jPlayer.convertTime(pt));
			// 			});
			// 			
			// 			
			// 			
			// $( '#audio_content a' ).click(function(e) {
			// 	return false;
			// });
			// 
			// 
			// // allow tabbing onto player and start/stopping with return key	
			// $( '#jplayer_play, #jplayer_pause' ).keypress(function(event) {
			// 
			// 	if (event.keyCode == '13') {
			// 		
			// 		if($( '#jquery_jplayer' ).jPlayer("getData", "diag.isPlaying")){
			// 			$( '#jquery_jplayer' ).jPlayer("pause");
			// 		} else {
			// 			$( '#jquery_jplayer' ).jPlayer("play");
			// 		}
			// 
			// 		event.preventDefault();
			// 
			// 	}
			// 	
			// });
			// 		
			// 
			// $( '#jplayer_play, #jplayer_pause' ).dblclick(function() {
			// 	$( '#jquery_jplayer' ).jPlayer("stop");
			// });
			// 	
			// 	
			// // stat tracking
			// $( '#audio_content a, #jplayer_play' ).click(function(){
			// 	// pageTracker._trackEvent("media", "play song", '3,2,1 & None', 0);
			// }); 
	}
	
	// DISCOGRAPHY stuff
	if ($( 'body#discography' ).length){
		
		$( '#releases img.cover' ).click(function() { 
			$(this).parent().parent().find('.tracklisting').slideToggle(); 
			return false; 
		});
		
	}

	// DISCOGRAPHY stuff
	if ($( 'body#contact' ).length){
		
		$( 'form#contact_form' ).validate({
			messages: {
			   name: {
			         required: "— We need your email address to contact you",
			         minlength: jQuery.format("— At least {0} characters required!")
			       },
			   email: {
			     required: "— We need your email address to contact you",
			     email: "— Please enter a valid email address"
			   },
			  message: "Please write some words for us. Thanks!"
			 }
		});

	}
	
	// BLOG stuff
	if ($( 'body#blog' ).length){
			$('.entry img').each(function(i)
			{
				var img = $(this);
				fixImage(img,180);
			}
	);

}


});

function fixImage(image,size) {
	var width = image.width();
	var height = image.height();
	
	if (width > height) { 
	if (width > size) {
	width = width * size / height;
	height = size;
	};
	} else {
	if (height > size) {
	height = height * size / width;
	width = size;
	};
	};
	
	image.height(height);
	image.width(width);
}

/* Nano Templates (Tomasz Mazur, Jacek Becela) */

(function($){
  $.nano = function(template, data) {
    return template.replace(/\{([\w\.]*)\}/g, function (str, key) {
      var keys = key.split("."), value = data[keys.shift()];
      $.each(keys, function () { value = value[this]; });
      return (value === null || value === undefined) ? "" : value;
    });
  };
})(jQuery);
