/**----------------------------audio.js JSON schema--------------------------------------
audio = audioBaseUrl, coverArtbaseUrl, audioEntries

audioEntries:
	id
	speaker
	title
	event
	album
	year
	fileUrl
	isFileURLAbsolute
	coverArt
	coverOrientation - 0=landscape, 1=portrait, 2=square
	length
	video

-------------------------library.js JSON schema----------------------------------------
library:
	rootId - string - id of the root panel
	panelArray - array of all panels

panel:
	id: string
	title: string
	leftButton: reference
	rightButton: reference
	[referenceArray | audioQuery]

referenceArray: array of references
audioQuery: someAudioField [startsWith | equals] someValue (free standing wild cards only)

reference:
	label - string
	url - string(valid url)
	type - panel | audio | html
**/
/**
 * TorahWeb Audui UI
 * @author TorahWeb
 * @copyright The TorahWeb Foundation, 2007. All Rights Reserved.
 * email Comments / Bugs to: torahweb at torahweb dot org
 */

/*
 * need to have old html page as initial page to gracefully degrade if javsscript is disabled using <noscript/>
 * 
 * need to add "Loading audio library..." wait thingie as the whole body until we are ready and loaded
 */
var TW_AUI = new Object();
TW_AUI.DEBUG = false;
TW_AUI.slideSpeed = 20;
TW_AUI.slideInterval = 1; //cannot be zero in IE 6
TW_AUI.libraryUrl = "/audio/library.js";
TW_AUI.library = null;
TW_AUI.audioUrl =  "/audio/audio.js";
TW_AUI.audio = null;
TW_AUI.panelDivs = new Object();
TW_AUI.panels = new Object();
TW_AUI.titles = new Object();
TW_AUI.queryCache = new Object();
TW_AUI.entriesById = new Object();
TW_AUI.audioTxtCache = new Object();
TW_AUI.videoTxtCache = new Object();
TW_AUI.audioDivId = "TW_AUI_playAudio";
TW_AUI.videoIframeId = "videoIframe";
TW_AUI.allVideo = "allVideo";
TW_AUI.rootPageId = "index";
TW_AUI.rootPageTitle = "Yom Iyun Audio";
TW_AUI.mp3Url = "";
TW_AUI.titleFrame = null;
TW_AUI.downloadBaseUrl = "/cgi-bin/download.pl?name=";
TW_AUI.panelName = "panel";
TW_AUI.audioName = "audio";

/**
 * download the library.json file and create the inital page
 */
TW_AUI.init = function(panelID, audioID)
{
	TW_AUI.displayLoading();
	TW_AUI.loadLibrary();
	var root = null;
	//build panels and find the root panel
	for(var i=0; i < TW_AUI.library.panelArray.length; i++)
	{
		var pan = TW_AUI.library.panelArray[i];
		TW_AUI.buildPanel(pan, true);
		if(pan.id == TW_AUI.library.rootId)
		{
			root = pan;
		}
	}
	TW_AUI.removeLoading();
	//init title bar frame
	TW_AUI.titleFrame = parent.frames["titleBar"];
	TW_AUI.titleFrame.init();

	//create title bar
	TW_AUI.setTitlebar(root);
	
	//create initial choice panel
	
	//if no query, show root
	if(!panelID && !audioID)
	{
		var rootDiv = TW_AUI.panelDivs[root.id];
	    rootDiv.style.left = "0";
	    rootDiv.style.display = "block";		
		//pre-fetch swf file to speed up first audio page
		TW_AUI.asynchXHR("mp3player.swf");
	}
	//show requested audio page
	else if(audioID)
	{
		TW_AUI.playAudio(null, audioID);
	}
	else if(panelID)
	{
		var panelDiv = TW_AUI.panelDivs[panelID];
	    panelDiv.style.left = "0";
	    panelDiv.style.display = "block";		
		//set the title bar
		TW_AUI.setTitlebar(TW_AUI.panels[panelID]);		
		//pre-fetch swf file to speed up first audio page
		TW_AUI.asynchXHR("mp3player.swf");
	}	
}
/**
 * 
 */
TW_AUI.displayLoading = function()
{
	var newDiv = document.createElement('div');
	newDiv.align = "center";
	newDiv.style.width = "100%";
	newDiv.id = "loading";
	newDiv.innerHTML = '<img src="../images/loading.gif"><BR><font face="Arial, sans-serif">Loading audio library...</font>';
	document.body.appendChild(newDiv);
}
/**
 * 
 */
TW_AUI.removeLoading = function()
{	
	document.body.removeChild(document.getElementById("loading"));
}

/**
 * load json data
 */
