google.load("earth", "1", {
	'other_params' : 'sensor=false'
});
var tt = window.tt || {}; // application global
//var gex = null;
//var ge = null;

var geocoder;
var truck;

var ttReady;  //shortcut
$(document).ready( function() {

	//geocoder = new GClientGeocoder();  //NOTE not sure where this resides
	
	//GLOBALS SET
	tt.cg.modimg = "http://media.mytimetrails.com/modimg/";
	tt.cg.appimg = "http://media.mytimetrails.com/appimg/";
	tt.cg.pdfimg = "http://media.mytimetrails.com/pdfimg/";
	tt.cg.mapimg = "http://media.mytimetrails.com/mapimg/";
	// RPX login
	tt.cg.currentRpxTokenUrl = (tt.cg.alpha == "1" ? "http%3A%2F%2Flocalhost%3A8080%2FTimeTrails%2Fid"
			: "http%3A%2F%2Fdemo.mytimetrails.com%2Fid");
	// $(window).bind('resize', function () {}
	
	// Unit Testing
	//if(tt.cg.alpha == "1") tt.UnitTestSuite();
	
	//UTILITY CONTROL ICONS
	tt.makeControlSpace.ResetCtrlIcons();
	
	  $(".ctrlIconDiv").mouseover(function ()
	  {
		  tt.makeControlSpace.SetCtrlIcon(this,"Hover");
	  });

	  $(".ctrlIconDiv").mouseout(function ()
	  {
		  tt.makeControlSpace.SetCtrlIcon(this,"Normal");
	  });

	  $(".ctrlIconDiv").mousedown(function ()
	  {
		  tt.makeControlSpace.SetCtrlIcon(this,"Compressed");
	  });

	  $(".ctrlIconDiv").mouseup(function ()
	  {//empty
	  });

	  $(".ctrlIconDiv").click(function ()
	  {//empty
	  });
	
	//DIALOG
    $("#dialog_ui").dialog({
    	dialogClass : 'ui-dialog',
    	draggable: false,
    	autoOpen : false,
    	position: [20,150],
    	width: 100,
    	maxWidth: 100,
    	//title: 'Title',
    	//buttons: { "Ok": function() { $(this).dialog_ui("close"); } },
    	show: 'none',
    	hide: 'none',
    	bgiframe: true
    	});
   

	
	//LAYOUT	
	tt.makeLayout.InitLayout();	
	if(tt.cg.permitLevel()>1) {
		tt.makeLayout.InitTabs();
	}
	tt.makeFisheye.InitializeFisheye();


	//DRAG EVENTS
	//NOTE - generalize this to attach to any el and move to utilit
	$('#timeCircleBox').mousedown(function(e){
		tt.cg.circleBoxDownX = e.pageX;
		tt.cg.circleBoxDownY = e.pageY;
	});
	
	$('#timeCircleBox').mouseup(function(e){
		var offset_x =e.pageX - tt.cg.circleBoxDownX;
		var offset_y =e.pageY - tt.cg.circleBoxDownY;
		if(offset_x && offset_y) {
			tt.timesel.DragLimits(offset_x,offset_y);
		}
	});

	//SLIDER RANGE
	 $('#sliderTimeSpan').slider( {
		 //accept : '.indicator',
		 //restricted: true,
		 //opacity: 0.6,
		 range : true,
		 min : 0,
		 max : 100,
		 values : [ 0, 100 ],
		 stop : function(event, ui) {
		 	tt.timesel.HandleTimeSlider(ui.values[0], ui.values[1]);}
	 });
	 
	 
	//TEXT DISABLING
	$.extend($.fn.disableTextSelect = function() {
		return this.each(function(){
			if($.browser.mozilla){//Firefox
				$(this).css('MozUserSelect','none');
			}else if($.browser.msie){//IE
				$(this).bind('selectstart',function(){return false;});
			}else{//Opera, etc.
				$(this).mousedown(function(){return false;});
			}
		});
	});

	$('#timeCircleBox').disableTextSelect(); 	
	 
	
	 //FINAL ACTIONS
	 // set intitial time span
	 tt.timesel.Initialize();
		
	 google.earth.createInstance('map3d', initCB, failureCB);
	 
	
});

/*
 * Current Globals - simple public singleton for current globals
 * 
 * @author ktyson
 * 
 */

var ttCurrentGlobals; //shortcut
tt.cg = {
	//Server storage mappings
	appimg : null,
	modimg : null,
	// drag tracking
	circleBoxDownX : null,
	circleBoxDownY : null,
	//Map feature vars
	coordset : null,
	square : null, //square
	point : null,
	line : null,
	latitude : null,
	longitude : null,
	altitude : null,
	circles : [], //set of polygon circle features
	points : [], //set of point PMs
	mouseIsDraggy : false,
	catchDelete : false, //stinkin hack
	mouseClickCutoff : 300, //milliseconds
	featureName : null,
	featureDesc : null,
	featurePos : null,

	//base
	currentRpxTokenUrl : "",
	topickeywords : "",
	topicname : "",
	requestedKML : null,
	themeList : null,
	currentLat : 0,
	currentLon : 0,
	dragInfo : null,
	//xmlhttp : null,

	resourcesRequested : null, //obj stores all resources that match
	resourcesTimelined : null,
	resourcesAvacled : null,
	resStartIndex  : 0,
	resStopIndex : 8,
	resTotalFound : 0,
	resMatchType : "",
	
	playspaceOpen : false,
	fisheyeOpen : false,
	playspaceSelected : false,
	resourcesClicked : [],	
	resourcesLength : 0, //length of selected category
	utilityType : "", //string tracking the current utility display type
	checkedThemes : "", //string to hold the checked elems
	requestedHelp : "Help_0.0", //string holding current help
	help : null, //object holding json current help
	forum : null, //object holding json current messages
	currentThread : "",
	helpList : new Object(),
	topics : null,

	//layout
	layout : null,
	activeCtrl : "None",

	//animation
	featuresIn : new Object(),
	styleList : new Object(),

	//permit and version
	CurrentEmail : "",
	CurrentPermit : "",
	alpha : 1, //0 = Beta demo mode   1 = Alpha test log mode	
	permitLevel : function() {
		var result = 0; // guest
	switch (tt.cg.CurrentPermit) {
	case "user":
		result = 1;
		break;
	case "author":
		result = 2;
		break;
	case "admin":
		result = 3;
		break;
	}
	return result;
}

};


/*
 * Init and Fail Callbacks for GE
 * 
 */


function initCB(object) {
	ge = object;
	gex = new GEarthExtensions(ge);
//("init gex");	
	ge.getWindow().setVisibility(true);
	ge.getOptions().setStatusBarVisibility(true);
		
	var navControl = ge.getNavigationControl();
	navControl.setVisibility(ge.VISIBILITY_SHOW);

	
	
	tt.makeControlSpace.ShowLogo(0,0);

	// listen for mouseup on the window or globe

	/*
	 * google.earth.addEventListener(ge.getWindow(), 'dblclick', function(event) {
	 * ("dblclick"); event.preventDefault();
	 * 
	 * });
	 */

	google.earth.addEventListener(ge.getWindow(), 'dblclick', function(event) {
		event.preventDefault();
	});

	google.earth.addEventListener(ge.getGlobe(), 'click', function(event) {
		event.preventDefault();
	});

	google.earth.addEventListener(ge.getWindow(), 'mouseup', function(event) {

		//deBugClog("3dmap","mouseup");

			var hitTestResult = ge.getView().hitTest(event.getClientX(),
					ge.UNITS_PIXELS, event.getClientY(), ge.UNITS_PIXELS,
					ge.HIT_TEST_GLOBE);

			if(event.getClientX() < 120 && event.getClientY() < 120)
			{
				//may be a time ctrl request
				tt.makeControlSpace.ActivateTimeControl(event.getClientX(),event.getClientY());
			} 
			else if (hitTestResult) 
			{
				tt.cg.latitude = hitTestResult.getLatitude();
				tt.cg.longitude = hitTestResult.getLongitude();
				tt.cg.altitude = hitTestResult.getAltitude() || 0;

				// deBugClog("3dmap","clear drag " + tt.cg.mouseIsDraggy + " " +
				// new Date().getTime());
			clearTimeout();

			if (tt.cg.mouseIsDraggy === false) // normal click
			{
				//deBugClog("3dmap","mouse " + event.getButton());	

				if (event.getButton() === 0) // left click
				{
					//deBugClog("3dmap","FeatureMode " + tt.feature.FeatureMode());

					if (!tt.feature.FeatureMode()) // featuremode is null - not
													// an edit
					{
						deBugClog("3dmap", "at mouseup " + tt.cg.featureName+ " , "+tt.cg.featureDesc );
						
						tt.makeFisheye.PopulateFisheye();
						
						tt.makePlayspace.AddToyFromFeat(tt.cg.featurePos);
				
											
					} else // featuremode is active
					{
						//deBugClog("3dmap","editMode on " + tt.feature.EditModeOn());	
						if (tt.feature.EditModeOn()) // an add edit
						{
							//make the edit
							tt.feature.AddPointToFeature();
						} else {
							//handle deletes
							if (tt.cg.catchDelete) {
								tt.cg.catchDelete = false;
							} else {
								//add and draw					
								tt.feature.DrawFeatures(false);
							}
						}
					}
				} else if (event.getButton() === 2) // 0 = left, 1 = mid, 2 =
													// right
				{
					// right-click request for resources
				}
			} //mouse was used to drag

			tt.cg.mouseIsDraggy = false;
		}
	});
	// listen for mousedown on the window (look specifically for point
	// placemarks)
	google.earth.addEventListener(ge.getWindow(), 'mousedown', function(event) {
		//start the draggy timer
			tt.cg.mouseIsDraggy = false; // assume no drag
			setTimeout(( function() {
				tt.cg.mouseIsDraggy = true;
			}), tt.cg.mouseClickCutoff);
			// deBugClog("3dmap","set drag " + tt.cg.mouseIsDraggy + " " + new
			// Date().getTime());

			// test to see if user clicked a named feature
			tt.cg.featureName = null;
			tt.cg.featureDesc = null;
			tt.cg.featurePos = null;
			if (event.getTarget().getType() == 'KmlPlacemark') {
				tt.cg.featureName = event.getTarget().getName() || null;
				tt.cg.featurePos = event.getTarget().getDescription() || null;
			}

			deBugClog("3dmap", "at mousedown " + tt.cg.featureName);
			// deBugClog("3dmap","event info: " + event.getTarget().getType() +
			// " " + event.getTarget().getGeometry().getType());

		});

	// listen for mousemove on the globe
	google.earth.addEventListener(ge.getGlobe(), 'mousemove', function(event) {
		//drawContinuousLine(event);
		});
}

function failureCB(object) {
	('Google Earth Plugin load failed');
}




/*
 * Controller for timeline
 * 
 * @name timesel
 * @function
 * @param 
 */

