/* 
 *	Author: Andrew Woods <awoods@gotvoice.com
 *  Project: Greetings
 *
 */


/* ========================================================================= *
 *      SitePoint Functions                                                  *
 *                                                                           *
 * i. From "The Javascript Anthology"                                        *
 * ========================================================================= */

// [i.]
// public boolean initTooltips()
// - Uses the class attribute to look for the value "hastooltip".
//   This creates a div whose content is populated by the moused-over
//   elements "title" attribute
// 

try { console.log('init console... done'); }
catch(e) { console = { log: function() {} } };

function attachEventListener(target, eventType, functionRef, capture)
{
	if (typeof target.addEventListener != "undefined"){
		target.addEventListener(eventType, functionRef, capture);
	}
	else if (typeof target.attachEvent != "undefined")
	{
		var functionString = eventType + functionRef;
		target["e" + functionString] = functionRef;
		
		target[functionString] = function(event)
		{
			if (typeof event == "undefined")
			{
				event = window.event;
			}
			target["e" + functionString](event); 	
		}
		target.attachEvent("on" + eventType, target[functionString]);	
	}
	else 
	{
		eventType = "on" + eventType;
		
		if (typeof target[eventType] == "function")
		{
			var oldListener = target[eventType];
			target[eventType] = function()
			{
				oldListner();
				
				return functionRef();
			}
		}
		else
		{
			target[eventType] = functionRef;
		}
	}
}

function detachEventListener(target, eventType, functionRef, capture){
	
	if (typeof target.removeEventListener != "undefined")
	{
		target.removeEventListener(eventType, functionRef, capture); 
	}
	else if (typeof target.detachEvent != "undefined")
	{
		var functionString = eventType + functionRef;
		target.detachEvent("on" + eventType, target[functionString]);
		
		target["e" + functionString] = null;
		target[functionString] = null;
	}
	else
	{
		target["on" + eventType] = null;	
	}
}


function addLoadListener(fn)
{
	if (typeof window.addEventListener != "undefined")
	{
		window.addEventListener('load', fn, false);
	}
	else if (typeof document.addEventListener != "undefined")
	{
		document.addEventListener('load', fn, false);
	}
	else if (typeof window.attachEvent != 'undefined')
	{
		window.attachEvent('onload', fn);
	}
	else
	{
		var oldfn = window.onload;
		if (typeof window.onload != 'function')
		{
			window.onload = fn;
		}
		else
		{
			window.onload = function()
			{
				oldfn();
				fn();
			}	
		}
	}	
}

function getElementsByAttribute(attribute, attributeValue)
{
	var elementArray = new Array();
	var matchedArray = new Array();
	
	if (document.all)
	{
		elementArray = document.all;
	}
	else
	{
		elementArray = document.getElementsByTagName("*");
	}
	
	for (var i=0; i < elementArray.length; i++)
	{
		if (attribute == "class")
		{
			var pattern = new RegExp("(^| )"
				+ attributeValue + "( |$)");
			
				
			if (pattern.test(elementArray[i].className))
			{
				matchedArray[matchedArray.length] = elementArray[i];
			}
		}
		else if (attribute == "for")
		{
			if (elementArray[i].getAttribute("htmlFor") ||
			    elementArray[i].getAttribute("for"))
			{
				if (elementArray[i].htmlFor == attributeValue)
				{
					matchedArray[matchedArray.length] = elementArray[i];
				}
			}
		}
		else if (elementArray[i].getAttribute(attribute) == attributeValue)
		{
			matchedArray[matchedArray.length] = elementArray();
		}	
	}
	return matchedArray;
}


function getEventTarget(event)
{
	var targetElement = null;
	
	if (typeof event.target != "undefined")
	{
		targetElement = event.target;	
	}
	else
	{
		targetElement = event.srcElement;
	}
	
	while (targetElement.nodeType == 3 &&
		targetElement.parentNode != null)
	{
		targetElement = targetElement.parentNode;
	}
	return targetElement;
}