TW_AUI.loadLibrary = function()
{
	/*
	//get audio.json
	var metaLib = document.getElementById("TW_AUI.audio");
	if(TW_AUI.DEBUG)
	{
		alert("metaLib = " + metaLib);
	}
	TW_AUI.audioUrl = metaLib.getAttribute("audioUrl");
	if(TW_AUI.DEBUG)
	{
		alert("TW_AUI.audioUrl = " + TW_AUI.audioUrl);
	}
	var audiotxt = TW_AUI.synchXHR(TW_AUI.audioUrl);
	TW_AUI.audio = eval("audio=" + audiotxt).audio;	
	
	//get library.json
	var metaLib = document.getElementById("TW_AUI.library");
	TW_AUI.libraryUrl = metaLib.getAttribute("libraryUrl");
	var libtxt = TW_AUI.synchXHR(TW_AUI.libraryUrl);
	TW_AUI.library = eval("lib=" + libtxt).library;	
	*/
	var audiotxt = TW_AUI.synchXHR(TW_AUI.audioUrl);
	var obj = eval('(' + audiotxt + ')');
	TW_AUI.audio = obj.audio;	
	
	var libtxt = TW_AUI.synchXHR(TW_AUI.libraryUrl);
	var obj = eval('(' + libtxt + ')');
	TW_AUI.library = obj.library;	
	
	//TW_AUI.library = audio.audio;
	//TW_AUI.library = library.library;	
}
/**
 * sets the title bar
 * @param {Object} panel
 */
TW_AUI.setTitlebar = function(panel)
{
	var titleText = "";
	if(TW_AUI.titles[panel.id])
	{
		titleText = TW_AUI.titles[panel.id];
	}
	else
	{
		//start table
		titleText = '<table width="100%" cellspacing="0" cellpadding="0">\n<tr width="100%">\n';
		//left button
		titleText += TW_AUI.buildButton(panel, "leftButton");	
		//main title
		titleText += '<td id="title" class="toolbar">' + panel.title + '</td>\n';
		//right button
		titleText += TW_AUI.buildButton(panel, "rightButton");	
		//end table
		titleText += '</tr>\n</table>\n';
		TW_AUI.titles[panel.id] = titleText;
	}
	/*
	var divId = "titleBar";
	var titleDiv = document.getElementById("titleBar");
	titleDiv.innerHTML = titleText;	
	*/
	TW_AUI.titleFrame.setTitleBar(titleText);
}
/**
 * builds one of the title buttons
 * @param {Object} panel
 * @param {Object} btnId
 */
TW_AUI.buildButton = function(panel, btnId)
{
	var txt = "";
	txt += '<td id="' + btnId + '" class="toolbar button"';
	//build button
	var btn = panel[btnId];
	if(btn)
	{
		//build button to another panel
		if(btn.type == "panel")
		{
			txt += 'onclick="';
			if(panel.id == TW_AUI.allVideo)
			{
				txt += 'TW_AUI.removeVideo();';
			}
			txt += 'TW_AUI.switchPages(\'' + panel.id + '\', \'' + btn.url + '\', true);">';
			txt += btn.label + "</td>\n";
		}
		//TODO: type == "audio" and type == "html"
	}
	else
	{
		txt += '<td width="10%" id="' + btnId + '" class="toolbar button">&nbsp</td>\n';
	}
	return txt;
}

/**
 * remove video div
 */
TW_AUI.removeVideo = function()
{
	if(TW_AUI.panelDivs[TW_AUI.audioDivId])
	{
		TW_AUI.panelDivs[TW_AUI.audioDivId].innerHTML = "no video";
		TW_AUI.panelDivs[TW_AUI.audioDivId].style.left = "100%";    		
	}
}

/**
 * build given panel's HTML
 * @param {Object} panel
 * @param {Object} overwrite
 */
TW_AUI.buildPanel = function(panel, overwrite)
{
	//if it already exists and we should not overwrite, return
	if(TW_AUI.panelDivs[panel.id] && !overwrite)
	{
		return;
	}

	//build up HTML of the panel
	var txt = "";
	//txt += '<div width="100%" id="choices" class="choicePanel">\n \
	txt += '<table width="100%" cellspacing="0" cellpadding="0">\n';
	if(panel.referenceArray)
	{
		for(var i=0; i < panel.referenceArray.length; i++)
		{
			var ref = panel.referenceArray[i];
			if(TW_AUI.DEBUG)
			{
				alert(panel.id + ".reference = " +ref );
			}
			var choiceID = panel.id + "." + ref.url;
			txt += '<tr width="100%">\n<td width="100%">\n<div class="choice" width="100%"';
			txt += 'id="' +  choiceID + '" onmouseover="TW_AUI.setHighlight(\'' + choiceID + '\');" onmouseout="TW_AUI.unsetHighlight(\'' + choiceID + '\');" ';
			if(ref.type == "panel")
			{
				txt += 'onclick="TW_AUI.switchPages(\'' + panel.id + '\', \'' + ref.url + '\', false);"';
				txt += '>' + ref.label;			
			}
			else if(ref.type == "audio")
			{
				//get the audio entry
				var audioId = ref.url;
				var entry = TW_AUI.findEntryById(audioId);				
				//build the title from the audio entry
				var title = entry.title;
				var sname = TW_AUI.getShortName(entry);
				if(sname)
				{
					title += " (" + TW_AUI.getShortName(entry)+ ")";					
				}
				//create the rest of this HTML				
				txt += 'onclick="TW_AUI.playAudio(\'' + panel.id + '\', \'' + audioId + '\');">' + title;			
			}
			//TODO: build link directly to an audio!!
			//TODO: build link to html
			 
			txt += '</div>\n</td>\n</tr>';
		}		
	}
	else if(panel.audioQuery)
	{
		txt += TW_AUI.createChoicesFromAudioQuery(panel);
	}		
	txt += '</table>\n'; //</div>';
	
	//create div
	var newDiv = document.createElement('div');
	newDiv.style.width="100%";
	newDiv.id = panel.id;
	newDiv.setAttribute("class", "choicePanel");
	newDiv.setAttribute("className", "choicePanel");
	newDiv.innerHTML = txt;
	document.body.appendChild(newDiv);
	
	//hold onto it
	TW_AUI.panels[panel.id] = panel;
	TW_AUI.panelDivs[panel.id] = newDiv;
}
/**
 * 
 * @param {Object} panel
 */