var ttTimeselector; //shortcut
tt.timesel = ( function() {

	//private attributes in closure
	var initializing = false;
	
	var outerStartLimit = null;
	var outerEndLimit = null;
	var outerStartLimitDefault = isoToDate("-3700-01-01");
	var outerEndLimitDefault = isoToDate("2010-01-01");
	var startFrozen = false;
	var endFrozen = false;

	var currentStartDate;
	var currentEndDate;
	
	var timeCircleHeight = 50;  //supposed to be timeline ht
	
	var timeAccelerationFactor = 1;

	//time increments in milliseconds
/*	var y_500 = 1.577e13;
	var y_100 = 3.154e12;
	var y_10 = 3.154e11;
	var y_1 = 3.154e10;
	var d_30 = 2.628e9;
	var d_1 = 8.64e7;
	var m_60 = 3.6e6;
	var m_1 = 60000;
*/
	//make an array of time increment objects
	var timeIncrements = [];
	var timeInc = {};
	var timeIncGreater = {};
	var timeIncLesser = {};
	timeIncrements.push(
			{name : "half-millenium", 
				mSecs : 1.577e13,
				dateFormat : "YYYY",
				tickColor : "#ff00ff"}); // purple
	timeIncrements.push(
			{name : "century", 
				mSecs : 3.154e12, 		
				dateFormat : "YYYY",
				tickColor : "#0000ff"}); // blue
	timeIncrements.push(
			{name : "decade", 
				mSecs : 3.154e11,
				dateFormat : "YYYY",
				tickColor : "#00ffff"}); //aqua
	timeIncrements.push(
			{name : "year", 
				mSecs : 3.154e10,
				dateFormat : "YYYY",
				tickColor : "#00ff00"}); // green
	timeIncrements.push(
			{name : "month", //30 days
				mSecs : 2.628e9,
				dateFormat : "YYYY-mm",
				tickColor : "#ffff00"}); // yellow
	timeIncrements.push(
			{name : "day", 
				mSecs : 8.64e7,
				dateFormat : "DD",
				tickColor : "#ff0000"}); // red
	timeIncrements.push(
			{name : "hour", 
				mSecs : 3.6e6,
				dateFormat : "HH",
				tickColor : "#ffffff"}); //white
	timeIncrements.push(
			{name : "five-minute", 
				mSecs : 60000 * 5,
				dateFormat : "MM",
				tickColor : "#f0f0f0"}); //gray

	
	// private methods in closure	
	
	function handleTimeSlider(startPercent, endPercent){
		

		var totalTimeSpan = outerEndLimit.getTime() - outerStartLimit.getTime();
		var newStartDateTime = outerStartLimit.getTime() + (totalTimeSpan * (startPercent/100));
		var newEndDateTime = outerStartLimit.getTime() + (totalTimeSpan * (endPercent/100));
		var newStartDate = new Date(newStartDateTime);
		var newEndDate = new Date(newEndDateTime);
		var startString = dateToISO(newStartDate,"YYYY-mm-DD");
		var endString = dateToISO(newEndDate,"YYYY-mm-DD");
		
		setLimits( [ 0, 0 ], startString, endString);
		
	}
	
	function setTimeSlider(){
	
		var totalTimeSpan = outerEndLimit.getTime() - outerStartLimit.getTime();
		var startPercentDecimal = (currentStartDate.getTime() - outerStartLimit.getTime()) 
			/ totalTimeSpan;
		var endPercentDecimal = (currentEndDate.getTime() - outerStartLimit.getTime())
			/ totalTimeSpan;
		var startPercent = Math.floor(startPercentDecimal * 100);
		var endPercent = Math.floor(endPercentDecimal * 100);
		if(startPercent < 0) startPercent = 0;
		if(startPercent > 100) startPercent = 100;
		if(endPercent < 0) endPercent = 0;
		if(endPercent > 100) endPercent = 100;
deBugClog("timesel", "startPercentDecimal " + startPercentDecimal +" endPercentDecimal "+ endPercentDecimal
		+ " startPercent " + startPercent + " endPercent " +  endPercent);	

		$("#sliderTimeSpan").slider("values", 0, [startPercent]);
		$("#sliderTimeSpan").slider("values", 1, [endPercent]);

	}
	
	
	
	function resetTimeFactors(){
		// pick a time tick interval
		var span = currentTimeSpan();
		
		for(i = 0; i < timeIncrements.length; i++){		
			if(span > timeIncrements[i].mSecs){
				timeIncGreater = (i > 0 ? 
						timeIncrements[i - 1] : timeIncrements[i]);
				timeIncLesser= (i < timeIncrements.length - 1 ? 
						timeIncrements[i + 1] : timeIncrements[i]);
				timeInc = timeIncrements[i];
				break;
			}		
		}

deBugClog("timeselxxx", " span " + span + 
		" timeIncrements.length " + timeIncrements.length +
		" timeInc.name  " + timeInc.name + 
		" timeInc.mSecs  " + timeInc.mSecs + 
		" dateFormat " + timeInc.dateFormat + 
		" tickColor " + timeInc.tickColor +
		" timeIncGreater.name  " + timeIncGreater.name  + 
		" timeIncLesser.name  " + timeIncLesser.name +
		" timeIncLesser.mSecs  " + timeIncLesser.mSecs);
		
		
	}
	

	function toggleDateLimit(which) {
		if(which === 0) {//start was toggled
			if(startFrozen){ // start is already frozen
				setDateLimit(0);
				startFrozen = false;
			}else{
				startFrozen = true;
			}			
		} else { //end was toggled
			if(endFrozen){ // already frozen
				setDateLimit(1);
				endFrozen = false;
			}else{
				endFrozen = true;
			}
		}
		setLimits( [ 0, 0 ]);
	}

	function setDateLimit(which) {
		var whichSide = (which===0 ? "Start" : "End");
		var yearEntered = parseInt(prompt("Set " + whichSide + " Year:"));
		if(yearEntered){			
			if(yearEntered > -3700 && yearEntered < 2100){		
				if(which === 0) {//start was entered
					setLimits( [ 0, 0 ], yearEntered + "-01-01");
				} else { //end
					setLimits( [ 0, 0 ], null, yearEntered + "-01-01");
				}
				
			} else { //bad entry
				("Enter a year between -3700 and 2100");
			}
		}
	}
	
	function msecToPixelRatio() {
		return currentTimeSpan() / timeLineWidth();
	}
	
	function timeLineWidth() {
		return parseInt($(window).width() * 0.9);
	}

	function currentTimeSpan() {
		var result = currentEndDate.getTime() - currentStartDate.getTime();
		return result;
	}
	function currentTimeRatio() {
		var c = currentTimeSpan();
		var l = outerEndLimitDefault.getTime()
				- outerStartLimitDefault.getTime();
		return c / l;
	}
	function timeRatioPixelHt() {
		var n = currentTimeRatio(); //time shown to time possible
		var h = timeCircleHeight; // pixels - set above
		return Math.ceil((h * (1 - n)));
	}
	
	function timeRatioPixelWid() {
		var n = currentTimeRatio(); //time shown to time possible
		var h = 30; // variable height
		var m = 20; // minimum ht
		return m + Math.ceil((h * (1 - n)));		
	}

	function marginDiff() {
		var halfHt = Math.floor(timeCircleHeight / 2);
		return Math.floor(timeCircleHeight / 2 - (timeRatioPixelHt()) / 2);

	}

	function writeTimeScale() {

		// resize time horizon line
		$("#timeCircleBoxLiner").css("height", timeRatioPixelHt());
		$("#timeCircleBoxLiner").css("border-color", timeInc.tickColor);

		// write the limit dates
//		$("#startDateLimit").html(
//				dateToISO(currentStartDate, timeInc.dateFormat).toString());
//		$("#endDateLimit").html(
//				dateToISO(currentEndDate, timeInc.dateFormat).toString());

//deBugClog("timesel", "tickIntervalPixels : " + tickIntervalPixels);

		var tlA = []; //timeline array
		
		var numMainTicks = Math.ceil(msecToPixelRatio() 
				/ timeInc.mSecs * timeLineWidth());
		var pixelFirstMainTick = (Math.ceil(currentStartDate.getTime(),timeInc.mSecs) 
			- currentStartDate.getTime())
			/ msecToPixelRatio();
		var numMinorTicks = Math.ceil(msecToPixelRatio() 
				/ timeIncLesser.mSecs * timeLineWidth());
		var pixelFirstMinorTick = (Math.ceil(currentStartDate.getTime(),timeIncLesser.mSecs) 
			- currentStartDate.getTime())
			/ msecToPixelRatio();
		
deBugClog("timesel", "numMainTicks " + numMainTicks +  
		" pixelFirstMainTick " + pixelFirstMainTick +  
		" numMinorTicks " + numMinorTicks +  
		" pixelFirstMinorTick " + pixelFirstMinorTick);

		for(i = 0; i < numMinorTicks; i++)
		{
			var tickPixel = Math.floor(pixelFirstMainTick + (i * timeIncLesser.mSecs / msecToPixelRatio()));
			var tickDate = new Date(currentStartDate.getTime()
						+ ((i  * timeIncLesser.mSecs))); 
			var tickDateLabel = dateToISO(tickDate, timeIncLesser.dateFormat,true);
			
			if(i === numMinorTicks - 1){ //last Minor = last Major
				tickDateLabel = dateToISO(tickDate, timeInc.dateFormat, true);
				tlA.push("<span class='minorTick' id='dtmm" + i + "' title='" + tickDateLabel + "' "
						+ "style='left:" + tickPixel 
						+ "px;color:" + timeInc.tickColor + ";'>|</span>");
				
				tlA.push("<span class='mainTickLabel' id='dtll" + i + "' style='left:" 
						+ (tickPixel + 4) + "px;'>"
						+ tickDateLabel + "</span>");
				
			} else {
				tlA.push("<span class='minorTick' id='dtmm" + i + "' title='" + tickDateLabel + "' "
						+ "style='left:" + tickPixel 
						+ "px;color:" + timeIncLesser.tickColor + ";'>.</span>");
			}
		}		
		
		for(i = 0; i < numMainTicks; i++)
		{
			
			var tickPixel = Math.floor(pixelFirstMainTick + (i * timeInc.mSecs / msecToPixelRatio()));
			var tickDate = new Date(currentStartDate.getTime()
						+ ((i  * timeInc.mSecs))); 
			var tickDateLabel = dateToISO(tickDate, timeInc.dateFormat,true);
			if(i===0 && timeInc.mSecs <= 8.64e7){//first tick and less than day
				//show a full date
				tlA.push("<span class='mainTickLabel' id='dayDate'" 
						+ "style='left:" + tickPixel 
						+ "px;color:" + timeInc.tickColor 
						+ ";'>" + dateToISO(currentStartDate, "YYYY-mm-DD",true) + "</span>");			
			}else{				
				tlA.push("<span class='mainTick' id='dtm" + i + "' "
						+ "style='left:" + tickPixel 
						+ "px;color:" + timeInc.tickColor 
						+ ";'>|</span>");
				
				tlA.push("<span class='mainTickLabel' id='dtl" + i + "' style='left:" 
						+ (tickPixel + 4) + "px;'>"
						+ tickDateLabel + "</span>");
			}
		}

		lineScale = tlA.join("");
		
//deBugClog("timesel", "scale HTML : " + lineScale);
		$("#timeScale").html(lineScale);

	}

	
	function writeResImages()
	{
//(timeRatioPixelWid());
		if (tt.cg.resourcesTimelined === null) {
			tt.getResources.SendAjax("resImage");
		}
		var myImages = "";
		$("#imgResources").empty();
		var usedZones = [];  //array to track timeline zones already used for icons
//(tt.cg.resourcesTimelined.resources.length);
		if(tt.cg.resourcesTimelined.resources){
			for(i=0; i < tt.cg.resourcesTimelined.resources.length; i++){
	
				var r = tt.cg.resourcesTimelined.resources[i]; 
				
				var inUsedZone = false;
				// determine if the res img is included in the current interval
				// the resource start and end dates
				var startDatePic = isoToDate(r.StartDate); //returns a Date object
				var endDatePic = isoToDate(r.EndDate); //returns a Date object
				var centerDatePic = new Date();
				centerDatePic.setTime(startDatePic.getTime()
						+ ((endDatePic.getTime() - startDatePic.getTime()) / 2)) //returns a Date object;	
				var imgPxl=parseInt(Math.abs(currentStartDate.getTime() - centerDatePic.getTime() )
						/ msecToPixelRatio());	
				var imgWid=timeRatioPixelWid();
	
				if (centerDatePic.getTime() > currentStartDate.getTime()  && centerDatePic.getTime()  < currentEndDate.getTime() ) {
					
					for(var x = 0; x < usedZones.length; x++)
					{
	//("imgPxl " + imgPxl + " usedZone " + usedZones[x]);
						if(Math.abs(imgPxl - usedZones[x]) < imgWid){
							inUsedZone = true;
						}			
					}
					if(!inUsedZone){
					
					myImages += '<img class="resImage" onclick="tt.makePlayspace.AddToyFromRes('
						+ i + ',this);" src="'+r.Image.replace(".jpg","000.png")
					+'" style="left:' + imgPxl + 'px;height:'+ imgWid + 'px;"></img>';
	//deBugClog("toy", " Resource : " + r.Resource);				
	//deBugClog("timesel", " Name : "+r.Name+ " ctrDate : " + centerDatePic+" imgPxl : "+imgPxl+", StartDate: "+r.StartDate+", Enddate: "+r.EndDate+ " Image: "+r.Image.replace(".jpg","000.png")/*+ "ISO date : "+ dateToISO(centerDatePic,"YYYY-mm")*/);
	//					myImages += '<img class="resImage" onclick="tt.makePlayspace.AddToy(\''
	//						+r.Image.replace(".jpg","") +'\',\'Model3D\');" src="'+r.Image.replace(".jpg","000.png")
	//						+'" style="left:' + imgPxl + 'px;height:'+ imgWid + 'px;"></img>';	
						//width:' + imgWid +'px
	//							myImages += '<img class="resImage" onclick="tt.makePlayspace.DisplayResImage(\''
	//								+r.Image.replace(".jpg","00.png")+'\');" src="'+r.Image.replace(".jpg","000.png")
	//								+'" style="left:' + imgPxl + 'px;"></img>';	
						
						usedZones.push(imgPxl);				
					}
				}
			}
			//(myImages);
			$("#imgResources").append(myImages);
		}
	}
	
	function dragLimits(offset_x,offset_y)
	{
		//("offset_x " + offset_x + " offset_y " + offset_y);
		timeAccelerationFactor = 1;
		if(offset_x > (timeLineWidth() / 5)){
			timeAccelerationFactor = 2;
		} else if(offset_x > (timeLineWidth() / 4)){
			timeAccelerationFactor = 3;
		} else if(offset_x > (timeLineWidth() / 3)){
			timeAccelerationFactor = 4;
		} else if(offset_x > (timeLineWidth() / 2)){
			timeAccelerationFactor = 5;
		}
		
		
		if(Math.abs(offset_y) > Math.abs(offset_x)){
			//expandTime or contractTime
			if(offset_y > 0){// pull down - contractTime
				setLimits([1,-1]);
			}else{ //pull up - expandTime
				setLimits([-1,1]);
			}
		} else {
			//backTime or forwardTime
			if(offset_x > 0){//pull left - backTime
				setLimits([-1,-1]);
			} else { // pull right - forwardTime
				setLimits([1,1]);
			}
		}
	}

	function setLimits(limits, startDate, endDate) {
		
		if (startDate)
			currentStartDate = isoToDate(startDate);
		if (endDate)
			currentEndDate = isoToDate(endDate);

		outerStartLimit = outerStartLimitDefault;
		outerEndLimit = outerEndLimitDefault;

		resetTimeFactors();
		var changeFactor = (timeInc.mSecs ? timeInc.mSecs : 0);
		var addToStart = parseFloat(limits[0]) * changeFactor * timeAccelerationFactor;
		var addToEnd = parseFloat(limits[1]) * changeFactor * timeAccelerationFactor;
		$("#startDateLimit").css("color", "white");
		$("#endDateLimit").css("color", "white");
		

		if (startFrozen) {
			addToStart = 0;
			$("#startDateLimit").css("color", "yellow");
		}
		if (endFrozen) {
			addToEnd = 0;
			$("#endDateLimit").css("color", "yellow");
		}

		//deBugClog("timesel", "current start: " + currentStartDate);
		//deBugClog("timesel", "current end: " + currentEndDate);
		//deBugClog("timesel", "add to current start: " + addToStart);
		//deBugClog("timesel", "add to current end: " + addToEnd);

		if (currentStartDate.getTime() + addToStart > currentEndDate.getTime()
				+ addToEnd) {
			deBugClog("timesel", "invert");
			// if allowed, the times would invert
			// anchor at middle - bring end to close interval
//			var middle = (currentEndDate.getTime() - currentStartDate.getTime()) / 2;
//			currentStartDate = new Date(currentStartDate.getTime() + middle);
//			currentEndDate = new Date(currentStartDate.getTime() + timeIncrements[3].mSecs); //add one year
		
			var changeFactor = (timeIncLesser.mSecs ? timeIncLesser.mSecs : 0);
			var addToStart = parseFloat(limits[0]) * changeFactor * timeAccelerationFactor;
			var addToEnd = parseFloat(limits[1]) * changeFactor * timeAccelerationFactor;
			currentStartDate = new Date(currentStartDate.getTime() + addToStart);
			currentEndDate = new Date(currentEndDate.getTime() + addToEnd);		
				
		} else if (currentStartDate.getTime() + addToStart < outerStartLimit) {
			deBugClog("timesel", "earlier");
			// if allowed, start would be earlier than earliest allowed
			// set start at limit
			currentStartDate = outerStartLimit;
			startFrozen = true;
			if (currentEndDate.getTime() + addToEnd >   outerStartLimit) {
				currentEndDate = new Date(currentEndDate.getTime() + addToEnd);
			}
		} else if (currentEndDate.getTime() + addToEnd > outerEndLimit) {
			deBugClog("timesel", "later");
			// if allowed, end would be later than latest allowed
			// set end at limit

			if (currentStartDate.getTime() + addToStart < outerEndLimit) {
				currentStartDate = new Date(currentStartDate.getTime()
						+ addToStart);
			}
			currentEndDate = outerEndLimit;
			endFrozen = true;
			allowUpdate = false;
		} else {
			//deBugClog("timesel", "normal");
			currentStartDate = new Date(currentStartDate.getTime() + addToStart);
			currentEndDate = new Date(currentEndDate.getTime() + addToEnd);
			//deBugClog("timesel", "currentStartDate " + currentStartDate);
		}
		
		resetTimeFactors();
		writeTimeScale();
		writeResImages();
		setTimeSlider();
		
		if(!tt.cg.topickeywords){
			//("timesel");
			//reset view icon
			//tt.makeWait.ShowViewIcon(false);
			//reset view button
			//tt.makeWait.SetViewButton(true);	
			if(!initializing) tt.makeBalloon.DisplayBalloon("","Wait");
		}
		
	}
	
	function initialize(){
		initializing = true;
		setLimits( [ 0, 0 ], "1604-01-01", "1890-01-01");
		initializing = false;
	}
	
	//public methods
	return {
		Initialize : function() { initialize(); },
		SetLimits : function(limits, startdate, enddate) {
			setLimits(limits, startdate, enddate);
		},
		DragLimits : function(offset_x,offset_y) {
			dragLimits(offset_x,offset_y);
		},
		CurrentStartDate : function(pretty) {
			if(pretty){
				return dateToISO(currentStartDate,timeInc.dateFormat,true);
			}else{
				return dateToISO(currentStartDate);
			}
			
		},
		CurrentEndDate : function(pretty) {
			if(pretty){
				return dateToISO(currentEndDate,timeInc.dateFormat,true);
			}else {
				return dateToISO(currentEndDate);
			}
		},
		ToggleDateLimit : function(which) {
			toggleDateLimit(which);
		},
		SetDateLimit : function(which) {
			setDateLimit(which);
		},
		CurrentTimeSpan : function() {
			return currentTimeSpan();
		},
		CurrentTimeRatio : function() {
			return currentTimeRatio();
		},
		WriteTimeScale : function() {
			writeTimeScale();
		},
		HandleTimeSlider : function(startPercent, endPercent) {
			handleTimeSlider(startPercent, endPercent);
		}

	}
})();


