// aimsRedline.js
// not standard IMS .js file - created to support the redline tool
//
/* Redline will:
	-load form for annotating the screen with redlines and text blurbs
	-request/recieve a map from IMS with those features printed on it
	-pass the filepath reference for that map to a CGI script that will e-mail it to REGIS support
   Redline allows our users to indicate any incorrect data and e-mail to us to fix it
*/

// Global Variables
var addRedlineReq = false;		//marks if redline notation should be added to XML statement
var firstUp = false;		//marks if this is the initial loading of the redline tool
var currentRedline = null;	//the current redline control being manipulated
var currentRedtitle = null;	//the user-friendly title for the redline currently being editted.
var currentRedtext = null;	//the current redtext control being manipulated
var redlineLine = ["redline1","redline2","redline3","redline4","redline5"];
var redlineText = ["redtext1","redtext2","redtext3","redtext4","redtext5"];
var redlineTitle = ["Redline #1","Redline #2","Redline #3","Redline #4","Redline #5"];
var redlineVisible = [false, false, false, false, false];
var redlineMarkup = ["","","","",""];		//the original string stored if the user wishes to redo a redline
var redlineXY = ["","","","",""];
var arrow = "zip";		//stores direction of line to determine placement of textbox
var mainUp = false;		//will prevent a new redline from drawing if procedure is not followed.
var textX = 0;			//these two used in getRedlineXY to convert pixel coords to mapunits
var textY = 0;			//...
var theMapFile;			//contains the file name of the redlined map for inclusion in a cgi submission
var RedlineWindow;		//stores reference to external Redline Window, to be accessed programatically  

//Global arrays for use in developing multiple lines of text on screen
var redtext1XML = new Array(28);
var redtext2XML = new Array(28);
var redtext3XML = new Array(28);
var redtext4XML = new Array(28);
var redtext5XML = new Array(28);



var redtext1XY = new Array(28);
var redtext2XY = new Array(28);
var redtext3XY = new Array(28);
var redtext4XY = new Array(28);
var redtext5XY = new Array(28);

function clearArrays(index) {
	for (var a=0;a<28;a++) {
		if ((index == 0) || (index == 100)) { 
			redtext1XML[a] = "";
			redtext1XY[a] = "";
		}
		if ((index == 1) || (index == 100)) { 
			redtext2XML[a] = "";
			redtext2XY[a] = "";
		}
		if ((index == 2) || (index == 100)) { 
			redtext3XML[a] = "";
			redtext3XY[a] = "";
		}
		if ((index == 3) || (index == 100)) {
			redtext4XML[a] = "";
			redtext4XY[a] = "";
		}
		if ((index == 4) || (index == 100)) {
			redtext5XML[a] = "";	
			redtext5XY[a] = "";
		}
	}	
}

function loadInterface() {
	//sets up redline editting interface when redline button clicked
	if (mapLoaded) {
		//
	} else {
		alert("This tool cannot be used until a map is loaded.");
		return;
	}
	
	if (currentRedline == null) {
		//alert("To the user: This tool is currently under construction. This message window will be removed when the Redline tool is operational. Thank you for your patience.");
		firstUp = true;
		currentRedline = redlineLine[0];
		currentRedtitle = redlineTitle[0];
		currentRedtext = redlineText[0];
		redlineVisible[0] = true;
		clearArrays(100);
	}
	//delete me...
	//testTheLayer();

	//debugOn = 4;
	//alert(isNav5up);
	if (useTextFrame) {
		parent.TextFrame.document.location= appDir + "redlineInit.htm";
	} else {
		Win1 = open(appDir + "redlineInit.htm","RedlineWin","width=625,height=150,scrollbars=yes,resizable=yes");
		RedlineWindow = Win1;
	}
	

}

function testTheLayer(){
	showLayer("redtext1");
	var string = parent.MapFrame.document.getElementById("redtext1").firstChild.nodeValue = "This no work.";
	alert(string);
	
}