function getScrollingPosition()
{
	var position = [0, 0];
	
	if (typeof window.pageYOffset != 'undefined')
	{
		position = [
			window.pageXOffset,
			window.pageYOffset
		];
	}
	else if (typeof document.documentElement.scrollTop != 'undefined'
	 && document.documentElement.scrollTop > 0 || 
	    document.documentElement.scrollLeft > 0)
	{
		position = [
			document.documentElement.scrollLeft,
			document.documentElement.scrollTop
		];
		
	}
	else if (typeof document.body.scrollTop != 'undefined')
	{
		position = [
			document.body.scrollLeft,
			document.body.scrollTop
		];
		
	}
	
	return position;
}

function  getViewportSize()
{
	var size = [0, 0];
	
	if (typeof window.innerWidth != 'undefined'){
		size = [
			window.innerWidth,
			window.innerHeight
		];
	}
	else if (typeof document.documentElement != 'undefined' &&
		typeof document.documentElement.clientWidth != 'undefined' &&
		document.documentElement.clientWidth != 0)
	{
		size = [
			document.documentElement.clientWidth,
			document.documentElement.clientHeight
		];
	}
	else {
		size = [
			document.getElementsByTagName('body')[0].clientWidth,
			document.getElementsByTagName('body')[0].clientHeight
		];
	}
	return size;
}

// [i.]
// public boolean initTooltips()
// - Uses the class attribute to look for the value "hastooltip".
//   This creates a div whose content is populated by the moused-over
//   elements "title" attribute
// 

function initTooltips()
{
	
	var tips = getElementsByAttribute("class", "hastooltip");
	
	for (var i=0; i<tips.length; i++)
	{
		attachEventListener(tips[i], "mouseover", showTip, false);
		attachEventListener(tips[i], "mouseout", hideTip, false);
		
	}
	
	return true;
}
function initTrackSelect()
{
	
	var sel = getElementById("trackSelect");
	
	attachEventListener(sel, "click", setPlaybackModeUsingString(value), false);
	
	return true;
}

// [i.]
// public boolean showTip(event)
// - Uses the class attribute to look for the value "hastooltip".
//   This creates a div whose content is populated by the moused-over
//   elements "title" attribute
// 
function showTip(event){
	if (typeof event == "undefined")
	{
		event = window.event;
	}

	var target = getEventTarget(event);
	
	while (target.className == null ||
	  !/(^| )hastooltip( |$)/.test(target.className)
	)
	{
		target = target.parentNode;
	}
	
	
	var tip = document.createElement("div");
	var content = target.getAttribute("title");
	
	target.tooltip = tip;
	target.setAttribute("title", "");
	
	if (target.getAttribute("id") != ""){
		tip.setAttribute("id", target.getAttribute("id") + "tooltip");
	}
	
	tip.className = "tooltip";
	tip.appendChild(document.createTextNode(content));
	
	var scrollingPosition = getScrollingPosition();
	var cursorPosition = [0, 0];
	
	if (typeof event.pageX != "undefined" &&
	    typeof event.x != "undefined")
	{
		cursorPosition[0] = event.pageX;
		cursorPosition[1] = event.pageY;
	}    
	else
	{
		cursorPosition[0] = event.clientX + scrollingPosition[0];
		cursorPosition[1] = event.clientY + scrollingPosition[1];
	}	

	tip.className = "tooltip";	
	tip.style.position = "absolute";
	tip.style.left = cursorPosition[0] + 10 + "px";
	tip.style.top = cursorPosition[1] + 10 + "px";
	
	tip.style.visibility = "hidden";
	
	document.getElementsByTagName("body")[0].appendChild(tip);
	
	/*  */
	
	var viewportSize = getViewportSize();
	/* Determine the x-coordinate of the div */
	if (cursorPosition[0] - scrollingPosition[0] + 10 + 
		tip.offsetWidth > viewportSize[0] - 25)
	{
		tip.style.left = scrollingPosition[0] + viewportSize[0] - 25 - 
		tip.offsetWidth + "px";
	}
	else
	{
		tip.style.left = cursorPosition[0] + 10 + "px";
	}


	/* Determine the y-coordinate of the div */
	if (cursorPosition[1] - scrollingPosition[1] + 10 + 
		tip.offsetHeight > viewportSize[1] - 25)
	{
		if (event.clientX > (viewportSize[0] - 25 - tip.offsetWidth))
		{
			tip.style.top = cursorPosition[1] - tip.offsetHeight - 10 + "px"; 
		}
		else 
		{
			tip.style.top = scrollingPosition[1] + viewportSize[1] - 25 - tip.offsetHeight + "px";
		}
	}
	else
	{
		tip.style.top = cursorPosition[1] + 10 + "px";
	}

	tip.style.visibility = "visible";
	
	return true;
}