TW_AUI.createChoicesFromAudioQuery = function(panel)
{
	if(!panel.audioQuery)
	{
		return;		
	}
	//parse the query
	var results = panel.audioQuery.split(" ");
	var field = results[0];
	var op = results[1];
	var val = results[2];
	//get the query results
	var queryResult = TW_AUI.queryCache[panel.audioQuery];
	if(!queryResult)
	{
		if(op == "startsWith")
		{
			queryResult = TW_AUI.doStartsWithQuery(field, val);
		}
		else if(op == "equals")
		{
			queryResult = TW_AUI.doEqualsQuery(field, val);
		}		
		TW_AUI.queryCache[panel.audioQuery] = queryResult;
	}
	//build the html
	var txt = "";
	var showName = TW_AUI.showSpeaker(panel);

	for(var i=0; i < queryResult.length; i++)
	{
		var entry = queryResult[i];
		if(TW_AUI.DEBUG)
		{
			alert(panel.id + ".reference = " +entry );
		}
		var choiceID = panel.id + "." + entry.id;
		txt += '<tr width="100%">\n<td width="100%">\n<div class="choice" width="100%"';
		txt += 'id="' +  choiceID + '" onmouseover="TW_AUI.setHighlight(\'' + choiceID + '\');" onmouseout="TW_AUI.unsetHighlight(\'' + choiceID + '\');" ';
		//speical case for the "all videos" panel
		if(panel.id == TW_AUI.allVideo)
		{
			//txt +=  'onclick="window.open(\'' + TW_AUI.audio.videoBaseUrl + entry.video + '\');"';			
			txt += 'onclick="TW_AUI.playVideo(\'' + entry.id + '\', \''+ TW_AUI.allVideo + '\');"';
		}
		else
		{
			txt += 'onclick="TW_AUI.playAudio(\'' + panel.id + '\', \'' + entry.id + '\');"';
		}
		txt += '>' + entry.title;
		if(showName)
		{
			var sname = TW_AUI.getShortName(entry);
			if(sname)
			{
				txt += " (" + sname + ")";				
			}
		}
		txt += '</div>\n</td>\n</tr>';
	}
	return txt;
}
/**
 * determine if for given panel speaker names should be shown
 * @param {Object} panel
 */
TW_AUI.showSpeaker = function(panel)
{
	if(panel.id=="rneu"|| panel.id=="rros"|| panel.id=="rsch"|| panel.id=="rsac"|| panel.id=="rsob"|| panel.id=="rtwe"|| panel.id=="dtwe"|| panel.id=="rwil" || panel.id=="ryud")
	{
		return false;
	}
	return true;
}
/**
 * get short version of speaker name
 * @param {Object} entry
 */
TW_AUI.getShortName = function(entry)
{
	var val = null;
	if(TW_AUI.startsWith(entry.id, "rneu"))
	{
		val = "R' Neuburger";
	}
	else if(TW_AUI.startsWith(entry.id, "rros"))
	{
		val = "R' Rosensweig";
	}
	else if(TW_AUI.startsWith(entry.id, "rsch"))
	{
		val = "R' Schachter";
	}
	else if(TW_AUI.startsWith(entry.id, "rsac"))
	{
		val = "R' Sacks";
	}
	else if(TW_AUI.startsWith(entry.id, "rsob"))
	{
		val = "R' Sobolofsky";
	}
	else if(TW_AUI.startsWith(entry.id, "rtwe"))
	{
		val = "R' Twersky";
	}
	else if(TW_AUI.startsWith(entry.id, "dtwe"))
	{
		val = "R' Dr. Twerski";
	}
	else if(TW_AUI.startsWith(entry.id, "rwil"))
	{
		val = "R' Willig";
	}
	else if(TW_AUI.startsWith(entry.id, "ryud"))
	{
		val = "R' Yudin";
	}
	else if(TW_AUI.startsWith(entry.id, "mros"))
	{
		val = "P. Rosenthal";
	}
	return val;
}
/**
 * get long version of speaker name
 * @param {Object} entry
 */