function backToInterface(chosen) {
	//when a button is clicked to return to the Interface, this will set the new current DHTML layer
	if (chosen == "new") {
		for (var q=0;q<redlineVisible.length;q++) {
			if (redlineVisible[q] == false) {
				currentRedline = redlineLine[q];
				currentRedtitle = redlineTitle[q];
				currentRedtext = redlineText[q];
				redlineVisible[q] = true;
				loadInterface();
				return;
			}
		}
		//if you're here, there aren't any available ones left
		alert("You cannot have more than five redline markers. However, you can edit a previous one if you wish.");
	} else {
		if (useTextFrame) {
			var theIndex = parent.TextFrame.document.redlineMain.redlinenum.options.selectedIndex;
			var theValue = parent.TextFrame.document.redlineMain.redlinenum.options[theIndex].text;
		} else {
			var theIndex = RedlineWindow.document.redlineMain.redlinenum.options.selectedIndex;
			var theValue = RedlineWindow.document.redlineMain.redlinenum.options[theIndex].text;
		}
		for (var z = 0;z<redlineTitle.length;z++) {
			if (redlineTitle[z] == theValue) {
				currentRedline = redlineLine[z];
				currentRedtitle = redlineTitle[z];
				currentRedtext = redlineText[z];
				redlineXY[z] = "";
				clearArrays(z);
				hideLayer(currentRedline);
				hideLayer(currentRedtext);
				loadInterface();
				return;
			}
		}
		//if you're here, something's wrong
		alert("That layer is not found");
		return; 
	} 
					
}

function eraseRedline() {
	var destination;
	if (useTextFrame) destination = parent.TextFrame;
	else destination = RedlineWindow; 
	var theIndex = destination.document.redlineMain.redlinenum.options.selectedIndex;
	var theValue = destination.document.redlineMain.redlinenum.options[theIndex].text;
	for (var z = 0;z<redlineTitle.length;z++) {
		if (redlineTitle[z] == theValue) {
			hideLayer(redlineLine[z]);
			hideLayer(redlineText[z]);
			redlineVisible[z] = false;
			redlineMarkup[z] = "";
			redlineXY[z] = "";
			clearArrays(z);	
		}
	}
	//reload window to refresh select box
	if (useTextFrame) {
		parent.TextFrame.document.location= appDir + "redlineMain.htm";
	} else {
		Win1 = open(appDir + "redlineMain.htm","RedlineWin","width=575,height=150,scrollbars=yes,resizable=yes");
	}

}

function getName(theReply) {
	//first step in invoking the cgi script: Get user name and attach reference to redlined map in a hidden field. This form
	//..will then be submitted to the cgi script
	// first we retrieve the map name for inclusion in a hidden field.
	var theURL = "";
	theURL = getURL(theReply);
	if (theURL != "") {
		var chars = theURL.length
		var lastSlash = theURL.lastIndexOf('/',chars);
		theMapFile = theURL.substr(lastSlash+1);	
	} else {
		alert("A submission map could not created. Please contact the REGIS help desk.");
		cancelRedline();
		return;
	}
	if (useTextFrame) {
		parent.TextFrame.document.location= appDir + "redlineSubmit.aspx?Map=" + theMapFile;
	} else {
		Win1 = open(appDir + "redlineSubmit.aspx?Map="+theMapFile,"RedlineWin","width=700,height=200,scrollbars=yes,resizable=yes");
		Win1.resizeTo(700,200);
	}
}


function getMap() {
	//submits request for map with editting features added before passing control to cgi script
	legendTemp=legendVisible;
	legendVisible=false;
	//selectBlurb="";
	showLayer("LoadMap");
	var theString = writeXML();
	//for the Perl script, the number below should be 100
	sendToServer(imsURL,theString,100);
	return;

}