// [i.]
// public boolean hideTip(event)
// - Uses the class attribute to look for the value "hastooltip".
//   This creates a div whose content is populated by the moused-over
//   elements "title" attribute
// 

function hideTip(event)
{
	if (typeof event == "undefined")
	{
		event = window.event;
	}
	
	var target = getEventTarget(event);
	
	while (target.className == null ||
		!/(^| )hastooltip( |$)/.test(target.className))
	{
		target = target.parentNode;
	}
	
	if (target.tooltip != null)
	{
		target.setAttribute("title", 
			target.tooltip.childNodes[0].nodeValue);
		target.tooltip.parentNode.removeChild(target.tooltip);	
	}
	
	return false;
}


/* ========================================================================= *
 *      User Interface Functions                                             *
 * ========================================================================= */

function setPageDefaults(){
	// draw the list of categories
	loadCategories('mainCategory');
	
	// Select the radio buttion
	//document.getElementById('send_mp3').usebackground[1].checked = true;

	// Select the Type of background
	//document.recordmessage.tracktype[0].checked = true;
    setPlaybackModeUsingString("fg");


	// Determine the type of background selection
	chooseBgType("archive");
	
	// Display the layer to prevent a background selection.
	//disablingLayer(true);
	
	initTooltips()
}

function loadCategories(elementId)
{
	var e = document.getElementById(elementId);
	document.getElementById("subCategory").innerHTML="<i>Please select a category</i>";
	document.getElementById("trackCell").style.display="none";
	
	for (key in bgsounds)
	{
		// Create the elements
		var listItem = document.createElement('li');
		var link = document.createElement('a');
		
		// Fill the hyperlink with the word to click on
		link.id = key;
		link.setAttribute('href', "javascript:loadSubCategories('subCategory', '" + key + "');");
		link.innerHTML = key;
		
		// add the link to the list item <li><a></li>
		listItem.appendChild(link);
		
		// add the list item to the list
		e.appendChild(listItem);
	}
}


function loadSubCategories(elementId, categoryId)
{
	var elem = document.getElementById(elementId);

	updateCategorySelection("mainCategory", categoryId);
	document.getElementById("subcatCell").className="list";
	document.getElementById("trackCell").style.display="none";
	elem.className = "category";	

	// Remove the existing content
	elem.innerHTML = "";

	subdata = bgsounds[categoryId];
	
	for (var key in subdata)
	{
		// Create the elements
		var listItem = document.createElement('li');
		var link = document.createElement('a');
		
		// Fill the hyperlink with the word to click on
		link.id = key;
		link.className="";
		link.setAttribute('href', 'javascript:loadTracks("trackList", "' + categoryId + '", "' + key + '")');
		link.innerHTML = key;
		
		// add the link to the list item <li><a></li>
		listItem.appendChild(link);
		
		// add the list item to the list
		elem.appendChild(listItem);
	}
	document.getElementById(categoryId).className="current";
	
}

function disablingLayer(value)
{
	var form = document.getElementById('bgtypeform');
	var disableLayer = document.getElementById('disable');
	
	if (value)
	{
		//alert("create the disabling layer");
		disableLayer.style.display="block";
		
	}
	else
	{
		//alert("remove the disabling layer");
		disableLayer.style.display="none";
	}
}

function makeParameter(name, value){
	var parameter = document.createElement('param');
	parameter.setAttribute("name", name);
	parameter.setAttribute("value", value);
	
	return parameter;
}

