/**
 * Constants
 */
var LINK_DISABLED_COLOR = "#8A8A8A";
var LINK_ENABLED_COLOR = "#ABA000";

var SLOWSPEED = 500;
var MEDIUMSPEED = 350;

STRING_RELATED_ARTIST_FOUND = "Related artist added to artist list";
STRING_ARTIST_DELETED = "Artist deleted from list";
var IsNewSong = new Boolean(true);
var IsUserInitiated = new Boolean(false);
var IsPlaying = new Boolean(false);
var UseKeyboard = true;
var UseRoles = true;
//var UseProperties = false;
var IsMute = false;
var UseStates = true;
var UseLiveRegions = true;
var UseRelationships = true;
var UseLandmarks = true;
var IsDebug = false;  // to determine when to output text to console
var tObj = null; // Holds reference to toolbar object in application
var eObj = null;  // Holds reference to edit object for searching artist
var lObj = null;  // Holds reference to list of tracks object
var qObj = null;  // Holds reference to queue of items to play object 
var sliderObj = null;
var timerObj = null;
var playBtn = null;
var prevBtn = null;
var nextBtn = null;
var saveBtn = null;
var searchBtn = null;
var shuffleLink =  null;
var bannerTxt = null;

var createDiv = null;
var queueDiv = null;
var playDiv = null;

var headerDiv = null;
var footerDiv = null;
var contentDiv = null;
var searchDiv = null;
var resultsDiv = null;

var layoutQ = null;
var layoutP = null;
/**
 * UI Functions
 */
 
function startApp()
{
	
	// Initialize the two lists used within application 
	tracks = new QList("listTracks","li","trackItem");  
	q=new QList("listQueue","qi","queueItem");
	
	// Obtain references to UI components in application
	tObj = axs.id('customToolbar');  // Holds reference to toolbar object in application
	lObj = axs.id("listTracks");  // Holds reference to list of tracks object
	qObj = axs.id("listQueue");  // Holds reference to queue of items to play object 
	eObj = axs.id("editArtist");  // Holds reference to edit object for searching artist
	//eObj.value="";  // Make sure edit is blank when reset
	//eObj.onkeypress=printKey;
	dObj = axs.id("dialog");
	
	statusObj = axs.id("playerStatus");  // Holds reference to status object
	timerObj = axs.id("txtTime");	  // Holds reference to time being displayed
	sliderObj = axs.id("hSlider");    // Holds reference to slider object	

	playBtn = axs.id("p1");    // Holds reference to play/pause button
	prevBtn = axs.id("p2"); // Holds reference to previous queue button
	nextBtn = axs.id("p3");   // Holds reference to next queue button
	saveBtn = axs.id("p4");   // Holds reference to save button

	searchBtn = axs.id("imgSearch");
	shuffleLink = axs.id("linkShuffle");
	bannerTxt = axs.id("txtBanner");	
	
	createDiv = axs.id("CREATE");
	queueDiv = axs.id("QUEUE");
	playDiv = axs.id("PLAY");
	
	headerDiv = axs.id("HEADER");
	footerDiv = axs.id("FOOTER");
	contentDiv = axs.id("CONTENT");
	searchDiv = axs.id("searchContainer");
	resultsDiv = axs.id("results");
	layoutQ = axs.id("layoutQueue");
	layoutP = axs.id("layoutPlay");
	
	disableUI();

//  Check to see if queue is being loaded
	readData();
	
	// Can turn on/off ARIA and keyboard

	updateARIARoles();
	updateARIAStates();
	updateARIALandmarks();
	updateARIARelationships();	
	updateARIALiveRegions();

}

function updateKeyboard()
{

	if(UseKeyboard)
	{


appCommands.init();
toolbarCommands.init();

trackCommands.init();
queueCommands.init();
q.ResetFocus();
	}
}
function toggleKeyboardCbx()
{
	checkbox=axs.id("c1");	
	UseKeyboard=checkbox.checked;
	updateKeyboard();
}