function setTextbox() {
	//shows text box and enters text when line has been drawn
	//these two will store the redlinexXML and redlinexXY when being worked on, and then will be copied back to the originals
	var tempRedlineXY;
	var tempRedlineXML;
	
	//here the current redline undergoing editting is determined
	var currentIndex;
		for (var r=0;r<redlineLine.length;r++) {
			if (redlineLine[r] == currentRedline) {
				currentIndex = r;
			}
		}

	//now the correct arrays are copied over
	if (currentIndex == 0) {
		tempRedtextXY = redtext1XY;
		tempRedtextXML = redtext1XML;
	} else if (currentIndex == 1) {
		tempRedtextXY = redtext2XY;
		tempRedtextXML = redtext2XML;
	} else if (currentIndex == 2) {
		tempRedtextXY = redtext3XY;
		tempRedtextXML = redtext3XML;
	} else if (currentIndex == 3) {
		tempRedtextXY = redtext4XY;
		tempRedtextXML = redtext4XML;
	} else if (currentIndex == 4) {
		tempRedtextXY = redtext5XY;
		tempRedtextXML = redtext5XML;
	}
	if (useTextFrame) var theString = parent.TextFrame.document.forms[0].labelText.value;
	else var theString = RedlineWindow.document.forms[0].labelText.value;
	var charCount = theString.length
	if (charCount > 550) {
		alert("Your message is "+charCount+" characters long. That's too long to fit in a redline text space. Please trim your message down to less than 550 characters (including spaces and punctuation)");
		return;
	}
	//var newString = convertString(theString, "single");
	var newString;
	redlineMarkup[currentIndex] = theString;

	var numero = "";
	if (currentRedtext == "redtext1") {
		numero = "#1 - ";
	} else if (currentRedtext == "redtext2") {
		numero = "#2 - ";
	} else if (currentRedtext == "redtext3") {
		numero = "#3 - ";
	} else if (currentRedtext == "redtext4") {
		numero = "#4 - ";
	} else if (currentRedtext == "redtext5") {
		numero = "#5 - ";
	}
	newString = numero + theString;
	var content = '<FONT SIZE="-2">'+newString+'</FONT>';
	if (charCount >= 1) {
		//here the same message is split up as separate strings for generating layers in XML
		//this makes the resultant map easier to read
		var starter = 0;
		var ender = 20;
		var spaceDiff = 0;
		// xmlRows determines how many rows of text will be listed on the map. Different from screenRows
		var xmlRows = 0; 
		var theEnd = 0;
		var done = false
		while (done == false) {
			//alert("The character at the current end position is: "+theString.charAt(ender)); 
			if (theString.charAt(ender) != " ") {
				var lastSpace = theString.lastIndexOf(" ",ender);
				var firstSpace = theString.indexOf(" ", ender);
				var lastDist = Math.abs(ender - lastSpace);
				var firstDist = Math.abs(firstSpace - ender);
				//alert("The lastspace is "+lastSpace+"  and the firstspace is "+firstSpace);
				//alert("The lastDist is "+lastDist+" and the firstDist is "+firstDist);
				if ((firstSpace != -1) || (lastSpace != -1)) {
					if (firstSpace == -1) theEnd = true;
					if ((lastDist > firstDist) || (theEnd)) {
						//alert("Going forward to the next break");
						if (theEnd) {
							ender = theString.length;
							done = true;
						} 
						else ender = firstSpace;
						spaceDiff = firstDist;
		 			} else if (firstDist >= lastDist) {
						//alert("Going back to a previous break");
						ender = lastSpace;
						spaceDiff = 0 - lastDist;

					}
				} else {
					// we go here if both space markers are - 1
					//alert("We have only one word");
					ender = theString.length;
					done = true;
					//alert("We have reached the end of the string."); 
					spaceDiff = 0;
				}
			} else {
				//alert("This space will be fine");
				spaceDiff = 0;
			}
			var stringPiece = theString.slice(starter,ender);
			if ((stringPiece != "") && (stringPiece != " ")) {
				tempRedtextXML[xmlRows] = stringPiece;
				//alert("This is xmlRow #"+xmlRows);
				//alert("Piece #"+xmlRows+" will be.... "+ stringPiece);
				xmlRows += 1;
			}
			starter = starter + 20 + spaceDiff;
			ender += 20;	
		}
	}
	//screenRows determines how large the on-screen dhtml textbox containing the string will be 
	var screenRows = Math.ceil(charCount/20);
	if (screenRows == 0) {
		screenRows = 1;
	}
	var rowPixels = ((screenRows - 1) * 10) + 15;
	//to convert X and Y coords to mapunits
	var u = Math.pow(10,numDecimals);
	var mouseString = "";

	if (arrow == "left") {
		if (isNav5up) Netclip(currentRedtext,(zleft-100),(ztop-10),100,rowPixels);
 		else moveLayer(currentRedtext,zleft-150,ztop-10);
		
		var moveBottom = ztop;
		for (var c=0;c<xmlRows;c++) {
			getRedlineXY((zleft-150),moveBottom);
			var uX = parseInt(textX * u + 0.5) / u;
			var uY= parseInt(textY * u + 0.5) / u;
			mouseString = uX+" "+uY;
			tempRedtextXY[c] = mouseString;
			moveBottom += 10;
		}
	}
	if (arrow == "right") {
		if (isNav5up) Netclip(currentRedtext,zright,(ztop-10),150,rowPixels);
		else moveLayer(currentRedtext,zright,ztop-10);

		var moveBottom = ztop;
		for (var c=0;c<xmlRows;c++) {
			getRedlineXY(zright,moveBottom);
			//alert(zright+"   "+moveBottom+"   "+textX+"   "+textY);
			var uX = parseInt(textX * u + 0.5) / u;
			var uY= parseInt(textY * u + 0.5) / u;
			mouseString = uX+" "+uY;
			tempRedtextXY[c] = mouseString;
			moveBottom += 10;
		}
	}
	if (arrow == "up") {
		if (isNav5up) Netclip(currentRedtext,(zleft-50),(ztop-50),150,rowPixels);
		else moveLayer(currentRedtext,zleft-50,ztop-50);
		var moveBottom = (ztop-50);
		for (var c=0;c<xmlRows;c++) {
			getRedlineXY((zleft-50),moveBottom);
			var uX = parseInt(textX * u + 0.5) / u;
			var uY= parseInt(textY * u + 0.5) / u;
			mouseString = uX+" "+uY;
			tempRedtextXY[c] = mouseString;
			moveBottom += 10;
		}
	}
	if (arrow == "down")  {
		if (isNav5up) Netclip(currentRedtext,(zleft-50),zbottom,150,rowPixels);
		else moveLayer(currentRedtext,zleft-50,zbottom);
		var moveBottom = zbottom;
		for (var c=0;c<xmlRows;c++) {
			getRedlineXY((zleft-50),moveBottom);
			var uX = parseInt(textX * u + 0.5) / u;
			var uY= parseInt(textY * u + 0.5) / u;
			mouseString = uX+" "+uY;
			tempRedtextXY[c]= mouseString;
			moveBottom += 10;
		}
	}
	
	

	if (isNav5up == false) clipLayer(currentRedtext,0,0,150,rowPixels);
	replaceLayerContent(currentRedtext,content);
	showLayer(currentRedtext);

	//now the correct arrays are copied back
	if (currentIndex == 0) {
		redtext1XY = tempRedtextXY;
		redtext1XML = tempRedtextXML;
	} else if (currentIndex == 1) {
		redtext2XY = tempRedtextXY;
		redtext2XML = tempRedtextXML;
	} else if (currentIndex == 2) {
		redtext3XY = tempRedtextXY;
		redtext3XML = tempRedtextXML;
	} else if (currentIndex == 3) {
		redtext4XY = tempRedtextXY;
		redtext4XML = tempRedtextXML;
	} else if (currentIndex == 4) {
		redtext5XY = tempRedtextXY;
		redtext5XML = tempRedtextXML;
	}
	
	if (useTextFrame) {
		parent.TextFrame.document.location= appDir + "redlineMain.htm";
	} else {
		Win1 = open(appDir + "redlineMain.htm","RedlineWin","width=575,height=150,scrollbars=yes,resizable=yes");
	}
	
}

