
// There is a major bug in Mozilla where the onLoad event for the body gets called before the
// plugins on the page are loaded, this seems to work around it.
var tOnLoadTimer = null;
var vectorMode = "polygon";
var ECWVectorLayer = null;
var clickmapbuilder = false;

var isLoaded = false;

var ImageLinkPrefix = '../';
var ImageLinkSuffix = '.htm';

var sFilename2 = "";
var sFilename3 = "";

var sTLX, sTLY, sBRX, sBRY;

var ECWNoPluginUrl = "/ecwplugins/DownloadPlugin.htm";

var nResult;
nResult = ECWCheck();	
//alert(nResult);

if (nResult <= 0) 
{
	/*
	if( document.images )
		location = ECWNoPluginUrl;
	else
		location.href = ECWNoPluginUrl;
	*/
	setCookie("NCSPluginInstallMethod", "HTML");
} 
else if (nResult == 5 && getPluginInstallMethod("NCSPluginInstallMethod") != "JAVA")
{
	// ECWCheck recommends Java, but the user didn't choose it
	// Java is buggy in this interface in Safari (toolbar not visible)
	setCookie("NCSPluginInstallMethod", "HTML");
}
else if (nResult == 6) 
{
	setCookie("NCSPluginInstallMethod", "HTML");
}

function displayCookie() {
	alert("NCSPluginInstallMethod = " + getCookie("NCSPluginInstallMethod"));
}

function SaveViewCoords() 
{
	var decy = false;

	var TLX = document.ECWView1.GetLayerImageTopLeftWorldCoordinateX("RasterLayer");
	var TLY = document.ECWView1.GetLayerImageTopLeftWorldCoordinateY("RasterLayer");
	var BRX = document.ECWView1.GetLayerImageBottomRightWorldCoordinateX("RasterLayer");
	var BRY = document.ECWView1.GetLayerImageBottomRightWorldCoordinateY("RasterLayer");

	var TLX2 = document.ECWView1.GetTopLeftWorldCoordinateX();
	var TLY2 = document.ECWView1.GetTopLeftWorldCoordinateY();
	var BRX2 = document.ECWView1.GetBottomRightWorldCoordinateX();
	var BRY2 = document.ECWView1.GetBottomRightWorldCoordinateY();

	if (BRY < TLY)
		decy = true;
	
	if (sFilename2 != "") {
	
		TLX = Math.min(TLX, document.ECWView1.GetLayerImageTopLeftWorldCoordinateX("RasterLayer2"));
		BRX = Math.max(BRX, document.ECWView1.GetLayerImageBottomRightWorldCoordinateX("RasterLayer2"));

		if (decy)
		{
			TLY = Math.max(TLY, document.ECWView1.GetLayerImageTopLeftWorldCoordinateY("RasterLayer2"));
			BRY = Math.min(BRY, document.ECWView1.GetLayerImageBottomRightWorldCoordinateY("RasterLayer2"));
		}
		else
		{
			TLY = Math.min(TLY, document.ECWView1.GetLayerImageTopLeftWorldCoordinateY("RasterLayer2"));
			BRY = Math.max(BRY, document.ECWView1.GetLayerImageBottomRightWorldCoordinateY("RasterLayer2"));
		}
		
	}

	if (sFilename3 != "") {
	
		TLX = Math.min(TLX, document.ECWView1.GetLayerImageTopLeftWorldCoordinateX("RasterLayer3"));
		BRX = Math.max(BRX, document.ECWView1.GetLayerImageBottomRightWorldCoordinateX("RasterLayer3"));

		if (decy)
		{
			TLY = Math.max(TLY, document.ECWView1.GetLayerImageTopLeftWorldCoordinateY("RasterLayer3"));
			BRY = Math.min(BRY, document.ECWView1.GetLayerImageBottomRightWorldCoordinateY("RasterLayer3"));
		}
		else
		{
			TLY = Math.min(TLY, document.ECWView1.GetLayerImageTopLeftWorldCoordinateY("RasterLayer3"));
			BRY = Math.max(BRY, document.ECWView1.GetLayerImageBottomRightWorldCoordinateY("RasterLayer3"));
		}
	}
	
	sTLX = Math.max(TLX, TLX2);
	sBRX = Math.min(BRX, BRX2);
	
	if (decy)
	{
		sTLY = Math.min(TLY, TLY2);
		sBRY = Math.max(BRY, BRY2);
	}
	else
	{
		sTLY = Math.max(TLY, TLY2);
		sBRY = Math.min(BRY, BRY2);
	}
}