function toggleRoleCbx()
{
	checkbox=axs.id("c1");	
	UseRoles=checkbox.checked;
	updateARIARoles();
}

function toggleRoleStateCbx()
{
	checkbox=axs.id("c2");	
	UseStates=checkbox.checked;
	UseRoles=checkbox.checked;
	updateARIARoles();
	updateARIAStates();
}

function togglePropertiesCbx()
{
	checkbox=axs.id("c2");	
	UseStates=checkbox.checked;
	UseRoles=checkbox.checked;
	UseRelationships=checkbox.checked;
	updateARIARoles();
	updateARIAStates();
	updateARIARelationships();
}

function toggleStateCbx()
{
	checkbox=axs.id("c2");	
	UseStates=checkbox.checked;
	updateARIAStates();
}

function toggleRelationshipCbx()
{
	checkbox=axs.id("c3");	
	UseRelationships=checkbox.checked;
	updateARIARelationships();
}

function toggleLandmarkCbx()
{
	checkbox=axs.id("c4");	
	UseLandmarks=checkbox.checked;
	updateARIALandmarks();
}

function toggleLiveRegionCbx()
{
	checkbox=axs.id("c5");	
	UseLiveRegions=checkbox.checked;
	updateARIALiveRegions();
}

function readData() 
{
	var srchString = decodeURIComponent(location.search.substring(1, location.search.length));
	if (srchString.length > 0) 
	{
		var group = srchString.split("id=");
		loadQueue(group[1]);
		updateInstructions("Archived Queue Loaded");
		enablePreviousButton();
		enableToolbar();
	}
}

function updateARIARoles()
{
	if(UseRoles)
	{
		createDiv.setAttribute("role","region");
		queueDiv.setAttribute("role","region");
		playDiv.setAttribute("role","region");
		
		resultsDiv.setAttribute("role","presentation");		
		layoutQ.setAttribute("role","presentation");
		layoutP.setAttribute("role","presentation");
		
		dObj.setAttribute("role","dialog");
		
		playBtn.setAttribute("role","button");
		prevBtn.setAttribute("role","button");
		nextBtn.setAttribute("role","button");
		saveBtn.setAttribute("role","button");
		searchBtn.setAttribute("role","button");
		tObj.setAttribute("role","toolbar");
		lObj.setAttribute("role","listbox");
		qObj.setAttribute("role","listbox");
		statusObj.setAttribute("role","status");
		timerObj.setAttribute("role","progressbar");
		bannerTxt.setAttribute("role","description");  // TODO UPDATE
	}
	else
	{
		createDiv.removeAttribute("role");
		queueDiv.removeAttribute("role");
		playDiv.removeAttribute("role");
		
		resultsDiv.removeAttribute("role");		
		layoutQ.removeAttribute("role");
		layoutP.removeAttribute("role");
		
		dObj.removeAttribute("role");
		
		playBtn.removeAttribute("role");
		prevBtn.removeAttribute("role");
		nextBtn.removeAttribute("role");
		saveBtn.removeAttribute("role");
		searchBtn.removeAttribute("role");
		tObj.removeAttribute("role");
		lObj.removeAttribute("role");
		qObj.removeAttribute("role");
		statusObj.removeAttribute("role");
		timerObj.removeAttribute("role");
		bannerTxt.removeAttribute("role");  // TODO UPDATE
	}
}

