/* Lana Del Rey / Universal Music Group / v1.2 / Live
===========================================================*/

$(document).ready(function() {
	initNavigation();
	initOverlay();
	$('body').append('<div id="ytmask" />');
});

/* Ajax Loading & History Deep Linking
===========================================================*/

$.address.change(function(event) {
	loadPage();
});

function loadPage() 
{	

	var path = $.address.path();

	$('#ajaxContainer').fadeOut(250, function() {
		// ajax request
	 	$("#ajaxContainer").load(path + ' #ajaxInner', function() {

			$('#ajaxContainer').fadeIn(250);

			var section = $.address.pathNames();
			
			if (section[0] === undefined)
			{
				section = "home";
			}
			else
			{
				section = section[0];
			}

			// !important: assign body id to page 
			$('body').attr('id', section);

			// set page title
			$.address.title("Lana Del Rey - " + section.substr(0, 1).toUpperCase() + section.substr(1).toLowerCase() );

			// bring yt player in front of opacity mask
			bringYouTubePlayerToFront();

			// initialises page specific functions
			switch(section) {
				case "music":
					initMusic();
					break;
				case "gallery":
					initGallery();	
					initPlaylist();	
					sendYouTubePlayerToBack();
					break;
				case "home":
					initHome();
					initPlaylist();
					break;
				default:
 					break;
			}

		});
		
	});
}

/* Gallery
===========================================================*/

function initGallery()
{
	$('a#mediaToggle').bind('click', toggleVideoSlider);
	
	// open media tray for the user
	toggleVideoSlider();

	// load default photo
	var defaultPhoto = $('#playlist.gallery li:first a').attr('rel');
	$.backstretch(defaultPhoto, {speed: 350, minW: 0, centeredY: false});
	
	$('#playlist.gallery li:first a').addClass('active');

	// click handler
	$('#playlist.gallery li a').click(function(event) {
		var active = $(this).hasClass('active'),
			target = $(this).attr("rel");

		if (!active)
		{
			$('#playlist.gallery li a').removeClass('active');
			$(this).addClass('active');
			$('#backstretch').fadeOut(350, function(){
				$(this).remove();
				$.backstretch(target, {speed: 350, minW: 0, centeredY: false});
			});
		}
		event.preventDefault;
		return false;
	});
}

/* Home
===========================================================*/

var ytplaylist;
var yttotal;
var ytindex = 0;

function initHome()
{

	// put mask behind player
	$('#ytmask').css('z-index', '-999999');

	// assign click handlers
	$('a#mediaToggle').bind('click', toggleVideoSlider);
	$('#playlist.video li a').bind('click', videoHandler);

	// create an array and push video id for each
	ytplaylist = new Array();
	$('#playlist li a').each(function(index, item) {
		ytplaylist.push(item.rel);
	});
	// add number of videos to total variable
	yttotal = ytplaylist.length - 1;

	$('#latestPackshot').hover(function() {
		$(this).fadeTo('fast', 1);
	}, function() {
		$(this).fadeTo('slow', 0.5);
	});
}

// Navigation Hover

