// show.js
// (c) 2006, Android Technologies, Inc.

// Global AJAX object.
var gAjaxShowStuff	= null;
var PHP_DIR = "./";
// var updateTimer = null;
var gShowID = null;

// Variable to checked by setTimeout() driven code loops
//  to stop the chain of calls.
var gUpdating = false;		

// The last_access date/time of the most recently retrieved show details.
var gSdLastAccess = null;

// The last_access date/time of the most recently retrieved public notice.
var gPnLastAccess = null;

// The last_access date/time of the most recently retrieved show link.
var gSlLastAccess = null;

// Set a field's innerHTML property to the contents of theText, but only if the
//  current contents is different from the Text.
function setField(elementID, theText)
{
	var div = document.getElementById(elementID);
	
	if (!div)
	{
		stopUpdating();
		alert("(setField) Unable to find the " + elementID + " text area.");
		return;
	} // if (!div)
	
	if (div.innerHTML != theText)
		div.innerHTML = theText;
} // setShowDetails();

// Set the contents of the show details DIV to the given.
function setShowDetails(showDetails)
{
	setField("show_details", showDetails);	
} // setShowDetails();


// Set the contents of the public notice DIV to the given.
function setPublicNotice(thePublicNotice)
{
	setField("public_notice", thePublicNotice);
} // setPublicNotice();

// Append the contents of TABLE in the "show links" DIV to the new link.
	// Helper function to build the mini table for the submitting user name and notes.
	function getShowLinkMiniTable(userName, notes)
	{
		var tblHtml =
			"<TABLE ALIGN=LEFT VALIGN=TOP>\n" +
			"    <TR>\n" +
			"        <TD WIDTH=\"30%\">\n" +
			"            <P><b>Submitter:</b> " + userName + "</P>\n" +
			"        </TD>\n" +
			"    </TR>\n" +
			"    <TR>\n" +
			"        <TD WIDTH=\"70%\">\n" +
			"            <P><b>Notes:</b> " + notes + "</P>\n" +
			"        </TD>\n" +
			"    </TR>\n" +
			"</TABLE>\n";
			
		return tblHtml;					
	} // function getShowLinkMiniTable()
function appendShowLink(linkNum, linkHtml, userName, notes)
{
	var tblShowLinks = document.getElementById("tblShowLinks");
	
	if (!tblShowLinks)
	{
		alert("(appendShowLink) Unable to find the show links table.");
		return;
	}

	// New row. Put it at the front of the table.
    var trNew = tblShowLinks.insertRow(0); 
	 
	var tdLinkNum = trNew.insertCell(-1);
    tdLinkNum.style.width = "10%";
    tdLinkNum.style.verticalAlign = "top";	 
	tdLinkNum.innerHTML = "<p>" + linkNum + "</p>";
	
	var tdUserMiniTable = trNew.insertCell(-1);
    tdUserMiniTable.style.width = "70%";
    tdUserMiniTable.style.verticalAlign = "top";	 
	tdUserMiniTable.innerHTML = "<p>" + getShowLinkMiniTable(userName, notes) + "</p>";
	
	var tdLinkHtml = trNew.insertCell(-1);
    tdLinkHtml.style.width = "20%";
    tdLinkHtml.style.verticalAlign = "top";	 
	tdLinkHtml.innerHTML = "<p>" + linkHtml + "</p>";
	
    /*	
	// New row.
	var trNew = document.createElement("TR");
	
	// New cell - link num.
	var pLinkNum = document.createElement("P");
	pLinkNum.innerHTML = "" + linkNum;
	
	var tdLinkNum = document.createElement("TD");
	tdLinkNum.setAttribute("WIDTH", "10%");
	tdLinkNum.setAttribute("VALIGN", "TOP");
	// tdLinkNum.setAttribute("innerHTML", "" . linkNum);
	tdLinkNum.appendChild(pLinkNum);
	
	// New cell - link html.
	var pLinkHtml = document.createElement("P");
	pLinkHtml.innerHTML = linkHtml;
	
	var tdLinkHtml = document.createElement("TD");
	tdLinkHtml.setAttribute("WIDTH", "20%");
	// tdLinkHtml.setAttribute("innerHTML", linkHtml);
	tdLinkHtml.appendChild(pLinkHtml);
	
	var tdUserMiniTable = document.createElement("TD");
	tdUserMiniTable.setAttribute("WIDTH", "70%");
	tdUserMiniTable.setAttribute("VALIGN", "TOP");
	
	tdUserMiniTable.innerHTML = getShowLinkMiniTable(userName, notes);
	// tdUserMiniTable.innerHTML = "<p>hello</p>";
	
	// Add the cells to the row.
	trNew.appendChild(tdLinkNum);
	trNew.appendChild(tdUserMiniTable);
	trNew.appendChild(tdLinkHtml);
	
	// Add the new table data element to the table.
	tblShowLinks.appendChild(trNew);
	*/
} // function setShowLinks()