function RestoreViewCoords() 
{
	document.ECWView1.SetExtents(sTLX, sTLY, sBRX, sBRY);
}


function SetExtentsFitWidth() {

	var decy = false;

	var TLX = document.ECWView1.GetLayerImageTopLeftWorldCoordinateX("RasterLayer");
	var TLY = document.ECWView1.GetLayerImageTopLeftWorldCoordinateY("RasterLayer");
	var BRX = document.ECWView1.GetLayerImageBottomRightWorldCoordinateX("RasterLayer");
	var BRY = document.ECWView1.GetLayerImageBottomRightWorldCoordinateY("RasterLayer");
	
	if (BRY < TLY)
		decy = true;
	
	if (sFilename2 != "") {
	
		TLX = Math.min(TLX, document.ECWView1.GetLayerImageTopLeftWorldCoordinateX("RasterLayer2"));
		BRX = Math.max(BRX, document.ECWView1.GetLayerImageBottomRightWorldCoordinateX("RasterLayer2"));

		if (decy)
		{
			TLY = Math.max(TLY, document.ECWView1.GetLayerImageTopLeftWorldCoordinateY("RasterLayer2"));
			BRY = Math.min(BRY, document.ECWView1.GetLayerImageBottomRightWorldCoordinateY("RasterLayer2"));
		}
		else
		{
			TLY = Math.min(TLY, document.ECWView1.GetLayerImageTopLeftWorldCoordinateY("RasterLayer2"));
			BRY = Math.max(BRY, document.ECWView1.GetLayerImageBottomRightWorldCoordinateY("RasterLayer2"));
		}
		
	}

	if (sFilename3 != "") {
	
		TLX = Math.min(TLX, document.ECWView1.GetLayerImageTopLeftWorldCoordinateX("RasterLayer3"));
		BRX = Math.max(BRX, document.ECWView1.GetLayerImageBottomRightWorldCoordinateX("RasterLayer3"));

		if (decy)
		{
			TLY = Math.max(TLY, document.ECWView1.GetLayerImageTopLeftWorldCoordinateY("RasterLayer3"));
			BRY = Math.min(BRY, document.ECWView1.GetLayerImageBottomRightWorldCoordinateY("RasterLayer3"));
		}
		else
		{
			TLY = Math.min(TLY, document.ECWView1.GetLayerImageTopLeftWorldCoordinateY("RasterLayer3"));
			BRY = Math.max(BRY, document.ECWView1.GetLayerImageBottomRightWorldCoordinateY("RasterLayer3"));
		}
		
	}

	var w = document.ECWView1.GetViewWidth();
	var h = document.ECWView1.GetViewHeight();
	
	var y = (h/w)*(BRX-TLX) + TLY;
	if (decy) y = -y;
	
	document.ECWView1.SetExtents(TLX, TLY, BRX, y);

}