var ttMakeControlSpace; //shortcut
tt.makeControlSpace = (function() {
	
	function displayUtilityPanel(utilityName)
	 {
//(utilityName);
		$('#utilitySpace').empty();
	
		switch (utilityName)		
		{
		case "Control":
			$('#utilitySpace').html(makeControlPanel());
			tt.makeAvacle.LoadAvacleResources();
			break;
		case "Login": 
			$('#utilitySpace').html(tt.makeLogin.HTML()); 
			break;
		case "Search": 
			$('#utilitySpace').html(tt.makeSearch.HTML()); 
			tt.makeSearch.SetSearch();
			break;
		case "Help": 
			//tt.makeHelp.HTML(); 
			tt.makeHelp.ResetHelp("Help_0");
			break;
		case "Forum": 
			tt.makeForum.SetForum();
			break;	
		case "Upload": 
			$('#utilitySpace').html(tt.makeUpload.HTML()); 
			break;
		default:
		}
	 }
	
	function setContentGELayers(){
		
		var cA = [];
		
		cA.push("<div><div>Google Earth Layers</div>");
		cA.push("<input class='keywordCheckBox' type='checkbox' value='ModernBorders'"); 
		cA.push("onclick='tt.map.SetGeLayer(ge.LAYER_BORDERS,this.checked);'/>");
		cA.push("Show Modern Borders");
		cA.push("<br/>");
		cA.push("<input class='keywordCheckBox' type='checkbox' value='ModernRoads' ");
		cA.push("onclick='tt.map.SetGeLayer(ge.LAYER_ROADS,this.checked);'/>");
		cA.push("Show Modern Roads");
		cA.push("<br/>");
		cA.push("<input class='keywordCheckBox' type='checkbox' value='LatLonGrid' ");
		cA.push("onclick='tt.map.SetGrid(this.checked);'/>");
		cA.push("Show Global Grid");
		cA.push("</div>");
		
		return cA.join("");
		
	}
	
	function setContentGEControls() {
		
		var cA = [];
		
		cA.push("<div>");
		cA.push("<input id='toggleGECtrl' type='checkbox' ");
		cA.push("onclick='tt.makeControlSpace.ToggleGEControls(this.checked);' ");
		cA.push("checked='false'/>");
		cA.push("Show GE Controls");
		//cA.push("<div class='ctrlBlock'><div id='ctrlTimeLabel'>Time</div>");
		//cA.push("<img id='ctrlTime' src = '" + tt.cg.appimg + "TTcontrol02.png' usemap='#tmap'></img>");		
		cA.push("</div>");		
		
		return cA.join("");
	}
	
	function setContentAvacleControls(){
		var cA = [];
		
		cA.push("<div class='ctrlBlock'>");
		cA.push("<div id='ctrlTimeLabel'>Time Trails Avacle</div>");		
		cA.push("	<table class='center'>");
		cA.push("<tr>");
		cA.push("<td>");


		cA.push("</td>");
		cA.push("</tr>");

		cA.push("<tr>");
		cA.push("<td>");

		cA.push("<select id='foundVehicles'></select>");

		cA.push("<input type='button' onclick='tt.makeAvacle.InitAvacle(true);' value='Start'/>");
		cA.push("<input type='button' onclick='tt.makeAvacle.InitAvacle(false);' value='Reset'/>");
		cA.push("</td>");
		cA.push("</tr>");

		cA.push("<table class='center'>");
		cA.push("<tr>");
		cA.push("<td><img id='ctrlAvacle' src = '" + tt.cg.appimg + "key_all.png' usemap='#avamap'></img></td>");

		cA.push("</tr>");
		cA.push("</table>");

		cA.push("</td>");
		cA.push("</tr>");
		cA.push("</table>");
				
		cA.push("</div></div>");		
		
		return cA.join("");		
	}
	
	function makeControlPanel() {
				
		return setContentGELayers() + setContentGEControls() + setContentAvacleControls();
				
	}
		

	function activateTimeControl(clickX,clickY){
//(clickX + " " + clickY);	
		if(clickX === 0 && clickY === 0) return;
		
		var centerX = 70;
		var centerY = 70;
		var slope = (clickY - centerY) / (clickX - centerX);
		var south = (clickY > centerY ? true : false);			
		var which = "";
		if(south && (slope > 0 && slope < 1.0)){
			which = "right";
		}else if (south && (slope > -1.0 && slope < 0.0)){
			which = "left";
		}else if (south){
			which = "bottom";
		}else if (slope > 0 && slope < 1.0){
			which = "left";
		}else if (slope > -1.0 && slope < 0.0){
			which = "right";
		}else{
			which = "top";
		}
//(south + " " + slope + " " + which);
		switch(which){
			case "top": tt.timesel.SetLimits([-1,1]); break;
			case "bottom": tt.timesel.SetLimits([1,-1]); break;
			case "right": tt.timesel.SetLimits([1,1]); break;
			case "left": tt.timesel.SetLimits([-1,-1]); break;
		}
	}
	 
	function showLogo(xPos, yPos) {
		
		//var state = tt.cg.layout.state;
		
		/* for debugging
		 * var westCurrentSize = state.west.size;
		var westMinimumSize = state.west.minSize;
		var containerInnerWidth = state.container.innerWidth;
		var containerPaddingLeft = state.container.paddingLeft;
		 ("state.container.innerHeight "+(state.container.Height)+ " wcenterMinimumSize:"+state.center.minSize+" containerInnerWidth: "+
				state.container.innerWidth+" containerPaddingLeft:"+state.container.paddingLeft);
		*/
		
		//createNativeHTMLButton(0,0,139,131); //x,y,wid,ht
		createScreenOverlayButton(tt.cg.appimg + "TT_IMG_Logo.png",0,0,139,131);
		createScreenOverlayButton(tt.cg.appimg + "TTcontrol02.png",44,48,50,50);		
		
	}
	
	
	
	function toggleGEControls(which)
	{
		tt.map.SetNavVisibility(which);
		if(which){
			$("#ctrlTime").show();
			$("#ctrlTimeLabel").show();
		} else {
			$("#ctrlTime").hide();
			$("#ctrlTimeLabel").hide();
		}
	}
	

	
	function setCtrlIcon(me,action){
		//actions = Normal, Hover, Compressed
		var baseName = me.id.substring(4);
		var src = "";				
		
		if(action==="Compressed"){ //only fired on mousedown	
			if(tt.cg.activeCtrl !== "None" && tt.cg.activeCtrl !== baseName){
				//close existing
				$('#utilitySpace').empty();
				tt.makeLayout.ClosePanel("east");				
				srcToClose = tt.cg.appimg + tt.cg.activeCtrl + "_" + "Normal" + "_Transparent.png";	
				$("#ctrl" + tt.cg.activeCtrl).find("img").attr("src", srcToClose);
				
				//now open this
				tt.cg.activeCtrl = baseName;
				displayUtilityPanel(baseName);
				tt.makeLayout.OpenPanel("east");		
				src = tt.cg.appimg + baseName + "_" + "Compressed" + "_Transparent.png";
				
			} else if(tt.cg.activeCtrl !== "None"){ //close and uncompress button								
				tt.cg.activeCtrl = "None";
				$('#utilitySpace').empty();
				tt.makeLayout.ClosePanel("east");				
				src = tt.cg.appimg + baseName + "_" + "Normal" + "_Transparent.png";	
			}else{//open and compress button				
				tt.cg.activeCtrl = baseName;
				displayUtilityPanel(baseName);
				tt.makeLayout.OpenPanel("east");		
				src = tt.cg.appimg + baseName + "_" + "Compressed" + "_Transparent.png";
			}
		}else if(action!=="Compressed"){//catch if a hover type action
			if(tt.cg.activeCtrl === baseName){//keep it compressed
				src = tt.cg.appimg + baseName + "_" + "Compressed" + "_Transparent.png";
			}else{
				src = tt.cg.appimg + baseName + "_" + action + "_Transparent.png";	
			}
		}else{
			//just set img as default
			src = tt.cg.appimg + baseName + "_" + action + "_Transparent.png";	
		}
		//set the ctrl button image
		$(me).find("img").attr("src", src);
	}
	
	function resetCtrlIcons(){
		if(tt.cg.activeCtrl === "None"){
			setCtrlIcon($("#ctrlSearch").get(0),"Normal");
			setCtrlIcon($("#ctrlControl").get(0),"Normal");
			setCtrlIcon($("#ctrlLogin").get(0),"Normal");
			setCtrlIcon($("#ctrlHelp").get(0),"Normal");
			setCtrlIcon($("#ctrlForum").get(0),"Normal");
			setCtrlIcon($("#ctrlUpload").get(0),"Normal");	
		}
	}


	
	//public
	return {
		DisplayUtilityPanel : function(utilityName) {displayUtilityPanel(utilityName);},
		ShowLogo : function(xPos, yPos) {showLogo(xPos, yPos);},
		ToggleGEControls : function(which) {toggleGEControls(which);},
		SetCtrlIcon : function(me,action) {setCtrlIcon(me,action); },
		ResetCtrlIcons : function() {resetCtrlIcons(); },
		ActivateTimeControl : function(clickX,clickY) {activateTimeControl(clickX,clickY); }
		
	}
})();



var ttMakeAvacle; //shortcut
tt.makeAvacle = (function() {

	function initAvacle(turnOn){

		if(turnOn){
			startLoc = {
					  lat: 0,
					  lon: 0,
					  heading: 0
					};
			if(tt.cg.latitude){
				startLoc.lat = tt.cg.latitude;
				startLoc.lon = tt.cg.longitude;
			}
//alert(startLoc.lat + " " + startLoc.lon);
			
			var selectEl = $("#foundVehicles").get(0);
			var modelPath = tt.cg.modimg + "chariot.kmz";
			var r = {};
			var res = presetRes.resources;
			for (var i=0; i<selectEl.options.length; i++){
				if (selectEl.options[i].selected==true){
					for(var j=0; j<res.length; j++){	
//(selectEl.options[i].value + " " + res[j].Name);
						if(selectEl.options[i].value === res[j].Name){
							r = res[j];
							//break;
						}
					}
				}
			}
//alert("toy" + " modelPath : " + modelPath);
//tt.makeBalloon.DisplayBalloon("","Wait");
			truck = new Truck(r,startLoc);
			//truck = new Truck();
			keyboardFocusHack(ge);
//tt.makeBalloon.Close();
		}else{
			//truck.destroy();
			//truck = null;
			//window.location.reload();
			resetGE();
		}
		
	}
	
	var presetRes = {'resources':[
    {'Name':'Horse and Chariot','ModelUrl':'chariot.kmz','Scale':1,'Orientation':90,
    	'CamHeight':40,'TrailingDistance':180,
    	'TiltFactor':80,'RangeFactor':0,'AccelFactor':50.0,
    	'PreventJump':false,'ClampToType':0},
	{'Name':'Trojan Horse','ModelUrl':'trj.kmz','Scale':1,'Orientation':90,
    	'CamHeight':80,'TrailingDistance':230,
    	'TiltFactor':80,'RangeFactor':0,'AccelFactor':50.0,
    	'PreventJump':false,'ClampToType':0},
	{'Name':'Trireme','ModelUrl':'tri.kmz','Scale':5,'Orientation':90,
    	'CamHeight':20,'TrailingDistance':70,
    	'TiltFactor':80,'RangeFactor':0,'AccelFactor':50.0,
    	'PreventJump':false,'ClampToType':0},
	{'Name':'HMS Victory','ModelUrl':'HMS_Victory.kmz','Scale':1,'Orientation':90,
    	'CamHeight':80,'TrailingDistance':230,
    	'TiltFactor':80,'RangeFactor':0,'AccelFactor':50.0,
    	'PreventJump':false,'ClampToType':0},
	{'Name':'Titanic','ModelUrl':'Titanic.kmz','Scale':1,'Orientation':90,
    	'CamHeight':80,'TrailingDistance':180,
    	'TiltFactor':80,'RangeFactor':0,'AccelFactor':50.0,
    	'PreventJump':false,'ClampToType':0},
	{'Name':'Ironclad','ModelUrl':'Ironclad.kmz','Scale':1,'Orientation':90,
    	'CamHeight':30,'TrailingDistance':70,
    	'TiltFactor':80,'RangeFactor':0,'AccelFactor':50.0,
    	'PreventJump':false,'ClampToType':0},
	{'Name':'Model T','ModelUrl':'Model_T.kmz','Scale':1,'Orientation':90,
    	'CamHeight':10,'TrailingDistance':30,
    	'TiltFactor':80,'RangeFactor':0,'AccelFactor':20.0,
    	'PreventJump':false,'ClampToType':0},
	{'Name':'Raft','ModelUrl':'rft.kmz','Scale':0.5,'Orientation':90,
    	'CamHeight':30,'TrailingDistance':90,
    	'TiltFactor':80,'RangeFactor':0,'AccelFactor':50.0,
    	'PreventJump':false,'ClampToType':0},	
	{'Name':'Hoplite','ModelUrl':'hpl.kmz','Scale':0.05,'Orientation':90,
    	'CamHeight':7,'TrailingDistance':12,
    	'TiltFactor':80,'RangeFactor':0,'AccelFactor':50.0,
    	'PreventJump':false,'ClampToType':0}
	]};
	
	function loadAvacleResources()
	{		
		if(tt.cg.resourcesAvacled == null){
			tt.getResources.SendAjax("avacles");
		}
		
		var selectEl = $("#foundVehicles").get(0);
		selectEl.options.length = 0;

		if(tt.cg.resourcesAvacled){
			for(i=0; i<tt.cg.resourcesAvacled.resources.length; i++)
			{
				var r = tt.cg.resourcesAvacled.resources[i];
				selectEl.options[i] = new Option(r.Name,r.Name);
			}
		}		
	}
	
	
	function drive(whichWay){
		
		switch(whichWay){
			case 'accel': 
				gasButtonDown=true; 
				$("#ctrlAvacle").attr("src",tt.cg.appimg + "key_up.png");
				break;
			case 'moveLeft': 
				leftButtonDown=true; 
				$("#ctrlAvacle").attr("src",tt.cg.appimg + "key_left.png");
				break;
			case 'decel': 
				reverseButtonDown=true; 
				$("#ctrlAvacle").attr("src",tt.cg.appimg + "key_down.png");
				break;
			case 'moveRight': 
				rightButtonDown=true; 
				$("#ctrlAvacle").attr("src",tt.cg.appimg + "key_right.png");
				break;
			default:
				$("#ctrlAvacle").attr("src",tt.cg.appimg + "key_all.png");
				gasButtonDown=false;
				leftButtonDown=false;
				reverseButtonDown=false;
				rightButtonDown=false;
		}
	
		//(whichWay);
		
	}
	
	function resetGE(){
		//clearFeatures();
		tt.getFeatures.AbortAjax();
		
		tt.getFeatures.ClearFeatureRefresh();
		$('#map3d').empty();		
		google.earth.createInstance('map3d', initCB, failureCB);		
	}


//public
return {
	InitAvacle : function(turnOn) { initAvacle(turnOn); },
	LoadAvacleResources : function()  { loadAvacleResources(); },
	Drive : function(whichWay) {drive(whichWay); },
	ResetGE : function() { resetGE(); }
	
}
})();




/*
 * Display the Timesail balloon
 * 
 */

