/**
 * KANM JavaScript file containing the most commonly used functions, along wtih
 * AJAX functions.
 * 
 * @author Daniel Cousineau (dcousineau@gmail.com)
 * @version 0.0.1
 */

window.onload = initialize;

var songIterator;
var showIterator;
var invSong;
var invShow;

/**
 * Initializes KANM page (begins AJAX calls for the Now Playing list, etc.)
 */
function initialize()
{
	songIterator = "2";
	showIterator = "2";
	invSong = "";
	invShow = "";
	
	updateNowPlaying();
}

/**
 * Update now playing list
 */
function updateNowPlaying()
{	
	var xmlReq = new XMLHttpRequest();
	
	xmlReq.onreadystatechange = function () {
		if( xmlReq.readyState == 4 )
		{
			if( xmlReq.status == 200 )
			{
				var nowPlaying = xmlReq.responseText.parseJSON();
				
				curTitle = document.getElementById('title' + invSong).innerHTML;
				curArtist = document.getElementById('artist' + invSong).innerHTML;
				curShow = document.getElementById('show' + invShow).innerHTML;
				
				if( curShow != '<a href="#'+nowPlaying.show_id+'">'+nowPlaying.show+'</a>' )
					swapShow( nowPlaying.show_id, nowPlaying.show );
					
				if( curTitle != nowPlaying.title || curArtist != nowPlaying.artist )
					swapSong( nowPlaying.title, nowPlaying.artist );
				
				setTimeout(updateNowPlaying, 15000); //re-update after 1500ms
			}
		}
	}
	
	xmlReq.open('GET', './test.json', true);
	xmlReq.send(null);
}

function swapSong( title, artist )
{
	if( songIterator == "" )
	{
		songIterator = "2";
		invSong = "";
	}
	else
	{
		songIterator = "";
		invSong = "2";
	}
	
	Effect.Fade('title' + songIterator,{duration:0.5, queue: {position:'front', scope:'titlescope', limit:4} });
	Effect.Fade('artist' + songIterator,{duration:0.5, queue: {position:'front', scope:'artistscope', limit:4} });

	document.getElementById('title' + invSong ).innerHTML = title;
	document.getElementById('artist' + invSong ).innerHTML = artist;
	
	Effect.Appear('title' + invSong,{duration:0.5, queue: {position:'end', scope:'titlescope', limit:4} });
	Effect.Appear('artist' + invSong,{duration:0.5, queue: {position:'end', scope:'artistscope', limit:4} });
}

function swapShow( id, show )
{
	if( showIterator == "" )
	{
		showIterator = "2";
		invShow = "";
	}
	else
	{
		showIterator = "";
		invShow = "2";
	}
	
	Effect.Fade('show' + showIterator,{duration:0.5, queue: {position:'front', scope:'showscope', limit:2} });

	document.getElementById('show' + invShow).innerHTML = '<a href="#'+id+'">'+show+'</a>';
	//Alter Link Properties

	Effect.Appear('show' + invShow,{duration:0.5, queue: {position:'end', scope:'showscope', limit:2} });
}