TW_AUI.getLongName = function(entry)
{
	var val = " ";
	if(TW_AUI.startsWith(entry.id, "rneu"))
	{
		val = "Rav Yaakov Neuburger";
	}
	else if(TW_AUI.startsWith(entry.id, "rros"))
	{
		val = "Rav Michael Rosensweig";
	}
	else if(TW_AUI.startsWith(entry.id, "rsch"))
	{
		val = "Rav Hershel Schachter";
	}
	else if(TW_AUI.startsWith(entry.id, "rsac"))
	{
		val = "Rav Yonason Sacks";
	}
	else if(TW_AUI.startsWith(entry.id, "rsob"))
	{
		val = "Rav Zvi Sobolofsky";
	}
	else if(TW_AUI.startsWith(entry.id, "rtwe"))
	{
		val = "Rav Mayer Twersky";
	}
	else if(TW_AUI.startsWith(entry.id, "dtwe"))
	{
		val = "Rav Dr. Abraham J.Twerski";
	}
	else if(TW_AUI.startsWith(entry.id, "rwil"))
	{
		val = "Rav Mordechai Willig";
	}
	else if(TW_AUI.startsWith(entry.id, "ryud"))
	{
		val = "Rav Benjamin Yudin";
	}
	else if(TW_AUI.startsWith(entry.id, "mros"))
	{
		val = "Mr. Philip Rosenthal";
	}
	return val;
}

/**
 * 
 */
TW_AUI.doEqualsQuery = function(field, val)
{
	var entries = TW_AUI.audio.audioEntries;
	var matches = new Array();
	if(!entries)
	{
		return matches;
	}
	for(var i=0; i < entries.length; i++)
	{
		//if the field exists in this entry...
		var efield = entries[i][field];
		if(efield)
		{
			//and matches the query value...
			if( (val == "*") || (efield == val) )
			{
				matches.push(entries[i]);
			}			
		}
	}
	return matches;
}
/**
 * 
 */
TW_AUI.doStartsWithQuery = function(field, val)
{
	var entries = TW_AUI.audio.audioEntries;
	var matches = new Array();
	if(!entries)
	{
		return matches;
	}
	for(var i=0; i < entries.length; i++)
	{
		//if the field exists in this entry...
		var efield = entries[i][field];
		if(efield)
		{
			//if it can start with anything, done
			if(val == "*")
			{
				matches.push(entries[i]);				
			}
			else if(TW_AUI.startsWith(efield,val))
			{
				matches.push(entries[i]);
			}
		}
	}
	return matches;
}
/**
 * see if field starts with val
 * @param {Object} field
 * @param {Object} val
 */
TW_AUI.startsWith = function(field, val)
{
	//if it is at least as long as the value in the query....
	if (field.length >= val.length) 
	{
		//and it actaulyl starts with that value...
		var start = field.slice(0, val.length);
		if (start == val) 
		{
			return true;
		}
	}
	return false;	
}
/**
 * find an audio entry with given id
 * @param {Object} id
 */
TW_AUI.findEntryById = function(id)
{
	if(TW_AUI.entriesById[id])
	{
		return TW_AUI.entriesById[id];
	}
	var entries = TW_AUI.audio.audioEntries;
	if(!entries)
	{
		return;
	}
	for(var i=0; i < entries.length; i++)
	{
		if(entries[i].id == id)
		{
			//cache it
		 	TW_AUI.entriesById[id] = entries[i];
			return entries[i];
		}
	}
}
/**
 * switches pages and then stops the audio
 * @param {Object} toID
 */
TW_AUI.stopAudio = function (toID)
{
	//switch pages
	TW_AUI.switchPages(TW_AUI.audioDivId, toID, true);
	//kill off audio
	TW_AUI.panelDivs[TW_AUI.audioDivId].innerHTML = "No Audio";
}
/**
 * 
 * @param {Object} fromId
 * @param {Object} audioId
 * @param {boolean} nonTitle - true if should not change title bar
 */