var ttMakeBalloon; //shortcut
tt.makeBalloon = ( function() {

	//private vars
	var blnWid = 0;
	var blnHt = 0;
	var winWid = 0;
	var winHt = 0;
	
	var contentString = "";
	var balloon = null;
	
	function setHTML(html){
		contentString = html;
	}
	
	function displayBalloon(url, mode) {
		
		
		balloon = ge.getBalloon();
		if (balloon === null) // create one
		{
			balloon = ge.createHtmlDivBalloon('');
		}		
		setDimensions(mode);
		setContent(mode);
		
//alert(contentString);
		if(mode==="YouTube" || mode==="PDF"){
			tt.makeLayout.ClearPanels();
		}
		
		// get the balloon	
		var div = document.createElement('div');
		div.innerHTML = contentString;
		balloon.setContentDiv(div);
//alert("set it");
		ge.setBalloon(balloon);
//alert("made it");



		// auxiliary functions
		function setContent(mode){
//(url);
			var cA = []; // contentArray
			//make the content
			if(mode==="YouTube"){
				//close
				//cA.push("<div  id='closeButton' ");
				cA.push("<div ");
				cA.push("style='color:white;position:absolute;right:4px;top:4px;' ");
				cA.push("onclick='tt.makeBalloon.Close();'>X</div>");
				
				cA.push("<div style='background-color:#FFFFFF;'>");			
				cA.push("<object width='" + blnWid + "' height='" + blnHt + "'><param name='movie' ");
				cA.push("value='" + url + "'/>");
				cA.push("<param name='allowFullScreen' value='true'/>");
				cA.push("<embed src='" + url + "' ");
				cA.push("type='application/x-shockwave-flash' allowfullscreen='true'");
				cA.push("width='" + blnWid + "' height='" + blnHt + "'></embed></object>");
				cA.push("</div>");			
			
			}else if(mode==="Wait"){

				cA.push("<div style='background-color:#000000;'>");
				
				//var imgPath = tt.cg.appimg + "Compass-Animation.gif"
				
				var imgWait = tt.cg.appimg + "Wait.gif";
				var imgGreen = tt.cg.appimg + "Green_Normal.png";
				var imgRed = tt.cg.appimg + "Red_Normal.png";
				cA.push("<table style='margin-left:auto; margin-right:auto;'>");
				cA.push("<tr><td colspan='2' height='20'>");
				cA.push("<img id='wait' style='display:none;' src='" 
						+ imgWait + "' height='20' width='140'></img>");
				cA.push("</td><tr><td>");
				cA.push("<img id='green' src='" 
						+ imgGreen + "' height='70' width='70' " 
						+ " onmouseover='tt.makeBalloon.OverButton(this);' "
						+ " onmouseout='tt.makeBalloon.OutButton(this);' "
						+ " onclick='tt.makeBalloon.ClickButton(this,function(){tt.getFeatures.ViewTimeTrails();})'></img>");
				cA.push("</td><td>");
				cA.push("<img id='red' src='" 
						+ imgRed + "' height='70' width='70' "
						+ " onmouseover='tt.makeBalloon.OverButton(this);' "
						+ " onmouseout='tt.makeBalloon.OutButton(this);' "						
						+ "onclick='tt.makeBalloon.ClickButton(this,function(){tt.makeAvacle.ResetGE();})'></img>");
				cA.push("</td></tr>");
				cA.push("</table>");
				//cA.push("style='color:white;background-color:red;text-align:center;font-weight:bold;' ");
				//cA.push("onclick='tt.makeAvacle.ResetGE();'>Cancel</div>");
				cA.push("</div>");
				
			}else if(mode==="PDF"){
				
				cA.push("<div style='background-color:#000000;'>");
				cA.push("<div id='flashContent'></div>")
				
				cA.push("<script type='text/javascript'>");
				
				cA.push("var flashvars = {");
				cA.push("SwfFile : escape('" + url + "'),");
				cA.push("Scale : 0.6,");
				cA.push("ZoomTransition : 'easeOut',");
				cA.push("ZoomTime : 0.5,");
				cA.push("ZoomInterval : 0.1,");
				cA.push("FitPageOnLoad : false,");
				cA.push("FitWidthOnLoad : false,");
				cA.push("PrintEnabled : true,");
				cA.push("FullScreenAsMaxWindow : true,");
				cA.push("localeChain: 'en_US'");
				cA.push("};");
				
				cA.push("var params = {};");
				cA.push("params.quality = 'high';");
				cA.push("params.bgcolor = '#ffffff';");
				cA.push("params.allowscriptaccess = 'sameDomain';");
				cA.push("params.allowfullscreen = 'true';");
			    
				cA.push("var attributes = {};");
				cA.push("attributes.id = 'FlexPaperViewer';");
				cA.push("attributes.name = 'FlexPaperViewer';");
				
				cA.push("swfobject.embedSWF(" 
						+ "'" + tt.cg.pdfimg + "FlexPaperViewer.swf'," 
						+ "'flashContent',"
						+ "'" + blnWid + "','" + blnHt + "',"
						+ "'9.0.124',"
						+ "''," //"'${expressInstallSwf}',"
						+ "flashvars,params,attributes);");
				
				cA.push("swfobject.createCSS('#flashContent', 'display:block;text-align:left;');");
		
				cA.push("</script>");
				cA.push("</div>");
		
								
			} else { //this catches when no mode is sent
				return;
			}
//alert(cA.join(""));
			contentString = cA.join("");
					
		}
		
		function setDimensions(mode){
			
			balloon.setBackgroundColor('#000000'); 
			
			winWid = parseInt($(window).width() * 0.7);
			winHt = parseInt($(window).height() * 0.6);	
			
			//if(mode==="YouTube" || mode==="PDF"){							

			if(mode==="Wait"){
				
				//blnWid = 200;
				//blnHt = 100;
			}else{
				var htRatio = 200/320;
				if(winWid*htRatio < winHt){
					blnWid = winWid;
					blnHt = parseInt(winWid*htRatio);
				}else{//base on ht not wid
					blnHt = winHt;
					blnWid = parseInt(winHt*(1/htRatio));
				}
				//reduce ht to accomodate close
				blnHt = blnHt - 40;
			}
			
		}

	}
	
	
	function setPDFWheel(){
		if(window.addEventListener)
		window.addEventListener('DOMMouseScroll', handleWheel, false);
		window.onmousewheel = document.onmousewheel = handleWheel;
	
		if (window.attachEvent)
		window.attachEvent("onmousewheel", handleWheel);

	}
	
	function handleWheel(event){
		if(!window.document.FlexPaperViewer.hasFocus()){return true;}
		window.document.FlexPaperViewer.setViewerFocus(true);
		window.document.FlexPaperViewer.focus();

		if(navigator.appName == "Netscape"){
			if (event.detail)
				delta = 0;
			if (event.preventDefault){
				event.preventDefault();
				event.returnValue = false;
				}
		}
		return false;
	}

	function setPDF(){
	    //For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection. -->
	    var swfVersionStr = "9.0.124";
	    //To use express install, set to playerProductInstall.swf, otherwise the empty string. -->
	    var xiSwfUrlStr = "${expressInstallSwf}";
	    var flashvars = {
	          SwfFile : escape(tt.cg.pdfimg + "TestPaper.swf"),
			  Scale : 0.6,
			  ZoomTransition : "easeOut",
			  ZoomTime : 0.5,
				  ZoomInterval : 0.1,
				  FitPageOnLoad : false,
				  FitWidthOnLoad : false,
				  PrintEnabled : true,
				  FullScreenAsMaxWindow : true,
				  localeChain: "en_US"
			  };
		 var params = {
	
		    }
	    params.quality = "high";
	    params.bgcolor = "#ffffff";
	    params.allowscriptaccess = "sameDomain";
	    params.allowfullscreen = "true";
	    var attributes = {};
	    attributes.id = "FlexPaperViewer";
	    attributes.name = "FlexPaperViewer";
	    
	    swfobject.embedSWF(
	        tt.cg.pdfimg + "FlexPaperViewer.swf", "flashContent",
	        "500", "300",
	        swfVersionStr, xiSwfUrlStr,
	        flashvars, params, attributes);
		swfobject.createCSS("#flashContent", "display:block;text-align:left;");
	}
	
	function close() {
		
		ge.setBalloon(null);
	
	}
	
	function clickButton(objSent,funcSent){
		
		var color = $(objSent).attr("id");
		if(color==="green"){
			$("#wait").show();
		}
		
		var src = $(objSent).attr("src");
		var compress = src.replace("Normal","Compressed");
//(compress);
		$(objSent).attr("src",compress);
		//setTimeout("release();",1000);
		funcSent();
		
		function release(){
			$(objSent).attr('src',src);
		}
	}
	
	function overButton(objSent){
		var src = $(objSent).attr("src");
		var over = src.replace("Normal","Hover");
		
		if(over)$(objSent).attr("src",over);
	}
	
	function outButton(objSent){
		var src = $(objSent).attr("src");
		var out = src.replace("Hover","Normal");	
		if(out) $(objSent).attr("src",out);
	}

	return {
		DisplayBalloon : function(url, mode) {
			displayBalloon(url, mode);
		},
		Close : function() {
			close();
		},
		SetHTML : function(html) { setHTML(html); },
		ClickButton : function(objSent,funcSent) { clickButton(objSent,funcSent); },
		OutButton : function(objSent) { outButton(objSent); },
		OverButton : function(objSent) { outButton(objSent); }
		
	}
})();

var ttMakeFisheye; //shortcut
tt.makeFisheye = ( function() {

	var resWereSelected = false;
	var resSelectDirection = 1;
	var numberResShow = 8;
	var atStartOfResources = false;
	var atEndOfResources = false;
	
	function resetNumberResShow(){

		var winWid = parseInt($(window).width() * 0.95);
		var pixPerRes = 100;	
		var estRoom = Math.ceil(winWid / pixPerRes);		
		numberResShow = estRoom;

	}
	
	function resMatch(resType){
		//toggles the type setting on/off
		//to provide fisheye filtering
		if(resType == tt.cg.resMatchType){
			tt.cg.resMatchType = ""; //reset
		}else{
			tt.cg.resMatchType = resType;
		}
		populateFisheye();
	}
	
	function resSelect(direction){
		//respond to forward and backward
		//arrow keys on either side of fisheye
		resSelectDirection = direction;
		resWereSelected = true;
		populateFisheye();
		resWereSelected = false;
		
	}
	
	function fireFisheye(){
	
		$('#fisheye2').Fisheye(
			{
				maxWidth: 110,
				items: 'a',
				itemsText: 'span',
				container: '.fisheyeContainer',
				itemWidth: 70,
				proximity: 80,
				alignment : 'left',
				halign : 'center'
			});		
	}
	
	function initializeFisheye() {
				
		$("#selectResLeft").attr("src",tt.cg.appimg + "leftarrow_gray.png");
		$("#selectResRight").attr("src",tt.cg.appimg + "rightarrow_gray.png");
		$("#closeButtonSouth").attr("src",tt.cg.appimg + "retract_up.png");
		$("#closeButtonWest").attr("src",tt.cg.appimg + "retract_right.png");
		
		$('#selectResRight').mouseover(function() {
			setArrow("right","over");			
		});
		$('#selectResLeft').mouseover(function() {
			setArrow("left","over");			
		});
		$('#selectResRight').mouseout(function() {
			setArrow("right","out");			
		});
		$('#selectResLeft').mouseout(function() {
			setArrow("left","out");			
		});
		$('#selectResRight').mouseup(function() {
			setArrow("right","up");			
		});
		$('#selectResLeft').mouseup(function() {
			setArrow("left","up");			
		});
	};
	
	
	function getCommonName(categoryName) {
		switch (categoryName) {
			case "MovingImageClip": return "Clips";break;
			case "FeatureInfo": return "Info";break;
			case "Text": return "Books";break;
			case "MovingImage": return "Movies";break;
			case "ComputerGame": return "Games";break;
			case "Music": return " Music";break;
			case "TextQuote": return " Quotes";break;
			case "PhysicalObject": return " Replicas";break;
			case "Model3D": return " Models";break;
			case "Image": return " Images";break;
			default: return "";
		}
	}

	function populateFisheye() {
	
		//set search factors
		resetNumberResShow();
//("sendRes " + resWereSelected);
		if(resWereSelected){ //arrow was pressed
			tt.cg.resStartIndex = tt.cg.resStartIndex + (numberResShow * resSelectDirection);			
			if(tt.cg.resStartIndex <= 0) //backed up to start
			{
				tt.cg.resStartIndex = 0;
			}
		}else{ //based on ge click
			tt.cg.resStartIndex = 0;
			tt.cg.resStopIndex = tt.cg.resStartIndex + numberResShow;
		}
		tt.cg.resStopIndex = tt.cg.resStartIndex + numberResShow;
		
		
		//request resources
		tt.getResources.SendAjax("fisheye");
		
		//determine start and end factors
		tt.cg.resTotalFound = tt.cg.resourcesRequested.totalFound;
		if(tt.cg.resStartIndex === 0){
			atStartOfResources = true;
		}else{
			atStartOfResources = false;
		}
			
		if(tt.cg.resStopIndex > tt.cg.resTotalFound){
			atEndOfResources = true;
		}else{
			atEndOfResources = false;
		}
		
//("atStart: " + atStartOfResources + "  atEnd: " + atEndOfResources);		
		
		if (tt.cg.resourcesRequested.resources.length > 0) {							
				
			var cA = [];
			cA.push('<div id="fisheyeContainer" class="fisheyeContainer">');
	
			for (i = 0; i < tt.cg.resourcesRequested.resources.length; i++) {
				var r = tt.cg.resourcesRequested.resources[i];			
		
				var firstLink = "<a class='fisheyeItem2' "
					+ "onclick='tt.makePlayspace.AddToyFromRes(" + i + ",this);'>";
			
				cA.push(firstLink);
				if (r.Image){
					cA.push("<img src='" + r.Image	+ "'></img><span class='lbl"
						+ r.Type + "' onclick='tt.makeFisheye.ResMatch(\"" 
						+ r.Type + "\");' title='Toggle Resource Filter'>"
						+ r.Name.substr(0,30) + "</span>");
				}
				cA.push("</a>");	
			}
			cA.push("</div>");

			$("#fisheye2").empty().append(cA.join(" "));				
			fireFisheye();
			setArrow("right","out");
			setArrow("left","out");
			if(!tt.cg.fisheyeOpen) toggleFisheye();
			
		} else { //no resources to display
				
			$("#fisheye2").empty();
			if(tt.cg.fisheyeOpen) toggleFisheye();
		}

	}
	
	function toggleFisheye() {
		tt.cg.fisheyeOpen = !tt.cg.fisheyeOpen;
		if(tt.cg.fisheyeOpen){ 
			tt.makeLayout.OpenPanel("south");
			$("#closeButtonSouth").attr("src", tt.cg.appimg + "retract_down.png");
		}else{
			tt.makeLayout.ClosePanel("south");
			$("#closeButtonSouth").attr("src", tt.cg.appimg + "retract_up.png");
		}
	}
	
	function setArrow(side,action){
		//onclick="tt.makeFisheye.ResSelect(-1);" 
		
		var elName = "";
		var imgName1 = "";
		var imgName2 = "";
		var takeAction = true;
		var dir = 0;
		
		if(side === "right" ){
			elName = "#selectResRight";
			imgName1 = "rightarrow";
			dir = 1;
			if(atEndOfResources) takeAction = false;
		}else{			
			elName = "#selectResLeft";
			imgName1 = "leftarrow";
			dir = -1;
			if(atStartOfResources) takeAction = false;
		}
		
		
		if(action === "up" && takeAction){
			resSelect(dir);
			return;
		}else if(action === "over" && takeAction){
			imgName2 = "_hover.png";
			$(elName).attr("src",tt.cg.appimg + imgName1 + imgName2);
		}else if(takeAction){
			imgName2 = "_normal.png";
			$(elName).attr("src",tt.cg.appimg + imgName1 + imgName2);
		}else{
			imgName2 = "_gray.png";
			$(elName).attr("src",tt.cg.appimg + imgName1 + imgName2);
		}
		
//		("action " + action 
//				+ " side " + side 
//				+ " start " + atStartOfResources 
//				+ " end " + atEndOfResources);

		
		

	}

	//public methods
	return {
		SetArrow : function(side,action) { setArrow(side,action); },
		PopulateFisheye : function() {populateFisheye();},
		InitializeFisheye : function() {initializeFisheye();},
		ToggleFisheye : function() {toggleFisheye();},
		ResSelect : function(direction) { resSelect(direction); },
		ResMatch : function(resType) { resMatch(resType); },
		GetCommonName : function(categoryName) {
			//utility to translate res type into friendlier name - not used?
			return getCommonName(categoryName); }
	}
})();


