SET_DHTML(RESET_Z);
var mapservpath="";
var mapFilePath="";
var imageURL= "/1972-aust-mosaic-543-RGB"; 
var imageURL2 = "/USA/Processed/LANDSAT/US_TrueColor1";
var imageURL3 = "/Canada/Processed/Landsat/mosaic-colour-balanced/2004-05_mosaic-RGB2_geo";

//variables for geolocation
var tlx,tly,brx,bry;
var leftoffset = 0;
var topoffset = 0;
var imgWidth, imgHeight;

var dragDIV, borderDiv, bottomDiv, specialLayer;

var activeLayer="";
var activeLayers="";
var activeLayersArray = new Array();

var labelstr="";

var pickX = 0; //point on image were image is selected
var pickY = 0;

var imageDragged;
var loaded = false;

var isDataImage = false;
var dataImageParams = "";
var data_parameter = "";
var data_datasetid = "";
var data_date="";
var data_forecast= "";
var data_frequency="";
var data_LUT="";

var isFading = false;
var curTimeout = 0;

//image tiling variables
var hTiles = 1;
var vTiles = 1;	
var tileWidth;
var tileHeight;
var tileRef = new Array(2);
var vectorRef;
var backBufferImg = new Array(2);
var backBufferVec;
var imgTimeout;
var vecTimeout;
var bufferTime = 1000; //milliseconds
var boxZoomDiv;
var theCurrentRequest = null;

var se;
var drawDIV;

var lastImage = "";
var minimapZoomDiv;

var _currentMode = "";
var successfulRequestedImage = false;

/*****************************************************************
* Function init
* Initialisation Function for viewer
*****************************************************************/
initialiseViewer = function(){

         
    //need to reset drag drop elements otherwise things break
    if (dd.elements.length > 0) 
        dd.elements = new Array(0);
           
    ADD_DHTML("dragDIV");
          
    //local values passed from server 
    mapservpath = $get("hd_mapServerPath").value;
    mapFilePath = $get("hd_mapFilePath").value;    	
    borderDiv = $get("border");
    bottomDiv = $get("bottom");	    
    specialLayer = $get("special_layer");
    
    dragDIV = dd.elements.dragDIV; 

    window.onresize = resizeBrowser;   
  
    document.oncontextmenu = function(){if($get("border")) return false;}; //stop context menu from appearing
        
    borderDiv.onmousemove = minimapUpdate;
       
    setOpacity('panButton', '90');
    setOpacity('zoomButton', '90');
    setOpacity('infoButton', '90');
    setOpacity('pointsButton', '90'); 

    tlx = new Number($get("tlx").value);
    tly = new Number($get("tly").value);
    brx = new Number($get("brx").value);
    bry = new Number($get("bry").value);
           
    //initialise variables

    imgWidth = 1;
    imgHeight = 1; 
    imageDragged = false;
    
    for(var tile in tileRef)
        tileRef[tile] = null;
    for(var tile in backBufferImg) 
        backBufferImg[tile] = null;
        
    vectorRef = null;
    backBufferVec = null;
    loaded = true; 
    
    //clear any vectors or images    
    cleanOldObjects();

    //current layers to display
    activeLayersArray = new Array();
    if ($get("active_layers").value!=""){
        var layers = $get("active_layers").value.split(",");
        for (var i in layers){
            activeLayersArray.push(layers[i]);
        }
    }
    
    if ($get("AccountConfigured").value.toLowerCase() == "false")
    {
        setMode("pan"); 
        //$get("menuButtons").style.width = "250px";
        $get("pointsButton").style.border = "solid thin red";
        $get("instructionText").style.display = "inline";
    }else
    {
        setMode("pan");                
    }
    
    updateImageSource();    
    //toggleImage(); 
    resizeBrowser();     
    doUpdateLegend();
    doUpdateScaleBar();  
};

checkViewer = function() {
    if (!successfulRequestedImage)  resizeBrowser();
};

/*****************************************************************
* Function cleanOldObjects
* Cleans any old images/vectors from borderdiv container
*****************************************************************/
cleanOldObjects = function(typeId)
{    
    for(var i = 0; i < borderDiv.childNodes.length; i++)
    {   
        if(borderDiv.childNodes[i].id != null) 
        {   
            if(typeId == null) 
            {
                if(borderDiv.childNodes[i].id == "vectorImg" || borderDiv.childNodes[i].id == "cisImage")
                {
                    borderDiv.removeChild(borderDiv.childNodes[i]);
                }
            } 
            else
            {
                if(borderDiv.childNodes[i].id.indexOf(typeId) != -1)
                    borderDiv.removeChild(borderDiv.childNodes[i]);             
            }   
        }   
    }    
};

/*****************************************************************
* Function updateImageSource
* Changes the image source
*****************************************************************/
updateImageSource = function()
{    
    if ($get("hd_imageId").value.indexOf(",")>-1){
       isDataImage = true;
       dataImageParams = $get("hd_imageId").value;
       var params = dataImageParams.split(",");
       data_parameter = params[0];
       data_frequency = params[1]; 
       
       if (params[2]==1){
            data_forecast = true;
       }else{
            data_forecast = false;
       }
       
       data_datasetid = params[3]; 
       data_date = params[4]; 
        
    }else if ($get("hd_imageId").value!=""){
        
        isDataImage = false;
        if ($get("hd_imageId").value=="0"){
            imageURL= "/1972-aust-mosaic-543-RGB";
        }else if ($get("hd_imageId").value=="1"){
             imageURL= "/1977-aust-mosaic-543-RGB";
        }else if ($get("hd_imageId").value=="2"){
             imageURL= "/1980-aust-mosaic-543-RGB";
        }else if ($get("hd_imageId").value=="3"){
             imageURL= "/1985-aust-mosaic-543-RGB";
        }else if ($get("hd_imageId").value=="4"){
             imageURL= "/1988-aust-mosaic-543-RGB";
        }else if ($get("hd_imageId").value=="5"){
             imageURL= "/1989-aust-mosaic-543-RGB";
        }else if ($get("hd_imageId").value=="6"){
             imageURL= "/1991-aust-mosaic-543-RGB";
        }else if ($get("hd_imageId").value=="7"){
            imageURL= "/1992-aust-mosaic-543-RGB";
        }else if ($get("hd_imageId").value=="8"){
             imageURL= "/1995-aust-mosaic-543-RGB";
        }else if ($get("hd_imageId").value=="9"){
             imageURL= "/1998-aust-mosaic-543-RGB";
        }else if ($get("hd_imageId").value=="10"){
             imageURL= "/2000-aust-mosaic-543-RGB";
        }else if ($get("hd_imageId").value=="11"){
             imageURL= "/2002-aust-mosaic-543-RGB";
        }else if ($get("hd_imageId").value=="12"){
             imageURL= "/2004-aust-mosaic-543-RGB";
        }else if ($get("hd_imageId").value=="13"){
             imageURL= "/2005-aust-mosaic-543-RGB";  
        }else if ($get("hd_imageId").value=="14"){
             imageURL= "/2006-aust-mosaic-543-RGB";  
        }else if ($get("hd_imageId").value=="15"){
             imageURL= "/2000-aust-mosaic-543-RGB-pansharpened";       
        }
    }else{
        imageURL= "";
    }
};