function SetExtentsFitAll() {

	var decy = false;

	var TLX = document.ECWView1.GetLayerImageTopLeftWorldCoordinateX("RasterLayer");
	var TLY = document.ECWView1.GetLayerImageTopLeftWorldCoordinateY("RasterLayer");
	var BRX = document.ECWView1.GetLayerImageBottomRightWorldCoordinateX("RasterLayer");
	var BRY = document.ECWView1.GetLayerImageBottomRightWorldCoordinateY("RasterLayer");
	
	if (BRY < TLY)
		decy = true;
	
	if (sFilename2 != "") {
	
		TLX = Math.min(TLX, document.ECWView1.GetLayerImageTopLeftWorldCoordinateX("RasterLayer2"));
		BRX = Math.max(BRX, document.ECWView1.GetLayerImageBottomRightWorldCoordinateX("RasterLayer2"));

		if (decy)
		{
			TLY = Math.max(TLY, document.ECWView1.GetLayerImageTopLeftWorldCoordinateY("RasterLayer2"));
			BRY = Math.min(BRY, document.ECWView1.GetLayerImageBottomRightWorldCoordinateY("RasterLayer2"));
		}
		else
		{
			TLY = Math.min(TLY, document.ECWView1.GetLayerImageTopLeftWorldCoordinateY("RasterLayer2"));
			BRY = Math.max(BRY, document.ECWView1.GetLayerImageBottomRightWorldCoordinateY("RasterLayer2"));
		}
		
	}

	if (sFilename3 != "") {
	
		TLX = Math.min(TLX, document.ECWView1.GetLayerImageTopLeftWorldCoordinateX("RasterLayer3"));
		BRX = Math.max(BRX, document.ECWView1.GetLayerImageBottomRightWorldCoordinateX("RasterLayer3"));

		if (decy)
		{
			TLY = Math.max(TLY, document.ECWView1.GetLayerImageTopLeftWorldCoordinateY("RasterLayer3"));
			BRY = Math.min(BRY, document.ECWView1.GetLayerImageBottomRightWorldCoordinateY("RasterLayer3"));
		}
		else
		{
			TLY = Math.min(TLY, document.ECWView1.GetLayerImageTopLeftWorldCoordinateY("RasterLayer3"));
			BRY = Math.max(BRY, document.ECWView1.GetLayerImageBottomRightWorldCoordinateY("RasterLayer3"));
		}
		
	}

	document.ECWView1.SetExtents(TLX, TLY, BRX, BRY);

}

function LoadHandler() {

	clearTimeout(tOnLoadTimer);

	ECWToolbar1.setCurrentItem("UID_VIEW_PAN");
	
	//alert(sFilename);

	if (document.ECWView1.AddLayer("ECW", sFilename, "RasterLayer", "") < 0 ) {
	   //alert(document.ECWView1.GetLastErrorText());
	   //document.ECWView1.AddLayer("ECW", "ecwp://#servername#/ecwplugins/ecw_logo.ecw", "RasterLayer", "");
	   alert("Error opening ECW high-resolution image.  The image is not available.");
	   }
	
	if (clickmapbuilder == true) {
		//alert("Image 1 width = " + document.ECWView1.GetLayerImageSizeX("RasterLayer"));
	}

	if (sFilename2 != "") {
		if (document.ECWView1.AddLayer("ECW", sFilename2, "RasterLayer2", "") < 0 ) {
		   alert(document.ECWView1.GetLastErrorText());
		   //document.ECWView1.AddLayer("ECW", "ecwp://#servername#/ecwplugins/ecw_logo.ecw", "RasterLayer", "");
		   alert("Error opening ECW high-resolution image.  The image is not available.");
		   }
		}

	if (sFilename3 != "") {
		if (document.ECWView1.AddLayer("ECW", sFilename3, "RasterLayer3", "") < 0 ) {
		   alert(document.ECWView1.GetLastErrorText());
		   //document.ECWView1.AddLayer("ECW", "ecwp://#servername#/ecwplugins/ecw_logo.ecw", "RasterLayer", "");
		   alert("Error opening ECW high-resolution image.  The image is not available.");
		   }
		}

	//alert("NCSPluginInstallMethod = " + getPluginInstallMethod("NCSPluginInstallMethod"));

	if (getPluginInstallMethod("NCSPluginInstallMethod") != "HTML") {

		// Add the clickmap builder simple vector overlay
		if (document.ECWView1.AddLayer("simplevector", "", "VectorOverlay", ";") < 0) {
			alert(document.ECWView1.GetLastErrorText());
		}
		else {
			ECWVectorLayer = new NCSVectorLayer(document.ECWView1, "VectorOverlay");
		}
		
		// Add the click areas
		if (LinkCount + LinkPolyCount > 0)
		{
			document.ECWView1.AddLayer("simplevector", "", "ClickAreaPoly", ";");
			document.ECWView1.AddLayer("simplevector", "", "ClickArea", ";");
			
			document.ECWView1.SetLayerParameter("ClickArea", "color=#FF0000;linewidth=3");
			document.ECWView1.SetLayerTransparency("ClickArea", "#", 0.5);
	
			document.ECWView1.SetLayerParameter("ClickAreaPoly", "color=#FF0000;linewidth=3");
			document.ECWView1.SetLayerTransparency("ClickAreaPoly", "#", 0.5);
	
			for (var i = 0; i < LinkCount; i++)
			{
				points = LinkTLX[i] + "," + LinkTLY[i] + "|" + LinkBRX[i] + "," + LinkTLY[i] + "|";
				points = points + LinkBRX[i] + "," + LinkBRY[i] + "|" + LinkTLX[i] + "," + LinkBRY[i];
				document.ECWView1.SetLayerParameter("ClickArea", "polygon" + (i+1) + "=" + points);
			}
	
			for (var i = 0; i < LinkPolyCount; i++)
			{
				var points = "";
				for (var j = 0; j < LinkPolyXs[i].length; j++)
				{
					if (j > 0)
					{
						points = points + "|";
					}
					points = points + LinkPolyXs[i][j] + "," + LinkPolyYs[i][j];
				}
				document.ECWView1.SetLayerParameter("ClickAreaPoly", "polygon" + (i+1) + "=" + points);
			}
		}
	}

	document.ECWView1.SetBackGroundColor("#DDDDDD");
	//document.ECWView1.SetExtentsAll();
	//SetExtentsFitWidth();

	if (sTLX && sTLY && sBRX && sBRY)
	{
		RestoreViewCoords();
	}
	else
	{
		SetExtentsFitAll();
	}
	
	isLoaded = true;
}				