TW_AUI.playAudio = function(fromId, audioId, noTitle)
{
	//when a link to an audio panel is clicked, set the innerHTML of the singelton
	//audio div to the html of this audio file and then show the panel

	var entry = TW_AUI.findEntryById(audioId);	 
	var txt = TW_AUI.getAudioHTML(entry, fromId);
	var audioDiv = TW_AUI.panelDivs[TW_AUI.audioDivId];
	if(!audioDiv)
	{
		//create div
		audioDiv = document.createElement('div');
		audioDiv.style.width="100%";
		audioDiv.id = TW_AUI.audioDivId;
		audioDiv.setAttribute("class", "audioPanel");
		audioDiv.setAttribute("className", "audioPanel");
		document.body.appendChild(audioDiv);	
		//hold onto it
		TW_AUI.panelDivs[TW_AUI.audioDivId] = audioDiv;	 	
	}
	//add audio HTML
	audioDiv.innerHTML = txt;	
	//add audio mp3
	var flashvars = "%3Cmp3player%20version=%221%22%3E%3Cmusic%20url=%22" + TW_AUI.mp3Url + "%22%20urlencoded=%22false%22%20volume=%22100%22%20loop=%22false%22%20usecache=%22true%22%20buffer=%224%22%20autoplay=%22true%22%20/%3E%3Clayout%20id=%22custom%22%3E%3Citem%20id=%22playbar%22%20x=%2210%22%20y=%2210%22%20/%3E%3Citem%20id=%22playbutton%22%20x=%2210%22%20y=%2235%22%20/%3E%3Citem%20id=%22stopbutton%22%20x=%2260%22%20y=%2235%22%20/%3E%3Citem%20id=%22volumecontrol%22%20x=%22180%22%20y=%2238%22%20/%3E%3C/layout%3E%3Cstyles%3E%3CBackground%20backgroundColor=%22#CECED5%22%20useBevel=%22true%22%20bevelAlpha=%2270%22%20transparent=%22true%22%20/%3E%3CButton%20themeColor=%22#7998DF%22%20useCustom=%22false%22%20customPlayPauseURL=%22%22%20customStopURL=%22%22%20/%3E%3CControlIcons%20backgroundColor=%22#6F7777%22%20/%3E%3CLoadBar%20backgroundColor=%22#FFFFFF%22%20borderColor=%22#C4CCCC%22%20fillColor=%22#7998DF%22%20/%3E%3CPlayBar%20backgroundColor=%22#F7F7F7%22%20outerBorderColor=%22#919999%22%20innerBorderColor=%22#C4CCCC%22%20fillColor=%22#7998DF%22%20fontSize=%228%22%20color=%22#000000%22%20streamingText=%22STREAMING%22%20pausedText=%22PAUSED%22%20width=%22270%22%20/%3E%3CSliderThumbs%20backgroundColorOff=%22#6F7777%22%20backgroundColorOn=%22#7998DF%22%20/%3E%3CUIBorder%20borderColor=%22#666666%22%20borderWidth=%220%22%20/%3E%3CVolumeControl%20themeColorOff=%22#6F7777%22%20themeColorOn=%22#7998DF%22%20/%3E%3C/styles%3E%3C/mp3player%3E";
	var so = new SWFObject("mp3player.swf", "twaudio", "290", "66", "7", "#CECED5", "high");
	so.addParam("wmode", "transparent");
	so.addParam("play", "true");
	so.addVariable("config", flashvars);
	so.addVariable("bgcolor", "#CECED5");
	so.write("audioSpan");	
	//show it
	var fromPage = TW_AUI.panelDivs[fromId];
	//try getting it directly....
	if(!fromPage)
	{
		fromPage = document.getElementById(fromId);	
	}
	//...if not there, assume we are accessign this audio directly form a different HTML page
	if(!fromPage)
	{
	    audioDiv.style.left = "0";
	    audioDiv.style.display = "block";		
	}
	else
	{
		TW_AUI.slidePages(fromPage, audioDiv, false);	
	}
	if(!noTitle)
	{
		//set the title bar - left button is stop audio and back to previous panel, right button is audio home	 
		TW_AUI.setAudioTitlebar(fromId);				
	}
	
	//allow user to bookmark the audio
	TW_AUI.setHash(TW_AUI.audioName, audioId);
	
	//add reflection
	TW_AUI.addReflection(entry);
	//setTimeout(function(){Reflection.add(img, options);}, 150);

}
/**
 * 
 * @param {Object} fromId
 * @param {Object} audioId
 */
TW_AUI.playVideo = function(audioId, fromId)
{
	var entry = TW_AUI.findEntryById(audioId);	 
	var txt = TW_AUI.getVideoHTML(entry, fromId);
	var videoDiv = TW_AUI.panelDivs[TW_AUI.audioDivId];
	if(!videoDiv)
	{
		//create div
		videoDiv = document.createElement('div');
		videoDiv.style.width="100%";
		videoDiv.id = TW_AUI.audioDivId;
		videoDiv.setAttribute("class", "audioPanel");
		videoDiv.setAttribute("className", "audioPanel");
		document.body.appendChild(videoDiv);	
		//hold onto it
		TW_AUI.panelDivs[TW_AUI.audioDivId] = videoDiv;
	}
	//add video HTML
	videoDiv.innerHTML = txt;	
//    videoDiv.style.left = "0";
//    videoDiv.style.display = "block";		

	//show it
	var fromPage = TW_AUI.panelDivs[fromId];
	//try getting it directly....
	if(!fromPage)
	{
		fromPage = document.getElementById(fromId);	
	}
	//...if not there, assume we are accessign this video directly form a different HTML page
	if(!fromPage)
	{
	    videoDiv.style.left = "0";
	    videoDiv.style.display = "block";		
	}
	else
	{
		TW_AUI.slidePages(fromPage, videoDiv, false);	
	}
}
/**
 * add reflection to the cover art
 * @param {Object} entry
 */
TW_AUI.addReflection = function(entry)
{
	//figure out the height, w, and h of the image
	var rheight;
	var w;
	var h;
	if(entry.coverOrientation == 0)
	{
		rheight = 1/3;
		w = 256;
		h = 199;
	}
	else if(entry.coverOrientation == 1)
	{
		rheight = 1/4;
		w = 200;
		h = 259;
	}
	else if(entry.coverOrientation == 2)
	{
		rheight = 1/4;
		w = 252;
		h = 258;
	}
	//get the image from the DOM and prepare options
	var img = document.getElementById("audioImg");		
	var options = new Object();
	options.height = rheight;
	
	//need to make a new image in case the h & w is set explicitly in the HTML
	//var img2 = new Image();
	//img2.src = img.src;
	//limit how many times the reflection will be atempted
	var attemptLimit = 200;
	var attempts = 0;
	//var msg = "";

    var timer = setInterval(reflect, 125);
    
    function reflect()
	{
		//msg += "img2.height = " +  img2.height  + "img2.width = " +img2.width + "\n";
		attempts++;
		// && img2.height == h && img2.width == w
		if(img.complete)
		{
			Reflection.add(img, options);
            clearInterval(timer);
			//var msg = "success in " + attempts + " attempts";
			//alert(msg);
			return;
		}
		//give it on last try and give up
        if (attempts >= attemptLimit)
		{
			Reflection.add(img, options);
            clearInterval(timer);
			//var msg = "last try after " + attempts + " attempts";
			//alert(msg);
        }
    }
}
/**
 * sets the title bar when playing audio
 * @param {Object} fromId the id of panel that we got to the audio from
 */