function playFileInWindow(filepath){
		
	/* Player Parameters */
	var LOOP = "false";
	var WIDTH = 300;
	var HEIGHT = 12;
	var CONTROLLER = "true";
	var BACKGROUND_COLOR = "white";
	
	var playerContainer = document.getElementById('inlinePlayer');
	var player = "";
	
	player = document.createElement('embed');
	
	player.setAttribute('id', 'embedPlayer');
	player.setAttribute('src', filepath);
	player.setAttribute('loop', LOOP);
	player.setAttribute('type', 'audio/mpeg');
	player.setAttribute('width', WIDTH);
	player.setAttribute('height', HEIGHT);
	player.setAttribute('controller', CONTROLLER);
	player.setAttribute('background', BACKGROUND_COLOR);

	playerContainer.style.visibility="hidden";
	playerContainer.innerHTML="";
	playerContainer.appendChild(player);

	parent.resizeIframe();
}
	

/*
public void updateCategorySelection(String elementId, String categoryId){

description: Assigns the highlight color to the the category list.
   This only sets a class name. The actual styling is done with CSS.

*/ 
function updateCategorySelection(elementId, categoryId){

	var e = document.getElementById(elementId);

	e.innerHTML = "";	
	
	for (key in bgsounds)
	{
		// Create the elements
		var listItem = document.createElement('li');
		var link = document.createElement('a');
		
		// Fill the hyperlink with the word to click on
		
		link.id = key;
		link.className = (key == categoryId) ? "current" : "";
		link.setAttribute('href', "javascript:loadSubCategories('subCategory', '" + key + "');");
		link.innerHTML = key;
		
		// add the link to the list item <li><a></li>
		listItem.appendChild(link);
		
		// add the list item to the list
		e.appendChild(listItem);
	}
}

/*
public void updateSubCategorySelection(elementId, categoryId, subcategoryId)

description: Assigns the highlight color to the the subcategory list.
   This only sets a class name. The actual styling is done with CSS.

*/

function updateSubCategorySelection(elementId, categoryId, subcategoryId)
{
	var e = document.getElementById(elementId);

	e.innerHTML = "";	
	
	for (key in bgsounds[categoryId])
	{
		// Create the elements
		var listItem = document.createElement('li');
		var link = document.createElement('a');
		
		// Fill the hyperlink with the word to click on
		
		link.id = key;
		link.className = (key == subcategoryId) ? "current" : "";
		link.setAttribute('href', 'javascript:loadTracks("trackList", "' + categoryId + '", "' + key + '")');

		link.innerHTML = key;
		
		// add the link to the list item <li><a></li>
		listItem.appendChild(link);
		
		// add the list item to the list
		e.appendChild(listItem);
	}
}


function loadTracks(elementId, categoryId, subcategoryId)
{
	var elem = document.getElementById(elementId);

	updateSubCategorySelection("subCategory", categoryId, subcategoryId);
	document.getElementById(subcategoryId).className="current";
	document.getElementById("trackCell").style.display="block";
	document.getElementById("trackCell").className="list";
	elem.className = "category";
	
	// Remove the existing content
	elem.innerHTML = "";
	
	trackdata = bgsounds[categoryId][subcategoryId];
	for (record in trackdata){
		var track = trackdata[record];
		var songTitle    = track.title;
		var songLocation = track.data;

		// Create the elements
		var listItem = document.createElement('li');
		var link = document.createElement('a');
		var listenLink = document.createElement('a');
		var listenImg = document.createElement('img');
		
		// Fill the hyperlink with the word to click on
		listItem.id = songTitle;
		link.id = songTitle + 'Link';
		link.setAttribute('href', 'javascript:background_chg("' + songLocation + '","' + songTitle + '");');
		link.setAttribute("title", songTitle);
		link.innerHTML = songTitle;

		// Link for the user to listen to the Track before selecting it
		listenImg.setAttribute("src", "/images/buttons/play-arrow-small.gif");
		listenImg.setAttribute("border", "0");

		/* 
		   IE didn't seem to like the javascript in the onclick	event, so I migrated to the href.
		   Mozilla, of course, didn't have a problem with it.
		*/
		listenLink.setAttribute('href', "javascript:playFileInWindow('" + songLocation + "');" );
		listenLink.appendChild(listenImg);
		
		// add links to the list item
		//listItem.appendChild(listenLink);
		listItem.appendChild(link);

		// add the list item to the list
		elem.appendChild(listItem);
	}

	parent.resizeIframe();
	
}


