var g_wndInstructions = null;
var g_sSelectedConfigID = "none";
var g_nCurrentActivityID = 0;
var g_sLanguage = "es";

// sniff the browser
var g_sBrowser = document.all ? "IE" : "NN";
var g_fBrowserVersion = 5;
var g_sOS = navigator.platform.indexOf('Mac') == -1 ? "Win" : "Mac";
if (g_sBrowser == "IE")
{
	nVersionIndex = navigator.userAgent.indexOf('MSIE ') + 5;
	g_fBrowserVersion = parseFloat(navigator.userAgent.substring(nVersionIndex,nVersionIndex+4));
}
else if (g_sBrowser == "NN")
{
	g_fBrowserVersion = parseFloat(navigator.appVersion.substring(0,4));
	if (g_fBrowserVersion == 5)
	{
		nVersionIndex = navigator.userAgent.indexOf('Netscape6/') + 10;
		g_fBrowserVersion = parseFloat(navigator.userAgent.substring(nVersionIndex,nVersionIndex+3));
	}
}

// if there is only one activity display it whenever we are asked to display the activity list
if (g_asActivityPages.length == 1) g_sActivityList = g_sWorkspaceDir + g_asActivityPages[0];

function paramValue(sName,sDefault)
{
	var sValue;
	var sQueryString = window.location.search;
	var nBegin = sQueryString.indexOf(sName);
	if (nBegin == -1) return sDefault;
	nBegin += sName.length + 1;
	var nEnd = sQueryString.indexOf("&",nBegin);
	if (nEnd == -1) nEnd = sQueryString.length;
	sValue = sQueryString.substring(nBegin, nEnd);
	return sValue;
}
function initFrames()
{
	if (typeof(window.location.search) == "unknown") {window.open("refresh.html","_self");return;}
	var sPage = paramValue("open","none");
	if (sPage == "instructions") displayHelp();
	else if (sPage == "teacher") displayLessonPlan();
	else if (sPage == "activities" && g_nActivityCount > 0)
	{
		var nIndex = paramValue("index",0);
		if (nIndex > g_nActivityCount) nIndex = 0;
		var nID = paramValue("id",0);
		if (nID != 0)
		{
			for (nActivity = 0; nActivity < g_nActivityCount; nActivity++)
			{
				if (g_anActivityIDs[nActivity] == nID)
				{
					nIndex = nActivity;
					break;
				}
			}
		}
		g_nCurrentActivityIndex = nIndex;
		g_nCurrentActivityID = g_anActivityIDs[nIndex];
		displayCurrentActivity();
	}
}
function toggleMaximize()
{
	if (!document.all || navigator.platform.indexOf('Mac') != -1) return;
	
	var sButtonImage = new String(frames.workspace.document.images.maxbtn.src);
	setMaximized(sButtonImage.indexOf("restore") == -1);
}
function setMaximized(bMaximize)
{
	if (!document.all || navigator.platform.indexOf('Mac') != -1) return;

	var sButtonImage = new String(frames.workspace.document.images.maxbtn.src);
	if (bMaximize == true && sButtonImage.indexOf("restore") == -1)
	{
		frames.workspace.document.images.maxbtn.src = "images/restore.gif";
		frames.inst.cols='100%,*';
	}
	else if (bMaximize == false && sButtonImage.indexOf("maximize") == -1)
	{
		frames.workspace.document.images.maxbtn.src = "images/maximize.gif";
		frames.inst.cols='*,280';
	}
}
function clearWorkspace()
{
	frames.workspace.document.applets['save'].clearWorkspace();
}
function loadConfig(sConfigFile,sConfigID,sIsUserConfig,sConfigName)
{
	if (!g_bCanLoad || sConfigFile == null) return;

	// NN6 and IE-Mac (JS version should never be called on these browsers)
	if ((g_sBrowser == "NN" && g_fBrowserVersion >= 6) || (g_sBrowser == "IE" && g_sOS == "Mac")) return;

	// all other browsers
	else frames.workspace.document.applets['save'].loadConfig(sConfigFile,sConfigID,sConfigName,sIsUserConfig);

	// set the focus to ourselves
	window.focus();
}
function loadCurrentConfig()
{
	if (!g_bCanLoad) return;

	// get the name of the config file
	var sConfigFile = g_asActivityConfigs[g_nCurrentActivityIndex];

	// if there is a config file for the activity, load it into the virtual manipulative
	if (sConfigFile != "") loadConfig(sConfigFile,null,"false",null);
	else clearWorkspace();
}
function lookupActivity()
{
	for (nIndex = 0; nIndex < g_nActivityCount; nIndex++)
	{
		if (g_anActivityIDs[nIndex] == g_nCurrentActivityID)
		{
			g_nCurrentActivityIndex = nIndex;
			return;
		}
	}
	g_nCurrentActivityIndex = -1;
}
function loadCurrentActivity()
{
	// if there is no current activity, display the list of activities
	if (g_nCurrentActivityID == 0) displayActivityList();
	else
	{
		// tell the controller that we are displaying an activity
		if (g_bCanLoad) frames.workspace.document.applets['save'].setDisplayingActivity("true");

		// display the activity frames
		displayInstructionPage("activityframes.html");

		// load the config for the activity
		loadCurrentConfig();	
	}
}
function loadActivity(nActivityID)
{
	// store the current activity
	g_nCurrentActivityID = nActivityID;
	g_sSelectedConfigID = "none";

	// lookup the activity page
	lookupActivity();
	
	// display it
	loadCurrentActivity();
}
function changeActivityPage()
{
	// if no activities, display the activity list
	if (g_nCurrentActivityIndex == -1) displayActivityList();

	// navigate to the activity page
	else
	{
		if (g_sBrowser == "IE" && g_sOS == "Win") frames.instructions.activitypage.location.href = g_sWorkspaceDir + g_asActivityPages[g_nCurrentActivityIndex];
		else if (g_wndInstructions != null && !g_wndInstructions.closed) g_wndInstructions.activitypage.location.href = g_sWorkspaceDir + g_asActivityPages[g_nCurrentActivityIndex];
		loadCurrentConfig();	
	}
}
function nextActivity()
{
	if (g_nCurrentActivityIndex < g_nActivityCount - 1) g_nCurrentActivityIndex++;
	else g_nCurrentActivityIndex = 0;
	changeActivityPage();
}
function prevActivity()
{
	if (g_nCurrentActivityIndex != 0) g_nCurrentActivityIndex--;
	else g_nCurrentActivityIndex = g_nActivityCount - 1;
	changeActivityPage();
}
function displayActivityList()
{
	// display the activity list
	displayInstructionPage(g_sActivityList);
	
	// there is more than one activity (so we are displaying a list)
	if (g_asActivityPages.length > 1)
	{
		// clear the current activity id
		g_nCurrentActivityID = 0;

		// if we successfully opened the activity list, set the focus to it
		if (g_wndInstructions != null && !g_wndInstructions.closed) g_wndInstructions.focus();
		// if the applet has the ability to save, let it know that we are not displaying an activity
		if (g_bCanLoad) frames.workspace.document.applets['save'].setDisplayingActivity("false");
	}
}
function displayInstructionPage(sPage)
{
	// IE-Win browsers
	if (g_sBrowser == "IE" && g_sOS == "Win")
	{
		frames.instructions.location.href = sPage;
		setMaximized(false);
	}
	// NN-Win and all Mac browsers
	else
	{
		// instructions frame not open yet
		if (g_wndInstructions == null || g_wndInstructions.closed || (g_sBrowser == "IE" && g_sOS == "Mac") || (g_sBrowser == "NN" && g_fBrowserVersion >= 6))
		{
			var nScreenWidth = screen.availWidth;
			if (nScreenWidth > 1500) nScreenWidth = (nScreenWidth / 2) - 5;
			var nScreenHeight = screen.availHeight - 32;
			var nWidth = 280;
			var nLeft = nScreenWidth - nWidth - 6;

			// IE-Mac
			if (g_sBrowser == "IE")
			{ 
				var nVersionIndex = navigator.userAgent.indexOf('MSIE ') + 5;
				var sAppVersion = navigator.userAgent.substring(nVersionIndex,nVersionIndex+4);
				var fAppVersion = parseFloat(sAppVersion);

				// IE-Mac4
				if (fAppVersion < 5)
				{
					nScreenHeight = nScreenHeight + 7;
					nWidth = nWidth - 10;
					nLeft = nLeft + 13;
					window.moveTo(6,42);
					window.resizeTo(nLeft - 18, nScreenHeight);
					g_wndInstructions = window.open('','instructions','left=' + nLeft + ',width=' + nWidth + ',height=' + nScreenHeight + ',resizable=yes,scrollbars=1,toolbar=0,status=0,location=0,menubar=1');
					g_wndInstructions.document.location.href = sPage;
					g_wndInstructions.resizeTo(nWidth, nScreenHeight);
					g_wndInstructions.moveTo(nLeft,42);
				}
				// IE5-MacOS
				else if (fAppVersion < 5.2)
				{
					nScreenHeight += 7;
					nWidth -= 27;
					nLeft += 18;
					window.moveTo(0,0);
					window.resizeTo(nLeft - 12, nScreenHeight - 20);
					g_wndInstructions = window.open(sPage,'instructions','left=' + nLeft + ',width=' + nWidth + ',height=' + nScreenHeight + ',resizable=yes,scrollbars=1,toolbar=0,status=0,location=0,menubar=1');
					window.focus();
				}
				// IE5-MacOSX
				else 
				{
					nScreenHeight += 7;
					nWidth -= 18;
					nLeft += 7;
					window.moveTo(0,0);
					window.resizeTo(nLeft-1, nScreenHeight - 28);

					g_wndInstructions = window.open(sPage,'instructions','left=' + nLeft + ',width=' + nWidth + ',height=' + nScreenHeight + ',resizable=yes,scrollbars=1,toolbar=0,status=0,location=0,menubar=1');
					window.focus();
				}
			}
			// NN
			else if (g_sBrowser == "NN")
			{
				// NN-Win
				if (g_sOS == "Win")
				{
					// NN6-Win
					if (g_fBrowserVersion >= 6)
					{
						window.moveTo(0,0);
						window.resizeTo(nLeft,nScreenHeight+32);
						g_wndInstructions = window.open(sPage,"instructions",'resizable=yes,top=0,left=' + nLeft + ',width=' + nWidth + ',height=' + nScreenHeight + ',scrollbars=1,toolbar=0,status=0,location=0,menubar=0');
						g_wndInstructions.resizeTo(nWidth+10, nScreenHeight + 32);
					}
					// NN4-Win
					else
					{
						window.moveTo(0,0);
						window.resizeTo(nLeft-12, nScreenHeight - 24);
						g_wndInstructions = window.open(docDir() + sPage,"instructions",'left=' + nLeft + ',width=' + nWidth + ',height=' + nScreenHeight + ',resizable=yes,scrollbars=1,toolbar=0,status=0,location=0,menubar=0');
					}
				}
				// NN4-Mac
				else 
				{
					nLeft -= 6;
					if (nScreenWidth - window.innerWidth < 200)
					{
						window.onunload=null;
						window.resizeTo(nLeft-12, nScreenHeight+2);
						window.onunload=destroyInstructions();
					}
					g_wndInstructions = window.open(docDir() + sPage,"instructions",'left=' + nLeft + ',width=' + nWidth + ',height=' + (nScreenHeight+2) + ',resizable=yes,scrollbars=1,toolbar=0,status=0,location=0,menubar=1');
				}
			}
		}
		// instructions frame already open
		else
		{
			g_wndInstructions.document.location.href = docDir() + sPage;
		}	
	}
}
// this function is only called on Mac IE or NN 6
function initInstructions(sPage)
{
	var nAdj = 0;
	if (sPage == "filler.html" || (g_asActivityPages.length == 0 && sPage == "filler.html")) sPage = "instructions.html";
	else nAdj = 286;

	var nScreenWidth = screen.availWidth;
	if (nScreenWidth > 1500) nScreenWidth = (nScreenWidth / 2) - 5;
	var nScreenHeight = screen.availHeight - 32;
	var nWidth = 280;
	var nLeft = nScreenWidth - nWidth - 6;

	// IE
	if (g_sBrowser == "IE")
	{
		// IE4-Mac
		if (g_fBrowserVersion < 5)
		{
			nScreenHeight = nScreenHeight + 7;
			nWidth = nWidth - 10;
			nLeft = nLeft + 13;
			g_wndInstructions = window.open(sPage,"instructions",'left=' + nLeft + ',width=' + nWidth + ',height=' + nScreenHeight + ',resizable=yes,scrollbars=1,toolbar=0,status=0,location=0,menubar=1');
			g_wndInstructions.resizeTo(nWidth, nScreenHeight);
			g_wndInstructions.moveTo(nLeft,42);
			window.resizeTo(nScreenWidth-(12 + nAdj),nScreenHeight);
			window.focus();
		}
		// IE5-MacOS
		else if (g_fBrowserVersion < 5.2)
		{
			window.moveTo(0,0);
			nScreenHeight = nScreenHeight + 7;
			nWidth -= 27;
			nLeft += 18;
			if (g_asActivityPages.length == 0 && sPage == "instructions.html") return;
			window.resizeTo(nLeft-12,nScreenHeight-21);
			g_wndInstructions = window.open(sPage,'instructions','left=' + nLeft + ',width=' + nWidth + ',height=' + nScreenHeight + ',resizable=yes,scrollbars=1,toolbar=0,status=0,location=0,menubar=1');
			window.focus();
		}
		// IE5-MacOSX
		else 
		{
			nScreenHeight += 7;
			nWidth -= 18;
			nLeft += 7;
			if (g_asActivityPages.length == 0 && sPage == "instructions.html") return;
			g_wndInstructions = window.open(sPage,'instructions','left=' + nLeft + ',width=' + nWidth + ',height=' + nScreenHeight + ',resizable=yes,scrollbars=1,toolbar=0,status=0,location=0,menubar=1');
			window.focus();
		}
	}
	// NN6
	else if (g_sBrowser == "NN")
	{
		window.resizeTo(nScreenWidth - nAdj,nScreenHeight + 32);
		if (g_asActivityPages.length == 0 && sPage == "instructions.html") return;
		g_wndInstructions = window.open(sPage,"instructions",'resizable=yes,top=0,left=' + nLeft + ',width=' + nWidth + ',height=' + nScreenHeight + ',scrollbars=1,toolbar=0,status=0,location=0,menubar=0');
		g_wndInstructions.resizeTo(nWidth+10, nScreenHeight + 32);
		setTimeout('window.focus()',500);
	}
	else alert("Unsupported browser: " + g_sBrowser + " " + g_sBrowserVersion + " for " + g_sOS);
}
function getCurrentActivity()
{
	if (g_nCurrentActivityIndex == -1) return "none";
	else return g_sWorkspaceDir + g_asActivityPages[g_nCurrentActivityIndex];
}
function displayCurrentActivity()
{
	loadCurrentActivity();
	setMaximized(false);
}
function displayHelp()
{
	displayInstructionPage(g_sHelpPage);
}
function displayLessonPlan() 
{
	displayInstructionPage(g_sTeacherPage);
}
function displayNCTMStandard()
{
	var nHeight = screen.availHeight * .9;
	var nWidth = screen.availHeight - 12;
	if (nWidth > 640) nWidth = 640;
	window.open(g_sNCTMURL,'nctm','resizable=yes,toolbar=0,status=0,location=0,menubar=0,scrollbars=1,width=' + nWidth + ',height=' + nHeight);
}
function returnToNavPages()
{
	if (g_wndInstructions != null && !g_wndInstructions.closed) destroyInstructions();

	if (opener && opener.closed == false)
	{
	   // Determine name of the page displayed by opener
	   curURL = opener.location.href;
	   pageName = getPageName(curURL);

	   // If it is the query page, determine whether to redirect
	   if (isQueryPage(pageName))
	   {
	      sPageLang = pageName.substring(pageName.length - 2);

	      // If language has changed, redirect to vlibrary. Otherwise, do nothing
	      if (sPageLang != g_sLanguage)
	      {
	         opener.location = "vlibrary.html";
	      }
	   }
	   else
	   {
	      // Redirect to the same page, but for the current language
	      urlPrefix = getUrlBeforeLanguage(curURL) + "/" + g_sLanguage + "/nav/";
	      //urlPrefix = "../../" + g_sLanguage + "/nav/";
	      newURL = urlPrefix + pageName;

	      if (opener.location != newURL)
	      {
	         opener.location = newURL;
	      }
	   }

	   opener.focus();
	}
	else
	{
	   opener = window.open("vlibrary.html");
	}

	if (g_sOS == "Mac") window.close();
}
// called by saveconfig.html when a user has specified a config name and clicks the Save As button
function saveUserConfig(dlgWindow,sConfigName)
{
	// set the focus to ourselves
	window.focus();

	// if not running on Mac-NN close the save config dialog, now (Mac-NN crashes)
	if (!(!document.all && navigator.platform.indexOf('Mac') != -1)) dlgWindow.close();

	// get the name of the currently selected config
	sCurrentConfigName = frames.workspace.document.applets['save'].getUserConfigName();

	// if the current and the new config have same name, we are doing an update
	if (sCurrentConfigName == sConfigName) ret = frames.workspace.document.applets['save'].updateUserConfig();

	// otherwise we are creating a new one
	else ret = frames.workspace.document.applets['save'].createUserConfig(sConfigName);

	// successfully saved config
	if (ret == "ok")
	{
		// notify the user
		alert("Configuration saved.");

		// if config list isn't open yet, do so now
		setMaximized(false);
		
		// if not displaying an activity
		if (frames.workspace.document.applets['save'].getDisplayingActivity() == "false")
		{
			// ask the applet to refresh the activity list
			// JS in NN doesn't refresh the cache
			if (!document.all && (g_wndInstructions == null || g_wndInstructions.closed)) displayActivityList();
			else if (sCurrentConfigName != sConfigName) frames.workspace.document.applets['save'].refreshActivityList();	
		}
	}
	// failed to save config
	else alert("Unable to save configuration");

	// for some reason, we can now close Mac-NN without crashing	
	if (!document.all && navigator.platform.indexOf('Mac') != -1) dlgWindow.close();
}
function saveWorkspace()
{
	// NN6 and IE-Mac
	if ((!document.all && document.getElementById) || (document.all && navigator.platform.indexOf('Mac') != -1))
	{
		alert("saveWorkspace() should not be called on IE-Mac or NN6")
		return;
	}
	// Mac-NN must open the activity list before saving or will loose state by forced refresh
	if (!document.all && navigator.platform.indexOf('Mac') != -1 && (g_wndInstructions == null || g_wndInstructions.closed)) displayActivityList();

	// get the name of the current config
	sConfigName = frames.workspace.document.applets['save'].getUserConfigName();

	// open the save config HTML dialog
	if (!sConfigName || sConfigName == null) window.open("saveconfig.html","saveconfig",'resizable=no,top=200,left=200,width=340,height=100,scrollbars=0,toolbar=0,status=0,location=0,menubar=0');
	else window.open("saveconfig.html?" + sConfigName,"saveconfig",'resizable=no,top=200,left=200,width=340,height=100,scrollbars=0,toolbar=0,status=0,location=0,menubar=0');
}
function splitString(sString)
{
	var sArray = new Array("a","b");
	var nLength = sString.length();
	var nCommaPos = sString.indexOf(",");
	if (nCommaPos == -1)
	{

		sArray[0] = sString;
		sArray[1] = sString;
	}
	else
	{
		sArray[0] = sString.substring(0,nCommaPos);
		sArray[1] = sString.substring(nCommaPos + 1, nLength);
	}
	return sArray;
}
function deleteConfig(sConfigsName, sConfigFile, sConfigName, sConfigID)
{
	// verify that the user wants to delete
	if (confirm('Delete the ' + sConfigsName.toLowerCase() + ' named "' + sConfigName + '"?'))
	{
		// ask the controller to do the delete
		frames.workspace.document.applets['save'].deleteConfig(sConfigFile,sConfigID,"false");

		// deleting the currently selected config
		if (sConfigID == g_sSelectedConfigID)
		{
			g_sSelectedConfigID = "none";
			frames.workspace.document.applets['save'].clearWorkspace();
		}
		// notify the user and give the serlvet a chance to rewrite the activity list
		alert("Configuration deleted.");

		// ask the applet to refresh the activity list
		frames.workspace.document.applets['save'].refreshActivityList();
	}
}
function printWorkspace()
{
	// NN-Mac
	if (!document.all && navigator.platform.indexOf('Mac') != -1)
	{
		alert("Because of limited Java support on Netscape for the Mac, print functionality is not available on this platform. Please try Mac Internet Explorer.");
	}
	else
	{
		hwnd = window.open("", "_print");
		hwnd.document.location.href = "printmsg.html";
		frames.workspace.document.applets['print'].print(false,null);
	}
}
function selectConfig(sConfigID)
{
	if (document.all && navigator.platform.indexOf('Mac')==-1)
	{
		if (g_sSelectedConfigID != "none" && window.instructions.document.images["c" + g_sSelectedConfigID]) window.instructions.document.images["c" + g_sSelectedConfigID].src = "images/spacer.gif";
		if (window.instructions.document.images["c" + sConfigID]) window.instructions.document.images["c" + sConfigID].src="images/selected.gif";
	}
	else if (g_wndInstructions != null && !g_wndInstructions.closed)
	{
		if (g_sSelectedConfigID != "none" && g_wndInstructions.document.images["c" + g_sSelectedConfigID]) g_wndInstructions.document.images["c" + g_sSelectedConfigID].src = "images/spacer.gif";
		if (g_wndInstructions.document.images["c" + sConfigID]) g_wndInstructions.document.images["c" + sConfigID].src="images/selected.gif";
	}
	g_sSelectedConfigID = sConfigID;
}
function selectConfigByID(sConfigID)
{
	g_sSelectedConfigID = sConfigID;
}
function selectCurrentConfig()
{
	if (!g_bCanLoad) return;
	g_sSelectedConfigID = frames.workspace.document.applets['save'].getUserConfigID();
	if (g_sSelectedConfigID != "none") selectConfig(g_sSelectedConfigID);
}
function loadUserConfig(sConfigFile,sConfigID,sConfigName)
{
	loadConfig(sConfigFile,sConfigID,"true",sConfigName);
	selectConfig(sConfigID);
}
function destroyInstructions()
{
	if (g_wndInstructions != null && !g_wndInstructions.closed)
	{
		g_wndInstructions.onunload = null;
		g_wndInstructions.close();
	}
}
function docDir()
{
	var sDoc = new String(document.location);
	sDoc = sDoc.substring(0,sDoc.lastIndexOf("/")+1);
	return sDoc;
}
function navLanguage(box)
{
  // Determine selected language
  language = box.options[box.selectedIndex].value;

  // Determine page name
  curURL = window.location.href;
  pageName = getPageName(curURL);

  // Redirect to the same page, but for the selected language
  newURL = "../../" + language + "/nav/" + pageName;
  window.top.location = newURL
}
function getPageName(curURL)
{
  indexLastSlash = curURL.lastIndexOf("/");
  if (indexLastSlash == -1)
  {
    indexLastSlash = curURL.lastIndexOf("\\");
  }
  pageName = curURL.substring(1+indexLastSlash);

  return pageName;
}
function getUrlBeforeLanguage(curURL)
{
  for (i = 0; i < 3; i++)
  {
    indexLastSlash = curURL.lastIndexOf("/");
    if (indexLastSlash == -1)
    {
      indexLastSlash = curURL.lastIndexOf("\\");
    }
    curURL = curURL.substring(0, indexLastSlash);
  }

  return curURL;
}
function isQueryPage(pageName)
{
    return ("query.htm" == pageName.substring(0, 9));
}