/*
 * Test of Playspace Click on 3dobject-image on timeline - place it in west
 * panel playspace @return none
 */
var ttMakePlayspace; //shortcut
tt.makePlayspace = ( function() {
	
	var Toys;
	var playWidth = 340; //pixels wide
	var edging = 16; //pixels of margin and padding
	
	//RESOURCE TOYS
	function addToyFromRes(iRes, sentObj){
		var r = null;
		//determine where resource originates
		if($(sentObj).hasClass("resImage")){
			r = tt.cg.resourcesTimelined.resources[iRes];	
		}else if ($(sentObj).hasClass("fisheyeItem2")){			
			r = tt.cg.resourcesRequested.resources[iRes];
		}

		if(r){
				

			//snag any youtube shunts
			var shuLink = "";
			var shuPositonStart = r.Description.lastIndexOf(':::') + 3;
			var shuPositonEnd = r.Description.lastIndexOf('::;');
			if (shuPositonStart > 0 && shuPositonEnd > 0) {
				//grab the shunt link
				shuLink = r.Description.substring(shuPositonStart, shuPositonEnd);
				// remove the img url
				r.Description = r.Description.replace(':::' + shuLink + '::;', '');
			}
							
			var imgBase = r.Image.replace(".jpg","").replace(".kmz","");
			var resType = r.Type;
			var asin = r.ASIN.trim();
			var otherUri = r.Resource;
			var name = r.Name;
			var desc = r.Description;
			var img = r.Image.trim();
			var creatorInfo = r.Creator;
			
			addToy(imgBase, resType, asin, otherUri, name, desc, img, creatorInfo, shuLink);

		}
	}

	//FEATURE TOYS
	function addToyFromFeat(feat){
		
		//do an ajax call for one resource uri	
		if(feat){
			tt.getFeatures.FetchSingleFeature(feat);
		
		}
		
	}
	
	
	
	//TOYS
	
	function addToy(imgBase,resType,asin,otherUri,name,desc, imgUri, creatorInfo, shuLink){
		
		var closeImg = tt.cg.appimg + "close.png";
		var wikipediaImg = tt.cg.appimg + "wikipedia.png";
		var amazonImg = tt.cg.appimg + "amazon_button.png";
		var fullscreenImg = tt.cg.appimg + "fullscreen.png";
		var globeImg = tt.cg.appimg + "globe.png";
		
		var randomId = "t" + Math.floor(Math.random() * 10000);	
		var dialogDiv = "#" + randomId + "dia";
		
		var imgUri00 = imgBase + "00.png"; //for res objs from timeline
		var kmzUri = imgBase + ".kmz";
		name = (name ? name : resType);
		desc = (desc ? desc : "No Info Available");
		
		var imgHTML = [];
		imgHTML.push("<div class='pcup1' id='" + randomId + "'>");
		//what image to show
		if(resType === "Model3D"){
			imgHTML.push("<img src='" + imgUri00 + "'"
					+ " onclick='tt.makePlayspace.ShowText(\"" + randomId +"\");'></img>");
		} else if (resType === "MovingImageClip") {
			imgHTML.push("<object width='320' height='200'" +
					" onclick='tt.makePlayspace.ShowText(\"" + randomId +"\");'>");
			imgHTML.push("<param name='movie' ");					
			imgHTML.push("value='" + otherUri + "'/>");
			imgHTML.push("<param name='allowFullScreen' value='true'/>");
			imgHTML.push("<embed src='" + otherUri + "' ");
			imgHTML.push("type='application/x-shockwave-flash' allowfullscreen='true'");
			imgHTML.push("width='320' height='200'></embed></object>");
		} else if (resType === 'Text' && shuLink) {
			imgHTML.push("<object width='320' height='200'" +
					" onclick='tt.makePlayspace.ShowText(\"" + randomId +"\");'>");
			imgHTML.push("<param name='movie' ");					
			imgHTML.push("value='" + shuLink + "'/>");
			imgHTML.push("<param name='allowFullScreen' value='true'/>");
			imgHTML.push("<embed src='" + shuLink + "' ");
			imgHTML.push("type='application/x-shockwave-flash' allowfullscreen='true'");
			imgHTML.push("width='320' height='200'></embed></object>");
		} else {
			imgHTML.push("<img src='" + imgUri + "'"
					+ " onclick='tt.makePlayspace.ShowText(\"" + randomId +"\");'></img>");
		}
		
		//add the text back div
		//imgHTML.push("<div class='textBack'>");
		//if(name){		
			imgHTML.push("<div id='" + randomId + "Name' class='standardHeader' style='display:none;'>" + name + "</div>");
			imgHTML.push("<div id='" + randomId + "Desc' class='standardType' style='display:none;'><p>" + desc + "</p></div>");
			imgHTML.push("<div id='" + randomId + "Creator' class='standardType' style='display:none;'><p>by " + creatorInfo + "</p></div>");
		//}
	
		//add the button background div
		imgHTML.push("<div class='buttonBack'>");
		
//(imgBase + " " + resType + " " + asin + " " + otherUri + " " + name + " " + desc);


		
		//do we have a movie clip expand?
		if(resType === "MovingImageClip"){
			imgHTML.push("<img");
			imgHTML.push(" onclick='tt.makeBalloon.DisplayBalloon(\"" + otherUri + "\",\"YouTube\");'");
			imgHTML.push(" id='geClipButton' class='playButton'");
			imgHTML.push(" src='" + fullscreenImg + "'></img>");			
		}
		//do we have a shunt linking a movie to a youtube trailer?
		if(shuLink && resType !== "Text"){		
			imgHTML.push("<img");
			imgHTML.push(" onclick='tt.makeBalloon.DisplayBalloon(\"" + shuLink 
					+ "\",\"YouTube\");'");
			imgHTML.push(" id='geClipButton' class='playButton'");	
			imgHTML.push(" src='" + fullscreenImg + "'></img>");
		}
		//do we have a shunt linking a text type to a pdf doc?
		if(shuLink && resType === "Text"){		
			imgHTML.push("<img");
			imgHTML.push(" onclick='tt.makeBalloon.DisplayBalloon(\"" + shuLink 
					+ "\",\"PDF\");'");
			imgHTML.push(" id='geClipButton' class='playButton'");
			imgHTML.push(" src='" + fullscreenImg + "'></img>");	
		}
		//do we have a kmz button?
		if(resType === "Model3D"){
			imgHTML.push("<img");
			imgHTML.push(" onclick='tt.map.SetNetworkLink(\"" + kmzUri + "\");'");
			imgHTML.push(" id='geKmzButton'  class='playButton'");
			imgHTML.push(" src='" + globeImg + "'></img>");			
		}
		//do we have asin?
//alert("asin:" + asin + ":");
		if(asin){		
			imgHTML.push("<img");
			imgHTML.push(" onclick='window.open(\"http://astore.amazon.com/mytimetrails-20/detail/"
					+ asin + "\",\"_blank\")'");
			imgHTML.push(" id='amazonButton' class='playButton'");
			imgHTML.push(" src='" + amazonImg + "'></img>");
		}
		//do we have an otherUri as a wikipedia link?
		if(otherUri && resType === "FeatureInfo"){		
			imgHTML.push("<img");
			imgHTML.push(" onclick='window.open(\"" + otherUri + "\", \"_blank\")'");
			imgHTML.push(" id='wikipediaButton' class='playButton'");
			imgHTML.push(" src='" + wikipediaImg + "'></img>");
		}
		
		//always send a remove
		imgHTML.push("<img");
		imgHTML.push(" onclick='tt.makePlayspace.RemoveToy(\"" + randomId +"\");'");
		imgHTML.push(" id='closeButton' class='playButton'");
		imgHTML.push(" src='" + closeImg + "'></img>");
		
		imgHTML.push("</div>");
		
		imgHTML.push("</div>");
				
//(imgHTML.join(""));		
		//if(tt.cg.permitLevel()>1){
		//	tt.makeBalloon.SetHTML(imgHTML.join(""));
		//	tt.makeBalloon.DisplayBalloon("","");
		//}else{
			$("#playspace").prepend(imgHTML.join(""));
			if(!tt.cg.playspaceOpen)togglePlayspace();
			setWidths();	
			$('#closeButtonWest').prependTo($('#playspace'));
		//}
			
		//setTimeout(eval("tt.makePlayspace.ShowText('" + randomId + "')"),3000);
		
	}

	function setWidths(){
		var ctr = 0;
		
		$("div.pcup1 img").each(function() {
			//calc a suggested width
			
			if(ctr < 1){
				myWidth = playWidth - edging;
			}else if(ctr < 3){
				myWidth = Math.floor((playWidth / 2) - edging * 1.5);
			}else if(ctr >= 3){
				myWidth = Math.floor((playWidth / 3) - edging * 3.5);
			}
			
           //Get the width of the image
           //var width = $(this).width();

           //Max-width substitution (works for all browsers)
           //if (width > 300) {
             $(this).css("width", myWidth + "px");
           //}
           ctr++;
		});
	}

	function removeToy(objid) {
		//remove from playspace
		$("#" + objid).remove();
		var htmlLen = $("#playspace").html().length;
		//(htmlLen);
		if(htmlLen < 220){
			togglePlayspace();		
		}
		setWidths();
		if($("#dialog_ui").dialog('isOpen')) $("#dialog_ui").dialog('close');
		
	}
	
	function showText(objid) {
		
		if($("#dialog_ui").dialog('isOpen')) $("#dialog_ui").dialog('close');

		var nameDiv = "#" + objid + "Name";
		var descDiv = "#" + objid + "Desc";
		var creatorDiv = "#" + objid + "Creator";
		
		if($(nameDiv).html()){
			$("#dialog_ui").html(
					$(descDiv).html() 
					+ $(creatorDiv).html());
			$('#dialog_ui').dialog('option', 'title', $(nameDiv).html());
			$("#dialog_ui").css("color","white");
			//$("#dialog_ui").css("background-url",tt.cg.pdfimg + "transparency_blue.png");	
			$("#dialog_ui").dialog('open');
			setTimeout('$("#dialog_ui").dialog("close");', 8000);
		}
		
	
		
//		var copyHTML = $("#" + objid).html();
//		removeToy(objid);
//		$("#playspace").prepend(copyHTML);
//		tt.makeLayout.OpenPanel("west");
//		setWidths();
	}
	
	function togglePlayspace(){
		
		tt.cg.playspaceOpen = !tt.cg.playspaceOpen;
		if(tt.cg.playspaceOpen){ 
			tt.makeLayout.OpenPanel("west");
			$("#closeButtonWest").attr("src", tt.cg.appimg + "retract_left.png");
		}else{
			tt.makeLayout.ClosePanel("west");
			$("#closeButtonWest").attr("src", tt.cg.appimg + "retract_right.png");
		}

		
	}
	

	
	function workPlayToggle(){
			
		if(tt.playspaceSelected){ //show workspace
			$("#playspace").hide();
			$("#workspace").show();
			tt.playspaceSelected = false;
			$("#tabWork").css("color","yellow");
			$("#tabPlay").css("color","silver");
			
		}else{ //show playspace
			$("#playspace").show();
			$("#workspace").hide();
			tt.playspaceSelected = true;
			$("#tabWork").css("color","silver");
			$("#tabPlay").css("color","yellow");
		}				
	}



	//public methods
	return {

		RemoveToy : function(obj) {
			removeToy(obj);
		},
		ShowText : function(obj) {
			showText(obj);
		},
		AddToyFromRes : function(iRes,sentObj) {
			addToyFromRes(iRes,sentObj);
		},
		AddToyFromFeat : function(feat) {
			addToyFromFeat(feat);
		},
		AddToy : function(imgBase,resType,asin,otherUri,name,desc, imgUri, creatorInfo, shuLink) {
			addToy(imgBase,resType,asin,otherUri,name,desc, imgUri, creatorInfo, shuLink);
		},
		TogglePlayspace : function() {
			togglePlayspace();
		},
		WorkPlayToggle : function() {
			workPlayToggle();
		}
	}
})();


var ttMakeLayout; //shortcut
tt.makeLayout = ( function() {
	
	
	
	function initLayout(){
		tt.cg.layout = $('body').layout( {
			
			spacing_closed : 1,
			spacing_open : 1,
			east__size : 100,
			west__size : 50,
			north__size : 100,
			south__size : 50,		
			fxName: "slide",
			fxSettings: { duration: 5000, easing: "bounceInOut" }//,
//			east__togglerAlign_closed : "top",
//			east__togglerAlign_open : "top",	
//			east__togglerContent_open: "&#8250;", // "Ý"
//			east__togglerContent_closed: "&#8249;" ,// "Ü"
//			west__togglerAlign_closed : "top",
//			west__togglerAlign_open : "top",	
//			west__togglerContent_open: "&#8249;" , // "Ü" 
//			west__togglerContent_closed:  "&#8250;" //,// "Ý"
			//south__togglerAlign_open : "top",
			//south__togglerContent_closed:  "&#136", // 
			//south__togglerAlign_closed : "top"	

		/*	west__spacing_closed : 21,
			west__togglerAlign_closed:	"top"		// align to top of resizer
				,	west__togglerLength_open:		0			// NONE - using custom togglers INSIDE west-pane
				,	west__togglerTip_open:		"Close West Pane"
				,	west__togglerTip_closed:		"Open West Pane"
				,	west__resizerTip_open:		"Resize West Pane"
				,	west__slideTrigger_open:		"click" 	// default
				//	add 'bounce' option to default 'slide' effect
				,	west__fxSettings_open:		{ easing: "easeOutBounce" }*/
			
		});
		
		if (tt.cg.CurrentPermit === "guest"){
			closePanel("west");
			$("#playspace").css("background-color", "black");	
		}

		
		//$(".ui-layout-toggler").append("<img  src='http://www.iconspedia.com/uploads/1775723519.png'/>");
		
		
	}
	
	function closePanel(panel){	
		if(panel === "east"){
			tt.cg.layout.sizePane("east",100);
		}else if (panel === "south"){
			tt.cg.layout.sizePane("south",50);
		}else if (panel === "west"){
			tt.cg.layout.sizePane("west",70);
		}else{		
			tt.cg.layout.close(panel);	
		}
	}

	function openPanel(panel){
		if(panel === "east"){
			tt.cg.layout.sizePane("east",480);
		}else if (panel === "south"){
			tt.cg.layout.sizePane("south",180);}
		else if (panel === "west"){
			tt.cg.layout.sizePane("west",360);
		}else{
			tt.cg.layout.open(panel);	
		}
	}
	
	function clearPanels(){
		//closePanel("east");
		if(tt.cg.activeCtrl !== "None"){
			var ctrlMe = $("#ctrl" + tt.cg.activeCtrl).get(0);
			tt.makeControlSpace.SetCtrlIcon(ctrlMe,"Compressed");
		}
		
		if(tt.cg.playspaceOpen)tt.makePlayspace.TogglePlayspace();
		//closePanel("west");
		if(tt.cg.fisheyeOpen)tt.makeFisheye.ToggleFisheye();
		//closePanel("south");		
	}
	
	/*	

	// save selector strings to vars so we don't have to repeat it
	// must prefix paneClass with "body > " to target ONLY the outerLayout panes
	var westSelector = "body > .ui-layout-west"; // outer-west pane

	 // CREATE SPANs for pin-buttons - using a generic class as identifiers
	$("<span></span>").addClass("pin-button").prependTo( westSelector );
	// BIND events to pin-buttons to make them functional
	tt.cg.layout.addPinBtn( westSelector +" .pin-button", "west");

	 // CREATE SPANs for close-buttons - using unique IDs as identifiers
	$("<span></span>").attr("id", "west-closer" ).prependTo( westSelector );
	// BIND layout events to close-buttons to make them functional
	tt.cg.layout.addCloseBtn("#west-closer", "west");

*/
	

	function initTabs(){
	
	$("#wsTabs").tabs({
			select: function(event, ui) { 
				addTabs(ui.index);
			}

		});
		
	}
	
	function addTabs(idx){
//alert("here"); 
	switch(idx){
		case 0: tt.ws.SetCurrentRecord(Resource); break;
		case 1: tt.ws.SetCurrentRecord(Feature); break;
		case 2: tt.ws.SetCurrentRecord(Help); break;
		case 3: tt.ws.SetCurrentRecord(Message); break;
		case 4: tt.ws.SetCurrentRecord(User); break;
	}
	
//	<!-- 
//	<span id="editResources" class="divButton" onclick="tt.ws.SetCurrentRecord(Resource);" title="Resources">RSC</span>
//	<span id="editFeatures" class="divButton" onclick="tt.ws.SetCurrentRecord(Feature);" title="Features">FTR</span>
//	<span id="editHelp" class="divButton" onclick="tt.ws.SetCurrentRecord(Help);" title="Help">HLP</span>
//	<span id="editMessages" class="divButton" onclick="tt.ws.SetCurrentRecord(Message);" title="Messages">MSG</span>			
//	
//<xsl:if test="contains($permit,'admin')">	
//	<span id="editUsers" class="divButton" onclick="tt.ws.SetCurrentRecord(User);" title="User">USR</span>
//</xsl:if>
	
	}


	//public methods
	return {
		InitLayout : function() {initLayout();},
		ClosePanel : function(panel) {closePanel(panel);},
		OpenPanel : function(panel) {openPanel(panel);},
		ClearPanels : function() {clearPanels();},
		InitTabs : function() {initTabs();}
	}
})();