function getSiteUrl()
{
	var url = window.location.protocol + "//" + window.location.hostname;
	if (window.location.port != 80) { url += ":" + window.location.port; }
	return(url);
}



function chooseBgType(item)
{
	/* These values must match the 'value' on the radio buttons */
	var ARCHIVE = "archive";
	var UPLOAD  = "fileupload";
	var ARCHIVE_ID = "libtab";
	var ARCHIVE_ACTIVE_SRC = "/images/library-tab.jpg";
	var ARCHIVE_INACTIVE_SRC = "/images/library-tab_f2.jpg";
	var UPLOAD_ID = "mp3tab";
	var UPLOAD_ACTIVE_SRC = "/images/record-tab_f2.jpg";
	var UPLOAD_INACTIVE_SRC = "/images/record-tab.jpg";
	
	if (item)
	{
		switch (item)
		{
			case ARCHIVE:
				document.getElementById(ARCHIVE).style.display = "block";
				document.getElementById(UPLOAD).style.display  = "none";
				document.getElementById(ARCHIVE_ID).title = "Archive";
				document.getElementById(ARCHIVE_ID).src = ARCHIVE_ACTIVE_SRC;
				document.getElementById(UPLOAD_ID).title = "Upload";
				document.getElementById(UPLOAD_ID).src = UPLOAD_INACTIVE_SRC;
				break;
				
			case UPLOAD:
				document.getElementById(ARCHIVE).style.display = "none";
				document.getElementById(UPLOAD).style.display  = "block";
				document.getElementById(ARCHIVE_ID).title = "Library";
				document.getElementById(ARCHIVE_ID).src = ARCHIVE_INACTIVE_SRC;
				document.getElementById(UPLOAD_ID).title = "Archive";
				document.getElementById(UPLOAD_ID).src = UPLOAD_ACTIVE_SRC;
				break;
				
			default:
				alert("Either '" + ARCHIVE + "' or '" + UPLOAD + "' must be selected");
				break;	
		}
	}
	else
	{
		document.getElementById(ARCHIVE).className = "unseen";
		document.getElementById(UPLOAD).className  = "unseen";
	}
}

// Determine if the user wants to include a background
function useBackgroundTrack(form, value) {

	if (value == true)
	{
		// Since there is no isForegroundInstalled() function in the applet,
		// I have to assume it's installed.
		if (isBackgroundInstalled())
		{
		    setPlaybackModeUsingString("bg");
			//document.recordmessage.tracktype[1].checked = true;
		}
		else 
		{
		    setPlaybackModeUsingString("mixed");
			//document.recordmessage.tracktype[2].checked = true;
		}		
		disablingLayer(false);
	}
	else if (value == false) 
	{
		// Since there is no isForegroundInstalled() function in the applet,
		// I have to assume it's installed.
		//document.recordmessage.tracktype[0].checked = true;
	    setPlaybackModeUsingString("fg");
		disablingLayer(true);
	}
	else  
	{
		alert("Invalid response:" + value);
	}

}

/* ========================================================================= *
 *      Applet Functions                                                     *
 * ========================================================================= */

// public void background_chg(SelectList track)
function background_chg(track, title)
{
	var trackPath = getSiteUrl() + track;

	// set the player to auto-play background
	document.gvrecorder.disableTimelineEditor();
	document.gvrecorder.enableAutoBackgroundPlayback();

	document.gvrecorder.setBackgroundMixURL(trackPath);
	document.gvrecorder.enablePlay();

	// update the selection display
	clearHref = "<a href=javascript:deleteBackground()><img src='/images/icons/icon-remove.png' border='0'/></a>";
	if (document.getElementById('selectedbg')) {
	  document.getElementById('selectedbg').innerHTML=title + "&nbsp;&nbsp;&nbsp;" + clearHref;
	}
	if (document.getElementById('selectedbg2')) {
	  document.getElementById('selectedbg2').innerHTML=title;
	}

	// update the radio buttons
	if (document.getElementById('track_bg')) {
	  document.getElementById('track_bg').disabled = false;
	  if (document.gvrecorder.getForegroundDuration() > 0 &&
	      document.getElementById('track_mix')) {
	    document.getElementById('track_mix').disabled = false;
	    document.getElementById('track_mix').checked = true;
	  }
	  else
	  {
	    document.getElementById('track_bg').checked = true;
	  }
	}
	setMixLen();
	setPlaybackModeUsingString('mixed');

	// set the selection list to active for this clip
	p = document.getElementById('trackList');
	for (var i = 0; i < p.childNodes.length; i ++)
	{
	  if (p.childNodes[i].id == title)
	  { document.getElementById(title + 'Link').className = "current"; }
	  else { document.getElementById(p.childNodes[i].id + 'Link').className = "list";}
	}
}


