(function(jq){
	jq.btemplate = function(ele,dat){
		var tmp = jq(ele).html();
		jq.each(dat,function(key,value){
			while(tmp.indexOf('%'+key+'%') != -1)
			tmp = tmp.replace('%'+key+'%',value);
		}); return tmp;
	}
})(jQuery);

var lyhome = {
	init: function() {

		jQuery('#commit').bind('click',lyhome.commitSearch);
		jQuery('#query').bind('keypress',function(e){if(e.keyCode==13){jQuery('#commit').click();}});

		lyhome.fetchTweets();
		
		return;
	},
	
	fetchTweets: function() {
		jQuery.post(
			'/api/1.0/tweets?' + (new Date()).getTime(),
			{ 'type':'latest' },
			function(obj) {
				var html = '';
				var iter = 0;
				jQuery(obj.deck).each(function(iter){
					if(iter == 2) return false;
				
					var data = {
						'TWITTER_URL':'http://twitter.com/' + this.username.toLowerCase(),
						'TWITTER_NAME':this.username,
						'TIME_AGO':this.timeago,
						'TWEET':this.tweet,
						'TWEET_URL':this.url
					}					
					
					html += jQuery.btemplate(((this.isTwitter)?('#template2a'):('#template2b')),data);
					return;
				});
				
				jQuery('#tweetdeck').html(html);
				
			},'json'
		);
		
		return;
	},
	
	commitSearch: function() {
		var q = jQuery.trim(jQuery('#query').val());

		
		jQuery.get(
			'/api/1.0/search?' + (new Date()).getTime(),
			{ 'q':q,'magic':'true' },
			function(obj){
				
				html = jQuery('#resultbox');
				html.empty();
				
				jQuery(obj.list).each(function(iter){

					var tweet = (this.artist + ' - ' + this.title).replace(/"/g,'');
					var hashtag = '';
					if(this.genre) hashtag += ' #' + this.genre.toLowerCase();
					hashtag += ' #nowplaying';
				
					var data = {
						'ID':iter,
						'TITLE':this.title,
						'ARTIST':this.artist,
						'ITUNES_LINK':this.itunesbuy,
						'DATAPATH':this.datapath,
						'COVERART':((this.coverart)?(this.coverart):('/gfx/blanklogo.png')),
						'TWEET':tweet,
						'HASHTAG':hashtag,
						'DATA':encodeURIComponent(jQuery.toJSON(this))
					};
					
					var temp = jQuery.btemplate('#template1',data);
					html.append(temp);
									
					if(!this.itunesbuy) jQuery('.btn-itunes:last').hide();

					AudioPlayer.embed("audioplayer-" + iter, {  
					    soundFile: encodeURIComponent(this.datapath),
					    titles: this.title,  
					    artists: this.artist
					});
				
				
					return;
				});
				

				jQuery('#resultarea').show();
				jQuery('a[rel*=facebox]').facebox();
				
				return;
			},'json'
		);

	}
};