/*
// Given an array of links, append the links to the show links table.
// Each array element expected to have a linkNum and a linkHtml field.
function appendShowLinks(showLinks)
{
	for (var i = 0; i < showLinks.length; i++)
	{
		appendShowLink(showLinks[i].linkNum, showLinks[i].linkHtml);
	} // for()
} // function appendShowLinks()
*/

// Set the contents of the "show links" DIV to the given.
function setShowLinks(showLinkHTML)
{
	setField("show_links", showLinkHTML);
	
	/*	
	var S = "";
	
	// Build a table for the show links.
	if (showLinks)	
	{
		S += '<table NAME="tblShowLinks" ID="tblShowLinks" BORDER=0 WIDTH="100%" HEIGHT="100%" CELLPADDING="5" CELLSPACING="5" >\n';
		
		for (var i = 0; i < showLinks.length; i++)
		{
			S += "<tr>\n";
			S += "<td>\n";
			
			S += showLinks[i] + "\n";
			
			S += "</td>\n";
			S += "</tr>\n";
		} // for()
		
		S += "</table>\n";
	} // if (showLinks)	
	else
		S = "None yet, keep listening!";
	
	div.innerHTML = S;
	*/
} // setShowLinks();


// This function will be called by the AJAX object when new show stuff
//  is received.
function showStuffReceived()
{
	if (!gAjaxShowStuff)
	{
		stopUpdating();
		alert("(showStuffReceived) AJAX object has not been initialized yet.");
		return;
	} // if (!gAjaxShowStuff)
	
	// Check the response code, should be 200.
	var httpStatusCode = gAjaxShowStuff.responseStatus[0];
	var httpStatusText = gAjaxShowStuff.responseStatus[1];
	
	if (httpStatusCode != HTTP_RESPONSE_OK)
	{
		stopUpdating();
		alert("(showStuffReceived) Show stuff request (" + httpStatusCode + "): " + httpStatusText + ".");
		return;
	} // if (httpStatusCode != HTTP_RESPONSE_OK)
	
	// Look for one of our error documents.
	var errorMessage = extractXMLTag("error", gAjaxShowStuff.response, false);
	
	if (errorMessage != "")
	{
		// We generated an error document.  Show it.
		stopUpdating();
		alert(errorMessage);
		return;
	} // if (errorMessage)
	
	// See if we have received the "no show" status.
	var noShowText =
		extractXMLTag("noshow", gAjaxShowStuff.response, false);
	var publicNotice = "";
	var showLinks = null;

	if (noShowText != "")
	{
		// Put it in the show details area.
		setShowDetails(noShowText);
	}
	else
	{
		// Get the show ID and store it.
		var showID =
			extractXMLTag("show_id", gAjaxShowStuff.response, false);
			
		if (showID != "")
		{
			// Update our variable.
			gShowID = showID;
		}
		
		// Get the show details.
		var sdLastAccess = 
			extractXMLTag("sd_last_access", gAjaxShowStuff.response, false);
			
		if (sdLastAccess != "")
		{
			// Update our global variable.
			gSdLastAccess = sdLastAccess;
		
			// Get the updated show details
			var showDetails = 
				extractXMLTag("show_details", gAjaxShowStuff.response, false);
			
			// Put it in the show details area.
			if (showDetails != "")
				setShowDetails(showDetails);
		} // if (sdLastAccess != "")
		
		// If there is an updated public notice, the pn_last_access value
		//  will be returned.
		var pnLastAccess = 
			extractXMLTag("pn_last_access", gAjaxShowStuff.response, false);
			
		if (pnLastAccess != "")
		{
			// Update our global variable.
			gPnLastAccess = pnLastAccess;
		
			// Get the updated public notice.
			var publicNotice = 
				extractXMLTag("public_notice", gAjaxShowStuff.response, false);
			
			// Put it in the public notice area.
			setPublicNotice(publicNotice);
		} // if (pnLastAccess != "")
		
		// If there are new show links, the sl_last_access value
		//  will be returned.
		var slLastAccess = 
			extractXMLTag("sl_last_access", gAjaxShowStuff.response, false);
			
		if (slLastAccess != "")
		{
			// Update our global variable.
			gSlLastAccess = slLastAccess;
		
			// Get the show links.
			showLinkXMLRecords = 
				extractXMLTagArray("show_link", gAjaxShowStuff.response, false);
				
			// Now convert the array show links XML data into an array of
			//  linkNum, linkHtml records.
			for (var i = 0; i < showLinkXMLRecords.length; i++)
			{
				// Parse one XML record.
				var linkNum =
					extractXMLTag("link_num", showLinkXMLRecords[i], false);
					
				if (linkNum === null)
				{
					stopUpdating();
					alert("(showStuffReceived) Missing link number in show link XML record array row: " + i);
					return;
				} // if (linkNum == "")
				
				var linkHtml =
					extractXMLTag("link_html", showLinkXMLRecords[i], false);
					
				if (linkHtml === null)
				{
					stopUpdating();
					alert("(showStuffReceived) Missing link HTML in show link XML record array row: " + i);
					return;
				} // if (linkHtml == "")
				
				var userName =
					extractXMLTag("user_name", showLinkXMLRecords[i], false);
				
				if (userName === null)
				{
					stopUpdating();
					alert("(showStuffReceived) Missing submitting user name in show link XML record array row: " + i);
					return;
				} // if (linkHtml == "")
				
				var notes =
					extractXMLTag("notes", showLinkXMLRecords[i], false);
					
				if (notes === null)
				{
					stopUpdating();
					alert("(showStuffReceived) Missing user notes in show link XML record array row: " + i);
					return;
				} // if (linkHtml == "")
				
				// Append the link.
				appendShowLink(linkNum, linkHtml, userName, notes);
			} // for()
		} // if (slLastAccess != "")
	} // else - if (noShowText != "")
	
	// Continue the chain of calls by making another timeout driven request.
	setTimeout("requestShowStuff()", 10000);
} // function showStuffReceived()