/*****************************************************************
* Function changeOpacity
* control fading in/out of objects, pass id of an object and 
* start and finish opacity and function will control the rest.
*****************************************************************/
changeOpacity = function (theObject, startOpacity, finishOpacity)
{
    var speed = 20;
    var timer = 0;
    
    if (!isFading)
    {
        isFading = true;  
        if(startOpacity > finishOpacity)
        {
            for(var i = startOpacity; i > finishOpacity; i--)
            {
                setTimeout("setOpacity('" + theObject + "'," + i + ")", (timer * speed));
                timer++;
            }
        }else if(startOpacity < finishOpacity)
        {
            for(var i = startOpacity; i < finishOpacity; i++)
            {
                setTimeout("setOpacity('" + theObject + "'," + i + ")", (timer * speed));
                timer++;
            }
        } 
        setTimeout("isFading = false", (timer * speed));
    }   
    else
    {        
        clearTimeout(curTimeout);
        curTimeout = setTimeout("changeOpacity('" + theObject + "', '" + startOpacity + "', '" + finishOpacity + "')", (timer * speed)); 
    }      
};

/*****************************************************************
* Functions setOpacity
* control fading in/out of objects, pass id of an object and 
* start and finish opacity and function will control the rest.
*****************************************************************/
setOpacity = function (theObject, opacity)
{
    var object = $get(theObject).style;
    object.filter = "alpha(opacity=" + opacity + ")";
    object.opacity = opacity / 100;
    object.mozOpacity = opacity / 100;
    object.khtmlOpacity = opacity / 100;     
};

/*****************************************************************
* Function updateMarkers
* updates the lat / long markers for current view
*****************************************************************/
updateMarkers = function ()
{
	var tlx2 = tlx;
	var tly2 = tly;
	var brx2 = brx;
	var bry2 = bry;	
	var mmX, mmY, mmW, mmH;
	var tlStr, brStr;
	
	if (imageDragged){		
		//adjust for drag
		width = Math.abs(brx-tlx);
		height = Math.abs(bry-tly);
		tlx2 = tlx - ((dragDIV.x - leftoffset)*(width/imgWidth));
		brx2 = tlx2 - (-width);
		tly2 = tly - (-(dragDIV.y - topoffset)*(height/imgHeight));
		bry2 = tly2 - height;
	}	
		
    if (tly2 < 0)    
        tlStr = "[" + new Number(Math.abs(tly2)).toFixed(3) + "\u00B0 S";
    else
        tlStr = "[" + new Number(Math.abs(tly2)).toFixed(3) + "\u00B0 N";
        
    if (tlx2 < 0)    
        tlStr = tlStr + ", " + new Number(Math.abs(tlx2)).toFixed(3) + "\u00B0 W]";
    else
        tlStr = tlStr + ", " + new Number(Math.abs(tlx2)).toFixed(3) + "\u00B0 E]";
        
    if (bry2 < 0)    
        brStr = "[" + new Number(Math.abs(bry2)).toFixed(3) + "\u00B0 S";
    else
        brStr = "[" + new Number(Math.abs(bry2)).toFixed(3) + "\u00B0 N";
        
    if (brx2 < 0)    
        brStr = brStr + ", " + new Number(Math.abs(brx2)).toFixed(3) + "\u00B0 W]";
    else
        brStr = brStr + ", " + new Number(Math.abs(brx2)).toFixed(3) + "\u00B0 E]";
        
    
	$get("topLeftLabel").innerHTML= tlStr;		
	$get("bottomRightLabel").innerHTML= brStr;
	
	//calc minimap box position/size
	if(bry2 > -8) bry2 = -8;
	if(tly2 > -8) tly2 = -8;
	if(tlx2 < 112) tlx2 = 112;
	if(brx2 < 112) brx2 = 112;	
	
	mmX = ((tlx2 - 112) / 43) * 102;	
	mmY = (Math.abs(tly2 + 8) / 38) * 82;	
	mmW = ((brx2 - tlx2) / 43) * 102;
	mmH = (Math.abs(bry2 - tly2) / 38) * 82;
	
	//limit to bounds
	if(mmX > 101) mmX = 101;
	if(mmX < 1) mmX = 1;
	if(tly2 > -8) mmY = 1;
	if(mmY > 81) mmY = 81;
	if(mmW < 1) mmW = 1;
	if(mmW + mmX > 102) mmW = 101 - mmX;
	if(mmH < 1) mmH = 1;
	if(mmH + mmY > 82) mmH = 81 - mmY;
	
	if (minimapZoomDiv == undefined)
    {
        minimapZoomDiv = document.createElement("DIV");
        minimapZoomDiv.id = "minimapZoomBox";
        minimapZoomDiv.style.position = "absolute";
        minimapZoomDiv.style.zIndex = "45";	                 
        minimapZoomDiv.style.border = "solid 1px red";                
        $get("minimap").appendChild(minimapZoomDiv);
    }
    
    minimapZoomDiv.style.left = parseInt(mmX) + "px";
    minimapZoomDiv.style.top = parseInt(mmY) + "px";
    minimapZoomDiv.style.width = parseInt(mmW) + "px";
    minimapZoomDiv.style.height = parseInt(mmH) + "px"; 
               
};