function updateARIAStates()
{
	if(UseStates)
	{
//		createDiv.setAttribute("aria-labelledby","lblCreate");
//		queueDiv.setAttribute("aria-labelledby","lblQueue");
//		playDiv.setAttribute("aria-labelledby","lblPlay");
		
		if(playBtn.alt=="Play")
		{

			playBtn.setAttribute("aria-pressed", "false");

		}
		else
		{

			playBtn.setAttribute("aria-pressed", "true");

		}
		
		if(playBtn.src == "img/button_play.gif")
		{
			playBtn.setAttribute("aria-disabled","false")	
		}
		else
		{
			playBtn.setAttribute("aria-disabled","true")	
		}
		
		if(prevBtn.src == "img/button_prev.gif")
		{
			prevBtn.setAttribute("aria-disabled","false")	
		}
		else
		{
			prevBtn.setAttribute("aria-disabled","true")	
		}
		
		if(nextBtn.src == "img/button_next.gif")
		{
			nextBtn.setAttribute("aria-disabled","false")	
		}
		else
		{
			nextBtn.setAttribute("aria-disabled","true")	
		}
		
		if(saveBtn.src == "img/button_save.gif")
		{
			saveBtn.setAttribute("aria-disabled","false")	
		}
		else
		{
			saveBtn.setAttribute("aria-disabled","true")	
		}


		//Set edit properties

		eObj.setAttribute("aria-autocomplete","false");

		//eObj.setAttribute("aria-labelledby","lblCreate");
	
		//Set toolbar properties
		tObj.setAttribute("aria-activedescendant","p1");
		tObj.setAttribute("tabindex","0");
	
		//qObj.setAttribute("aria-labelledby","lblTracks");
		
//		timerObj.setAttribute("aria-labelledby","lblTimer");
	}
	else
	{
		playBtn.removeAttribute("aria-pressed");
		eObj.removeAttribute("aria-autocomplete");
		tObj.removeAttribute("aria-activedescendant");
		timerObj.removeAttribute("aria-valuenow");
	}
}


function updateARIALandmarks()
{
	if(UseLandmarks)
	{
		headerDiv.setAttribute("role","banner");
		searchDiv.setAttribute("role","search");
		contentDiv.setAttribute("role","main");
		footerDiv.setAttribute("role","contentinfo");
		document.body.setAttribute("role","application");
	}
	else
	{
		headerDiv.removeAttribute("role");
		searchDiv.removeAttribute("role");
		contentDiv.removeAttribute("role");
		footerDiv.removeAttribute("role");
		document.body.removeAttribute("role");
	}
}

function updateARIARelationships()
{
	if(UseRelationships)
	{
		// LABEL SECTION
		createDiv.setAttribute("aria-labelledby","lblCreate");
		queueDiv.setAttribute("aria-labelledby","lblQueue");
		playDiv.setAttribute("aria-labelledby","lblPlay");
		eObj.setAttribute("aria-labelledby","lblCreate");
		qObj.setAttribute("aria-labelledby","lblQueue");
		timerObj.setAttribute("aria-labelledby","lblTimer");		
		tObj.setAttribute("aria-label","Queue Controls");		
		// CONTROLS SECTION
		searchBtn.setAttribute("aria-controls","listTracks");
		shuffleLink.setAttribute("aria-controls","listQueue");
		tObj.setAttribute("aria-controls","listQueue");
		// DESCRIBES SECTION
		eObj.setAttribute("aria-describedby","txtInstructions");	
//		qObj.setAttribute("aria-describedBy","txtInstructions");
	}
	else
	{
		// LABEL SECTION
		createDiv.removeAttribute("aria-labelledby");
		queueDiv.removeAttribute("aria-labelledby");
		playDiv.removeAttribute("aria-labelledby");
		eObj.removeAttribute("aria-labelledby");
		qObj.removeAttribute("aria-labelledby");
		timerObj.removeAttribute("aria-labelledby");
		
		// CONTROLS SECTION
		searchBtn.removeAttribute("aria-controls");
		shuffleLink.removeAttribute("aria-controls","listQueue");
		// DESCRIBES SECTION
		eObj.removeAttribute("aria-describedby");	
		qObj.removeAttribute("aria-describedBy");
	}
}