TW_AUI.setAudioTitlebar = function(fromId)
{
	var fromPanel;
	if(fromId)
	{
		fromPanel = TW_AUI.panels[fromId];
	}
	else
	{
		fromPanel = TW_AUI.panels[TW_AUI.rootPageId];		
	}
	var titleText = "";
	//start table
	titleText = '<table width="100%" cellspacing="0" cellpadding="0">\n<tr width="100%">\n';
	//left button
	titleText += '<td id="audio_leftButton" class="toolbar button"';
	titleText += 'onclick="TW_AUI.stopAudio(\'' + fromPanel.id  + '\');">';
	titleText += "Back to " + fromPanel.title + "</td>\n";
	//main title
	titleText += '<td id="title" class="toolbar">Now Playing</td>\n';
	//right button
	titleText += '<td id="audio_rightButton" class="toolbar button"';
	titleText += 'onclick="TW_AUI.stopAudio(\'' + TW_AUI.rootPageId  + '\');">Audio & Video Home</td>\n';
	//end table
	titleText += '</tr>\n</table>\n';

	/*
	var divId = "titleBar";
	var titleDiv = document.getElementById("titleBar");
	titleDiv.innerHTML = titleText;	
	*/
	TW_AUI.titleFrame.setTitleBar(titleText);	
}


/**
 * sets the title bar when playing audio
 * @param {Object} fromId the id of panel that we got to the audio from
 */
TW_AUI.setVideoTitlebar = function(audioId)
{
	var fromPanel;
	if(fromId)
	{
		fromPanel = TW_AUI.panels[fromId];		
	}
	else
	{
		fromPanel = TW_AUI.panels[TW_AUI.rootPageId];		
	}
	var titleText = "";
	//start table
	titleText = '<table width="100%" cellspacing="0" cellpadding="0">\n<tr width="100%">\n';
	//left button
	titleText += '<td id="audio_leftButton" class="toolbar button"';
	titleText += 'onclick="TW_AUI.playAudio(\'' + fromPanel.id  + '\');">';
	titleText += "Back to " + fromPanel.title + "</td>\n";
	//main title
	titleText += '<td id="title" class="toolbar">Now Playing</td>\n';
	//right button
	titleText += '<td id="audio_rightButton" class="toolbar button"';
	titleText += 'onclick="TW_AUI.stopAudio(\'' + TW_AUI.rootPageId  + '\');">Audio & Video Home</td>\n';
	//end table
	titleText += '</tr>\n</table>\n';

	/*
	var divId = "titleBar";
	var titleDiv = document.getElementById("titleBar");
	titleDiv.innerHTML = titleText;	
	*/
	TW_AUI.titleFrame.setTitleBar(titleText);	
}
/**
 * get the HTML code for a given audio entry
 * @param {Object} entry
 */
