//if(window.location.hash.substring(1).length>0){
//	window.location = window.location.pathname + '?' + window.location.hash.substring(1);
//}
/************************/
//start ajax spry
/************************/

// define the function input: url to parse, the div to place returned content in,
// the div to place the loading icon in (optional), and any post data if needed (optional)
//************ IMPORTANT: the url parameter requires the ? at the end of the file name ****************//
function parsePage(url, div, loadingDiv, postdata) {
   // create an object to contain data for being sent along with the request
	var myObj = new Object;
	// store the div id in the object for use in callback 
	myObj.div = div;
	// hide the inner html of the content div
   if(div=="mp3barLoading"){  
      // set the inner html of the content div if it is the mp3barLoading in the first mainList li                 
      Spry.Utils.setInnerHTML(div, 'Loading...');
   }else{
		showLoadingCover(); 
   }                                                              
   // make sure the element exists
	// and put the loading icon into the div, if the div was given
   if(obj=document.getElementById(loadingDiv)){
      // store the loading div id in the object for use in callback                                   
      myObj.loadingDiv = loadingDiv;
      // set the loading image in the div
      Spry.Utils.setInnerHTML(loadingDiv, '<image src="../../images/ajax-loader.gif" border="0">');
   }
   //alert(url);
	// if we do not have post data send request without post data
	if(!postdata){
      // use spry to load the url
      var req = Spry.Utils.loadURL("GET", url+'&ts='+new Date().getTime(), true, MySuccessCallback, { headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" }, errorCallback: MyErrorCallback, userData: myObj });
	} else {  
      // if we do have post data submit it with the request
      var req = Spry.Utils.loadURL("POST", url+'&ts='+new Date().getTime(), true, MySuccessCallback, { postData: postdata, headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" }, errorCallback: MyErrorCallback, userData: myObj });
	}
}
// the spry ajax request callbacks
function MySuccessCallback(req) {
   // if the div is NOT the mp3barLoading div then hide the loading cover
   if(req.userData.div=="mp3barLoading"){}else{
		hideLoadingCover();      
   } 
   // if the loadingdiv is given, empty it on return
   // second param must not be empty/null or spry will call error (i think date:sun june 27 7pm 2010)                                  
	if(req.userData.loadingDiv){ 
	  Spry.Utils.setInnerHTML(req.userData.loadingDiv, '');
	}
   // use spry to set html because it will parse javascript
	Spry.Utils.setInnerHTML(req.userData.div, req.xhRequest.responseText);                  
}
function MyErrorCallback(req) {
  // Throw an alert with the message that was
  // passed to us via the userData.
  alert("ERROR: " + req.xhRequest.responseText);
		hideLoadingCover(); 
}

function showLoadingCover(){
	var mc = document.getElementById('mainContent').offsetHeight;
	var mld = document.getElementById('mainListDiv').offsetHeight;
	if(mc>mld){
		document.getElementById('loadingCover').style.height = mc+'px';
	} else {
		document.getElementById('loadingCover').style.height = mld+'px';
	}
	// show the loading Cover                                 
	Spry.Utils.removeClassName("loadingCover","hide");
}
function hideLoadingCover(){
	Spry.Utils.addClassName("loadingCover","hide");
}

// it will show the loading cover and the message asking "is the user is still listening?" 
function stillListening(){
	document.mp3bar.pausePlay();
	var h = document.getElementById('mp3barWrap').offsetHeight;
	var mc = document.getElementById('mainContent').offsetHeight;
	var mld = document.getElementById('mainListDiv').offsetHeight;
	if(mc>mld){
		document.getElementById('stillListeningWrap').style.height = mc+'px';
	} else {
		document.getElementById('stillListeningWrap').style.height = mld+'px';
	}
	// show the loading Cover                                 
	Spry.Utils.removeClassName("stillListeningWrap","hide");
}
/***********************************/
// end ajax/spry
/***********************************/
 
/***********************************/
// start flash as3/javascript
/***********************************/

// flash calls this function whenever a change takes place. the event is the name of what happened.
// possible events are:LoadSourceAndPlay, Play, Pause, Ready, SoundLocRequest, SoundComplete, toEnd,
// toBegin, loadSource, setVolume
function flashEvent(theEvent, id, fileName, vol, playFrom, playFromKey, playFromPlKey){
	var div = 'mp3barGif';
//alert('flashEvent='+theEvent+'&id='+id+'&fileName='+fileName+'&volume='+vol+'&playFrom='+playFrom+'&playFromKey='+playFromKey+'&playFromPlKey='+playFromPlKey);
	if(playFrom=='Queue' && theEvent=='LoadSourceAndPlay'){
		div = 'Library_Loading_'+id;
	}
	//alert(theEvent);
   // parse/tell php what is going on, the callback goes into script/parse.php and executes the javascript
   // that flash will respond to
   parsePage('script/parse.php?', 'mp3barLoading', div, 'flashEvent='+theEvent+'&id='+id+'&fileName='+fileName+'&volume='+vol+'&playFrom='+playFrom+'&playFromKey='+playFromKey+'&playFromPlKey='+playFromPlKey);                          
}
  
/***********************************/
// end flash as3/javascript
/***********************************/ 

/***********************************/
// start url listener
/***********************************/
// recursive hash string checker
// checks the hash string for changes and spry/ajax parses the page based on the changes
// made oldHash global due to probles with the single quote/apostrophy in the get http url search name value pair
var oldHash='';
function getURL(){
	var locHref = window.location.href
	var i = locHref.indexOf("#");
	//if there is a hash or of i>=0
   if(i>=0){
   		// capture the new hash string before javascript decodes it
		var newHash = locHref.slice(i);
   } else {
	   	// assign nothing to the hash
   		var newHash = '';
   }
   // capture the new hash string after javascript decodes it
   // if the hashes do not match                                  
   if(oldHash==newHash){}else{
      // spry gets the new hash params as an object                                       
      var hashParams = Spry.Utils.getURLHashParamsAsObject(newHash);
      // spry urlComponentToObject accepts an http name/value pairs but requires that
      // the hash mark be taken off the beginning of the old string
      // in this way you get the old params for comparison/evaluation 
      var params = Spry.Utils.urlComponentToObject(oldHash.substring(1));
      // params.d is the key value for the Stations or Playlists array
      // if the old params.d exists remove the selected style
      if(params.d){
         Spry.Utils.removeClassName(params.v+params.d,'mainListDivLiSelected');
      } else {
         // else javascipt does not tell the diff between zero, empty or null or...whatever
         // so we must make sure the first item with zero key is not selected                      
         Spry.Utils.removeClassName(params.v+'0','mainListDivLiSelected');                                                         
      } 
      //*********************************************************************** 
      // params.v is the list being viewed like NowPlaying or Library
      // params.v is also half of what is being viewed when it is a dynamic list (eg. Station or Playlists)
      // the list name combined with the key number are the id for the document element
      // e.g. Station0, Station1, Playlists3, Playlists4, etc.
      //*********************************************************************** 
      // some of the break; statments in the following switch are marked out
      // so it will "fall back" on the next executable code segment
      // the idea may leed to confusion and came from the following web page
      // http://www.webdeveloper.com/forum/showthread.php?t=191879 
      switch (hashParams.v){
         case "NowPlaying":   
         //break;              
         case "Stations":
            // for these first 2 case statments
            // we only care if the params.v (what we are viewing) has changed
            if(hashParams.v==params.v){}else{
               // remove the old selected style                       
               Spry.Utils.removeClassName(params.v+'0','mainListDivLiSelected');
               Spry.Utils.removeClassName(params.v,'mainListDivLiSelected');
               // apply the new selected style
               Spry.Utils.addClassName(hashParams.v,'mainListDivLiSelected');
               // parse the page selected for viewing with all the parameters from hash
               // included in the get variables for php. remember earlier we pulled the hash off the string?
               // now we just pop it on the end of the url  
               parsePage(hashParams.v+'.php?'+newHash.substring(1), 'mainContent',hashParams.v+'Loading');
            }
         break;              
         case "Library":                                                
            // remove the old selected style                       
            Spry.Utils.removeClassName(params.v+'0','mainListDivLiSelected');
            Spry.Utils.removeClassName(params.v,'mainListDivLiSelected');
            // apply the new selected style
            Spry.Utils.addClassName(hashParams.v,'mainListDivLiSelected');
            // parse the page selected for viewing with all the parameters from hash
            // included in the get variables for php. remember earlier we pulled the hash off the string?
            // now we just pop it on the end of the url
            parsePage(hashParams.v+'.php?'+newHash.substring(1), 'mainContent',hashParams.v+'Loading'); 
         break;
         // for Playlists and Stations the page being parsed will need the key value for the station or playlist
         // therefor these two get unique execution code 
         case "Playlists": 
            //alert("Playlists")
         //break;
         case "Station":
            // playlists and Stations get much the same treatment
            // remove the old selected style 
            Spry.Utils.removeClassName(params.v,'mainListDivLiSelected');
            // apply the new selected style to the station or playlist        
            Spry.Utils.addClassName(hashParams.v+hashParams.d,'mainListDivLiSelected');
            // parse the corrisponding page and send the hash parameters as the get values.
            parsePage(hashParams.v+'.php?'+newHash.substring(1), 'mainContent', hashParams.v+'Loading');
         break;
		 case "upload":
		 //break;
		 case "w3c/HowTo":
            // if nothing is selected just remove the old selected style   
            Spry.Utils.removeClassName(params.v,'mainListDivLiSelected');
            parsePage(hashParams.v+'.php?'+newHash.substring(1), 'mainContent', 'mp3barGif');
		 break;
         default :
            // if nothing is selected just remove the old selected style   
            Spry.Utils.removeClassName(params.v,'mainListDivLiSelected');
            parsePage('Stations.php?', 'mainContent', 'mp3barGif');
		break;        
      }
   }
   oldHash = newHash;
   // call the function in a few moments with the hash parameters for next time
   // LJW 12/23/2010 1:30ish: previously the hash was sent in this timeout but now is global
   setTimeout("getURL();",300);
}

/***********************************/
// end url listener
/***********************************/ 
 
/***********************************/
// NowPlaying_Indicator
// & play from indicator
/***********************************/
// the NowPlaying_Indicator needs to be set from multiple files, a function was made to handle doing so
// setNowPlaying input: the id to be selected and the old id for deselecting
function setNowPlaying_Indicator(TheId, oldId){                                    
   // see if we have the right div
   if(obj = document.getElementById('NowPlaying_Indicator_'+oldId)){
      // this line removes the NowPlaying indicator
      obj.innerHTML = '<image src="../../images/triangleIndicatorEmpty.gif" border="0" width="11px" height="11px">';
   }
   // see if we have the right div
   if(!TheId){}else{if(obj = document.getElementById('NowPlaying_Indicator_'+TheId)){
      // this line sets the NowPlaying indicator
      obj.innerHTML = '<image src="../../images/triangleIndicator.gif" border="0" width="11px" height="11px">';
   }}
}
// the play from indicator can be selected much the same way                      
function setPlayFrom_Indicator(PlayFrom, PlayFromKey, oldPlayFrom, oldPlayFromKey){
   // see if we have the right div
   if(obj = document.getElementById(oldPlayFrom+'_Indicator_'+oldPlayFromKey)){ 
      // this line removes the PlayFrom_Indicator indicator
      obj.innerHTML = '<image src="../../images/triangleIndicatorEmpty.gif" border="0" width="11px" height="11px">';
   }
   // see if we have the right div
   if(obj = document.getElementById(PlayFrom+'_Indicator_'+PlayFromKey)){
      // this line sets the playFrom indicator 
      obj.innerHTML = '<image src="../../images/triangleIndicator.gif" border="0" width="11px" height="11px">';
   }
}
/***********************************/
// End NowPlaying_Indicator
/***********************************/ 

/***********************************/
// functions for the editing page
/***********************************/

// the editing functions must be defined in the main index page "global" (not sure why)
// Callback function that will update the response_form1 div with the response that comes from the server 
// this function fires after the edit.php page form has been submitted
function updateResponseDiv(req){ 
      hideLoadingCover(); 
	Spry.Utils.setInnerHTML('response_form1', req.xhRequest.responseText);
	//document.getElementById('form1').reset();
}                                                                                                    
// this function fires when a form in the edit.php page is submitted
function validateonsubmit(form){
   // if the form has been validated
	if (Spry.Widget.Form.validate(form) == true){
		// submit the form and call updateResponseDiv when complete
		Spry.Utils.submitForm(form, updateResponseDiv);
		// set the loading gif
      Spry.Utils.setInnerHTML('response_form1', '<image src="../../images/ajax-loader.gif" border="0">');
		showLoadingCover();
		return true;
	} else {
		// tell html not to submit the form
		return false;
	}
} 

//this populates the genre ordered list
var ordLi = new Array();
function populateLi(){
	var html = '';
	for(i=0;i<ordLi.length;i++){
		html += '<li style="position:relative;">'+ordLi[i]+' <a href="javascript:void(0);" onclick="removeGenre('+i+');" style="position:absolute; right:25px;"><strong>X</strong></a></li>'; 
	}
	document.getElementById("ordLi").innerHTML = html;
	// fill the field with the genres in string form
	document.getElementById("genreField").value = ordLi.join('|');
}
// add the new genre and refresh the list
function addGenre(val){
	notInList = true;
	for(i=0;i<ordLi.length;i++){
		if(ordLi[i] == val){
			notInList = false;
		} 
	}
	if(notInList){
		ordLi[ordLi.length] = val;
		populateLi();
	} else {
		document.getElementById("response_form1").innerHTML = val+' is already in the list';
	}
}
function removeGenre(key){
	ordLi.splice(key,1);
		populateLi();
}
/***********************************/
// end functions for the editing page
/***********************************/