function ECWToolbarCB(uid, value)
{
	if (uid == "UID_VIEW_PAN")
	{
		document.ECWView1.SetPointerMode(0);
	}
	else if (uid == "UID_VIEW_ZOOM")
	{
		document.ECWView1.SetPointerMode(1);
	}
	else if (uid == "UID_VIEW_ZOOMBOX")
	{
		document.ECWView1.SetPointerMode(3);
	}
	else if (uid == "UID_VIEW_POINTER")
	{
		vectorMode = "none";
		document.ECWView1.SetPointerMode(2);
	}
	else if (uid == "UID_ANNOT_SQUARE")
	{
		vectorMode = "rectangle";
		document.ECWView1.SetPointerMode(2);
	}
	else if (uid == "UID_ANNOT_POLYGON")
	{
		vectorMode = "polygon";
		// ECWVectorLayer.objectNumPoints = 0;
		document.ECWView1.SetPointerMode(2);
	}
	else if (uid == "UID_ANNOT_CIRCLE")
	{
		vectorMode = "circle";
		document.ECWView1.SetPointerMode(2);
	}
	else if (uid == "UID_VIEW_CUT")
	{
		ECWVectorLayer.clear();
	}
	else if (uid == "UID_VIEW_WIDTH")
	{
		SetExtentsFitWidth();
	}
	else if (uid == "UID_VIEW_RESET")
	{
		SetExtentsFitAll();
		//document.ECWView1.SetExtentsAll();
	}
	else if (uid == "UID_IMAGE_COMBO")
	{
		document.ECWView1.DeleteAllLayers();
		if (document.ECWView1.AddLayer("ECW", value, "RasterLayer", "") < 0 ) {
			alert(document.ECWView1.GetLastErrorText());
		}
	}
	else if (uid == "UID_PRINT")
	{
		printWindow();
	}
}

function clickMap(worldX, worldY) {
	for (var i = 0; i < LinkCount; i++) {
		// make sure we handle a square drawn in any direction (even backwards)
		if (((worldX <= LinkBRX[i] && worldX >= LinkTLX[i]) || (worldX >= LinkBRX[i] && worldX <= LinkTLX[i])) &&
			((worldY <= LinkBRY[i] && worldY >= LinkTLY[i]) || (worldY >= LinkBRY[i] && worldY <= LinkTLY[i])))	{
			document.location.href = ImageLinkPrefix + LinkImageId[i] + ImageLinkSuffix;
			return;
		}
	}
	for (var i = 0; i < LinkPolyCount; i++) {
		if (pointInPoly(LinkPolyXs[i], LinkPolyYs[i], worldX, worldY) == 1) 
		{
			document.location.href = ImageLinkPrefix + LinkPolyImageId[i] + ImageLinkSuffix;
			return;
		}
	}
}

