var defaultLinkColor = '#CAAA52';
var selectedLinkColor = '#436959';
var contentUrl = 'content.php';
var emailUrl = 'email.php';

var artists = new Array(3);
artists[0] = new Array(6);
artists[1] = new Array(6);
artists[2] = new Array(4);

artists[0][0] = 'thepolishambassador';
artists[0][1] = 'themantras';
artists[0][2] = 'antioquia';
artists[0][3] = 'thesiloeffect';
artists[0][4] = 'shortwavesociety';
artists[0][5] = 'formerchampions';

artists[1][0] = 'momentaryprophets';
artists[1][1] = 'thedharmainitiative';
artists[1][2] = 'peanutgringo';
artists[1][3] = 'bowler';
artists[1][4] = 'j3project';
artists[1][5] = 'pbr';

artists[2][0] = 'ginasobel';
artists[2][1] = 'thepolychrons';
artists[2][2] = 'thegnosablueprint';
artists[2][3] = 'santamariabros';

function checkAttendeeName()
{
    var attendeeNames = document.getElementById('attendee_names').value;
    if (attendeeNames.length < 5)
    {
        alert("Please enter your full name, then click the Buy Now button.");
        return false;
    }
    return true;    
}

function gotoPage(page_name)
{ 
	document.getElementById('left_area_content').innerHTML = document.getElementById('content_' + page_name).innerHTML;
	switch(page_name)
	{
		case 'main':
			break;
		case 'artists':
			showRandomArtist(1);
			showRandomArtist(2);
                        showRandomArtist(3);
			break;
		default:break;		
	}
}

function page_onLoad()
{
	gotoPage('main');
	startPlayer();
}
function showArtist(list_num, artist_name)
{
	showItem('artist', list_num, artist_name);
}
function showItem(item_type, list_num, item_id)
{
	var itemInfoDiv = document.getElementById(item_type + "_info_box_" + list_num);
	var myRequest = new ajaxObject(contentUrl);
	myRequest.callback = function(responseText, responseStatus, responseXML) {
		if (responseStatus==200)
		{
		      itemInfoDiv.innerHTML = responseText;
		      resetLinkColors(item_type, list_num);
		      document.getElementById(item_id).style.color = selectedLinkColor;
		}
		else
		{		      
		      itemInfoDiv.innerHTML = "There was an error retrieving the artist's content, please contact the webmaster.";
		}
	};
	myRequest.update('content_type=' + item_type + '&content_id=' + item_id);  // Server is contacted here.
}
function showRandomArtist(list_num)
{
	var intListNum = parseInt(list_num)-1;
	var randy = getRandy(artists[intListNum].length);
	showArtist(list_num, artists[intListNum][randy]);
}
function subscribe()
{
	var email = document.getElementById("email_addr").value;
	if (!isValidEmail(email))
	{ 
		document.getElementById('subscribe_confirm').innerHTML="<span style='color:red;'>Please enter a valid email address.</span>";
	}	
	else 
	{
		var myRequest = new ajaxObject(emailUrl);
		myRequest.callback = function(responseText, responseStatus, responseXML) {
			if (responseStatus==200 && responseText == '101')
			{
				document.getElementById('subscribe_confirm').innerHTML='Added successfully.';
			}
			else 
			{
				document.getElementById('subscribe_confirm').innerHTML='Subscription failure, please notify the webmaster.';
			}
		};
		myRequest.update('addr=' + email);  // Server is contacted here.
	}
}

// Helper Functions

function getRandy(max_val)
{
	return Math.floor(Math.random()*max_val);
}
function isValidEmail(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   return reg.test(email);
}
function randOrd()
{
	return (Math.round(Math.random())-0.5); 
} 
function resetLinkColors(item_type, list_num)
{
	if (item_type == 'org')
	{
		for (var i=0; i<orgs.length; i++)
		{
			document.getElementById(orgs[i]).style.color = defaultLinkColor;
		}
	}
	else 
	{
		var intListNum = parseInt(list_num)-1;
		for (var i=0; i<artists[intListNum].length; i++)
		{
			document.getElementById(artists[intListNum][i]).style.color = defaultLinkColor;
		}
	}
}

// Event Handlers

function handleKeyPress() 
{
	if (event.keyCode==13){
		subscribe();
	}
}
function websiteLink_mouseOver(artist_name)
{
	document.getElementById(artist_name + '_artist_social_link_name').innerHTML = 'website';
}
function socialLink_mouseOver(link_el, artist_name)
{
	document.getElementById(artist_name + '_artist_social_link_name').innerHTML = link_el.alt;
}
function socialLink_mouseOut(link_el, artist_name)
{
	document.getElementById(artist_name +'_artist_social_link_name').innerHTML = '';
}