// Function for setting up all of the live regions
function updateARIALiveRegions()
{
	if(UseLiveRegions)
	{
		//Songs Select Element
		lObj.setAttribute("aria-live","assertive");
		lObj.setAttribute("aria-relevant","removals");

		qObj.setAttribute("aria-live","assertive");
		qObj.setAttribute("aria-relevant","additions");
	
		//Status of Youtube Player
		statusObj.setAttribute("aria-live","polite");
		statusObj.setAttribute("aria-relevant","text");
		statusObj.setAttribute("aria-atomic","true");
	
		// Timer object
		timerObj.setAttribute("aria-live","off");
	}
	else
	{
		//Songs Select Element
		lObj.removeAttribute("aria-live");
		lObj.removeAttribute("aria-relevant");

		qObj.removeAttribute("aria-live");
		qObj.removeAttribute("aria-relevant");
	
		//Status of Youtube Player
		statusObj.removeAttribute("aria-live");
		statusObj.removeAttribute("aria-relevant");
		statusObj.removeAttribute("aria-atomic");
	
		// Timer object
		timerObj.removeAttribute("aria-live");
	}
}


function enableAriaProperties()
{
	if(UseProperties)
	{
		createDiv.setAttribute("aria-labelledby","lblCreate");
		queueDiv.setAttribute("aria-labelledby","lblQueue");
		playDiv.setAttribute("aria-labelledby","lblPlay");
		
		playBtn.setAttribute("aria-pressed", "false");
		
		//Set edit properties

		eObj.setAttribute("aria-autocomplete","false");
		eObj.setAttribute("aria-labelledby","lblCreate");
	
		//Set toolbar properties
		tObj.setAttribute("aria-activedescendant","p1");
		
	
		qObj.setAttribute("aria-labelledby","lblTracks");
		
		timerObj.setAttribute("aria-labelledby","lblTimer");
	}
}

// This function is used to disable all of the UI when app is started
function disableUI()
{

	disableSlider();
	
	// Used to update toolbar and buttons
	if(UseKeyboard)
	{
	tObj.setAttribute("tabindex",-1);
	}
	

	disablePlayButton();
	

	disablePreviousButton();

	disableNextButton();
	
	disableSaveButton();
	
//	uncheckBoxes();
	//TODO rename function to include fact that link is updated
//	ls = axs.id("linkShuffle");
//	ls.style.color=LINK_DISABLED_COLOR;
//	ls.setAttribute("aria-disabled",true);
}

function uncheckBoxes()
{
	c=axs.id("c1");	
	c.checked=false;
		c=axs.id("c2");	
	c.checked=false;
		c=axs.id("c3");	
	c.checked=false;
		c=axs.id("c4");	
	c.checked=false;
		c=axs.id("c5");	
	c.checked=false;
}
function disablePlayButton()
{
		playBtn.src="img/button_play_disabled.gif";
		if(UseStates)
		{
		playBtn.setAttribute("aria-disabled",true);
		}
}

function enablePlayButton()
{
	playBtn.src="img/button_play.gif";
	playBtn.setAttribute("aria-disabled",false);
}
function disablePreviousButton()
{

		prevBtn.src="img/button_prev_disabled.gif";
		if(UseStates)
		{
		prevBtn.setAttribute("aria-disabled",true);
		}
}

function enablePreviousButton()
{

		prevBtn.src="img/button_prev.gif";
		if(UseStates)
		{
			prevBtn.setAttribute("aria-disabled",false);
		}
		
		//TODO rename function to include fact that link is updated
	//	ls = axs.id("linkShuffle");
//		ls.style.color=LINK_ENABLED_COLOR;
//		ls.setAttribute("aria-disabled",false);
}

function disableNextButton()
{
		nextBtn.src="img/button_next_disabled.gif";
				if(UseStates)
		{
		nextBtn.setAttribute("aria-disabled",true);
		}
}