function initNavigation() 
{
	$('#nav li a').hover(function() {
		 $(this).animate({ color: "#ffffff" }, 150);
	}, function() {
		$(this).animate({ color: "#8D8D8D" }, 300);
	});
	
	// grab user timeline
	$.getJSON('https://api.twitter.com/1/statuses/user_timeline.json?screen_name=lanadelrey&count=5&include_entities=1&callback=?', function(json) {
		// iterate results 
		$.each(json, function(index) {
			// buid slide and add to slideshow
			$('<li>').append( format_links(json[index].text) ).append( ' <span>' + relative_time(json[index].created_at) + '</span>' ).appendTo('#lanatweets');
		}); 		

		// after all slides are added, start cycle
		$('#lanatweets').cycle({
			fx: 'scrollUp',
			timeout: 2000,
			pause: true
		});

	});

	// Convert the time stamp to a more human readable format
	function relative_time(timeString) {
	  var parsedDate = Date.parse(timeString);
	  var delta = (Date.parse(Date()) - parsedDate) / 1000;
	  var r = 'just now';
	  if  (delta < 60) {
	    r = delta + " seconds ago";
	  } else if (delta < 120) {
	    r = 'a minute ago';
	  } else if (delta < (45 * 60)) {
	    r = (parseInt(delta / 60, 10)).toString() + " minutes ago";
	  } else if (delta < (90 * 60)) {
	    r = 'an hour ago';
	  } else if (delta < (24 * 60 * 60)) {
	    r = '' + (parseInt(delta / 3600, 10)).toString() + " hours ago";
	  } else if (delta < (48 * 60 * 60)) {
	    r = 'a day ago';
	  } else {
	    r = (parseInt(delta / 86400, 10)).toString() + " days ago";
	  }
	  return r;
	}
	
	// Format Twitter urls, users and hash tags
	function format_links(t) {
		var rxp_url = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
		var rxp_user = /[\@]+([A-Za-z0-9-_]+)/gi;
		var rxp_hash = /[\#]+([A-Za-z0-9-_]+)/gi;

		t = t.replace(rxp_url,'<a target="_blank" href="$1">$1</a>');
		t = t.replace(rxp_user,'<a target="_blank" href="http://twitter.com/$1">@$1</a>');
		t = t.replace(rxp_hash,'<a target="_blank" href="http://search.twitter.com/search?q=&tag=$1&lang=all">#$1</a>');

		return t;
	}
	
	// Country menu
	$('#country').click(function(event) {
		$('#countries').toggle();
		$(this).toggleClass('active');
	});
	
	// Initialise navigation
	$('#yt-play').bind('click', togglePlayback);
	$('#yt-next').bind('click', nextVideo);
	$('#yt-prev').bind('click', prevVideo);

}

// Toggle Video Slider

function toggleVideoSlider(event)
{
	$('#mediaTray').slideToggle('1200', 'easeOutCirc', function(){
		if($("#mediaTray").is(":hidden"))
		{			
			$(this).find('#playlist li').hide();
			$('#prevCarousel, #nextCarousel').hide();			
			$('body').unbind('click', toggleVideoSlider);
		}
		else 
		{			
			$(this).find('#playlist li').each(function(index) {
				delay = index * 100;
				$(this).delay(delay).fadeIn(500);
				$('#prevCarousel, #nextCarousel').fadeIn(500);
			});
			$('body').bind('click', toggleVideoSlider);
		}
	});
	return false;
}

/* YouTube Player API
===========================================================*/

var videoid;
var ytplayer;

google.load("swfobject", "2.2");
google.setOnLoadCallback(createYouTubePlayer);

function createYouTubePlayer()
{
	var c = document.getElementById("ytplayer");
	if (!c) {
		var div = document.createElement("div");
		var body = document.body;
		div.setAttribute("id", "ytvideo");
		body.insertBefore(div,body.firstChild);
	}
	var params = { wmode: "transparent", allowScriptAccess: "always" };
	var atts = { id: "ytvideo", bgcolor: "#000000" };
	swfobject.embedSWF("http://www.youtube.com/apiplayer?version=3&enablejsapi=1&playerapiid=ytvideo", "ytvideo", "100%", "100%", "8", null, null, params, atts);
}

function onYouTubePlayerReady(playerId)
{
	var videoid = (ytplaylist ? ytplaylist[0] : defaultvideoID);
	ytplayer = document.getElementById("ytvideo");
	ytplayer.addEventListener("onStateChange", "onStateChange");
	ytplayer.loadVideoById(videoid);
	$('#ytmask').fadeTo('fast', 0.7);
	$('#ytmask').css('z-index', '-999999');
}

function onStateChange(newState) {
	// unstarted (-1), ended (0), playing (1), 
	// paused (2), buffering (3), video cued (5)
	if (newState == '1' || newState == '3') {
		$('#yt-play').addClass('playing');
	} else if (newState == '0' || newState == '2') {
		$('#yt-play').removeClass('playing');
	}
}

function videoHandler(event)
{
	if (ytplayer) {
		toggleVideoSlider();
		// grab the video it from the rel attribute
		videoid = $(this).attr('rel');
		// set index for secondary video nav
		ytindex = $(this).parent().index();
		// load video
		ytplayer.loadVideoById(videoid);
	}
	$('#playlist').find('a').removeClass('now-playing');
	$(this).addClass('now-playing');
	event.PreventDefault;
	return false;
}

function togglePlayback(event)
{
	playing = $('#yt-play').hasClass('playing');
	if (playing) {
		ytplayer.pauseVideo();
	} else {
		ytplayer.playVideo();
	}
	event.PreventDefault;
	return false;
}

function nextVideo(event)
{
	if (ytindex < yttotal)
	{
		ytindex = ytindex + 1;
		var nextid = $('#playlist li a').eq(ytindex).attr("rel");
		ytplayer.loadVideoById(nextid);
	}
	event.PreventDefault;
	return false;
}

function prevVideo(event)
{
	if (ytindex > 0)
	{
		ytindex = ytindex - 1;
		var nextid = $('#playlist li a').eq(ytindex).attr("rel");
		ytplayer.loadVideoById(nextid);		
	}
	event.PreventDefault;
	return false;
}

function bringYouTubePlayerToFront()
{
	$('#ytmask').css('z-index', '-999997');
	$('#ytvideo').css('z-index', '-999998');
	$('#ytvideo').css('visibility', 'visible');
	$('#backstretch').remove();
}

function sendYouTubePlayerToBack()
{
	$('#ytmask').css('z-index', '-1000000');
	$('#ytvideo').css('z-index', '-1000001');
	$('#ytvideo').css('visibility', 'hidden');
}

function initPlaylist()
{
	$('#playlist').jcarousel({
		scroll: 1,
		initCallback: customButtonCall,
		buttonNextHTML: null,
		buttonPrevHTML: null,
		itemFallbackDimension: 840
	});

	function customButtonCall(carousel) {	
		$('#prevCarousel').bind('click', function() {
	        carousel.prev();
	        return false;
	    });

	    $('#nextCarousel').bind('click', function() {
	        carousel.next();
	        return false;
	    });
	}
}

/* Music Functions (=Isotope)
===========================================================*/

function initMusic()
{

	var $container = $('#releases');

  	$container.isotope({
    	itemSelector: '.release',
    	masonry: {
      		columnWidth: 320
    	}
  	});

  	$('.release').click(function(){

	    var $this = $(this),        
	        expanded = $this.hasClass('open');

		if (!expanded) {
			// reset all to closed state
			$('.release').removeClass('open');
			$('.release').find('.sleeve').hide();
			// open the release
			$this.toggleClass('open');
		    $this.find('.sleeve').toggle();
		    $container.isotope( 'reLayout' );
		}

	});

}

/* VV List Overlay (=Overlay)
===========================================================*/

function initOverlay()
{
	$("a#mailing[rel]").overlay({
		closeOnClick: true,
		onBeforeLoad: function() 
		{
			// grab wrapper element inside content
			var wrap = this.getOverlay().find("#overlayContent");
			// load the page specified in the trigger
			wrap.load(this.getTrigger().attr("href"));
		}
	});
}

/* End of /scripts.js
===========================================================*/

