/** Javascript for cramerdev.com */

$(document).ready(function() {

	// Gets tweets from our pipe
	(function getTweets() {
	
		$.getJSON("http://pipes.yahoo.com/pipes/pipe.run?_id=buVINohM3hGFmzyd_g6H4A&_render=json&_callback=?", function (data) {
			var element = "latest-tweets", maxItems = 2, items = [], itemsDone = 0,
		        	txt = "",
	        		// A twitter username followed by a colon and whitespace
			        pattern = /^([\w|\d|_]+):\s/g; 

			try { items = data.value.items; } catch (e) {}

			$.each(items, function (index, i) {
				var isAtTweet = false;

			        i.user = i.description.match(pattern)[0].replace(/:\s$/, "");
			        i.description = i.description.replace(pattern, "");
			        i.date = i["y:published"] || {};
		        	isAtTweet = i.description.charAt(0) === "@";

				if (!isAtTweet) { // Skip @ tweets
			            itemsDone += 1;
			            txt += '<div class="tweet"><p>' + i.description +
			                '</p><p class="post-info"><a href="' + i.link + '">@' + i.user +
		        	        '</a> on ' + [i.date.month, i.date.day, i.date.year].join("/") +
		                	'</p></div>';
			        }

				if (itemsDone >= maxItems) { return false; } // break
			});
		
		$("#" + element).append(txt); });
	
	})();

	// Start slideshow
	(function startSlideshow() {
		$('#slideshow').cycle();
	})();
	
	// Replace text in input elements
	// Credits: Ryan Dunphey, http://octoberblue.com
	(function replaceFormText() {
	
		$('input, textarea').focus(function () {
			var t = $(this).data('initialValue');
			if (!t) {
				$(this).data('initialValue', this.value).val('');
			} else if (this.value === t) {
				this.value = '';
			}
		}).blur(function () {
			if (this.value === '') {
				this.value = $(this).data('initialValue');
			}
		});
				
	})();
		
	// Get Band Names for Dan's Profile
	(function getBandsDanM() {

		jQuery.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getTopArtists&user=starzonmyarmz&period=7day&format=json&api_key=14c6adbbf532fc6107889f1b239349cf&callback=?", function (data) {
		
			var element   = "top-artists",
		 	    maxItems  = 3,
			    items     = [],
			    itemsDone = 0,
			    txt       = "";
				
			try { items = data.topartists.artist; } catch (err) {}
				
			jQuery.each(items, function(index, i) {
												
				if ((maxItems - itemsDone) === 1) {
					txt += 'and ';
				}
						
				txt += '<a href="' + i.url + '">' + i.name;

				if ((maxItems - itemsDone) === 1) {
					txt += '</a>';
				} else {
					txt += '</a>, ';
				}

				itemsDone += 1;
						
				if (itemsDone >= maxItems) { return false; }
				
			});
						
			jQuery("#" + element).replaceWith(txt);

		});

	})();

});