$(document).ready(function() { 
	KFANS.rollover.init();
 
 	// Initialize Player
 	if ( $('.player')[0] ) {	// if we see a media player on the page
 		var tracksToShow = 3;
 		var playlist = '.player .playlist';
 		var xmlfile = $(playlist).attr('rel');	// URL for the XML playlist
	 	
	 	createPlayer(0, resetType, false, xmlfile); // init the player
	 	
	 	$(playlist + ' li:last').addClass('last');	// mark the last item in the list
	 	if ($(playlist + ' li').length > tracksToShow) {
	 		$('.playlistcontainer').css('overflow-y','scroll');	// add scroll if there is more than 3 tracks
	 	}
 	}
 	
	// Color box  
	$.fn.colorbox.settings.transition = "fade";
	$.fn.colorbox.settings.initialWidth = "0";
	$.fn.colorbox.settings.fixedWidth = "420";
	$.fn.colorbox.settings.fixedHeight = "800";	// Make it tall so there's room for it to grow for error messages
	$.fn.colorbox.settings.bgOpacity = ".60";
	$('a.ajax').colorbox();
	$("a.login").colorbox({inline:true, href:"#signinform"}); // Open hidden login form
	$("a.subscribe").colorbox({inline:true, href:"#subscribeform"}); // Open hidden subscribe form
	$("a.download").colorbox({inline:true, href:"#downloadform"}); // Open hidden download form
	$("a.artistsubscribeform").colorbox({inline:true, href:"#artistsubscribeform"});

	$('a.ajax, a.login').live("click",function() {
		return false;
	});
	
	// Links from one modal to another
	$('a.intermodal').live("click",function() {
	/*	var dest =  */
		$.fn.colorbox.close();
	});
	
	// Disappearing stuff
	setTimeout(function(){$(".disappear").fadeOut('slow')},5000);
			
	// Process our forms using AJAX
	$("#tellafriend_form .button, #member_form #signup, #saform form .button, #signin.button, form.ajax submit, form.ajax input.button").live("click", function() {		
		processAjaxForm($(this).parent(), $(this), $(this).parents('form').siblings(".message"));  // Form, button, msg box
		return false;
	});
	/* 
	$("#subscribeform .button").live("click", function() {		
		processAjaxForm($(this).parents("form"), $(this), $(this).parents('form').siblings(".message"));
		return false;
	});	
	*/
	// Share Popup
	var $sharepopup = $("#sharepopup");
	var $shareurl = $("#sharepopup .shareurl");
	$sharepopup.hide();
	
	$(".multishare").click(function() {
		toggleSharePopup($(this), $sharepopup);
		return false;
	});		
	
	$shareurl
		.focus(function() {
			$(this).select();
		})
		.click(function() {
			$(this).select();
		});
	
	// Close Share Popup if clicked elsewhere
	$('#modal-overlay').live("click", function() {
		$sharepopup.hide().removeClass("small");
		$('#modal-overlay').remove(); // remove overlay
	});
	
	// Share links using awe.sm
	$("a.share").live("click",function() {
		var tool = "";
		var channel = "";
		var dest = "";
		
		// Share track on twitter
		if ($(this).hasClass("twittertrack")) {
		  tool = "track-link";
		  channel = "twitter";
		  var artist = $("meta[name='artist']").attr('content');
		  var track = $(this).siblings('.track').find('.trackname').text();
		  dest = "http://twitter.com/home?status=I%20really%20dig%20"+artist+"%27s%20song%20%22"+track+"%22%20on%20100,000%20Fans%3A AWESM_TARGET";
		}
				
		// Share album on facebook
		if ($(this).hasClass("facebook")) {
		  channel = "facebook-post";
		  dest = "http://facebook.com/share.php?u=AWESM_TARGET%26t=";
		}

		// Share ablum on twitter
		if ($(this).hasClass("twitter")) {
		  channel ="twitter"
		  var artist = $("meta[name='artist']").attr('content');
		  dest = "http://twitter.com/home?status=Check%20out%20100,000%20Fans%20featured%20artist%20"+artist+"%3A AWESM_TARGET";
		}
		
		// Get the tool
		if ($(this).hasClass("sharelink")) {
			tool = "sharelink";
		}
		
		if ($(this).hasClass("sharebutton")) {
			tool = "sharebutton";
		}
		window.open(awesmURL(tool, channel, dest))
		return false;
	});
	
	// Review Form
	$("#reviewform #review").maxLength(250);
	
	// Post reviews to Twitter
	$("#reviews .review a.review-comment").click(function() {		
	//alert($(this).siblings(".commentbody").html())
		var review = escape("\"" + $(this).siblings(".commentbody").text()) + "\", " + $(this).siblings(".meta").children(".name").text() + " -  AWESM_TARGET";
		var dest = "http://twitter.com/home?status=" + review;
		window.open(awesmURL("review-comment", "twitter", dest));
		return false;
	});
		
	// Embedded videos
	prepEmbeddedVideos($('a.embed'));
	
	// Format the Campaign Monitor subscribe forms
	$(".cmform br").remove();
	$(".cmform input:text").addClass("text");
	$(".cmform label:eq(0)").html("Enter Your Email Address:");
	$(".cmform#downloadform input:submit").replaceWith('<input class="button ro" type="image" src="/images/button-getitnow.png"/>');
	$(".cmform#artistsubscribeform input:submit").replaceWith('<input class="button ro" type="image" src="/images/button-signupnow.png"/>');
	$(".cmform#artistsubscribeform label:gt(0), .cmform#artistsubscribeform input:checkbox").hide();
	
	// Auto select the appropriate segment for artist subscribe forms
	var artistname = $("#artistsubscribeform .artistname").text();
	var artistfield = $("#artistsubscribeform label:contains('"+artistname+"')").attr("for");
	$("#artistsubscribeform #"+artistfield).attr('checked', true);
	
	// Highlight tracks on hover 
	$(".player .playlist li").hover(
		function() {
			$(this).addClass("hovering");
		},
		function () {
			$(this).removeClass("hovering");
		}
	);
	
	// Tabs
	var $tabs = $("#tabs").tabs();
	if(window.location.hash) {
		$tabs.tabs('select', 1); // Switch to reviews tab if there's a url hash
	}
		
	// Ratings
	// Highlight the current rating
	starsOn($("#vote #stars img"), $("#vote #avg").text(), "on");
		
	// Highlight the stars on hover
	$("#vote #stars img").hover(function(){
		if ($("#vote #rating").val() == "0") {
			starsOn($("#vote #stars img"), $(this).attr('alt'), "over");
		}
	}, function() {
		if ($("#vote #rating").val() == "0") {
			starsOn($("#vote #stars img"), $("#vote #avg").text(), "on");
		}
	});
	
	// Submit a vote and highlight that star
	$("#vote #stars img").click(function(){
		if ($("#vote #rating").val() == "0") {
			vote($(this).attr('alt'));
			starsOn($("#vote #stars img"), $(this).attr('alt'), "on");
		}
	});

	// If there's no rating yet
	$("#overallrating:not(:has('#avg'))").html("N/R");

}); 