function custom_background_chg(el)
{
    var trackPath = "file://" + document.getElementById(el).value;

	if (trackPath.substr(trackPath.length - 4) != '.mp3')
	{
		alert("Please select a .mp3 file.");
		return;
	}

	shortname = document.getElementById(el).value;
	var re = /([\w ]+)\..+$/;
	var reRes = re.exec(shortname);
	if (reRes && reRes[1]) { shortname = reRes[1]; }

	document.gvrecorder.disableAutoBackgroundPlayback();

	// update the selection display
	clearHref = "<a href=javascript:deleteBackground()>[x]</a>";
	document.getElementById('selectedbg').innerHTML=shortname+ clearHref;
	if (document.getElementById('selectedbg2')) {
	  document.getElementById('selectedbg2').innerHTML=shortname;
	}

	// update the radio buttons
	if (document.getElementById('track_bg')) {
	  document.getElementById('track_bg').disabled = false;
	  if (document.gvrecorder.getForegroundDuration() > 0 &&
	      document.getElementById('track_mix')) {
	    document.getElementById('track_mix').disabled = false;
	    document.getElementById('track_mix').checked = true;
	  }
	  else
	  {
	    document.getElementById('track_bg').checked = true;
	  }
	}
	setMixLen();
	setPlaybackModeUsingString('mixed');

	var res = document.gvrecorder.setBackgroundMixURL(trackPath);
	document.gvrecorder.enablePlay();
	
	installTimer = setInterval("waitUntilInstalled()", 5000);
}

function setMixLen()
{
  if (document.getElementById('greetinglen'))
  {
    fglen = document.gvrecorder.getForegroundDuration();
    if (fglen > 0 && fglen < 1000) { fglen = 1000; }
    mixlen = document.gvrecorder.getMixedDuration();
    fglen = fglen / 1000;
    mixlen = mixlen / 1000;
    fglen = Math.floor(fglen);
    mixlen = Math.floor(mixlen);
    document.getElementById('greetinglen').innerHTML = (mixlen > 0) ? mixlen : fglen;
  }
}

function waitUntilInstalled(){

	var bgInstalled = isBackgroundInstalled();
	 
	if (bgInstalled){
		clearInterval(installTimer);
		enableTimelineEditor();
	}

}


function sendGreeting()
{
	form = document.getElementById("send_mp3");

	// Form Data
	var phoneData = form.assignToPhone[form.assignToPhone.selectedIndex].value.split("|");
	var phoneNumber  = phoneData[0];
	var pin          = phoneData[1];          
	var provider     = phoneData[2];     
	var accessNumber = phoneData[3]; 
	var tcode = form.tcode.value;

    document.gvrecorder.setTransactionCode(tcode);
    document.gvrecorder.addGreetingRecipient(accessNumber, phoneNumber, pin, provider);
 
  	if (document.gvrecorder.getForegroundDuration() == 0)
	//if (form.recorded.value != 1) 
	{
	    alert("Please record a message.");
	    return;
	}

    if (form.remain.value != -1) {
    	if (form.remain.value < 1) { alert ("You have no more greetings for this month."); return; }
    	form.remain.value--;
    	document.getElementById('remainingQty').innerHTML = form.remain.value;
    }

	console.log("Sending Greeting");
	document.gvrecorder.sendGreeting();
	console.log("Greeting Sent");
}

function greeting_recordingStart() 
{
}