function enableNextButton()
{
	nextBtn.src="img/button_next.gif";
			if(UseStates)
		{
	nextBtn.setAttribute("aria-disabled",false);		
		}
}

function disableSaveButton()
{
	saveBtn.src="img/button_save_disabled.gif";
			if(UseStates)
		{
	saveBtn.setAttribute("aria-disabled",true);		
		}
}

function enableSaveButton()
{
	saveBtn.src="img/button_save.gif";
			if(UseStates)
		{
	saveBtn.setAttribute("aria-disabled",false);		
		}
}


function enableToolbar()
{
	if(UseKeyboard)
	{
		tObj.setAttribute("tabindex",0);
	}
		enablePlayButton();		
		enableNextButton();
		enableSaveButton();
}


function disableSlider()
{
	// Disable DOJO Slider
	// TODO Investigate correct way to disable
				if(UseStates)
		{
	sliderObj.setAttribute("aria-disabled","false");	
		}
}

function setPlayingUI()
{
	playBtn.src = "img/button_pause.gif";

	playBtn.onclick = pause;
			if(UseStates)
		{
	playBtn.setAttribute("aria-pressed",true);
		}
	playBtn.alt = "Pause";
	playBtn.title = "Pause";	
	playBtn.className+="";
	disableSlider();
}

function setPausedUI()
{
	playBtn.src = "img/button_play.gif";

	playBtn.onclick = playSong;
			if(UseStates)
		{
	playBtn.setAttribute("aria-pressed",false);
		}
	playBtn.alt = "Play";
	playBtn.title = "Play";	
	playBtn.className+="";
}

function setPauseUI()
{
	playBtn.src = "img/button_play.gif";

	playBtn.onclick = playSong;
			if(UseStates)
		{
	playBtn.setAttribute("aria-pressed",false);
		}
	playBtn.alt = "Play";
	playBtn.title = "Play";	
}

function updateStatusAlert(txt)
{

	statusObj.style.backgroundColor = "#CC0000";
	statusObj.style.color = "#FFFFFF";
	if(UseLiveRegions)
	{
		statusObj.setAttribute("aria-live","assertive");
	}
	txtObj = axs.id("txtStatus");
	axs.r(txtObj,txt);		

}

function updateStatus(txt)
{

	statusObj.style.backgroundColor = "#F0F0E6";
	statusObj.style.color="#666666";
	if(UseLiveRegions)
	{
		statusObj.setAttribute("aria-live","polite");
	}
	txtObj = axs.id("txtStatus");
	axs.r(txtObj,txt);			
}

function ToggleVolume()
{

	if (IsMute == false)
	{
		ytplayer.mute();
		IsMute = true;	
		updateStatus("Sound turned off");
	}
	else
	{
		IsMute = false;	
		ytplayer.unMute();
		updateStatus("Sound turned on");
	}
}

function playSongSelected()
{
 	var songList = document.getElementById("listQueue");
	var songUrl = songList.options[songList.selectedIndex].value;
	userControlled=true;
	loadNewVideo(songUrl);
}


function populateQueue(response)
{
		out("populating queue");
		var lines = response.split("!!!");

		var queueList = axs.id("listQueue");
		var i = 0;
		
		while (i < lines.length-1)
		{
			
		var params = lines[i].split("***");
		

		if(params[0]!="")
		{
			q.AddItem(params[0],params[1]);	
		}
		
//		editArtistObj.value="";
//		window.setTimeout(function () { editArtistObj.focus(); },0);  // set focus back to add artist obj 
		
		i++;
		}
}








function updateInstructions(txt)
{
	txtObj=axs.id("txtInstructions");
	axs.r(txtObj,txt);
}



function onEditArtistFocus()
{	
	updateInstructions("Type in a song AND OR artist to search for.  Press Enter.");
}

function focusEditArtist()
{
	ea = axs.id("editArtist");
	window.setTimeout(function () {ea.focus();},0);  // focusItem must be in scope
}