// Toggles share popup
function toggleSharePopup($source, $popup) {
	
	if ($source.hasClass("small")) {
		if ($popup.hasClass("small")) {
			$popup.hide();
			$('#modal-overlay').remove(); // remove overlay
			$popup.removeClass("small");
		} else {
			$popup.removeClass("sharebutton");
			$popup.addClass("small");
			$('body').append('<div id="modal-overlay"></div>'); // add overlay
			$popup.show();
		}
	}
	
	if ($source.hasClass("sharebutton")) {
		if ($popup.hasClass("sharebutton")) {
			$popup.hide();
			$('#modal-overlay').remove(); // remove overlay
			$popup.removeClass("sharebutton");
		} else {
			$popup.removeClass("small");
			$popup.addClass("sharebutton");
			$('body').append('<div id="modal-overlay"></div>'); // add overla
			$popup.show();
		}
	}
	return true;
}

// Submit a vote
function vote(rating) {
	var $form = $("#vote form");
	
	$("#vote #rating").val(rating); // Set my vote
	
	var dataString = $form.serialize();
	var action = $form.attr('action');
	
	$.ajax({  
		type: "POST",  
		url: action,  
		data: dataString,  
		dataType: 'text',
		cache: false,
		success: function(data) { 
			$("#vote #ratingmsg").html("Thanks!");
	 	}
	 }); 		
	 return true;
}

// Highlight stars that are less than or equal to the target
// Expects a selection of star images and an index number for the target star and a state of on or over
function starsOn($stars, target, state) {
	var floor = Math.floor(target);
	var ceiling = floor + 1;
	$stars.slice(0,target).attr('src', '/images/star-'+state+'.png');
	$stars.slice(target).attr('src', '/images/star-off.png');
	if (target > floor && target < ceiling) {
		$stars.eq(floor).attr('src', '/images/star-on-half.png');
	}
}

KFANS = {};

// Thanks to http://peps.ca/blog/easy-image-rollover-script-with-jquery/
// Looks for anything with class .ro and changes source file.ext to file_o.ext on hover
KFANS.rollover = {
   init: function() {
      this.preload();
      $(".ro").live("hover", function(){  
	      	$(this).hover(
	         function () { $(this).attr( 'src', KFANS.rollover.newimage($(this).attr('src')) ); },
	         function () { $(this).attr( 'src', KFANS.rollover.oldimage($(this).attr('src')) ); }
	      );
		});
   },

   preload: function() {
      $(window).bind('load', function() {
         $('.ro').each( function( key, elm ) { $('<img>').attr( 'src', KFANS.rollover.newimage( $(this).attr('src') ) ); });
      });
   },
   
   newimage: function(src){
      return src.substring( 0, src.search(/(\.[a-z]+)$/) ) + '_o' + src.match(/(\.[a-z]+)$/)[0];
   },

   oldimage: function(src){
      return src.replace(/_o\./, '.');
   }
};