TW_AUI.getAudioHTML = function(entry, fromId)
{
	if(entry.isFileURLAbsolute == true || TW_AUI.audio.audioBaseUrl == null)
	{
		TW_AUI.mp3Url = entry.fileUrl;	 
	}
	else
	{
		TW_AUI.mp3Url = TW_AUI.audio.audioBaseUrl + entry.fileUrl;
	}
	var downloadUrl = TW_AUI.downloadBaseUrl + entry.fileUrl;
	
	 var txt = "";
	 if(TW_AUI.audioTxtCache[entry.id])
	 {
	 	txt = TW_AUI.audioTxtCache[entry.id];
	 }
	 else
	 {
		txt += '<table width="70%" border="0" cellspacing="0" cellpadding="15" align="center" > \
			  <tr class="audio"> \
		    <td width="16%" valign="center">';
		var rheight;
		var w;
		var h;
		if(entry.coverOrientation == 0)
		{
			rheight = 1/3;
			w = 256;
			h = 199;
		}
		else if(entry.coverOrientation == 1)
		{
			rheight = 1/4;
			w = 200;
			h = 259;
		}
		else if(entry.coverOrientation == 2)
		{
			rheight = 1/4;
			w = 252;
			h = 258;
		}
//		txt += '<img class="reflect rheight' + rheight + '"src="' + TW_AUI.audio.coverArtbaseUrl + entry.coverArt + '" width="' + w + '" height="' + h + '"><BR> \
//			</td><td width="84%" valign="center"><P>';
		txt += '<img id="audioImg" src="' + TW_AUI.audio.coverArtbaseUrl + entry.coverArt + '" width="' + w + '" height="' + h + '"><BR> \
			</td><td width="84%" valign="center"><P>';
		txt += TW_AUI.getLongName(entry) + '<br>' + entry.title + '<br>';
		txt += '<span class="audioInfo">' + entry.event + '<BR>';
		if(entry.info)
		{
			txt += entry.info + '<BR>';
		}
		txt += entry.length + ' minutes</span></P>';
		txt += '<span class="audioInfo"><a href="' + downloadUrl + '">Download Audio</a></span>';
		if(entry.video)
		{
			//txt += '<BR><span class="audioInfo" onclick="TW_AUI.stopAudio(\'' + fromId + '\');"><a href="' + TW_AUI.audio.videoBaseUrl + entry.video + '" target="_new">Watch Video</a></span>';
			//txt += '<BR><span class="audioInfo" onclick="TW_AUI.playVideo(\'' + fromId + '\',\'' + entry.id + '\');"><a href="#">Watch Video</a></span>';
			txt += '<BR><span class="audioInfo"><a href="javascript:TW_AUI.playVideo(\'' + entry.id + '\');">Watch Video</a></span>';
		}
		else
		{
			txt += '<BR><span class="audioInfo">No Video Available</span>';
		}
		txt += '<div id="audioSpan"></div>';
		var flashvars = "%3Cmp3player%20version=%221%22%3E%3Cmusic%20url=%22" + TW_AUI.mp3Url + "%22%20urlencoded=%22false%22%20volume=%22100%22%20loop=%22false%22%20usecache=%22true%22%20buffer=%224%22%20autoplay=%22true%22%20/%3E%3Clayout%20id=%22custom%22%3E%3Citem%20id=%22playbar%22%20x=%2210%22%20y=%2210%22%20/%3E%3Citem%20id=%22playbutton%22%20x=%2210%22%20y=%2235%22%20/%3E%3Citem%20id=%22stopbutton%22%20x=%2260%22%20y=%2235%22%20/%3E%3Citem%20id=%22volumecontrol%22%20x=%22180%22%20y=%2238%22%20/%3E%3C/layout%3E%3Cstyles%3E%3CBackground%20backgroundColor=%22#CECED5%22%20useBevel=%22true%22%20bevelAlpha=%2270%22%20transparent=%22true%22%20/%3E%3CButton%20themeColor=%22#7998DF%22%20useCustom=%22false%22%20customPlayPauseURL=%22%22%20customStopURL=%22%22%20/%3E%3CControlIcons%20backgroundColor=%22#6F7777%22%20/%3E%3CLoadBar%20backgroundColor=%22#FFFFFF%22%20borderColor=%22#C4CCCC%22%20fillColor=%22#7998DF%22%20/%3E%3CPlayBar%20backgroundColor=%22#F7F7F7%22%20outerBorderColor=%22#919999%22%20innerBorderColor=%22#C4CCCC%22%20fillColor=%22#7998DF%22%20fontSize=%228%22%20color=%22#000000%22%20streamingText=%22STREAMING%22%20pausedText=%22PAUSED%22%20width=%22270%22%20/%3E%3CSliderThumbs%20backgroundColorOff=%22#6F7777%22%20backgroundColorOn=%22#7998DF%22%20/%3E%3CUIBorder%20borderColor=%22#666666%22%20borderWidth=%220%22%20/%3E%3CVolumeControl%20themeColorOff=%22#6F7777%22%20themeColorOn=%22#7998DF%22%20/%3E%3C/styles%3E%3C/mp3player%3E";
		txt += '<script type="text/javascript"> \
			var so = new SWFObject("mp3player.swf", "twaudio", "290", "66", "7", "#CECED5", "high"); \
			so.addParam("wmode", "transparent"); \
			so.addParam("play", "true"); \
			so.addVariable("config","' + flashvars + '"); \
			so.addVariable("bgcolor", "#CECED5"); \
			so.write("audioSpan"); \
		</script>';
		txt += '</td></table>';
		//cache it
	 	TW_AUI.audioTxtCache[entry.id] = txt;
	 }
	return txt;	
}
/**
 * get the HTML code for a given audio entry
 * @param {Object} entry
 */
TW_AUI.getVideoHTML = function(entry, fromId)
{
	var video1 =  '<object width="400" height="302"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=';
	var video2 = '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=ffffff&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=';
	var video3 = '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=ffffff&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="302"></embed></object>';
	
	 var txt = "";
	 if(TW_AUI.videoTxtCache[entry.id])
	 {
	 	txt = TW_AUI.videoTxtCache[entry.id];
	 }
	 else
	 {
	 	//txt = '<CENTER><span class="loading audioInfo">Video is Loading...<br></span> \
		//<iframe class="video" id="' + TW_AUI.videoIframeId + '" name="videoFrame" scrolling="no" src="' + TW_AUI.audio.videoBaseUrl + entry.video + '" width="440" height="397" frameborder="0"></iframe> <BR>\
	 	txt = '<CENTER><BR>' + video1 + entry.video + video2 + entry.video + video3 + '<BR>\
		<span class="audioInfo">';
		if(!fromId)
		{
			txt += '<a href="javascript:TW_AUI.playAudio(null, \'' + entry.id + '\', true);">Return to Audio</a>';
		}
		else if(fromId == TW_AUI.allVideo)
		{
			txt += '<a href="javascript:TW_AUI.removeVideo();TW_AUI.switchPages(\'' + TW_AUI.audioDivId + '\', \'' + TW_AUI.allVideo + '\', true);">Return to All Video</a>';
		}
		
		txt += '</span></CENTER>';
	 }
	return txt;	
}
/**
 * switch from one page to another
 * @param {Object} fromID
 * @param {Object} toID
 * @param {Object} backwards
 */