/*****************************************************************
* Function minimapUpdate
* updates the minimap based on current mouse position
*****************************************************************/
minimapUpdate = function (e)
{
        //calc minimap
        var mmX, mmY;
        
        if (document.all)
        {
            e = event;
            eX = e.offsetX;
            eY = e.offsetY;
        }
        else
        {
            eX = e.layerX;
            eY = e.layerY;
        }
           
		mmX = (((tlx + (Math.abs(brx-tlx) * (eX / borderDiv.clientWidth))) - 112) / 43) * 102;
		if(mmX > 101) mmX = 101;
		if(mmX < 1) mmX = 1;
		mmY = (Math.abs((tly - (Math.abs(bry-tly) * (eY / borderDiv.clientHeight))) + 8) / 38) * 82;
		if(mmY > 81) mmY = 81;
		if(mmY < 1) mmY = 1;
		$get("verLine").style.left = new Number(mmX + 1).toFixed(0) + 'px';
		$get("horLine").style.top = new Number(mmY + 1).toFixed(0) + 'px';
		updateLocation(eX,eY);
};

/*****************************************************************
* Function updateLocation
* updates location based on input x y co-ords
*****************************************************************/
updateLocation = function (X,Y){
    var lblStr;
    var valY, valX;
    
    valY = tly - (Math.abs(bry-tly)*(Y/imgHeight));
    valX = tlx + (Math.abs(brx-tlx)*(X/imgWidth));
    
    if (valY < 0)    
        lblStr = "[" + new Number(Math.abs(valY)).toFixed(3) + "\u00B0 S";
    else
        lblStr = "[" + new Number(Math.abs(valY)).toFixed(3) + "\u00B0 N";
        
    if (valX < 0)    
        lblStr = lblStr + ", " + new Number(Math.abs(valX)).toFixed(3) + "\u00B0 W]";
    else
        lblStr = lblStr + ", " + new Number(Math.abs(valX)).toFixed(3) + "\u00B0 E]";
        
	$get("locateDiv").style.color='red';
	$get("locateDiv").innerHTML="Location: " + lblStr + " ";
	setTimeout("if($get('locateDiv') != null) $get('locateDiv').style.color='Black';",750);
};

/*****************************************************************
* Function getImage
* requests a new image from the custom image service
*****************************************************************/
changeView = function (x_,y_,width_,height_)
{  
    var width;
	var height;
	var xCoord;
	var yCoord;
	
	//check aspect
    xCoord = tlx + Math.abs(brx-tlx) * (x_ / imgWidth);
    yCoord = tly - Math.abs(bry-tly) * (y_ / imgHeight);
    
    aspectdb = Math.abs(brx-tlx) / Math.abs(bry-tly);
    aspect = width_ / height_;
    if (aspectdb > aspect)
    { 
        height = Math.abs(brx-tlx) / aspect;
        tly = tly - (-(height - Math.abs(bry - tly))/2);
        bry = tly - height;
    }
    else
    {
        width = Math.abs(bry - tly) * aspect;
        tlx = tlx - (width - Math.abs(brx - tlx))/2;
        brx = tlx + width;
    }	
    
    xCoord -= tlx;
    yCoord = Math.abs(yCoord - tly);
	    
	if (height_ != imgHeight || width_ != imgWidth){    
		//resized
		width = Math.abs(brx-tlx)*(imgWidth/width_);
		height = Math.abs(bry-tly)*(imgHeight/height_);
		tlx = tlx + xCoord - (width / 2);
		brx = tlx + width;
		tly = tly - yCoord + (height / 2);
		bry = tly - height;		
		
	}else{
		//dragged
		width = Math.abs(brx-tlx);
		height = Math.abs(bry-tly);
		tlx = tlx - ((x_-leftoffset)*(width/imgWidth));
		brx = tlx - (-width);
		tly = tly - (-(y_-topoffset)*(height/imgHeight));
		bry = tly - height;
	}
};

getImage = function ()
{ 	          
   //get new image
   if (isDataImage){
        cisRelay.extractRegionWithLUT(data_parameter,data_frequency,data_forecast,data_datasetid,data_date,tly,tlx,bry,brx,imgHeight,imgWidth,".gif",CisRequestCompleted, null, 0);
   }else{
        if (imageURL !="") {                    
            cisRelay.extractRegion(imageURL,tly,tlx,bry,brx,imgHeight,imgWidth,".gif",CisRequestCompleted, null, 0);                      
        }
        else
        {
            cleanOldObjects("cisImage");
        }
   } 
		
   loadControlService.updateExtents(tlx,tly,brx,bry);
};

/*****************************************************************
* Function getVectorImage
* requests a new vector overlay from mapServer
*****************************************************************/
getVectorImage = function ()
{		
    var variables = "";
    var tmpstr;
    activeLayers = "";
    
	for (var i in activeLayersArray){
	    if (activeLayersArray[i].indexOf(";")>0){
	        activeLayers = activeLayers + " " + activeLayersArray[i].substr(0,activeLayersArray[i].indexOf(";"));
	        variables = variables + "&" + activeLayersArray[i].substr(activeLayersArray[i].indexOf(";")+1,activeLayersArray[i].length-activeLayersArray[i].indexOf(";"));
	    }else{
	        activeLayers = activeLayers + " " + activeLayersArray[i];
	    }			
	}
	
	tmpstr = mapservpath + "?map=" + mapFilePath + "&layers=" + activeLayers + " " + specialLayer.value + "&mode=map&mapext=" + tlx + " " + tly + " " + brx + " " + bry + "&mapsize=" + imgWidth + " " + imgHeight + "&userid=" + $get('userid').value + "&selgid=" + $get('gid').value + "&rand=" + parseInt(Math.random() * 30000);
	if (lastImage != "")
	    tmpstr += "&fillStates=true"
	    
	if (backBufferVec != null)
	{
	    borderDiv.removeChild(backBufferVec);
	}
	backBufferVec = vectorRef;
	vectorRef = document.createElement("IMG");
	vectorRef.id = "vectorImg";
    vectorRef.src = tmpstr;
    vectorRef.style.position = "absolute";
    vectorRef.style.left = "0px";
    vectorRef.style.top = "0px";
    vectorRef.style.zIndex = "21";	 
    borderDiv.appendChild(vectorRef);        
	    
    if (vectorRef.addEventListener)
    {
        vectorRef.addEventListener("load", vecLoadFunction, false);
    }
    else if(vectorRef.attachEvent)
    {
        vectorRef.attachEvent("onload", vecLoadFunction);
    }
    else
    {
        vectorRef.onload = vecLoadFunction;
    }    
};