/*
 * singleton for upload html
 * 
 */

var ttMakeUpload; //shortcut
tt.makeUpload = ( function() {

	function setContentUpload() {
		var cA = [];

		cA.push("<div class='resource'>");
		cA.push("<div id='upload'>");
		cA.push("<hr/>");
		cA.push("Upload your GEDCOM or FOAF file:");
		cA.push("<div id='upload'>");
		cA.push("<form method='POST' enctype='multipart/form-data' action='kml' id='uploadform'> ");
		cA.push("<span style='color:black'>GED File to upload: </span><input type='file' name='uploadGEDCOM'><br>");
		cA.push("<span style='color:black'>FOAF File to upload: </span><input type='file' name='uploadFOAF'><br>");
		cA.push("<span style='color:black'>Topic Title: </span><input type='text' name='note'><br/> ");
		cA.push("<br/> ");
		cA.push("<input type='submit' value='Press' ><span style='color:black'> to upload the file!</span>");
		cA.push("</form></div>");
		cA.push("</div></div>");
		cA.push("<div id='upload' >Upload File</div><span id='status' ></span>");
		cA.push("<!--List Files-->");
		cA.push("<ul id='files' ></ul>");

		return cA.join("");
	}

	//the ajax upload does not work currently
	function uploadFile() {
		$.ajax( {
			type : "POST",
			url : "kml",
			cache : false,
			//data: "&key=" + tt.cg.requestedHelp ,
			success : function(msg) {
				//tt.cg.help = eval('(' + msg + ')');

			cA.push("<br>testing success <br> ");
		}
		});

		/*
		 * /////*cA.push("<form method='POST' enctype='multipart/form-data'
		 * action='kml' id='uploadform'> "); cA.push("GED File to upload: <input
		 * type='file' name='uploadGEDCOM'><br>"); cA.push("FOAF File to
		 * upload: <input type='file' name='uploadFOAF'><br>"); cA.push("Topic
		 * Title: <input type='text' name='note'><br/> "); cA.push("<br/> ");
		 * cA.push("<input type='submit' value='Press' > to upload the file!");
		 * cA.push("</form></div>");
		 */
	}

	//public methods
	return {
		HTML : function() {
			return setContentUpload();
		}
	}
})();

var ttMakeLogin; //shortcut
tt.makeLogin = ( function() {

	function setContentLogin() {
		var cA = [];

		
		//cA.push("<div id='login' style='float:left;'>");
		cA.push("<iframe src='https://timetrails.rpxnow.com/openid/embed?token_url=");	
		cA.push(tt.cg.currentRpxTokenUrl);
		cA.push("' scrolling='no' frameBorder='no' style='width:360px;height:220px;'>");
		cA.push("</iframe>");
		cA.push("<div id='loginWelcome'>WELCOME " + tt.cg.CurrentPermit.toUpperCase() + "</div>");
		//cA.push("</div>");

		return cA.join("");
	}
	//public methods
	return {
		HTML : function() {
			return setContentLogin();
		}
	}
})();


var ttMakeHelp//shortcut
tt.makeHelp = ( function() {
	
	function setContentHelp() {			
		var cA = [];

		if (tt.cg.help == null) {
			resetHelp("Help_0");
		}		
		
		cA.push("<div class='resource'>");	
		
		//test
		//cA.push("<span onclick='tt.NewHelp.ResetNewHelp(\"Help_0\");'>Test New Help</span>");		
		//cA.push("<div id='newHelp'></div>");
		
		
		cA.push("<div class='Help'>");
		cA.push("<div class='Question standardHeading'>");
		if (tt.cg.help.key != "Help_0") {
			var lastHelp = tt.cg.help.key.substring(0,
					tt.cg.help.key.length - 2);
//(lastHelp);
			cA.push("<span onclick='tt.makeHelp.ResetHelp(\"" + lastHelp + "\");'>");
			cA.push(tt.cg.help.question);
			cA.push("</span>");
		} else {
			cA.push(tt.cg.help.question);
		}
		cA.push("<br/><br/>");
		if (tt.cg.help.subquestions) // show each subquestion
		{
			for ( var i = 0; i < tt.cg.help.subquestions.length; i++) {
				SubQ = tt.cg.help.subquestions[i];
//(SubQ.position);					
				cA.push("<span class='SubQuestion standardLetter' onClick='tt.makeHelp.ResetHelp(\""
						+ SubQ.position + "\");'>" + SubQ.question
						+ "</span>");
			}
		}
		cA.push("<hr/>");
		cA.push("</div><div class='Answer' style='display:none'>");
		
		//snag any youtube shunts
		var shuLink = "";
		var answer = tt.cg.help.answer;
		var shuPositonStart = answer.lastIndexOf(':::') + 3;
		var shuPositonEnd = answer.lastIndexOf('::;');
		if (shuPositonStart > 0 && shuPositonEnd > 0) {
			//grab the shunt link
			shuLink = answer.substring(shuPositonStart, shuPositonEnd);
			// remove the img url
			answer = answer.replace(':::' + shuLink + '::;', '');
		}
		
		//do we have a shunt linking to a youtube trailer?
		if(shuLink){		
			cA.push("<div><span style='float:right' id='geClipButton' ");
			cA.push("onclick='tt.makeBalloon.DisplayBalloon(\"" + shuLink 
					+ "\",\"YouTube\");'><img src='" 
					+ tt.cg.appimg + "fullscreen.png' style='height:30px;width:30px;' ></img></span></div>");	
			cA.push("<object width='320' height='200'>");
			cA.push("<param name='movie' ");					
			cA.push("value='" + shuLink + "'/>");
			cA.push("<param name='allowFullScreen' value='true'/>");
			cA.push("<embed src='" + shuLink + "' ");
			cA.push("type='application/x-shockwave-flash' allowfullscreen='true'");
			cA.push("width='320' height='200'></embed></object>");
		}
		cA.push("<div class='standardType'>" + answer + "</div>");
		cA.push("</div></div></div>");		
//(cA.join(""));
		return cA.join("");
	}

	function resetHelp(reqHelp) {
//(reqHelp);
		$.ajax( {
			type : "GET",
			url : "ui?actionRequest=getHelpUI",
			data : "&key=" + reqHelp,
			cache : false,
			async : false,
			success : function(msg) {
//("success: " + msg);
				tt.cg.help = eval('(' + msg + ')');
				$('#utilitySpace').html(setContentHelp());
				setHelp();
			}
		});
	}
	
	function setHelp() {
		
		$(".Answer").show();				
		$('.standardType').jTypeWriter();	
		
	}

	//public methods
	return {
		HTML : function() { return setContentHelp(); },
		ResetHelp : function(reqHelp) { resetHelp(reqHelp);},
		SetHelp : function() { setHelp(); }
	}
})();

var ttNewHelp; //shortcut
tt.NewHelp = ( function() {

	//test
	//parse returned json - have to eval to get func
	//unpack json into html with sent function
	//open in popup window or in target div
	
	function resetNewHelp(reqHelpID) {
		$.ajax( {
			type : "GET",
			url : "ui?actionRequest=getNewHelpUI",
			data : "&key=" + reqHelpID,
			cache : false,
			async : false,
			success : function(msg) {
("success: " + msg);
				var newHelp = eval('(' + msg + ')');
				var target = $("#newHelp");
				newHelp.deploy(target);
			}
		});
	}	
	
	//public methods
	return {
		ResetNewHelp : function(reqHelpID) { resetNewHelp(reqHelpID); }
	}
})();


var ttMakeForum //shortcut
tt.makeForum = ( function() {
	
//	function setSelected(obj){
//		$(".selectThread").removeClass("standardSelected");
//		$(obj).addClass("standardSelected");		
//	}
	
//MAKE THREAD LIST
	function setForum() {
		$.ajax({
			type: "GET",
			url: "ui",
			data: "actionRequest=getMessage",
			cache : false,
			asynch: false,
			success: function(msg){
				setContentThreads(msg);
//("success " + msg);
			},
			error: function(xhr, status, error) {
				setContentThreads(xhr.responseText);
//("error " + xhr.responseText);
			}			  
		});
	}
	
	function setContentThreads(msg){
		
		tt.cg.forum = eval('(' + msg + ')');
		
		var cA = [];

		cA.push("<div id='threadList' class='loadForum'>");	
		cA.push("<div class='standardHeading'>Public Discussions</div>");
		for(i=0; i<tt.cg.forum.messages.length; i++)
		{
			var r = tt.cg.forum.messages[i];
			cA.push("<div id='" + r.Position + "' class='standardNoType standardItem' ");
			cA.push("onclick='tt.makeForum.SelectThread(\"" 
					+ r.Position + "\");'>" + r.ThreadName + "</div>");
		}		
		cA.push("</div>");

//(cA.join(""));
		$('#utilitySpace').html( cA.join(""));
		//$('.standardType').jTypeWriter();
		
	}
	
	
//MAKE MESSAGE LIST
	
	function selectThread(position) {	
		

		tt.cg.currentThread = position;
//("here");

		var cA = [];

		$.ajax({
		   type: "GET",
		   url: "ui",
		   //data: "actionRequest=getMessage&type=onlyMessages&position="+$("#availableThreads option:selected").val(),
		   data: "actionRequest=getMessage&type=onlyMessages&position="+position,
		   cache : false,
		   asynch : false,
		   success: function(msg){
			   setContentMessages(msg);			
		   },
		   error: function(xhr, status, error) {
			   setContentMessages(xhr.responseText);	
		   }
	
		 });
		
	}
	
	function setContentMessages(msg){
		
		var cA = [];
		
		tt.cg.forum = eval('(' + msg + ')');
//(msg + " " + tt.cg.forum.messages.length);
		
		
		cA.push("<div class='standardHeading standardClickable' onclick='tt.makeForum.SetForum();'>Messages</div>");
		
		cA.push("<div class='standardHeading threadPosition'>");
		cA.push(tt.cg.forum.messages[0].ThreadName);
		cA.push("</div>");
		cA.push("<div id='messageList' class='loadForum'>");
		if(tt.cg.CurrentEmail!=="")
		{		
			cA.push("<div>Post Message</div>");
			cA.push("<textarea id='enterMessageToThread' cols='30' rows='3'></textarea><br/>");
			cA.push("<input type='button' id='buttonPostMessageToThread' onclick='tt.makeForum.PostMessageToThread();' value='Send'/>");
		}							
		tt.cg.forum.messages.sort(compareDates); //Descending Sort 
		if(tt.cg.forum.messages.length>0)
		{	
			//create message list
			
			var m;
			for(i=0; i<tt.cg.forum.messages.length; i++)
			{
				m = tt.cg.forum.messages[i];
				var localDate = isoToDate(m.DateTime);
				var localDateStr = localDate.toLocaleDateString()
					+ " " + localDate.toLocaleTimeString();
				var shortUserName = m.EnteredBy.substring(0,m.EnteredBy.indexOf("@"));
				
//(r.DateTime + "  " + localDate);
				cA.push("<div class='standardType standardItem'>" + m.Body);
				cA.push("</div><div class='standardMinimum standardType'>" 
						+ shortUserName + "   " + localDateStr 
						+ "</div>");
			}
			cA.push("</div>");

//(cA.join(""));		
			$("#utilitySpace").empty().html(cA.join(""));	
			$('.standardType').jTypeWriter();
		}						
	}
	

	//POST MESSAGE
	
	function compareDates(a, b) {			
		
		var dateA = isoToDate(a.DateTime.replace(" ","T"));
		var dateB = isoToDate(b.DateTime.replace(" ","T"));
		//("a.DateTime: "+a.DateTime + " b.DateTime: "+b.DateTime+ " dateA:"+dateA+" dateB:"+dateB);
		return dateB-dateA;
	}

	function postMessageToThread() {
		var nowFormatted;
		var now = new Date(); 
		var utcDate = dateToISO(now,"YYYY-mm-DDThh:MM");

//(tt.cg.currentThread);
				
		if(tt.cg.currentThread!="")
		{	
			$.ajax({
				   type: "GET",
				   url: "ui",
				   beforeSend: function(){ },
				   data: "actionRequest=addMessage"
						+ "&Position=" + tt.cg.currentThread
							+ "_0_"+Math.ceil((Math.random()*100000))
						+ "&ThreadName="+ $(".threadPosition").text()
						+ "&Body="+ $("#enterMessageToThread").val()
						+ "&EnteredBy="+tt.cg.CurrentEmail
						+ "&DateTime="+utcDate,
				   cache : false,
				   success: function(msg){
						("success");
						$("#enterMessageToThread").text("");
				   },
				   error: function(xhr, status, error) {
					   ("error");
				   }			
				 });
			selectThread(tt.cg.currentThread);//Refreshing the Thread's list
		}
		else
		{
			("Select a Discussion Thread!");
		}
	}

	//public methods
	return {
		SetForum : function() {
			return setForum();
		},
		SelectThread : function(position) {
			selectThread(position);
		},
		SetSelected : function(obj) { setSelected(obj); },
		ShowMessage : function() {
			showMessage();
		},
		PostMessageToThread : function() {
			postMessageToThread();
		}

	}
})();