function getRedlineXY(xIn,yIn) {
		//a copy of the getMapXY function, in case those settings are needed for something else
		xDistance = Math.abs(right-left);
		yDistance = Math.abs(top-bottom);
		mouseX = xIn;
		pixelX = xDistance / iWidth;
		textX = pixelX * mouseX + left;
		mouseY = iHeight - yIn;
		pixelY = yDistance / iHeight;
		textY = pixelY * mouseY + bottom;
}



function convertString(theString, theType) {
	if (theString == undefined) newString = "";
	else {
		//adds an escape sequence for any single quote in the text
		var pieces = new Array();
		if (theType == "single") {
			pieces = theString.split("'");
			var subs = pieces.length;
			var newString = new String("");
			for (var i=0;i<subs;i++) {
				if (i == (subs-1)) {
					newString = newString + pieces[i];
				} else {
					newString = newString + pieces[i] + "\\" + "'";
				}
			}
		}else if (theType == "double") {
			pieces = theString.split('"');
			var subs = pieces.length;
			var newString = new String("");
			for (var i=0;i<subs;i++) {
				if (i == (subs-1)) {
					newString = newString + pieces[i];
				} else {
					newString = newString + pieces[i] + "'";
				}
			}		
		}
	}
	return newString;
}

function sendMap(){
	//runs when sendmap button has been selected
	alert("Send Map has been selected");
}