/*****************************************************************
* Function doUpdateLegend
* Request a new legend
*****************************************************************/
doUpdateLegend = function ()
{
    if (isDataImage){
        legendService.requestLegendForImage(mapservpath + "?map=" + mapFilePath + "&mode=legend&layers=" + activeLayers + " " + specialLayer.value + "&mapext=" + tlx + " " + tly + " " + brx + " " + bry, data_parameter,data_frequency,data_forecast,OnLegendRequestCompleted);
    }else{	    
        legendService.requestLegend(mapservpath + "?map=" + mapFilePath + "&mode=legend&layers=" + activeLayers + " " + specialLayer.value + "&mapext=" + tlx + " " + tly + " " + brx + " " + bry, OnLegendRequestCompleted );
    }
};

/*****************************************************************
* Function doUpdateScaleBar
* Request a new scalebar
*****************************************************************/
doUpdateScaleBar = function ()
{
	$get("scalebar").src = mapservpath + "?map=" + mapFilePath + "&mode=scalebar&mapext=" + tlx + " " + tly + " " + brx + " " + bry + "&mapsize=" + imgWidth + " " + imgHeight;
    
    var R = 6371; // km
    var dLat = (bry-tly) * (Math.PI / 180);
    var dLon = (brx-tlx) * (Math.PI / 180); 
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(tly * (Math.PI / 180)) * Math.cos(bry  * (Math.PI / 180 )) * 
            Math.sin(dLon/2) * Math.sin(dLon/2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    var d = R * c;        
    var imgDistance = Math.sqrt(imgWidth * imgWidth + imgHeight * imgHeight) / 30.8;
    $get("scaleText").innerHTML = "Scale 1 : " + Math.floor(d * 100000 / imgDistance);
};

/*****************************************************************
* Function IDresults
* Callback function for identify request
*****************************************************************/
IDresults = function (result)
{
	if (!result.success){
			labelstr = result.msg;
	}else{
		if (result.result.indexOf("found")>-1){
			labelstr = "(not found)";
			$get("identifyDiv").innerHTML="<font color='red'>" + labelstr + "</font>"
			setTimeout("if($get('identifyDiv') != null) $get('identifyDiv').innerHTML=labelstr",750);
		}else{
			labelstr = result.result;
			$get("identifyDiv").innerHTML="<font color='red'>" + labelstr + "</font>"
			setTimeout("if($get('identifyDiv') != null) $get('identifyDiv').innerHTML=labelstr",750);
		}
	}
};

/*****************************************************************
* Function OnLegendRequestCompleted
* Callback function for legend request service
*****************************************************************/
OnLegendRequestCompleted = function (response)
{
    if($get('legendDiv') != null)
        $get("legendDiv").innerHTML = response;   
};

/*****************************************************************
* Function CisRequestCompleted
* Callback function for CIS
*****************************************************************/
CisRequestCompleted = function (result, context)
{
	var imgStr;
	var requestId;		
	    
	if (result.indexOf("<fault>")>-1 || result.indexOf("error")>-1){	
		cleanOldObjects("cisImage" + context);
	}else{
	    successfulRequestedImage = true;
		imgStr= result.substr(result.indexOf(",")+1);
		imgStr= imgStr.substr(imgStr.indexOf(",")+1);
			
		if (backBufferImg[context] != null)
	    {
	        borderDiv.removeChild(backBufferImg[context]);
	    }
	    backBufferImg[context] = tileRef[context];           
        tileRef[context] = document.createElement("IMG");
        tileRef[context].id = "cisImage" + context;
        tileRef[context].src = imgStr;
        tileRef[context].style.position = "absolute";
        tileRef[context].style.left = "0px"; 
        tileRef[context].style.top = "0px"; 
        tileRef[context].style.zIndex = "20";	        
        
        borderDiv.appendChild(tileRef[context]);
        
        if (tileRef[context].addEventListener)
        {
            tileRef[context].addEventListener("load", function(){imgLoadFunction(context);}, false);
        }
        else if(tileRef[context].attachEvent)
        {
            tileRef[context].attachEvent("onload", function(){imgLoadFunction(context);});
        }
        else
        {
            tileRef[context].onload = function(){imgLoadFunction(context);};
        }                     
	}	
};

/*****************************************************************
* Function imgLoadFunction
* Called when image loaded to remove old image
*****************************************************************/
imgLoadFunction = function (context)
{
    if (backBufferImg[context] != null)
	{
	    try
	    {
        borderDiv.removeChild(backBufferImg[context]); 
	    }
	    catch(e)
	    {
	    } 
        backBufferImg[context] = null;
    }
};

/*****************************************************************
* Function vecLoadFunction
* Called when vector loaded to remove old vector
*****************************************************************/
vecLoadFunction = function ()
{
    if (backBufferVec != null)
    {
        try
	    {
        borderDiv.removeChild(backBufferVec);
	    }
	    catch(e)
	    {
	    }         
        backBufferVec = null;      
    }
};

/*****************************************************************
* Function resizeBrowser
* Function that resizes objects when the viewer changes size
*****************************************************************/
resizeBrowser = function ()
{
    var mainDiv = $get("mainDiv");
    
	if (loaded && borderDiv != null && borderDiv.parentNode != null && mainDiv != null){
	
        var windowHeight;
        
        if (typeof window.innerHeight != "undefined")
        {
            windowHeight = window.innerHeight;
        }
        else
        {
            if (document.documentElement && typeof document.documentElement.clientHeight != "undefined")
            {
               windowHeight = document.documentElement.clientHeight;
            }
            else
            {
                windowHeight = document.body.clientHeight;
            }
        }
        
        if (windowHeight > 1000) windowHeight = 1000;
        if (windowHeight < 650) windowHeight = 650;
        windowHeight = windowHeight - 300;
        mainDiv.style.height = windowHeight + "px";
        
        windowHeight = windowHeight - 110;
        borderDiv.style.height = windowHeight + "px";
        
        if ( mainDiv.clientWidth > 0) borderDiv.style.width = mainDiv.clientWidth - 30 + "px";
        
        dragDIV.h = windowHeight;
        dragDIV.w = mainDiv.clientWidth - 30;
        
        
        var theParent = borderDiv;
        
        leftoffset = 0;
        topoffset = 0;
        
        while(theParent)
		{
			leftoffset += theParent.offsetLeft;
			topoffset += theParent.offsetTop;
			theParent = theParent.offsetParent || null;
		}        
        
        dragDIV.moveTo(leftoffset,topoffset);
        if(borderDiv.clientWidth != imgWidth || borderDiv.clientHeight != imgHeight)
        {
            if((borderDiv.clientWidth>0)&&(borderDiv.clientHeight>0))
            {
		        imgWidth = borderDiv.clientWidth;
		        imgHeight = borderDiv.clientHeight;
        		
		        aspectdb = Math.abs(brx-tlx)/Math.abs(bry-tly);
	            aspect=imgWidth/imgHeight;
	            if (aspectdb > aspect)
	            { 
			            height = Math.abs(brx-tlx)/aspect;
			            tly=tly-(-(height-Math.abs(bry-tly))/2);
			            bry=tly-height;
	            }
	            else
	            {
			            width = Math.abs(bry-tly)*aspect;
			            tlx=tlx-(width-Math.abs(brx-tlx))/2;
			            brx=tlx+width;
	            }
        	    
		        dragDIV.resizeTo(imgWidth,imgHeight);
		        changeView(leftoffset,topoffset,imgWidth,imgHeight);		    
		        getImage();
		        getVectorImage();
		        updateMarkers();
		        doUpdateScaleBar(); 		       
                doUpdateLegend();
		        if(getMode() == "points")
		            changedViewSize();
		    }		    
        }
	}
};

setMode = function (mode)
{
    //common instructions to perform
    _currentMode = mode;
    
    dragDIV.setDraggable(true);
	
	$get("zoomButton").src="../images/icons/zoom_button.gif";
	$get("panButton").src="../images/icons/hand_button.gif";
	$get("infoButton").src="../images/icons/info_button.gif";
	$get("pointsButton").src="../images/icons/edit_button.gif";
	$get("identifyDiv").innerHTML="";
	$get("locationInfo").style.display = "none";
		  
    toggleEditFeatures(false);
        
    //mode specific instructions
    switch(mode)
    {
        case "zoom":        
            dragDIV.setCursor(CURSOR_CROSSHAIR);
	        borderDiv.style.cursor = "crosshair";
	        $get("zoomButton").src="../images/icons/hlzoom_button.gif";
	        break;
        case "pan":
            dragDIV.setCursor(CURSOR_MOVE);
	        borderDiv.style.cursor = "move";	        
	        $get("panButton").src="../images/icons/hlhand_button.gif";
            break;
        case "info":        
            dragDIV.setCursor(CURSOR_HAND);      
            borderDiv.style.cursor = "pointer";      
	        $get("infoButton").src="../images/icons/hlinfo_button.gif";
            break;      
        case "points":          
            toggleEditFeatures(true);
	        dragDIV.setDraggable(false);   
            dragDIV.setCursor(CURSOR_CROSSHAIR);  
            borderDiv.style.cursor = "crosshair";              
	        $get("pointsButton").src="../images/icons/hledit_button.gif";
	        $get("locationInfo").style.display = "block";
	        loadControlService.getUserPointsList(-1,false,loadPointsResult);	             
	        window.scrollBy(0,200);            
            break;
    }

};

getMode = function()
{
    return _currentMode;
};

loadPointsResult = function (result)
{
	$get("locationInfo").innerHTML=result.html;
	$get("pointsEditFinishLink").style.display = "";
	se.pointsRemaining = result.pointsCount;
};

updatedEditShape = function (result){
    loadControlService.getUserPointsList(-1,true,loadPointsResult);
    getVectorImage();
    se.clear();
    editPolySelect("add");      
    setTimeout("try{meteogramControl_Callback('RefreshPoints','',false);}catch(ex){}", 1000);
    setTimeout("try{geographyControl_Callback('RefreshPoints','');}catch(ex){}", 1000);
};

changedViewSize = function(){
    if (se!=null){                
        drawDIV.style.width = imgWidth + "px"; 
        drawDIV.style.height = imgHeight + "px";   
        se.viewOrigin.x=tlx;
        se.viewOrigin.y=tly;
        se.viewCellSizeX=(brx-tlx)/imgWidth;
        se.viewCellSizeY=Math.abs(bry-tly)/imgHeight;
        se.redrawShape();
    }
};

toggleEditFeatures = function (turnOn){
    if (!turnOn){
        // turning off
        if (se!=null){
           se.setMode("none");
           se.clear();
	       se.kill();
	       se=null;
	       try
	       {
	        borderDiv.removeChild(drawDIV); 
	       }
	       catch(ex)
	       {}
        }     
    }else{                   
	    if (se==null){
    	     
            drawDIV = document.createElement("DIV");
            drawDIV.id = "drawDIV";
            drawDIV.style.position = "absolute";
            drawDIV.style.left = "0px";
            drawDIV.style.top = "0px"; 
            drawDIV.style.zIndex = "22";	
            borderDiv.appendChild(drawDIV);
            se = new shapeEditor("drawDIV");
        }      
        drawDIV.style.width = imgWidth + "px"; 
        drawDIV.style.height = imgHeight + "px";   
        se.setColor("#00ffff");
        se.setFont("arial","11px",Font.BOLD);
        se.editShapeType="POINT";
        se.editshapename = "tblpoints";
        se.viewOrigin.x=tlx;
        se.viewOrigin.y=tly;
        se.viewCellSizeX=(brx-tlx)/imgWidth;
        se.viewCellSizeY=Math.abs(bry-tly)/imgHeight;
        //se.viewSRID = 26900;
        se.onAfterUpdate=updatedEditShape;
        se.onAfterGetFeature=function(){editPolySelect("afterSelect"); };
        //se.onAfterCompleteShape=function(){editPolySelect("afterCompleteShape");};
        se.snapShapes.push("qsec_mb_sk_ab");
        se.isNewShape=false;
        se.allowFeatureOverlapping=false;
        se.allowMergeOnlyIntersecting=true;
        se.editRestrictionQuery=null; 
        se.openConnection();   
        editPolySelect("add");
    }
};

editPolySelect = function (cmd, extraArg, arg2, arg3){
 
    switch(cmd)
    {
        case "add":
            se.getNewShape();
            se.setMode("drawingPoint"); //set mode and create new shape
            break;
        case "select":
            se.setMode("selectingEditFeature");     
            break;
        case "cancel":
            se.getNewShape();
            se.setMode("drawingPoint"); //set mode and create new shape
            loadControlService.getUserPointsList(-1,false,loadPointsResult);
            break;
        case "update":
            if (confirm('Save changes?')){
                if ($get(extraArg).value != "" && $get(arg2).value != "" && $get(arg3).value != "")
                {
                    se.editPart.x = $get(arg2).value;
                    se.editPart.y = $get(arg3).value;
                    se.save($get(extraArg).value);                   
                    $get(extraArg).value = ""; 
                }else{
                    alert("Name and location can not be blank, please try again!");
                }
            }    
            break;
        case "edit":  
            loadControlService.getUserPointsList(extraArg,false,loadPointsResult);
            se.loadFeature(extraArg);  
            break;
        case "save":
            if (confirm('Add new point?')){
                if ($get("featureName").value != "" && $get("featureLong").value != "" && $get("featureLat").value != "")
                {
                    se.editPart.addPoint($get("featureLong").value ,$get("featureLat").value ,null,null);						        
                    se.save($get("featureName").value);
                    $get("featureName").value = "";
                  
                }else{
                    alert("Name and location can not be blank, please try again!");
                }
            } 
            break;
        case "delete":
            if (confirm('Are you sure you want to delete point ?'))
            {
                se.delFeature(extraArg);    
            }
            break;   
    }  
};
/*****************************************************************
* Function my_PickFunc
* Called when drag drop type object picked up (mouse down)
*****************************************************************/
my_PickFunc = function ()
{	
	if (dd.obj == dragDIV)
	{	    
	    switch(getMode())
	    {
	        case "info":
	            if ($get('active_layer').value=="")
	            {
	                activeLayer="LGA";
	            }
	            else
	            {
	                activeLayer=$get('active_layer').value;
	            }
		        $get("identifyDiv").innerHTML="";
		        IdentifyFeatureService.QueryFeature(mapFilePath,activeLayer,tlx + " " + tly + " " + brx + " " + bry,dd.e.x - leftoffset,dd.e.y - topoffset,imgWidth,imgHeight,IDresults)
			    break;
	        case "zoom":					  
			    pickX = dd.e.x - leftoffset;
			    pickY = dd.e.y - topoffset; 
			    break;    
		    default:					  
			    pickX = dd.e.x - leftoffset;
			    pickY = dd.e.y - topoffset;
			    break;
	    }				
	}
	return false;
};

/*****************************************************************
* Function my_DragFunc
* Called when drag drop type object being dragged
*****************************************************************/
my_DragFunc = function ()
{    
    if (dd.obj == dragDIV)
	{
	    switch(getMode())
	    {
	        case "info":
	            if (dd.obj==dragDIV){
			        // dont allow move
			        dragDIV.moveTo(leftoffset,dragDIV.defy);
		        }
		        break;
	        case "zoom":	
	            imageDragged = true;
                if(dd.e.button <= 1)
		        {
                    if (boxZoomDiv == null)
                    {
                        boxZoomDiv = document.createElement("DIV");
                        boxZoomDiv.style.position = "absolute";
                        boxZoomDiv.style.left = pickX + "px";
                        boxZoomDiv.style.top = pickY + "px";
                        boxZoomDiv.style.zIndex = "35";	                 
                        boxZoomDiv.style.border = "solid 2px red";                
                        borderDiv.appendChild(boxZoomDiv);
                    }
                    
                    if (dragDIV.x - leftoffset >= 0)
                    {
                        boxZoomDiv.style.width = dragDIV.x - leftoffset + "px" ;
                    }else
                    {                    
                        boxZoomDiv.style.left = parseInt(pickX - Math.abs(dragDIV.x - leftoffset)) + "px";
                        boxZoomDiv.style.width = parseInt(Math.abs(dragDIV.x - leftoffset)) + "px" ;
                    }
                    if (dragDIV.y - topoffset >= 0)
                    {
                        boxZoomDiv.style.height = parseInt(dragDIV.y - topoffset) + "px";
                    }else
                    {                    
                        boxZoomDiv.style.top = parseInt(pickY - Math.abs(dragDIV.y - topoffset)) + "px";                
                        boxZoomDiv.style.height = parseInt(Math.abs(dragDIV.y - topoffset)) + "px";
                    }
                } 
                break;
	        case "pan":
	            if (dd.obj==dragDIV){
			        imageDragged=true;
        				
			        for (var tile in tileRef)
			        {
			            if (tileRef[tile] != null)
			            {   
			                tileRef[tile].style.left = dragDIV.x - leftoffset + "px";
			                tileRef[tile].style.top = dragDIV.y - topoffset + "px";        			        
			            }				    
			        }	
			        if (vectorRef != null)
			        {	
			            vectorRef.style.left = dragDIV.x - leftoffset + "px";
			            vectorRef.style.top =  dragDIV.y - topoffset + "px";
			        }
		        }
		        updateMarkers();	  
		        break;
			    
	    }	    
	}
};

/*****************************************************************
* Function my_DropFunc
* Called when drag drop type object dropped (mouse up)
*****************************************************************/
my_DropFunc = function ()
{
    if (dd.obj == dragDIV)
	{	
	    switch(getMode())
	    {	        
	        case "zoom":
	            var newWidth,newHeight,newX,newY, tmpH, tmpW,ratio;
            
                if(imageDragged && dd.e.button <= 1)
                {
	                if (boxZoomDiv != null)
                    {                    
                        if (boxZoomDiv.clientWidth < 5 || boxZoomDiv.clientHeight < 5)                        
                        {
                            //catch box to small problems here                             
                            newX = pickX;  
                            newY = pickY;
                            newWidth = imgWidth * 2;
                            newHeight = imgHeight * 2; 
                        }
                        else
                        {
                            newX = boxZoomDiv.offsetLeft + (boxZoomDiv.clientWidth / 2);
                            newY = boxZoomDiv.offsetTop + (boxZoomDiv.clientHeight / 2);                        
                            newWidth = imgWidth / (boxZoomDiv.clientWidth / imgWidth);
                            newHeight = imgHeight / (boxZoomDiv.clientHeight / imgHeight);
                        }  
                                                                       
                        if (boxZoomDiv.clientWidth < boxZoomDiv.clientHeight)
                            ratio = newHeight/imgHeight;             
                        else
                            ratio = newWidth/imgWidth;
                                
                        //temp resize of current image	
                        for (var tile in tileRef)
                        {  
                            if (tileRef[tile] != null)
                            {                  
                                tileRef[tile].style.top = parseInt((imgHeight / 2) - (ratio * imgHeight * (newY / imgHeight))) + "px";
                                tileRef[tile].style.left = parseInt((imgWidth / 2) - (ratio * imgWidth * (newX / imgWidth))) + "px";
                                tileRef[tile].style.width = parseInt(ratio * imgWidth) + "px";
                                tileRef[tile].style.height = parseInt(ratio * imgHeight) + "px";
                            }
                        }
            	                           
                        vectorRef.style.top = parseInt((imgHeight / 2) - (ratio * imgHeight * (newY / imgHeight))) + "px";
                        vectorRef.style.left = parseInt((imgWidth / 2) - (ratio * imgWidth * (newX / imgWidth))) + "px";
                        vectorRef.style.width = parseInt(ratio * imgWidth) + "px";
                        vectorRef.style.height = parseInt(ratio * imgHeight) + "px";
            	        
            	        changeView(newX,newY,newWidth,newHeight); 	                    	        
                        getImage();	                          	            
                        borderDiv.removeChild(boxZoomDiv);   
                        boxZoomDiv = null;   
                    }
	            }
	            else
	            {
	                if(dd.e.button <= 1)
	                {
                        newWidth = imgWidth * 2;
                        newHeight = imgHeight * 2;    
    	                
                    }else 
                    {
                        newWidth = imgWidth / 3;
                        newHeight = imgHeight / 3;
                    }    	
                    
                    //temp resize of current image	
                    for (var tile in tileRef)
                    {  
                        if (tileRef[tile] != null)
                        {                  
                            tileRef[tile].style.top = parseInt((imgHeight / 2) - (newHeight * (pickY / imgHeight))) + "px";
                            tileRef[tile].style.left = parseInt((imgWidth / 2) - (newHeight/imgHeight * imgWidth * (pickX / imgWidth))) + "px";
                            tileRef[tile].style.width = parseInt(newHeight/imgHeight * imgWidth) + "px";
                            tileRef[tile].style.height = parseInt(newHeight/imgHeight * imgHeight) + "px";
                        }
                    }
        	                           
                    vectorRef.style.top = parseInt((imgHeight / 2) - (newHeight * (pickY / imgHeight))) + "px";
                    vectorRef.style.left = parseInt((imgWidth / 2) - (newWidth * (pickX / imgWidth))) + "px";
                    vectorRef.style.width = parseInt(newWidth) + "px";
                    vectorRef.style.height = parseInt(newHeight) + "px";
    	            
    	            changeView(pickX,pickY,newWidth,newHeight);  		
                    getImage();		        
	            }				
	            getVectorImage();
	            imageDragged=false;
                updateMarkers();
                doUpdateScaleBar();                   
                doUpdateLegend();
                dragDIV.moveTo(leftoffset,topoffset);
                dragDIV.resizeTo(imgWidth,imgHeight);	
                break;
	        case "pan":
	            changeView(dragDIV.x,dragDIV.y,imgWidth,imgHeight);
	            getImage();
                getVectorImage();
                imageDragged=false;
                updateMarkers();
                dragDIV.moveTo(leftoffset,topoffset);
                dragDIV.resizeTo(imgWidth,imgHeight);
                break;
            default:
                dragDIV.moveTo(leftoffset,topoffset);
                dragDIV.resizeTo(imgWidth,imgHeight);
                break;
	    }         
    }	
};

/*****************************************************************
* Function roundOff
* Rounds a value to the precision
*****************************************************************/
roundOff = function (value, precision) {
    precision = parseInt(precision, 10);
    precision = (!precision ? 2 : precision);
    return Math.round(value*Math.pow(10,precision))/Math.pow(10,precision);
};

/*****************************************************************
* Function changeExtents
* Changes the current extents and reloads viewer
*****************************************************************/
changeToInitialExtents = function ()
{   
    try
    {    
    tlx = new Number($get("tlx").value);
    tly = new Number($get("tly").value);
    brx = new Number($get("brx").value);
    bry = new Number($get("bry").value);
    
    aspectdb = Math.abs(brx-tlx)/Math.abs(bry-tly);
    aspect=imgWidth/imgHeight;
    if (aspectdb > aspect)
    { 
            height = Math.abs(brx-tlx)/aspect;
            tly=tly-(-(height-Math.abs(bry-tly))/2);
            bry=tly-height;
    }
    else
    {
            width = Math.abs(bry-tly)*aspect;
            tlx=tlx-(width-Math.abs(brx-tlx))/2;
            brx=tlx+width;
    }
    //leftoffset,topoffset,imgWidth,imgHeight
    getImage();
    getVectorImage();
    updateMarkers();     
	doUpdateLegend();
    doUpdateScaleBar();
    }
    catch(ex)
    {
    }
};

toggleImage = function ()
{
    if (imageURL == "")
    {
        imageURL = lastImage;
        lastImage = "";    
        $get("imgStatus").innerHTML = "On";     
        //borderDiv.style.backgroundColor = "Black";                
		getImage();
		getVectorImage();
    }
    else
    { 
        lastImage = imageURL;
        imageURL = ""; 
        $get("imgStatus").innerHTML = "Off";
        borderDiv.style.backgroundColor = "rgb(153,179,204)";  
        cleanOldObjects("cisImage");
        getVectorImage();     
    }
};

moveToLocation = function (latitude,longitude,accuracy)
{   
    try
    {    
        var width;
        var height;
        
        switch(accuracy)
        {
            case 1:        
                width = 20;
                height = 15;
                break;
            case 2:        
                width = 15;
                height = 10;
                break;
            case 3:
                width = 10;
                height = 10;
                break;
            case 4:        
                width = 0.4;
                height = 0.4;
                break; 
            case 5:  
                width = 0.25;
                height = 0.25;
                break;
            case 6:  
                width = 0.15;
                height = 0.15;
                break;
            case 7:  
                width = 0.1;
                height = 0.1;
                break;
            case 8:  
                width = 0.05;
                height = 0.05;
                break;
            case 9:  
                width = 0.03;
                height = 0.03;
                break;
        }       
               
        tlx = longitude - width;
        tly = latitude + height;
        brx = longitude + width;
        bry = latitude - height;   
        
        changeView(leftoffset,topoffset,imgWidth,imgHeight);	
        getImage();             
        getVectorImage();  
        updateMarkers();    
	    doUpdateLegend();
        doUpdateScaleBar();                
    }
    catch(ex)
    {
    }
};

/*****************************************************************
* Function updateImg
* Changes the current image source / reloads image
*****************************************************************/
changeSelectedImg = function()
{
    var imgVal;
    var imgLbl;
    var imgList = $get('imgChoices'); 
        
    for(var i = 0; i < imgList.options.length; i++)
    {
        if(imgList.options[i].selected)
        {
            imgVal =  imgList.options[i].value;
            imgLbl =  imgList.options[i].innerHTML;
            break;
        }
    }    
    updateImg(imgVal);
};

updateImg = function (theValue, label)
{    
    $get('hd_imageId').value = theValue;
    if (theValue.indexOf(",")>-1)
    {
        //$get('imgLabel').innerHTML = label;
    }
    else
    {
        //$get('imgLabel').innerHTML = label;
    }    
    updateImageSource();
    getImage();
    doUpdateLegend();
};

/*****************************************************************
* Function selectLayer
* Changes the current selected layer
*****************************************************************/
selectLayer = function (theValue)
{
    $get('active_layer').value = theValue;
};

/*****************************************************************
* Function showSpecialLayer
* Changes to a special vector layer
*****************************************************************/
showSpecialLayer = function (theValue, label)
{
    //get rid of current image layer
    $get('hd_imageId').value = "";
    updateImageSource();
    getImage();
    $get('special_layer').value = theValue;
    $get('imgLabel').innerHTML = label;
    changeVectors();       
};

/*****************************************************************
* Function updateLayer
* Turns on / off a layer
*****************************************************************/
updateLayer = function (theValue)
{   
    var layers = $get('active_layers').value.split(",");
    var activeLayers = "";
    var inArray = false;  
      
    for(var i = 0; i < layers.length; i++)
    {
        if (layers[i] != "")
        {
            if(theValue == layers[i])
            {
                inArray = true;
            }
            else
            {
                activeLayers = layers[i] + "," + activeLayers ;            
            } 
        }           
    }
    
    if(!inArray)
    {
        activeLayers = activeLayers + theValue;
    }
    else
    {
        activeLayers = activeLayers.substring(0, activeLayers.length - 1);
    }
    
    $get('active_layers').value = activeLayers;    
    changeVectors();
};

/*****************************************************************
* Function changeVectors
* updates the vectors
*****************************************************************/
changeVectors = function (){
    activeLayersArray = $get('active_layers').value.split(",");   	
	getVectorImage();
	doUpdateLegend();
};

/*****************************************************************
* Function putCookie
* saves data to a cookie
*****************************************************************/
putcookie = function (c_name,value,expiredays) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate);
};

/*****************************************************************
* Function getCookie
* gets data from a cookie
*****************************************************************/
getcookie = function (c_name) {
    if(document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(c_name + "=");
        if(c_start != -1) {
            c_start = c_start + c_name.length + 1;
            var c_end = document.cookie.indexOf(";",c_start);
            if(c_end == -1)
                c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return null;
};

/***************************************************************/

showAddress = function() 
{
    var address = $get('address');    
    if(address) {
        cisRelay.GeocodeAddress(address.value,GeocodeCallback);
    }
};

GeocodeCallback = function(point) 
{
    var address = $get('address');
    if (point){            
        try
        {    
            if ((point.Name != null) && (point.Name.indexOf("Error") > -1))
            {
                ShowGenericPopup("Error","Adress not located, try simplifying the search. eg. town/suburb.");
            }
            else
            {
                address.value = '';
                moveToLocation(point.Latitude, point.Longitude, point.Accuracy);
            }
        }
        catch(ex)
        {
             ShowGenericPopup("Error", ex.message);
        }
    }
    else
    {
        ShowGenericPopup("Error", "Address not located, try simplifying the search. eg. town/suburb.");
    }
};  


if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();