function greeting_foregroundInstallResponse()
{
  setMixLen();
  if (document.gvrecorder.getMixedDuration() > 0)
  {
    document.getElementById('track_mix').disabled=false;
    document.getElementById('track_mix').checked=true;
    setPlaybackModeUsingString('mixed');
  }
}

function greeting_recordingStop()
{
  fglen = document.gvrecorder.getForegroundDuration();
  if (fglen > 0 && fglen < 1000) { fglen = 1000; }
  fglen = fglen / 1000;
  fglen = Math.floor(fglen);
  document.getElementById('fgduration').innerHTML=fglen;
  setMixLen();
  document.send_mp3.recorded.value = "1";
  document.getElementById('track_fg').disabled=false;
  if (document.gvrecorder.getMixedDuration() > 0)
  {
    document.getElementById('track_mix').disabled=false;
    document.getElementById('track_mix').checked=true;
    setPlaybackModeUsingString('mixed');
  }
}

function greeting_uploadResponse(code, text, groupid) 
{
	// alert('mine!');
	if (groupid == '') 
	{
		alert ("There was a problem sending the greeting.\nPlease try again.");
	}
	else
		alert ("Your greeting will be installed in a few minutes.");
}

function deleteBackground(){

	// update the display
	if (document.getElementById('selectedbg')) {
	  document.getElementById('selectedbg').innerHTML = "(none)";
	}
	if (document.getElementById('selectedbg2')) {
	  document.getElementById('selectedbg2').innerHTML = "none";
	}
	// update the radio button
	if (document.getElementById('track_fg')) {
	  document.getElementById('track_fg').checked = true;
	}

	if (document.getElementById('track_bg')) {
	  document.getElementById('track_bg').disabled = true;
	}
	if (document.getElementById('track_mix')) {
	  document.getElementById('track_mix').disabled = true;
	}
	setPlaybackModeUsingString('fg');

	document.gvrecorder.clearBackgroundMixURL();
	setMixLen();
	setTimeout(";",3000);
	var response = document.gvrecorder.isBackgroundInstalled();
}

function cancelEdit()
{
	location.href = "mixer.php";
}


function isTimelineEditorInstalled()
{
	// does nothing. Although it should.
	// A corresponding function needs to be added to the applet.
}


function enableTimelineEditor()
{
	if (isBackgroundInstalled())
	{
		document.gvrecorder.enableTimelineEditor();
	}	
}


function disableTimelineEditor()
{
	document.gvrecorder.disableTimelineEditor();
}


function isBackgroundInstalled()
{

	var response = document.gvrecorder.isBackgroundInstalled();

	return (response);
}


function setPlaybackMode(form){

	var fg = (form.foreground.checked) ? true : false;
	var bg = (form.background.checked) ? true : false;
	
	if (!fg & !bg) 
	{
		alert("Please select at least the foreground or background");
	}
	else if (fg && !bg)
	{
		// foreground only
		document.gvrecorder.setPlayModeForeground();
	}
	else if (!fg && bg)
	{
		// background only
		document.gvrecorder.setPlayModeBackground();
	}
	else
	{
		// mixed mode
		// set to mixed iff foreground exists
		if (document.gvrecorder.getForegroundDuration() != 0)
		{
		  document.gvrecorder.setPlayModeMixed();
		}
		else
		{
		  document.gvrecorder.setPlayModeBackground();
		}
	}
}


function setPlaybackModeUsingString(value)
{
	var FOREGROUND = "fg";
	var BACKGROUND = "bg";
	var MIXED      = "mixed";

	switch (value) 
	{
		case FOREGROUND:
			// foreground only
			if (document.gvrecorder)
			{
				document.gvrecorder.setPlayModeForeground();
			}
			break;
		case BACKGROUND:
			// background only
			document.gvrecorder.setPlayModeBackground();
			break;
		case MIXED:
			// mixed mode -- only if FG exists
			if (document.gvrecorder.getForegroundDuration() != 0)
			{
			  document.gvrecorder.setPlayModeMixed();
			}
			else
			{
			  document.gvrecorder.setPlayModeBackground();
			}
			break;
		default:
			alert("Please use one of the following: " + FOREGROUND + 
			     ", " + BACKGROUND + 
			     ", or " + MIXED  + ". Thanks.");
			break;
	}
}


