//
// Define a list of Microsoft XML HTTP ProgIDs.
//
var XMLHTTPREQUEST_MS_PROGIDS = new Array(
  "Msxml2.XMLHTTP.7.0",
  "Msxml2.XMLHTTP.6.0",
  "Msxml2.XMLHTTP.5.0",
  "Msxml2.XMLHTTP.4.0",
  "MSXML2.XMLHTTP.3.0",
  "MSXML2.XMLHTTP",
  "Microsoft.XMLHTTP"
);

//
// Define ready state constants.
//
var XMLHTTPREQUEST_READY_STATE_UNINITIALIZED = 0;
var XMLHTTPREQUEST_READY_STATE_LOADING       = 1;
var XMLHTTPREQUEST_READY_STATE_LOADED        = 2;
var XMLHTTPREQUEST_READY_STATE_INTERACTIVE   = 3;
var XMLHTTPREQUEST_READY_STATE_COMPLETED     = 4;

//
// Returns XMLHttpRequest object.
//
function getXMLHttpRequest()
{
  var httpRequest = null;

  // Create the appropriate HttpRequest object for the browser.
  if (window.XMLHttpRequest != null)
    httpRequest = new window.XMLHttpRequest();
  else if (window.ActiveXObject != null)
  {
    // Must be IE, find the right ActiveXObject.
    var success = false;
    for (var i = 0;
         i < XMLHTTPREQUEST_MS_PROGIDS.length && !success;
         i++)
    {
      try
      {
        httpRequest = new ActiveXObject(XMLHTTPREQUEST_MS_PROGIDS[i]);
        success = true;
      }
      catch (ex)
      {}
    }
  }

  // Display an error if we couldn't create one.
  if (httpRequest == null)
    alert("Error in HttpRequest():\n\n"
      + "Cannot create an XMLHttpRequest object.");

  // Return it.
  return httpRequest;
}
var request = getXMLHttpRequest();

function updateManInfo( p, prefix )
{
	if ( !prefix )
		prefix = "m";
	document.getElementById( prefix+"Author" ).firstChild.nodeValue = p.author;
	document.getElementById( prefix+"RelId" ).firstChild.nodeValue = p.relId;
	document.getElementById( prefix+"AbsId" ).firstChild.nodeValue = p.absId;
	document.getElementById( prefix+"URL" ).value = "http://" + window.location.host + "/geosite/view.php?id=" + p.absId;
	document.getElementById( prefix+"Embed" ).value = '<iframe src="http://' + window.location.host + '/geosite/lx/GeometryEditor/server/getMan.php?id=' + p.absId + '&type=page" style="overflow:hidden" width="' + p.data.width + '" height="' + p.data.height + '" frameborder="0" marginwidth="0px" marginheight="0px" scrolling="no"></iframe>';
	document.getElementById( prefix+"DataURL" ).value = "http://" + window.location.host + '/geosite/lx/GeometryEditor/server/getMan.php?id=' + p.absId;
}

function createManInfoHTML( prefix )
{
	return '<div class="manInfo"><h3 style="color:#003399">About this manipulative:</h3><table><tr><td>Author:</td><td id="' + prefix 
			+ 'Author">&nbsp;</td></tr><tr><td>Relative&nbsp;ID:</td><td id="' + prefix 
			+ 'RelId">&nbsp;</td></tr><tr><td>Absolute&nbsp;ID:</td><td id="' + prefix 
			+ 'AbsId">&nbsp;</td></tr><tr><td>URL:</td><td><input id="' + prefix 
			+ 'URL" size="30" value="" /></td></tr><tr><td>Embed:</td><td><input id="' + prefix 
			+ 'Embed" size="30" value="" /></td></tr><tr><td>Data&nbsp;URL:</td><td><input id="' + prefix
			+ 'DataURL" size="30" value="" /></td></tr></table></div>';
}

// randomId: lxSection's id
// randomId+'Instance': editor's div id
// randomId+'manName': the left cell showing the manipulative's name
// randomId+'info': the div on the right cell containing the man info
// each field in the man info has the randomId as the prefix