var ttMakeSearch; //shortcut
tt.makeSearch = ( function() {
	
	
	//GEOCODE EXAMPLE
	//ctrlHTML.push("To drive: use the buttons, or keyboard arrows (with focus on page).");
	//ctrlHTML.push("<div>");
	//ctrlHTML.push("<form name='searchform' id='searchform' action='javascript:submitLocation();void(0);'>");
	//ctrlHTML.push("<input type=text size=40 id='address' value='(enter a location)'></input>");
	//ctrlHTML.push("<input type=submit value='Teleport!'>");
	//ctrlHTML.push("</form>");
	//ctrlHTML.push("Presets:");
	//ctrlHTML.push("<input type=button value=\"San Fran\" onclick=\"doGeocode('San Francisco');\">");
	//ctrlHTML.push("<input type=button value=\"Everest\" onclick=\"truck.teleportTo(27.991283,86.924340,70);\">");
	//ctrlHTML.push("</div>");
	
	function setContentSearch() {
		var cA = [];
			
		cA.push("<div>");
		cA.push("<div id='topControl'>");	
		//cA.push("<DIV id='ctrlPanelTitle'>Title</DIV>");		
		
		//cA.push("<div id='waitingIcon'></div>");
		//cA.push("<span id='waitingMsg'></span>");
		
		//cA.push("<div id='viewButton'  ");
		//cA.push("onclick='tt.getFeatures.ViewTimeTrails();' style='display:none;'>View Time Trails!</div>");		
		
		cA.push("<input id='searchPhrase'></input>");
		cA.push("<input type='button' onclick='tt.makeSearch.SetSearch();');' value='Search'/>");		
		cA.push("</div>");
		cA.push("<div id='loadSearch'></div>");
		cA.push("</div>");

		return cA.join("");
	}
	
	function setSearch() {
	
		var searchPhrase = $("#searchPhrase").val();
		$("#loadSearch").empty().html(setContentTopics() + setContentThemes());				
		$('.standardType').jTypeWriter();	
		
	}
	
	function setSelected(obj){
		$(".selectTheme").removeClass("standardSelected");
		$(".selectTopic").removeClass("standardSelected");
		$(obj).addClass("standardSelected");
		
	}
	
	function showTopic(topicIndex) {
		//(topicIndex);
		// 32.26453,49.76261:2922km
		
		var parts = tt.cg.topics.topics[topicIndex].Coords.split(':');
		var km = parts[1].substring(0, parts[1].indexOf('km'));
		parts = parts[0].split(',');
		var lat = parts[0];
		var lon = parts[1];
		var start = tt.cg.topics.topics[topicIndex].Begin;
		var end = tt.cg.topics.topics[topicIndex].End;
		
		tt.cg.topickeywords = tt.cg.topics.topics[topicIndex].Position + ".";
		tt.cg.topicname = tt.cg.topics.topics[topicIndex].Name;
		
		
		// (lon + " " + lat + " " + km + " " + start + " " + end);

		tt.timesel.SetLimits( [ 0, 0 ], start, end);
		
		// clear existing features
		tt.feature.ClearAllFeatures();

		// call for features and animate
		// (lat + ", " + lon);

		ge.setBalloon(null);

//		jQuery.each(jQuery.browser, function(i) {
//		  if(!$.browser.msie){  //ie blows up on gex call
//			  gex.util.lookAt( [ parseFloat(lat), parseFloat(lon) ], {
//					range : (km * 3000)});			 
//		  break;
//		  }
//		});
		
		flyToLocation(parseFloat(lon),parseFloat(lat),km * 2000);
		
		//("topics");
		//reset view icon
		//tt.makeWait.ShowViewIcon(false);
		//reset View Button
		//tt.makeWait.SetViewButton(true);	
		tt.makeBalloon.DisplayBalloon("","Wait");
	}

	function setContentTopics() {
		
//("start topics");		
		var cA = [];
		if (tt.cg.topics === null) {
			//tt.getFeatures.SendTopicRequest();
			tt.getFeatures.SendAjax("topics");
		}
		cA.push("<div class='standardType standardHeading'>TOPICS</div>");
		if (tt.cg.topics) {
			for ( var key in tt.cg.topics.topics) {
				if(!isNaN(key)){
					var idTopic = tt.cg.topics.topics[key].Position;
					var label = tt.cg.topics.topics[key].Name;
					var colorFont = "blue";
					var nameStr = tt.cg.topics.topics[key].Name + "";
					if (nameStr.indexOf("GED*") >= 0) {
						colorFont = "red";
						label = label.replace("GED*", "");
					}
					if (nameStr.indexOf("FOAF*") >= 0) {
						colorFont = "green";
						label = label.replace("FOAF*", "");
					}
					
					cA.push("<div id='" + idTopic + "' class='selectTopic standardType standardItem' ");
					cA.push("onclick='tt.makeSearch.SetSelected(this);tt.makeSearch.ShowTopic(\"" + key + "\");' >" + label + "</div>");
					//cA.push("style='cursor:pointer;color:" + colorFont + ";'>" + label + "</div>");
				}
			}
		}
		//cA.push("</div>");
//("end topics");
		return cA.join("");
		
	}


	
	/***THEMES
	 * 
	 */
	
		
		function toggleSelected(obj, theme){
			//clear all topics
			$(".selectTopic").removeClass("standardSelected");
			//turn this theme on or off
			if($(obj).hasClass("standardSelected")){
				$(obj).removeClass("standardSelected");
				tt.cg.themeList[theme].selected = false;
			}else{
				$(obj).addClass("standardSelected");
				tt.cg.themeList[theme].selected = true;
			}
			
		}
		
		
		function setContentThemes() {
			var cA = [];

			// NOTES:
			/*
			 * must show all themes possible (themeList keys) must indicate
			 * (gray out/disable) which are not available (themeList values) because
			 * of latest time/space settings must show user's on/off selections
			 * (checkedThemes), and allow user to reset them
			 */
			
			if (tt.cg.themeList === null) {
				//tt.getFeatures.SendThemeRequest();
				tt.getFeatures.SendAjax("themes");
			}

			cA.push("<div class='standardType standardHeading'>THEMES</div>");
			cA.push("<div id='selectedKeywords' >");
		
			//for debugging
			var msg = "";
			for(var theme in tt.cg.themeList)
			{
			msg += theme + " loaded:" + tt.cg.themeList[theme].loaded + " seld: "
			  + tt.cg.themeList[theme].selected + "\n";
			}
//("tt.cg.themeList: \n" + msg);

			for ( var theme in tt.cg.themeList) {
				var themeName = theme.replace("_", " ");
				
				themeName = themeName.substring(0,1) + themeName.substring(1).toLowerCase();

				var sel = "";
				if (tt.cg.themeList[theme].selected) {
					sel = "standardSelected";
				}
				cA.push("<div id = 'id" + theme + "' class='" + sel + " selectTheme standardType standardItem' ");
				cA.push(" onclick='tt.makeSearch.ToggleSelected(this,\"" + theme + "\");tt.makeSearch.CheckTheme();'>" + themeName);
				cA.push("</div>");
			}
					
			cA.push("</div></br>");
			return cA.join("");
		}

		

		function getCheckedThemes() {
			var result = "";
			
//			var first = true;
//			$(".selectTheme .standardSelected").each(function() {			
//				var theme = $(this).attr("id");
//				if (!first) {
//					result += "|";
//				} else {
//					first = false;
//				}
//				result += theme;
//			});
			
			var first = true;
			for (theme in tt.cg.themeList) {
				if (tt.cg.themeList[theme].selected) {
					if (!first) {
						result += ", ";
					} else {
						first = false;
					}
					result += theme;
				}
			}
			
			
//("checked themes: \n" + result);
			return result;

		}

		function resetThemeCheckBoxes() {

			isSelected = $("#resetChecks ").attr("checked");
			$("#selectedKeywords :checkbox").each(function(){
				this.checked = isSelected;	
				//not working
				for (theme in tt.cg.themeList) {
					if (tt.cg.themeList[theme] == $(this).html()) {
						tt.cg.themeList[theme].selected = isSelected;
					}		
				}					
			});
			
			checkTheme();
			
		}
		
		function checkTheme(){
			
			tt.cg.topickeywords = null;
			//("theme");
			//reset view icon
			//tt.makeWait.ShowViewIcon(false);
			//reset view button
			//tt.makeWait.SetViewButton(true);	
			tt.makeBalloon.DisplayBalloon("","Wait");
		}
	
		
	//public methods
	return {
		HTML : function() {
			return setContentSearch();
		},
		SetSearch : function() {
			return setSearch();
		},
		ShowTopic : function(topicIndex) {
			showTopic(topicIndex);
		},
		SetSelected : function(objSent) {
			setSelected(objSent);
		},
		ResetThemeCheckBoxes : function() {
			resetThemeCheckBoxes();
		},
		GetCheckedThemes : function() {
			return getCheckedThemes();
		},
		CheckTheme : function() {
			checkTheme();
		},
		ToggleSelected : function(obj, theme) {
			toggleSelected(obj, theme);
		}
	}
})();


var ttMakeWait; //shortcut
tt.makeWait = ( function() {
		
	function setViewButton(isOn)
	{		
		
		//("keywords: " + tt.cg.topickeywords + (tt.cg.themeList ? " themeList len: " + tt.cg.themeList.length : ""));
		
		var viewLabel = "";
		if(isOn){		
			//either harvest single selected topic
			if(tt.cg.topickeywords) {
				viewLabel = tt.cg.topicname;
			} else {//or harvest themes
				var themes = "";
				var first = true;
				for (theme in tt.cg.themeList) {
					if (tt.cg.themeList[theme].selected) {
						if (!first) {
							themes += ", ";
						} else {
							first = false;
						}
						themes += theme;
					}
				}
//("setViewB " + themes);
				viewLabel = themes;
			}
			if(viewLabel){
				//harvest time
				var viewTime = tt.timesel.CurrentStartDate(true) + " to " 
						+ tt.timesel.CurrentEndDate(true);
			
				viewLabel = "View " + viewLabel + " : " + viewTime;
				//reset keywords
				
					
				$("#viewButton").show();
				$("#viewButton").text(viewLabel);
				//(label);
				blue();
				setTimeout(blink,500);
			}else{
				$("#viewButton").hide();	
				$("#viewButton").text("");
			}
			
		}else{
			$("#viewButton").hide();	
			$("#viewButton").text("");
		}
		
		function blue(){
			$("#viewButton").css("background-color","blue");
			$("#viewButton").css("color","white");			
		}
		
		function blink(){
			$("#viewButton").css("background-color","white");
			$("#viewButton").css("color","black");	
			setTimeout(blue,200);
		}
	}
	
	function showViewIcon(isOn,whichIcon,msg){
		if(isOn){
			var iconUrl = "";
			if(whichIcon==="Waiting"){
				iconUrl = tt.cg.appimg + "waiting_orange.gif";
			}else if(whichIcon==="Starting"){
				iconUrl = tt.cg.appimg + "startingarrow.gif";
			}
			$("#waitingIcon").empty().html('<img src="' + iconUrl + '" />');
			$("#waitingMsg").empty().html(msg);
		}else{
			$("#waitingIcon").empty();
			$("#waitingMsg").empty();
		}
	}	
	

	//public methods
	return {
		SetViewButton : function(isOn) {setViewButton(isOn)},		
		ShowViewIcon : function(isOn,whichIcon,msg) { showViewIcon(isOn,whichIcon,msg); }
	}
})();

var ttGetResources; //shortcut
tt.getResources = ( function() {
	
	function sendAjax(target){
		
		var actionUrl = "";
		var dataUrl = "";
		var targetFunc = null;

		//set query factors
		switch(target){
			case "resImage":
				actionUrl = "getResource";
				dataUrl = "&keywords=Model3D";
				targetFunc = (function(msg) { 
					tt.cg.resourcesTimelined =  eval('(' + msg + ')');
					});	
				break;
			case "avacles":
				actionUrl = "getResource";
				dataUrl = "&keywords=Avacle";
				targetFunc = (function(msg) { 
					tt.cg.resourcesAvacled =  eval('(' + msg + ')');
					});	
				break;
			default:
				actionUrl = "getResourceUI";
				dataUrl = "&ctrLat=" + tt.cg.latitude 
					+ "&ctrLon=" + tt.cg.longitude
					+ "&start=" + tt.timesel.CurrentStartDate() 
					+ "&end=" + tt.timesel.CurrentEndDate() 
					+ "&resStartIndex=" + tt.cg.resStartIndex  
					+ "&resStopIndex=" + tt.cg.resStopIndex
					+ "&resMatchType=" + tt.cg.resMatchType;
				targetFunc = (function(msg) { 
					tt.cg.resourcesRequested =  eval('(' + msg + ')');
					});
		}
				
		$.ajax( {
			type : "GET",
			url : "ui?actionRequest=" + actionUrl,
			data : dataUrl,
			async : false,
			cache : false,
			success : function(msg) {
//("success " + msg);				
				targetFunc(msg);
			},
			error: function(xhr, status, error) {
//("error " + xhr.responseText);				
				targetFunc(xhr.responseText);
			}
		});		
	}
		
	//public
	return {		
		SendAjax : function(target) { sendAjax(target); }
	}
	
})();