function onListTracksFocus()
{
	updateInstructions("Press the right arrow key to add song to queue");
}

function onListQueueFocus()
{
	updateInstructions("Press the left arrow or delete key to remove selected song from queue");
}


	
function onToolbarFocus()
{
	//TODO Decide if necessary
	//updateInstructions('Use left and right arrow keys to move through player controls');
}




		

function stopEvent(evnt) {
   if (evnt.stopPropagation) {
     evnt.stopPropagation();
   } else {
     evnt.cancelBubble = true;
   }
}	
	


// LIST QUEUE FUNCTIONS
function addTrackToQueue(track)
{
	
		try
		{

			q.AddItem(track.text, track.value)

				lt=axs.id("listTracks");
			  i=lt.selectedIndex;

			  lt.remove(i);

			  lt.selectedIndex=i-1;
		}
		catch(ex){
			
		alert(ex);



		}	
}

 


/**
 * AJAX Functions
 */



function loadQueue(id)
{
		dojo.xhrGet({

        url : "getData.php",  //the relative URL
		content:{
			"dn":id
		},
        // Run this function if the request is successful
        load : function(response, ioArgs) {
            

			populateQueue(response);

            return response; //always return the response back
        },

        // Run this function if the request is not successful
        error : function(response, ioArgs) {
            

            /* handle the error... */

            return response; //always return the response back
        }
    });


}


function displayDialog()
{
	var dia = axs.id("dialog");
	dia.style.display = "inline";

	var d = dijit.byId("dialog");
//	dojo.style(d.closeButtonNode,"visibility","hidden");
	var b = new dijit.form.Button({label: "Close"});
	d.titleNode.innerHTML = 'Queue Saved'
	d.title = "Save Your Queue";
    var handle = dojo.connect(b, "onClick", function() {
        d.hide();
        dojo.disconnect(handle);
    });

    d.show();
	dia = axs.id("dialog");
	dia.style.left="120px";
	dia.style.top="250px";
	dia.style.bgcolor="#362f2d";
	dia.style.color="#666666";
}

function processQueue()
{
	var saveString = q.ProcessItems();
	
	//txtArea.value=encodeURIComponent(txtArea.value);
	
	dojo.xhrGet({

        url : "newRecord.php",  //the relative URL
		content:{
			"name":"my first playlist",
			"data":saveString
		},
        // Run this function if the request is successful
        load : function(response, ioArgs) {
            
			q=axs.id("queueUrl");
			q.innerHTML="http://queuemusic.org/?id="+response;

			displayDialog();
            return response; //always return the response back
        },

        // Run this function if the request is not successful
        error : function(response, ioArgs) {
            

            // handle the error... 

            return response; //always return the response back
        }
    });


}



var userControlled=Boolean(false);




// Methods for listQueue control
function onQueueChange()
{
	IsNewSong=true;
	//displayDelete();
}



/*
* Application Commands
*/

function selectPreviousItem()
{
	userControlled=true;
	changeSong(-1);
}

function selectNextItem()
{
	userControlled=true;
	changeSong(1);
}

function changeSong(i)
{
 	//var songList = document.getElementById("listQueue");
	//var songIndex = songList.selectedIndex;
	//console.log(songIndex,"Song Index");
	if (i<0)
	{
		if(q.GetPlayIndex() == 0)
		{
			updateStatusAlert("At start of queue");			
			return;
		}
	}
	else if (i>0)
	{
		if((q.GetPlayIndex()) == (q.GetItemCount() - 1))
		{
			updateStatusAlert("At end of queue");
			return;
		}
	}

	q.PlayItem(i);
}

function playSong()
{
	// If song is paused
	if(IsNewSong==false)
	{
		play();		
	}
	else
	{		
		var queueO = q.GetCurrentItem();
		var songUrl =queueO.getAttribute("url");
		loadNewVideo(songUrl);
	}
}