function cancelRedline() {
	//runs when cancelredline button is pressed
	hideLayer("redline1");
	hideLayer("redtext1");
	hideLayer("redline2");
	hideLayer("redtext2");
	hideLayer("redline3");
	hideLayer("redtext3");
	hideLayer("redline4");
	hideLayer("redtext4");
	hideLayer("redline5");
	hideLayer("redtext5");
	for (var v=0;v<5;v++) {
		redlineXY[v] = "";
		clearArrays(100);
		redlineMarkup[v] = "";
		redlineVisible[v] = false;
	}
	if (toolMode == 30) clickFunction("zoomin");
	parent.ToolFrame.setToolPic("Zoom In");
	addRedlineReq = false;
	firstUp = true;
	currentRedline = null;
	redlining = false;
	if (!useTextFrame) RedlineWindow.close();
}

// start zoom in.... box displayed
function startRedlineDraw(e) {
	if (mainUp == true) return;
	moveLayer("theMap",hspc,vspc);
	getImageXY(e);
	var currentIndex;
	for (var r=0;r<redlineLine.length;r++) {
		if (redlineLine[r] == currentRedline) {
			currentIndex = r;
		}
	}			
	// keep it within the MapImage
		 
	if ((mouseX<iWidth) && (mouseY<iHeight)) {
		if (redlining) {
			stopRedlineDraw(e);
			
		} else {

			var u = Math.pow(10,numDecimals);
			var uX = parseInt(mapX * u + 0.5) / u;
			var uY= parseInt(mapY * u + 0.5) / u;
			var mouseString = uX+" "+uY;
			redlineXY[currentIndex] = mouseString;

			x1=mouseX;
			y1=mouseY
			x2=x1+1;
			y2=y1+1;
			zleft=x1;
			ztop=y1;
			zbottom=y1;
			zright=x1
			var str=x1+"   "+y1+"   "+x2+"   "+y2;
			window.status=str
			
			//boxIt(x1,y1,x2,y2);
			if (isNav5up) {
				Netclip(currentRedline,x1,y1,x2,y2);
		 		
	
			} else {
				clipLayer(currentRedline,x1,y1,x2,y1+ovBoxSize);
	
			}
			
			redlining=true;
			
		}
	}
	return false;
	
}

//called from writeXML function
function redlineXML() {
	var totalString = "";
	var currString = "";
	//first the lines...
	totalString = '<LAYER type="ACETATE" name="redlinelayer">\n'; 
	for (var q=0;q<redlineVisible.length;q++) {
		if (redlineXY[q] != "") {
			currString = "";
			currString += '<OBJECT units="DATABASE">\n';
			currString += '<LINE coords="'+redlineXY[q]+'">\n';
			currString += '<SIMPLELINESYMBOL color="255,0,0" width="2"/>\n';
			currString += '</LINE>\n';
			currString += '</OBJECT>\n';
			totalString += currString;
		}
	}
	//second, the text...
	for (var p=0;p<redlineVisible.length;p++) {
		if (redlineVisible[p]) {
			//alert("Now servicing redtext #"+p);
			var tempRedtextXY;
			var tempRedtextXML;
			if (p == 0) {
				tempRedtextXY = redtext1XY;
				tempRedtextXML = redtext1XML;
			} else if (p == 1) {
				tempRedtextXY = redtext2XY;
				tempRedtextXML = redtext2XML;
			} else if (p == 2) {
				tempRedtextXY = redtext3XY;
				tempRedtextXML = redtext3XML;
			} else if (p == 3) {
				tempRedtextXY = redtext4XY;
				tempRedtextXML = redtext4XML;
			} else if (p == 4) {
				tempRedtextXY = redtext5XY;
				tempRedtextXML = redtext5XML;
			} 
			for (var q=0;q<28;q++) {
				//alert(q+"   "+tempRedtextXY[q]);
				if ((tempRedtextXML[q] != "") && (tempRedtextXML[q] != " ") && (tempRedtextXML[q] != undefined)) {
					//alert("the current redtext line is... "+tempRedtextXML[q]);
					currString = "";
					currString += '<OBJECT units="DATABASE">\n';
					currString += '<TEXT coords="'+tempRedtextXY[q]+'" label="'+convertString(tempRedtextXML[q], "double")+'">\n';
					currString += '<TEXTMARKERSYMBOL fontsize="11" font="Times New Roman" fontcolor="255,0,0" glowing="255,255,0" overlap="false"/>\n';
					currString += '</TEXT>\n';
					currString += '</OBJECT>\n';
					totalString += currString;
				}
			}
		}
	}
	totalString += '</LAYER>\n';	
		
	return totalString;
}