TW_AUI.switchPages = function (fromID, toID, backwards)
{
	var newPage = TW_AUI.panelDivs[toID];
	if(!newPage)
	{
		newPage = document.getElementById(toID);	
	}
	var fromPage = TW_AUI.panelDivs[fromID];
	if(!fromPage)
	{
		fromPage = document.getElementById(fromID);	
	}
	//switch pages
	TW_AUI.slidePages(fromPage, newPage, backwards);
	//set the title bar
	TW_AUI.setTitlebar(TW_AUI.panels[toID]);

	//allow user to bookmark the audio
	TW_AUI.setHash(TW_AUI.panelName, toID);
}
/**
 * find a panel in the library
 * @param {Object} panelID
 */
TW_AUI.findPanel = function(panelID)
{
	for(var i=0; i < TW_AUI.library.panelArray.length; i++)
	{
		var pan = TW_AUI.library.panelArray[i];
		if(pan.id == panelID)
		{
			return pan;
		}
	}
	return null;
}
/**
 * this function derived from Joe Hewitt's iui
 * @param {Object} fromPage
 * @param {Object} toPage
 * @param {Object} backwards
 */
TW_AUI.slidePages = function(fromPage, toPage, backwards)
{
    toPage.style.left = "100%";    
    toPage.style.display = "block";
    scrollTo(0, 1);
    
    var percent = 100;
    slide();
    var timer = setInterval(slide, TW_AUI.slideInterval);
    
    function slide()
	{
        percent -= TW_AUI.slideSpeed;
        if (percent <= 0) 
		{
            percent = 0;
            clearInterval(timer);
			if (fromPage) 
			{
				fromPage.style.display = "none";
			}
            //setTimeout(updatePage, 0, toPage, fromPage);
        }
		if(fromPage)
		{
	        fromPage.style.left = (backwards ? (100 - percent) : (percent - 100)) + "%";			
		}
        toPage.style.left = (backwards ? -percent : percent) + "%";
    }
}
/**
 * highlight a choice row
 * @param {Object} rowId
 */
TW_AUI.setHighlight = function setHighlight(rowId)
{
	var row = document.getElementById(rowId);
	//5882D8 7998DF  7A97E0 
	row.style.background = "#7998DF url(images/listArrowOver.gif) no-repeat right center";
	//row.style.background = "#7288A5 url(images/listArrowOver.gif) no-repeat right center";
	row.style.color = "#FFFFFF";
}
/**
 * remove choice row highlight
 * @param {Object} rowId
 */
TW_AUI.unsetHighlight = function (rowId)
{
	var row = document.getElementById(rowId);
	row.style.background = "#FFFFFF url(images/listArrow.gif) no-repeat right center";
	row.style.color = "#000000";	
}
/**
 * set hash in address bar so users can bookmark
 * @param {Object} name
 * @param {Object} value
 */
TW_AUI.setHash = function(name, value)
{
	parent.parent.window.location.hash = "#" + name + "=" + value;
}



//*********************************************************************************************************
/**
 * make an XHR call
 */
TW_AUI.synchXHR = function(url)
{
	if(TW_AUI.DEBUG)
	{
		alert("TW_AUI.synchXHR: " + url);
	}
	//get a request object
	var request = false;
	request = TW_AUI.createXHR();

	//if we couldn't get the request object, bail
	if(!request)
	{
		alert('Giving up: ( Cannot create an XMLHTTP instance');
		return false;
	}
	//make the request
    request.open('GET', url, false);			
	request.setRequestHeader('Content-Type', 'text/xml');
	request.send(null);
	var responseText = request.responseText;
	if(TW_AUI.DEBUG)
	{
		alert("responseText: " + responseText);
	}
	return responseText;
}

TW_AUI.asynchXHR = function(url)
{
	if(TW_AUI.DEBUG)
	{
		alert("TW_AUI.synchXHR: " + url);
	}
	//get a request object
	var request = false;
	request = TW_AUI.createXHR();

	//if we couldn't get the request object, bail
	if(!request)
	{
		alert('Giving up: ( Cannot create an XMLHTTP instance');
		return false;
	}
	//make the request
    request.open('GET', url, true);
	request.send(null);
}

/**
 * create an XHR request object
 */
TW_AUI.createXHR = function()
{
	var xhr = false;
	if (window.XMLHttpRequest) // Mozilla, Safari,...
	{ 
		xhr = new XMLHttpRequest();
		if (xhr.overrideMimeType)
		{
			xhr.overrideMimeType('text/xml');
		}
	}
	else if (window.ActiveXObject)// IE
	{ 
		try
		{
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
                {
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {}
		}
	}
	return xhr;
}