/**
 * Slider and Time section
 */
function onSliderKeyPress(event)
{
	IsUserInitiated=true;
	//return event;
}
function onSliderChange(arguments)
{
//	console.log(arguments);
//	console.log("Time to change");
	sliderObj = dijit.byId('hSlider');
//	sliderObj.setvalue = arguments[0];
	sliderObj.setValue(arguments[0]);


	if(IsUserInitiated==true)
	{
		duration = getDuration();
		numValues = sliderObj.discreteValues;
		seekValue = (duration / numValues) * sliderObj.value;
		seekTo(seekValue);
		IsUserInitiated=false;
	//	console.log("set back to false");
	}
		
		
}

function roundNumber(num, dec)
{
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}


function convertTime(time, obj)
{
	time = Math.round(time);
	minutes = Math.round(Math.floor(time/60));
	seconds = roundNumber(Math.round(time%60),2);
	if(seconds < 10)
	{
		axs.r(obj,minutes+":0"+seconds);				
	}
	else
	{
		axs.r(obj,minutes+":"+seconds);		
	}	
}

function updateTime(){
	convertTime(getCurrentTime(),axs.id("curTime"));
	convertTime(getDuration(), axs.id("trackTime"));
	sliderObj = dijit.byId('hSlider');
	if(sliderObj)
	{
	incValue = Math.round(getDuration()/sliderObj.discreteValues);
	//console.log(incValue);
	i = Math.round(getCurrentTime()/incValue);
//	console.log(i);
//	console.log("SLIDER" + sliderObj.value);
	if(i > sliderObj.value)
	{
	//	console.log("its bigger");
		onSliderChange([i]);
	//sliderObj.value = 
	}
	//console.log("rounding " + Math.round(getCurrentTime()/incValue));
//	sliderObj.value = Math.round(getCurrentTime()/incValue);
	}
}

function resetTime(){
	axs.r(axs.id("curTime"),"0:00");	
	axs.r(axs.id("trackTime"),"0:00");
	onSliderChange([0]);
}

function getTimerValue()
{
	timerObj = axs.id("txtTime");
//TODO
	curTime = axs.id("curTime").innerHTML.split(":");

	cMin = curTime[0];
	cSec = curTime[1];
	if (cMin=="1")
	{
		text = "Track is at " + cMin + " minute and "; 
	}
	else
	{
		text = "Track is at " + cMin + " minutes and ";
	}
	if (cSec=="1")
	{
		text = text + cSec + " second.";			
	}
	else
	{
		text = text + cSec + " seconds.";			
	}
		if(UseStates)
		{
	timerObj.setAttribute("aria-valuenow",text);
		}
	//timerObj.setAttribute("title",text);
}


function dialogAlert(txtTitle, txtContent)
{
	var thisdialog = new dijit.Dialog({ title: txtTitle, content: txtContent });
	dojo.body().appendChild(thisdialog.domNode);
	thisdialog.startup();
	thisdialog.show();
}
/**
 * Modified Google Script Code from
 * http://code.google.com/apis/youtube/chromeless_example_1.html
 */

        function updateHTML(elmId, value) {
          document.getElementById(elmId).innerHTML = value;
        }

        function setytplayerState(newState) {
          updateHTML("playerstate", newState);
        }

        function onYouTubePlayerReady() {
          ytplayer = swfobject.getObjectById("myytplayer");
//          ytplayer = document.getElementById("myytplayer");
		//  console.log(ytplayer);
          setInterval(updateytplayerInfo, 1000);
          updateytplayerInfo();
          ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
        }

        function onytplayerStateChange(newState) {
          setytplayerState(newState);
        }