var ttGetFeatures; //shortcut
tt.getFeatures = ( function() {

	var xJax = null;
	
	//private
	function viewTimeTrails(){

		clearFeatureRefresh();
		
		var urlStr = "";
		var dataStr = "";	

		if(tt.cg.topickeywords)
		{
			urlStr = "ui?actionRequest=getFeature";
			dataStr = "&keywords=" + tt.cg.topickeywords;
		} else {
			urlStr = "ui?actionRequest=getFeatureUI";
			dataStr = "&start=" + tt.timesel.CurrentStartDate()
				+ "&end=" + tt.timesel.CurrentEndDate() 
				+ "&themes=" + tt.makeSearch.GetCheckedThemes();	
(!tt.makeSearch.GetCheckedThemes());
			if(!tt.makeSearch.GetCheckedThemes()) return;
		}
			
		xJax = $.ajax({
			type: "GET",
			url: urlStr,
			data: dataStr,
			cache:false,
			beforeSend: function() { 
				//tt.makeWait.SetViewButton(false);
				//tt.makeWait.ShowViewIcon(true,"Waiting","Loading Maps...");
				//tt.makeBalloon.DisplayBalloon("","Wait");
				},
		    complete: function() { 
				//tt.makeWait.ShowViewIcon(true,"Starting","Click the Play Arrow to Start"); 
				//tt.makeBalloon.Close();
				//tt.makeLayout.ClearPanels();
				//setTimeout("tt.makeLayout.ClearPanels();",3000);
				}, 
			//$("#playAnimation").empty().html('<div class="utilityButton" onclick="">Play to start</div>')},
			success: function(msg){			
				var featuresIn = eval('(' + msg + ')');
				tt.animation.SetFeatures(featuresIn);
				tt.animation.MakeTimeTrail();
				tt.cg.topickeywords = null;
				tt.makeBalloon.Close();
				tt.makeLayout.ClearPanels();
			}
		});		
	}

	function clearFeatureRefresh(){
		//NOTE - this ajax call is a hack to clear the ge timeslider control!!!			
		$.ajax({
			type: "GET",
			async : false,
			url: "ui?actionRequest=getFeatureUI",
			data: "&start=2222-01-01&end=2223-01-01",
			cache:false,
			success: function(msg){
				clearFeatures();
			}
		});		
		
	}
	
	function fetchSingleFeature(keyword) {
		
//("key " + keyword);

		$.ajax( {
			type : "GET",
			url :  "ui?actionRequest=getFeatureRes",
			data :  "&keywords=" + keyword,
			cache : false,
			success : function(msg) {
//("sendF success");
				processFeature(msg);
			},
			error: function(xhr, status, error) {
//("sendF error");
				processFeature(xhr.responseText);
			}
		});
	}
	
	
	function processFeature(msg){
		//("returned msg: " + msg);	

		featureObj = eval('(' + msg + ')');
		//if(featureObj.features.length !== 1) ("zero or two features where one expected");
		
		var f = featureObj.features[0];
		var resDesc = f.Description;
		var resName = f.Name;
		var resImg = ""; //for image
		var resSwf = ""; //for pdf-swf
		var resURI = ""; //for link

		//hands off a pdf to link to for the feature
		var imgPositonStart = resDesc.lastIndexOf('::::') + 4;
		var imgPositonEnd = resDesc.lastIndexOf(':::;');
		if (imgPositonStart > 0 && imgPositonEnd > 0) {
			//grab the pdf-swf url
			resSwf = resDesc.substring(imgPositonStart, imgPositonEnd);
			// remove the img url
			resDesc = resDesc.replace('::::' + resSwf + ':::;', '');
		}
		
		//hands off an image to display for the feature
		var imgPositonStart = resDesc.lastIndexOf(':::') + 3;
		var imgPositonEnd = resDesc.lastIndexOf('::;');
		if (imgPositonStart > 0 && imgPositonEnd > 0) {
			//grab the img url
			resImg = resDesc.substring(imgPositonStart, imgPositonEnd);
			// remove the img url
			resDesc = resDesc.replace(':::' + resImg + '::;', '');
		}
	
		//hands off a link (wiki ie) to link to for feature
		var uriPositionStart = resDesc.lastIndexOf('::') + 2;
		var uriPositionEnd = resDesc.lastIndexOf(':;');
		if (uriPositionStart > 0 && uriPositionEnd > 0) {
			resURI = resDesc.substring(uriPositionStart, uriPositionEnd);
			resDesc = resDesc.replace('::' + resURI + ':;', '');
		}		

//		'features' : [{'Position' : 'F.180.111','Style' : 'O_n_000_010_004_0_00_100','Name' : 'Virginia 1607-1788',
//			'Begin' : '1607-01-01','End' : '1788-01-01','Coords' : '','Description' : 'Colonial Borders',
//			'Notes' : 'based on Rand Historical Atlas','EnteredBy' : 'tyson.ben@gmail.com','Recipients' : '',
//			'Themes' : 'Settlement;Politics'
			
		
		
		//imgBase (-.kmz),resType,asin,otherUri (wiki),name,desc
	
		var imgBase = resImg.replace(".jpg","");
		var resType = (resSwf ? "Text" : "FeatureInfo");
		var asin = "";
		var otherUri = resURI;
		var name = resName;
		var desc = resDesc;
		var img = resImg;
	
		tt.makePlayspace.AddToy(imgBase, resType, asin, otherUri, name, desc, img, "", resSwf);

	}
	
	function loadThemes(msg){
		//("incoming theme list: " + msg);
		var themeArray = eval('(' + msg + ')');
		tt.cg.themeList = new Object();
		for (i = 0; i < themeArray.themes.length; i++) {
			tt.cg.themeList[themeArray.themes[i]] = {
				'loaded' : true,
				'selected' : false
			};
		}			
	}

	function sendAjax(target){
		
		var actionUrl = "";
		var dataUrl = "";
		var targetFunc = null;
	
		//set query factors
		switch(target){
			case "topics":
				actionUrl = "getFeatureTopics";
				dataUrl = "&start=" + tt.timesel.CurrentStartDate() 
					+ "&end=" + tt.timesel.CurrentEndDate() 
					+ "&rnd=" + Math.random();
				targetFunc = (function(msg) { 
					tt.cg.topics = eval('(' + msg + ')');
					
					});	
				break;				
			case "themes":
				actionUrl = "getFeatureThemes";
				dataUrl = "&start=" + tt.timesel.CurrentStartDate() + "&end="
						+ tt.timesel.CurrentEndDate() + "&themes="
						+ tt.makeSearch.GetCheckedThemes();
				targetFunc = (function(msg) { 
						loadThemes(msg);
					});	
				break;
			default:
		}
				
		$.ajax( {
			type : "GET",
			url : "ui?actionRequest=" + actionUrl,
			data : dataUrl,
			async : false,
			cache : false,
			success : function(msg) {
//("feature success");				
				targetFunc(msg);
			},
			error: function(xhr, status, error) {
//("features error");				
				targetFunc(xhr.responseText);
			}
		});		
	}
	
	//public
	return {
		
		SendAjax : function(target) { sendAjax(target); },
		ViewTimeTrails : function() {viewTimeTrails();},
		FetchSingleFeature : function(keyword){ fetchSingleFeature(keyword); },
		SendTopicRequest : function() { sendTopicRequest(); },
		SendThemeRequest : function() { sendThemeRequest(); },
		ClearFeatureRefresh : function() { clearFeatureRefresh(); },
		AbortAjax : function() { if(xJax)xJax.abort(); } 
				
	}
})();



/*
 * singleton for feature handling
 * 
 * @author ktyson
 */

var ttFeature //shortcut
tt.feature = ( function() {

	//private attributes in closure
	var featureMode = null;
	var editModeOn = false;

	// private methods in closure

	function setCurrentByView() {
		var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
		tt.cg.latitude = lookAt.getLatitude();
		tt.cg.longitude = lookAt.getLongitude();
		tt.cg.altitude = lookAt.getAltitude();
	}

	function clearAllFeatures() {
		var features = ge.getFeatures();
		while (features.hasChildNodes()) {
			var node = features.getLastChild();
			features.removeChild(node);
		}
	}

	function setEdit(isOn, sendingElement) {
		editModeOn = isOn;

		// var msg = "Edit mode is " + (editModeOn ? "on" : "off") + ".";
		// (msg);

		if (sendingElement) {
			sendingElement.style.backgroundColor = (editModeOn ? '#ffff00'
					: '#f5f5dc');
		} else {
			var buttons = getElementsByClass("mapUI2");
			buttons[0].style.backgroundColor = (editModeOn ? '#ffff00'
					: '#f5f5dc');
		}
	}

	function setMode(type, sendingElement) {
		deBugClog("3dmap", "setMode " + type);
		if (type !== featureMode) {
			featureMode = type;
			clearAllFeatures();
			tt.cg.points.length = 0;
			tt.cg.circles.length = 0;
			// ("Feature mode changed to " + featureMode);
		}
		var buttons = getElementsByClass("mapUI1");
		// reset other colors
		// NOTE - move to workspace?
		for (b in buttons) {
			buttons[b].style.backgroundColor = 'f5f5dc';
		}
		if (type !== null) {
			//make this color
			sendingElement.style.backgroundColor = '#ffff00';
			// clearEntry();
		}
	}

	function writeCoords() {
		//("here");
		var content = "";

		if (featureMode === "circle") {
			//can have a set of resource circles
			while (tt.cg.circles.length > 0) {
				var feature = tt.cg.circles.shift();
				content = content + feature.coverage + "; ";
			}
		}
		if (featureMode === "square") {
			content = content + tt.cg.square.coords;
		}
		if (featureMode === "point") {
			content = content + tt.cg.point.coords;
		}
		if (featureMode === "line") {
			for ( var i = 0; i < tt.cg.points.length; i++) {
				content = content + tt.cg.points[i].lon.toDeg() + ","
						+ tt.cg.points[i].lat.toDeg() + ",0 ";
			}
		}
		if (featureMode === "poly") {
			for ( var j = 0; j < tt.cg.points.length; j++) {
				content = content + tt.cg.points[j].lon.toDeg() + ","
						+ tt.cg.points[j].lat.toDeg() + ",0 ";
			}
			//repeat first to close
			content = content + tt.cg.points[0].lon.toDeg() + ","
					+ tt.cg.points[0].lat.toDeg() + ",0 ";
		}
		$('#entry').val(content);

	}
	function readCoords(coords) {

		//console.log("read " + coords);

		var cH = new coordsetHandler(coords, "X");
		var coordset = cH.coordset;
		var lat = 0;
		var lon = 0;

		if (cH.textIndicator !== "") {
			featureMode = cH.textIndicator;
			if (featureMode === "circle") {

				for (x in coordset) {

					lat = parseFloat(coordset[x].split(',')[0]);
					rest = coordset[x].split(',')[1];
					lon = parseFloat(rest.split(':')[0]);
					rest2 = rest.split(':')[1];
					km = parseFloat(rest2.substring(0, rest2.indexOf("km")));

					// ("lat: " + lat + " lon: " + lon + " km: " + km);

					// latblonb = tt.map.destination(lat,lon,(km * 0.009),0.0);
					latb = lat + (km * 0.009);
					lonb = lon + (km * 0.009);
					// (" latb: " + latb + " lonb: " + lonb);

					sides = 25;
					var polygon = new Polygon(lat, lon, latb, lonb, sides);
					tt.cg.circles.push(polygon);
				}

			}
			if (featureMode === "square") {
			}
			if (featureMode === "point") {
				lat = parseFloat(coordset[0].split(',')[1]);
				lon = parseFloat(coordset[0].split(',')[0]);

				tt.cg.latitude = lat;
				tt.cg.longitude = lon;
			}
			if (featureMode === "line") {
				for (x in coordset) {
					lat = parseFloat(coordset[x].split(',')[1]);
					lon = parseFloat(coordset[x].split(',')[0]);

					var placeLine = new PM(lat, lon, 'pointPlace' + x,
							'ff00ffff');
					tt.cg.points.push(placeLine);
				}
			}
			if (featureMode === "poly") {
				for (x in coordset) {
					lat = parseFloat(coordset[x].split(',')[1]);
					lon = parseFloat(coordset[x].split(',')[0]);

					var placePoly = new PM(lat, lon, 'pointPoly' + x,
							'ff00ffff');
					tt.cg.points.push(placePoly);
				}
			}
			//console.log("draw from readCoords");
			drawFeatures(true);

		}
	}

	function addPointToFeature() {

		var lat = tt.cg.latitude;
		var lon = tt.cg.longitude;
		try {
			//assume user wants a point between the two closest points in array
			var existingPts = [];

			for ( var x = 0; x < tt.cg.points.length; x++) {
				var dist = tt.map.distance(lat.toRad(), lon.toRad(),
						tt.cg.points[x].lat, tt.cg.points[x].lon);
				var pointData = [ x, dist ];
				existingPts.push(pointData);
				// console.log("added pointData for",x,"dist",dist,
				// "lat",tt.cg.points[x].lat.toDeg(), "log",
				// tt.cg.points[x].lon.toDeg(),
				// "new lat",lat,"new lon",lon);
			}
			//go thru the existing distance data to find closest point
			var leastDist = existingPts[0][1];
			var insertIndex = 0;
			for ( var y = 0; y < existingPts.length; y++) {
				if (existingPts[y][1] < leastDist) {
					leastDist = existingPts[y][1];
					insertIndex = y;
				}
				//console.log("checked for least on",y,"dist was",existingPts[y][1],
				//		"least dist now", leastDist,"least index now",insertIndex);
			}
			//choose the index above which to insert
			if (insertIndex === 0) {
				//at start of series
				insertIndex = 0;
			} else {
				if (insertIndex === existingPts.length - 1) {
					//at end of series
					insertIndex = insertIndex + 1;
				} else {
					if (existingPts[insertIndex - 1][1] < existingPts[insertIndex + 1][1]) {
						//in middle, and the previous is closer than the next
						insertIndex = insertIndex;
					} else {
						//next is closer than prev
						insertIndex = insertIndex + 1;
					}
				}
			}
			//console.log("decided to insert at " + insertIndex);

			tt.cg.point = new PM(lat, lon, 'pointPlaceAdded', 'ff00ffff');
			tt.cg.points.splice(insertIndex, 0, tt.cg.point);

			// console.log("draw from addPoint");
			drawFeatures(true);

			// setEdit(false);
		} catch (exc) {
			("add pt error " + exc);
		}

	}

	function removePointFromFeature(pm) {
		//("delete edit");
		try {
			//assume the user wants to delete this point
			// remove the point from the internal collection
			for (x in tt.cg.points) {
				//assume if the lats match exact - its the point
				// console.log("does " + tt.cg.points[x].lat + " = " + pm.lat);
				if (tt.cg.points[x].lat === pm.lat) {
					tt.cg.points.splice(x, 1);

					// console.log("removed " + x);
					break;
				}
			}
			//remove this - the visible ge feature
			ge.getFeatures().removeChild(pm.placemark);
			// turn off edit mode
			// setEdit(false);

			// console.log("draw from removePoint");
			drawFeatures(true);

		} catch (exc) {
			("delete error: " + exc);
		}
	}

	function drawFeatures(isRedraw) {
		//console.log("drawFeatures isRedraw",isRedraw);		
		// if isRedraw=true then the current lat and lon are NOT added first

		// lat and lon have been set on mouseup
		var lat = tt.cg.latitude;
		var lon = tt.cg.longitude;
		// store this point info as a PM in points array

		// create a geometry holder placemark for point, line, poly
		var tempPlacemark = ge.createPlacemark('');
		setStyle(tempPlacemark);
		// create a polygon object for circle, square
		var sides = 0;

		// circles are special cases - used only for resources
		if (featureMode === "circle") {
			sides = 25;
			var polygon = new Polygon(lat, lon, lat + 3, lon + 3, sides);
			tt.cg.circles.push(polygon);
		} else if (featureMode === "square") {
			//only one point at a time
			clearAllFeatures();
			sides = 4;
			tt.cg.square = new Polygon(lat, lon, lat + 3, lon + 3, sides);
		} else if (featureMode === "point") {
			//only one point at a time
			clearAllFeatures();
			tt.cg.point = new PM(lat, lon, 'pointPlace', 'ff00ffff');
		} else if (featureMode === "line") {
			clearAllFeatures();
			if (!isRedraw) {
				//add point PM into array
				var placeLine = new PM(lat, lon, 'pointPlace', 'ff00ffff');
				tt.cg.points.push(placeLine);
			}

			//draw current line
			var lineString = ge.createLineString('');
			for ( var i = 0; i < tt.cg.points.length; i++) {
				//push coords to line
				lineString.getCoordinates().pushLatLngAlt(
						tt.cg.points[i].lat.toDeg(),
						tt.cg.points[i].lon.toDeg(), 0);
				// draw this placemark
				ge.getFeatures().appendChild(tt.cg.points[i].placemark);
			}
			//draw the line
			tempPlacemark.setGeometry(lineString);
			ge.getFeatures().appendChild(tempPlacemark);

		} else if (featureMode === "poly") {
			clearAllFeatures();
			if (!isRedraw) {
				//add point PM into array
				var placePoly = new PM(lat, lon, 'pointPlace', 'ff00ffff');
				tt.cg.points.push(placePoly);
			}

			if (tt.cg.points.length > 1) {
				//draw current poly
				var poly = ge.createPolygon('');
				var outer = ge.createLinearRing('');
				poly.setOuterBoundary(outer);

				for ( var j = 0; j < tt.cg.points.length; j++) {
					outer.getCoordinates().pushLatLngAlt(
							tt.cg.points[j].lat.toDeg(),
							tt.cg.points[j].lon.toDeg(), 0);

					// draw this placemark
					ge.getFeatures().appendChild(tt.cg.points[j].placemark);
				}

				//repeat first coord to close		
				outer.getCoordinates().pushLatLngAlt(
						tt.cg.points[0].lat.toDeg(),
						tt.cg.points[0].lon.toDeg(), 0);

				tempPlacemark.setGeometry(poly);
				ge.getFeatures().appendChild(tempPlacemark);

			}
		}
	}
	//public methods
	return {
		SetMode : function(featureMode, sendingElement) {
			setMode(featureMode, sendingElement);
		},
		SetCurrentByView : function() {
			setCurrentByView();
		},
		ClearAllFeatures : function() {
			clearAllFeatures();
		},
		WriteCoords : function() {
			writeCoords();
		},
		ReadCoords : function(coords) {
			readCoords(coords);
		},
		DrawFeatures : function(isRedraw) {
			drawFeatures(isRedraw);
		},
		AddPointToFeature : function() {
			addPointToFeature();
		},
		RemovePointFromFeature : function(pm) {
			removePointFromFeature(pm);
		},
		SetEdit : function(isOn, sendingElement) {
			if (!isOn) // toggle it
		{
			isOn = !editModeOn;
		}
		setEdit(isOn, sendingElement);
	},
	EditModeOn : function() {
		return editModeOn;
	},
	FeatureMode : function() {
		return featureMode;
	}
	}
})();