/*
Point in Polygon function
Copyright (c) 1970-2003, Wm. Randolph Franklin 
http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is 
furnished to do so, subject to the following conditions: 

1. Redistributions of source code must retain the above copyright notice, this 
list of conditions and the following disclaimers. 

2. Redistributions in binary form must reproduce the above copyright notice in 
the documentation and/or other materials provided with the distribution. 

3. The name of W. Randolph Franklin may not be used to endorse or promote 
products derived from this Software without specific prior written permission.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
*/

function pointInPoly(xp, yp, x, y) {

	var i = 0;
	var j = 0;
	var c = 0;
	var npol = xp.length;
	
	for (j = npol - 1; i < npol; j = i++) {
        if ((((yp[i]<=y) && (y<yp[j])) ||
             ((yp[j]<=y) && (y<yp[i]))) &&
            (x < (xp[j] - xp[i]) * (y - yp[i]) / (yp[j] - yp[i]) + xp[i])) {
          if (c == 0) 
		  	c = 1;
		  else 
		    c = 0;
		}
	}
	return c;
}

// ---------------------- MOUSE FUNCTIONS ---------------------------

function ECWMouseDown(buttonMask, dScreenX, dScreenY , worldx, worldy)
{
	if (vectorMode != "none")
	{
    	var filled = false;
    	ECWVectorLayer.setMode((filled ? "filled" : "") + vectorMode);
        ECWVectorLayer.mouseDown(worldx, worldy);
    }
}

function ECWMouseUp(buttonMask, dScreenX, dScreenY , worldx, worldy)
{
	if (vectorMode != "none")
	{
		ECWVectorLayer.mouseUp(worldx, worldy);

		if (clickmapbuilder == true)
		{
			//update the fields with the points
			document.imgdata.points.value = ECWVectorLayer.objectPointsX + "; " + ECWVectorLayer.objectPointsY;
	
			//var r = document.imgdata.points.createTextRange();
			//r.select();
			//r.execCommand('copy');
	
		}
    }
	else
	{
		clickMap(worldx, worldy);
	}
	
}

function ECWMouseMove(buttonMask, dScreenX, dScreenY , worldx, worldy)
{
	if (vectorMode != "none")
	{
	   ECWVectorLayer.mouseMove(worldx, worldy);
    }
}

function ECWVectorSetLineWidth(value)
{
    ECWVectorLayer.lineThickness = value;
    ECWVectorLayer.redraw();
}

function ECWVectorSetPenColor(value)
{
    ECWVectorLayer.penColor = value;
    ECWVectorLayer.redraw();
}

function ECWVectorSetFillColor(value)
{
    ECWVectorLayer.fillColor = value;
    ECWVectorLayer.redraw();
}


function onLoadCB() {
	//resizeElements();
	tOnLoadTimer = setTimeout("LoadHandler()", 500);
}

function close_image()
{
	//document.ECWView1.Close(true); 
}

function prep_filename(sFile)
{
/*
	var sBase = window.location.href.substr(0, window.location.href.lastIndexOf("/"));
	sBase = sBase.substr(0, sBase.lastIndexOf("/"));
	sBase = sBase.replace("file:///", "");
	sBase = sBase.replace("file://", "//");
	var sFilename = sBase + sFile;
	sFilename = sFilename.replace(/\//g, "\\");
	sFilename = sFilename.replace(/%20/g, " ");
*/
/*	if (sFile.indexOf('HGSv') != -1) {
		sFile = sFile.replace(/\/ecw\//, '/');
		return 'ecwp://' + location.host + '/pab-images/original/FLP/HGS' + sFile;
	} else {
		return 'ecwp://' + location.host + '/rdic-images' + sFile;
	}
*/
	return 'ecwp://' + location.host + sFile;
}
function printWindow() {

	//ECWToolbar1.setCurrentItem('UID_VIEW_PAN');

	//mb = document.getElementById('menubar');
	//t1 = document.getElementById('temp1');

	//mb.swapNode(t1);

	factory.printing.portrait = false;
	factory.printing.header = '';
	factory.printing.footer = '';
	factory.printing.leftMargin = 0.25;
	factory.printing.topMargin = 0.25;
	factory.printing.rightMargin = 0.25;
	factory.printing.bottomMargin = 0.25;
	factory.printing.Print(true);
	
	//mb.swapNode(t1);
}