/*
Fired whenever the player's state changes. Possible values are unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5). When the SWF is first loaded, it will broadcast an unstarted (-1) event. When the video is cued and ready to play, it will broadcast a video cued event (5).
*/
function onytplayerStateChange(newState) 
{
	out("New Player State is: " + newState);
	// Possible values are unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5). 
	// Song sended by user
	if(newState==0 && userControlled==true)
	{
		updateStatus("Song Over");
		userControlled=false;
		IsPlaying=false;
		resetTime();
	}
	// Song ended due to end of track
	else if(newState==0 && userControlled==false)
	{
		resetTime();
		changeSong(1);
		IsPlaying=false;
	}
	else if(newState==1)
	{
		IsPlaying=true;

		updateStatus("Playing");
		// Make sure pause button is showing when item is playing
		setPlayingUI();
	}
	else if(newState==2)
	{
		updateStatus("Paused");
		// Make sure pause button is showing when item is playing
		setPausedUI();  
		IsPlaying=false;
	}
	else if(newState==3)
	{
		itemName = q.GetItemPlayingName();
		itemName = itemName.substr(0,22);
		updateStatus("Loading " + itemName);	
		IsPlaying=false;
	}

}

        function updateytplayerInfo() 
		{
			if(IsPlaying==true)
			{
			updateTime();
			}

        }

        // functions for the api calls
        function loadNewVideo(id, startSeconds) {
		if(id)
		{
		
	//TODO verify can remove

		
          if (ytplayer) {
            ytplayer.loadVideoById(id, parseInt(startSeconds));
			IsNewSong=false; // Set so that when new song is selected player knows to start new song
			
          }
        }
		}
		

        function cueNewVideo(id, startSeconds) {
          if (ytplayer) {
            ytplayer.cueVideoById(id, startSeconds);
          }
        }


        function play() {
          if (ytplayer) 
		  {
			ytplayer.playVideo();			
			return false;
          }
        }

        function pause() 
		{
          if (ytplayer) 
		  {
            ytplayer.pauseVideo();
          }
        }

        function stop() 
		{
          if (ytplayer) 
		  {
            ytplayer.stopVideo();
          }
        }

        function getPlayerState() {
          if (ytplayer) {
            return ytplayer.getPlayerState();
          }
        }

        function seekTo(seconds) {
          if (ytplayer) {
            ytplayer.seekTo(seconds, true);
          }
        }

        function getBytesLoaded() {
          if (ytplayer) {
            return ytplayer.getVideoBytesLoaded();
          }
        }

        function getBytesTotal() {
          if (ytplayer) {
            return ytplayer.getVideoBytesTotal();
          }
        }

        function getCurrentTime() {
          if (ytplayer) {
            return ytplayer.getCurrentTime();
          }
        }

        function getDuration() {
          if (ytplayer) {
            return ytplayer.getDuration();
          }
        }

        function getStartBytes() {
          if (ytplayer) {
            return ytplayer.getVideoStartBytes();
          }
        }

        function mute() {
          if (ytplayer) {
            ytplayer.mute();
          }
        }

        function unMute() {
          if (ytplayer) {
            ytplayer.unMute();
          }
        }
        
        function getEmbedCode() {
          alert(ytplayer.getVideoEmbedCode());
        }

        function getVideoUrl() {
          alert(ytplayer.getVideoUrl());
        }
        
        function setVolume(newVolume) {
          if (ytplayer) {
            ytplayer.setVolume(newVolume);
          }
        }

        function getVolume() {
          if (ytplayer) {
            return ytplayer.getVolume();
          }
        }

        function clearVideo() {
          if (ytplayer) {
            ytplayer.clearVideo();
          }
        }
        
// Used to display text for debugging purposes
function out(text)
{
	if(IsDebug)
	{
		console.log(text);	
	}
}


// TODO To Remove Possibly After SXSW
function displayConfig()
{
	configObj = axs.id("CONFIG");
	if(configObj.style.display=="none")
	{
		configObj.style.display = "block";
	}
	else
	{
			configObj.style.display = "none";
	}
	out(configObj);
}