// stop zoom box display... zoom in
function stopRedlineDraw(e) {
	redlining=false;
	if ((zright <zleft+2) && (zbottom < ztop+2)) {
		//zoomin(e);
	} else {
		var tempLeft=lastLeft;
		var tempRight=lastRight;
		var tempTop=lastTop;
		var tempBottom=lastBottom;
		var currentIndex;
		for (var r=0;r<redlineLine.length;r++) {
			if (redlineLine[r] == currentRedline) {
				currentIndex = r;
			}
		}
		var u = Math.pow(10,numDecimals);
		var uX = parseInt(mapX * u + 0.5) / u;
		var uY= parseInt(mapY * u + 0.5) / u;
		var mouseString = uX+" "+uY;
		redlineXY[currentIndex] = redlineXY[currentIndex] + ";" + mouseString;
		
		if (useTextFrame) {
			parent.TextFrame.document.location= appDir + "redlineText.htm";
		} else {
			Win1 = open(appDir + "redlineText.htm","RedlineWin","width=575,height=150,scrollbars=yes,resizable=yes");
		}
	}
	return true;

}

// clip redline layer to mouse coords
function redlineClip() {	
	var tempX=x1;
	var tempY=y1;
	var hozdif1 = x1 - x2;
	var hozdif2 = x2 - x1;
	var verdif1 = y1 - y2;
	var verdif2 = y2 - y1;
	if (hozdif1 > hozdif2) {
		var hozdif = hozdif1
	} 
	else {
		var hozdif = hozdif2
	}
	if (verdif1 > verdif2) {
		var verdif = verdif1
	}
	else {
		var verdif = verdif2
	} 
	
	if (hozdif > verdif) {
		if (x1>x2) {
			zright=x1;
			zleft=x2;
			arrow="left";
		} else {
			zleft=x1;
			zright=x2;
			arrow="right";
		}
		ztop = y1;
		zbottom=y1;
	}
	else {
		zleft = x1;
		zright = x1;


		if (y1>y2) {
			zbottom=y1;
			ztop=y2;
			arrow = "up";
		} else {
			ztop=y1;
			zbottom=y2;
			arrow = "down";
		}
	}
	
	if ((x1 != x2) && (y1 != y2)) {
		//clipLayer("zoomBox",zleft,ztop,zright,zbottom);
		//boxIt(zleft,ztop,zright,zbottom);
		if (hozdif > verdif) {
			if (isNav5up) {
				var difWidth= zright - zleft;
				var difHeight = zbottom - ztop; 
				Netclip(currentRedline,zleft,ztop,difWidth,ovBoxSize);
				
		 		/*
				moveLayer(currentRedline,0,ztop-ovBoxSize+1);
		 		*/
	
			} else {
				clipLayer(currentRedline,zleft,ztop,zright,ztop+ovBoxSize);	
			}
		}
		else {
			if (isNav5up) {
				var difWidth= zright - zleft;
				var difHeight = zbottom - ztop;
				Netclip(currentRedline,zleft,ztop,ovBoxSize,difHeight);

		 		/*
				//moveLayer(currentRedline,0,ztop-ovBoxSize+1);
		 		*/
	
			} else {
				clipLayer(currentRedline,zleft,ztop,zleft+ovBoxSize,zbottom);	
			}
		}
		
	}
	showLayer(currentRedline);
	//return false;
}

function Netclip(name,clipleft,cliptop,clipright,clipbottom) {
	
	var layer = getLayer(name);		
	
		    layer.left   = clipleft;
		    layer.top    = cliptop;
		    layer.width  = clipright;
		    layer.height = clipbottom;
	
		    

}
	