// Highlight and scroll to the active track
function highlightActiveTrack(index) {
	var highlightColor = "#faf8e6";
	var $target = $('.player .playlist li:eq('+index+')');
	//$('.player .playlist li a[index]').animate({backgroundColor:highlightColor}, 750);
	$('.player .playlist li').removeClass('active');
	$('.player .playlistcontainer').scrollTo($target, 800 );
	$target.addClass('active');
}

// Process a form using AJAX and insert the response or redirect
// Requires: 
//	$form - the form to process (jQuery object)
//	$button - the button that was pressed (jQuery object)
// 	$msgbox - html container for the resulting message (jQuery object)
//
// Expects a html response
// 		<div id="msgcontent"><div id="msg">Response</div></div>
// 		Inserts the contents of #msg
//
//		<div id="redirect">http://site.com</div>
//		Redirects to site.com
//
function processAjaxForm($form, $button, $msgbox) {
	var action = $form.attr('action');	// Get form action	
	var dataString = $form.serialize();	// Get field values
	var btnSrc = $button.attr('src');

	// Change button to spinner & hide the msgbox if it's open
	$msgbox.fadeOut('normal');
	$button.attr('disabled', 'disabled')
	.attr('src','/images/ajax-loader.gif');
	
	// Post the form
	$.ajax({  
	  type: "POST",  
	  url: action,  
	  data: dataString,  
	  dataType: 'text',
	  cache: false,
	  success: function(data) { 
		// if we see #redirect, redirect the window to that location
		// FYI filters only pick up top level elements
		
		// look for <a id="redirect" href="#">
	  	var redirect = $(data).filter("a#redirect").attr('href'); 
	  	if (!redirect) {
	  		// look for <p id="redirect"><a href="#">
		  	redirect = $(data).filter("#redirect").html();
		  	redirect = $(redirect).filter("a").attr('href');
		}
	  	if (redirect && redirect != "JavaScript:history.go(-1)") {
	  		window.location = redirect;
	  		return true;
	  	} 
	  	
	  	// otherwise show the return message
	  	var msg = $(data).filter('#msgcontent').html();

	  	msg = $(msg).filter('.msg').html();
	  	msg = '<div class="error">' + msg + '</div>';

	    $msgbox.hide()  
	    .html(msg)
	    .fadeIn('normal', function() {  
	      //$msgbox;  
	    });  
	    
	    // Reset the button
	    $('#spinner').fadeOut('normal');
		$button.removeAttr('disabled')
		.attr('src',btnSrc);
	  }
	 }); 		
	
	return true;
}

// Takes a pattern and preps those links to open an embedded YouTube video
// The links in the pattern should look like this: <a href="http://www.youtube.com/watch?v=Wvo-g_JvURI
//
function prepEmbeddedVideos($pattern) {
	$pattern.each(function(i) {
		// Get our YouTube URL
		var url = $(this).attr("href");
		
		// Get the 11 character video code
		var start = url.indexOf('watch?v=') + 8;
		var v = url.slice(start, start+11); 
		
		// When this link is clicked, it will pop a modal w/ the video embedded		
		$(this).colorbox({href:"/inc/video/"+v+"/"});	
	});
}

// Takes an awesm type, channel, and destination and returns an awe.sm URL for the current page
// Tool = sharelink, sharebutton, track-link, review-comment
// Channel = twitter, facebook-post, mailto
// Dest = the URL you want to shorten
function awesmURL(tool, channel, dest) {
	var apikey = "40497c2494141f6da5e7ca22bb4eec97f983f0a3664adcd816675418452a23a7"; // awe.sm API key

	return 'http://create.awe.sm/url/share?api_key=' + apikey + '&version=1&share_type=' + channel + '&create_type='+tool+'&target='+encodeURIComponent(location.href)+'&destination=' + dest;
}

// Thanks to http://yensdesign.com/2009/01/how-to-set-maxlength-textareas-by-creating-jquery-plugin/
jQuery.fn.maxLength = function(max){
	this.each(function(){
		//Get the type of the matched element
		var type = this.tagName.toLowerCase();
		//If the type property exists, save it in lower case
		var inputType = this.type? this.type.toLowerCase() : null;
		//Check if is a input type=text OR type=password
		if(type == "input" && inputType == "text" || inputType == "password"){
			//Apply the standard maxLength
			this.maxLength = max;
		}
		//Check if the element is a textarea
		else if(type == "textarea"){
			//Add the key press event
			this.onkeypress = function(e){
				//Get the event object (for IE)
				var ob = e || event;
				//Get the code of key pressed
				var keyCode = ob.keyCode;
				//Check if it has a selected text
				var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
				//return false if can't write more
				return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
			};
			//Add the key up event
			this.onkeyup = function(){
				//If the keypress fail and allow write more text that required, this event will remove it
				if(this.value.length > max){
					this.value = this.value.substring(0,max);
				}
			};
		}
	});
};