//xun
function createManHTML( randomId, manName )
{
	return '<div><span id="' + randomId + 'manName" class="manName">'+manName+'</span></div><div id="' + (randomId+'Instance') + '"></div>';
	// display:inline in the table style will make the menu not work
	var s = '<table style="margin:0px; padding:0px; vertical-align:-40%; border:0px" border="0" cellpadding="0" cellspacing="0"><tbody><tr><td style="vertical-align:top"></td><td style="vertical-align:top"><div><span id="' + randomId + 'manName" class="manName">'+manName+'</span></div><div id="' + (randomId+'Instance') + '"></div></td><td style="vertical-align:top;"><img src="img/arrowbright.gif" id="'+randomId+'img" onclick="expandInfo(\''+randomId+'\')" />'
			+ '<div style="display:none" id="' + randomId + 'info">' + createManInfoHTML( randomId ) + '</div>'
			+ '</td></tr></tbody></table>';
	return s;
}

function updatePageInfo( p )
{
	document.getElementById( "pAuthor" ).firstChild.nodeValue = p.author;
	document.getElementById( "pRelId" ).firstChild.nodeValue = p.relId;
	document.getElementById( "pAbsId" ).firstChild.nodeValue = p.absId;
	document.getElementById( "pURL" ).value = "http://" + window.location.host + "/geosite/view.php?id=" + p.absId;
	document.getElementById( "pEmbed" ).value = '<iframe src="http://' + window.location.host + '/geosite/view.php?simple=&id=' + p.absId + '" style="overflow:auto" width="800" height="600" frameborder="0" marginwidth="0px" marginheight="0px" scrolling="auto"></iframe>';
//	document.getElementById( "pDataURL" ).value = "http://" + window.location.host + '/geosite/tools/GeometryEditor/server/getMan.php?id=' + p.absId;
}



function FolderInfo()
{
	this.author = null;
	this.relId = null;
	this.name = null;
	this.trId = null;
}


function PageInfo()
{
	this.author = null;
	this.relId = null;
	this.absId = null;
	this.name = null;
	this.trId = null;
	this.data = null;
	this.isGeneralPage = true;
}
PageInfo.thePage = null;	

function ManInfo() 	// inherited form LXInfo
{
	this.data = null;
	this.relId = null;
	this.absId = null;
	this.name = null;
	this.trId = null;
	this.containers = [];
	this.containerIds = [];
	this.editors = [];
	this.isMan = true;
	this.isFocusMan = false;
	this.local = true;
}
ManInfo.arr = {};
ManInfo.theMan = null;
ManInfo.getManInfo = function( id ) {
	return ManInfo.arr[id];
};
ManInfo.newManInfo = function( absId ) {
	var t = new ManInfo();
	t.absId = absId;
	ManInfo.arr[absId] = t;
	return t;
};


// xun: need fix for relative id too
ManInfo.requestManData = function( ids, callback, scope )
{
	var req = getXMLHttpRequest();

  	var url = "./ajaxgetman.php?ids=" + ids.join(",");

  	req.onreadystatechange = function()
	{
		var i, t, p;

		if ( req.readyState == XMLHTTPREQUEST_READY_STATE_COMPLETED )
		{
			try
  			{
    			t = req.responseText;
    			t = eval( "("+t+")" );
    			var retIds = [];
   				for ( i=0; i<t.length; i++ ) {
   					var d = t[i];
   					p = ManInfo.arr[d.absId];
   					if ( !p )
   						p = ManInfo.newManInfo(d.absId);
   					p.data = d.data;
					p.author = d.author;
                    p.relId = d.relId;
					retIds.push( d.absId );
   				}
				if ( callback ) 
					scope ? scope[callback]( retIds ) : callback( retIds );
				
				/*
				for ( i=0; i<p.containers.length; i++ )
				{
					var em = new GeometryEditor( {instanceName: p.containerIds[i]} );
					p.editors.push( em );
					em.create( { renderTo: p.containerIds[i],
						data: p.data,
						dom: true,
						callback: GeometryEditor_OnCreateDone
					} );
				}
				*/
			}
			catch (e)
			{
				// don't alert: may show "syntax error"
				//alert(e.message)
			}
		}
	};

  	req.open( "GET", url, true );
  	req.send(null);

};