// AJAX
function ajaxObject(url) {                                           // This is the object constructor
   var that=this;                                                    // A workaround for some javascript idiosyncrocies
   this.updating = false;                                            // Set to true if this object is already working on a request
   this.callback = function () {};                                    // A post-processing call -- a stub you overwrite.

   this.update = function(passData) {                                // Initiates the server call.
      if (that.updating==true) { return false; }                     // Abort if we're already processing a call.
      that.updating=true;                                            // Set the updating flag.
      var AJAX = null;                                               // Initialize the AJAX variable.
      if (window.XMLHttpRequest) {                                   // Are we working with mozilla?
         AJAX=new XMLHttpRequest();                                  //  Yes -- this is mozilla.
      } else {                                                       // Not Mozilla, must be IE
         AJAX=new ActiveXObject("Microsoft.XMLHTTP");                //  Wheee, ActiveX, how do we format c: again?
      }                                                              // End setup Ajax.
      if (AJAX==null) {                                              // If we couldn't initialize Ajax...
         return false;                                               // Return false (WARNING - SAME AS ALREADY PROCESSING!)
      } else {
         AJAX.onreadystatechange = function() {                      // When the browser has the request info..
            if (AJAX.readyState==4) {                                //   see if the complete flag is set.
               that.updating=false;                                  //   Set the updating flag to false so we can do a new request
               that.callback(AJAX.responseText,AJAX.status);         //   Pass respons and status to callback.
               delete AJAX;                                          //   delete the AJAX object since it's done.
            }                                                        // End Ajax readystate check.
         };                                                           // End create post-process fucntion block.
         var timestamp = new Date();                                 // Get a new date (this will make the url unique)
         var uri=urlCall+'?'+passData+'&timestamp='+(timestamp*1);   // Append date to url (so the browser doesn't cache the call)
         AJAX.open("GET", uri, true);                                // Open the url this object was set-up with.
         AJAX.send(null);                                            // Send the request.
         return true;                                                // Everything went a-ok.
      }                                                              // End Ajax setup aok if/else block                 
   }
   
   // This area set up on constructor calls.
   var urlCall = url;                                                // Remember the url associated with this object.
}

// StringBuffer
function StringBuffer() { 
this.buffer = []; 
} 

StringBuffer.prototype.append = function append(string) { 
this.buffer.push(string); 
return this; 
}; 

StringBuffer.prototype.toString = function toString() { 
return this.buffer.join(""); 
}; 

// Nifty Playlist Functions

var NUM_SONGS = 15;
var currentSong = 0;

// Randomize the songs.
var songOrder = new Array(NUM_SONGS);
for (var i=0; i<NUM_SONGS; i++)
{
	songOrder[i] = i;
}
songOrder.sort(randOrd);
songOrder.sort(randOrd);

var songs = new Array(3);
songs[0] 	= new Array(NUM_SONGS);  // Song URLs
songs[1]	= new Array(NUM_SONGS);  // Band Names
songs[2]	= new Array(NUM_SONGS);  // Song Names

function loadPlaylist()
{
        buildSongInfo();
	var plsDiv = document.getElementById('nifty_playlist');
	if (plsDiv)
	{
		var buf = new StringBuffer();
		for (var i=0; i<NUM_SONGS; i++)
		{			
			buf.append("<div id=\"song_");
			buf.append(i);
			buf.append("\" class=\"nifty_playlist_item\">");
			buf.append("<div class=\"nifty_playlist_artist\">");
			buf.append(songs[1][songOrder[i]]);
			buf.append("</div><div class=\"nifty_playlist_song\">");
			buf.append(songs[2][songOrder[i]]);
			buf.append("</div></div>");
		}
		plsDiv.innerHTML = buf.toString();
	}
}
function nextSong()
{	
	if (currentSong < NUM_SONGS - 1)
	{
		currentSong++;	
	}
	else
	{
		currentSong = 0;
		
	}
	playSong(currentSong);
}
function prevSong()
{	
	if (currentSong > 0)
	{
		currentSong--;		
	}
	else
	{
		currentSong = 0;		
	}
	playSong(currentSong);		
}
function playSong(num)
{
	
	niftyplayer('niftyPlayer1').registerEvent('onPlay', 'showCurrentSong(' + num + ')');
	niftyplayer('niftyPlayer1').loadAndPlay(songs[0][songOrder[num]]);
}
function showCurrentSong(num)
{
	for (var i=0; i<NUM_SONGS; i++)
	{
		document.getElementById("song_" + [i]).style.display = "none";
	}
	document.getElementById("song_" + num).style.display = "block";
}
function startPlayer()
{	
	loadPlaylist();
	document.getElementById('nifty_playlist').style.display = "block";
	niftyplayer('niftyPlayer1').registerEvent('onSongOver', 'nextSong()');
	playSong(currentSong);
}

// Song info string manipulation

function buildSongInfo()
{
    var artistAndTitle;
       
    for (var i=0; i<NUM_SONGS; i++)
    {        
        artistAndTitle = songs[0][i].split("_-_");
        artistAndTitle[0] = artistAndTitle[0].substr(6, artistAndTitle[0].length - 1);
        artistAndTitle[1] = artistAndTitle[1].substr(0, artistAndTitle[1].length - 4);  
        songs[1][i] = artistAndTitle[0].replace(/_/g, " ");
        songs[2][i] = artistAndTitle[1].replace(/_/g, " ");                   
    }
}