// This function makes the AJAX request for new show stuff.
function requestShowStuff()
{
	/*
	var xmlData = 
		'magic_key=' + theMagicKey +
		'&' +
		'title=' + theTitle +
		'&' +
		'description=' + theDescription;
	*/
	
	// If the call chain/loop flag has been turned off, just exit.
	if (!gUpdating)
		return;
	
	// Defeat browser cachine.
	var dt = new Date();
	
	var xmlData = "t=" + dt.getTime();
	
	// Send the last access URL arguments too if we have any.
	if (gSdLastAccess)
		xmlData += "&sd_last_access=" + gSdLastAccess;
		
	if (gPnLastAccess)
		xmlData += "&pn_last_access=" + gPnLastAccess;
		
	if (gSlLastAccess)
		xmlData += "&sl_last_access=" + gSlLastAccess;
	
	var ajaxFile = PHP_DIR + 'get_show_stuff.php';
	
	// alert('ajaxfile = ' + ajaxFile);	
	gAjaxShowStuff 			= new sack(ajaxFile);
	
	// Do the AJAX request.
	gAjaxShowStuff.runAJAX(xmlData);
	
	// Have the ajax object run our desired "response received "function when the request completes.
	gAjaxShowStuff.onCompletion = showStuffReceived;
} // function requestShowStuff()

// This function is called by the onload handler for the show page.
function showOnload()
{
	startUpdating();
} // function showOnload()

// Start the update chain/loop.
function startUpdating()
{
	// Set the flag that will cause the timeout function to make another request when it's
	//  done.
	gUpdating = true;		
	
	// Make a single call now.
	requestShowStuff();

	/* OLD METHOD 	
	// setTimeout("requestShowStuff()", 10000);
	
	if (!updateTimer)
	{
		// Make a single call now.
		requestShowStuff();
		
		// Start the update timer.
		updateTimer = setInterval("requestShowStuff()", 10000);
	} // if (!updateTimer)
	*/
} // function startUpdating()

// Stop the update chain/loop.
function stopUpdating()
{
	// Stop the update timer.
	gUpdating = false;
	
	/*
	if (updateTimer)
	{
		clearInterval(updateTimer);
		updateTimer = null;
	} // if (updateTimer)
	*/
} // function stopUpdating()

// This function is called when a user presses the submit comment button.
function submitComment()
{
	var frm = document.getElementById("frmComment");
	
	if (!frm)
	{
		alert("(submitComment) Unable to find the comment form.");
		return;
	} // if (!frm)
	
	// Make sure we have a valid show ID.
	if (!gShowID)
	{
		alert("(submitComment) The show signature has not been obtained yet.");
		return;
	} // if (!frm)
	
	frm.show_id.value = gShowID;
	
	// Make sure the note is of a reasonable length.
	var comment = AllTrim(frm.notes.value);
	
	// alert("comment = " + comment);
	
	if (comment.length < 1)
	{
		alert("Please add a comment first.");
		return;
	} // if (comment.length < 1)
	
	// Do the submission.
	frm.submit();
} // function submitComment()