function normalizeRelId( relId )		// handle '/'
{
	return;
}

function checkAndUnescape( s )
{
	var t = document.getElementById( s );
	if ( t.value == "" )
		return false;
	t.value = unescape( t.value );
	return true;
}

lxRandomString = function( len ) 
{
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var strlen;
	if ( len )
		strlen = len;
	else
		strlen = 8;
	var t1, t2 = '';
	for ( var i=0; i<strlen; i++ ) 
	{
		t1 = Math.floor( Math.random() * chars.length );
		t2 += chars.substring( t1, t1+1 );
	}
	return t2;
};



function isFileNameLegal( name )
{
	if ( !/^(\w|\ )+$/.test(name) ) 		// \w Any word character [a-zA-Z0-9_]
	{
		alert( "Name can only contain letters, digits, underscore, or space!" );
		return false;
	}
	if ( name.charAt(0) == ' ' || name.charAt( name.length-1 ) == ' ' )
	{
		alert( 'Name cannot start or end with a space' );
		return false;
	}
	if ( name.length >= 60 )
	{
		alert( "A file or folder name can have at most 60 characters!" );
		return false;
	}
	if ( name == "submission" )
	{
		alert( 'Name "submission" is reserved' );
		return;
	}
	return true;
}


function isNameLegal( name )
{
	if ( !/^(\w|\ )+$/.test(name) ) 		// \w Any word character [a-zA-Z0-9_]
	{
		alert( "Name can only contain letters, digits, underscore, or space!" );
		return false;
	}
	if ( name.charAt(0) == ' ' || name.charAt( name.length-1 ) == ' ' )
	{
		alert( 'Name cannot start or end with a space' );
		return false;
	}
	if ( name.substr( 0, 9 ).toLowerCase() == "anonymous" )
	{
		alert( 'Name starting with "anonymous" is not allowed' );
		return false;
	}
	var i, t=name.toLowerCase();
	for ( i=0; i<foo.literals.length; i++ )
		if ( t == foo.literals[i] )
		{
			alert( 'Name "' + name + '" is reserved!' );
			return;
		}
	return true;
}


function showStatus( msg, s )
{
	var el = document.getElementById( "status" );
	if ( !el )
		return;
	el.firstChild.nodeValue = msg;
	if ( !s )
		setTimeout( "showStatus(statusStr[mode],true)", 2500 );
	else
	{
		if ( window.recoverThings ) 
			recoverThings();
	}
}

function GeometryEditor_errorReport( iName, msg )
{
	var i='NA';
	if ( window.lxEditors )
		for ( i in lxEditors )
			if ( lxEditors[i].instanceName == iName )
				break;
	lxErrRpt( i, msg );
}

function pageError( e, t )
{
	var t1 = (t==null)?"":t, s = t1 + " " + e.message + " " + e.name + " " + e.lineNumber + " " + e.fileName + " " + e.stack;
	lxErrRpt( 'NA', s );	
}
	
var LX_ERROR_REPORTED=false;
function lxErrRpt( manName, msg )
{
	if ( LX_ERROR_REPORTED )
	{
		return;
	}

	LX_ERROR_REPORTED = true;
	var s = "System error happened. It has been reported to the administrator.";
	showStatus( s, true );
	alert( s );
alert(msg);
	var d = encodeURIComponent(msg),
		id=PageInfo.thePage?PageInfo.thePage.absId:(ManInfo.theMan?ManInfo.theMan.absId:null);
  	request.onreadystatechange = function() {};
  	var url = "/geosite/ajaxerrrpt.php?id=" + id + '&manname=' + manName + '&mode=' + mode;
  	request.open( "POST", url, true );
  	request.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
  	request.send("data="+d);	
}



