﻿

var toolMode = "";
var m_measureGraphicFeature;
var currentTool = "";
var RedlineGraphicFeature = null;
var m_redlineToolbar = null;
var m_redlineXOffset = 0;
var m_redlineYOffset=0;
var currentTool = null;



   function toggleRedlining()
    {
        if (m_redlineToolbar == null)
            m_redlineToolbar = $get("RedlineTools");
       if (m_redlineToolbar != null)  
       {   
            //turn off other Tools:
             lastToolLatLong = arcgisWebApp.lastMode;
            arcgisWebApp.lastMode = "Redline";
           //Need toolbar names here -can't seem to get toolbar from tool -  TO DO!!!
            TurnOffTools();
            //set PolygonTool Active on Open
            var curElem = document.getElementById("PolygonTool");
            if ((currentTool != null)&&(currentTool != "")){
                curElem = document.getElementById(currentTool);
            }
            if (curElem)
            {
                currentTool = '';
                Toolbar_MouseDown(curElem) 
            }
            var theHeight = redlineGetMapHeight();
            var theTop = getTop();
            if (theHeight < 350)
                m_redlineToolbar.style.height = "300px";
            else
                m_redlineToolbar.style.height = (theHeight-50-theTop) + "px";
            m_redlineToolbar.style.left=0+"px";
            if (theTop > -1)
                m_redlineToolbar.style.top=theTop + "px";
            m_redlineToolbar.style.display = "";
            var elem = $get("downloadDiv");
            elem.innerHTML = "&nbsp;"
        }
        else  
            alert("I can't find the redlines!");
    }
    function getTop()
    {
        var headerDisplay = $get("PageHeader");
        var headerHeight = -1;
        if (headerDisplay)
            headerHeight = headerDisplay.clientHeight;
        var QS = $get("divQuickSearch");
        var QSHeight = 0;
        if (QS)
            QSHeight = QS.clientHeight;
        var theTop = headerHeight + QSHeight;
        return theTop;
    }
    function redlineGetMapHeight()
    {
        var pHeight = window.innerHeight;
		if (pHeight == null) {
			if (document.documentElement && document.documentElement.clientHeight)
				pHeight = document.documentElement.clientHeight;
			else
				pHeight = document.body.clientHeight;
		}
		var linkDisplay = $get("LinkBar");
		var linkHeight = 0;
		if (linkDisplay != null) linkHeight = linkDisplay.clientHeight;
		    
		var headerDisplay = $get("PageHeader");
        var fpHeight = pHeight - headerDisplay.clientHeight - linkHeight;
        if (isNaN(fpHeight) || fpHeight<5) fpHeight = 500;
        return fpHeight
    }
    

    function Toolbar_MouseOver(elem) {
        //elem.style.border = '1px solid black';
        img = elem.getElementsByTagName("img")[0];
        curSource = img.src;
        onindex = curSource.search(/-ON.gif/i);
        if (onindex == -1)
        {
            index = curSource.search(/.gif/i);
            if (index > -1)
            {
                newSource = curSource.substr(0,index) + "-OVER.gif";
                img.src = newSource;
            }
       }
    }
    
    function Toolbar_MouseOut(elem) {
        if (currentTool != elem.id) {
            img = elem.getElementsByTagName("img")[0];
            curSource = img.src;
            index = curSource.search(/-OVER.gif/i);
            if (index > -1)
            {
            newSource = curSource.substr(0,index) + ".gif";
            img.src = newSource;
            }
        }
    }
    
    function Toolbar_MouseDown(elem) {
        if (currentTool == elem.id) {
            // tool unselected
             img = elem.getElementsByTagName("img")[0];
            curSource = img.src;
            index = curSource.search(/-ON.gif/i);
            if (index > -1)
            {
            newSource = curSource.substr(0,index) + ".gif";
            img.src = newSource;
            }
            currentTool = '';
        }
        else {
            // tool selected
                 img = elem.getElementsByTagName("img")[0];
                curSource = img.src;
                onIndex = curSource.search(/-ON.gif/i);
                if (onIndex == -1)
                {
                    index = curSource.search(/-OVER.gif/i);
                    if (index == -1)
                        index = curSource.search(/.gif/i);
                     if (index > -1)
                    {
                        newSource = curSource.substr(0,index) + "-ON.gif";
                        img.src = newSource;
                    }
                }
            // unselect the previous tool
            if (currentTool != '') {
                var prevelem = document.getElementById(currentTool);
                var prevImg = prevelem.getElementsByTagName("img")[0];
                prevSource = prevImg.src;
                previndex = prevSource.search(/-ON.gif/i);
                 if (previndex > -1)
                {
                    prevnewSource = prevSource.substr(0,previndex) + ".gif";
                    prevImg.src = prevnewSource;
                }
            }            
            currentTool = elem.id;
            
            // start the drawing
            StartDrawing();
        }
    }
    
   //Handler for selecting and deleting ...
   function RedlineDeleteComplete(geom,evtArgs)
   {
        var geomString = '';
	    geomString = geom.getEnvelope().toString('|',':');
		type = 'DeleteEnvelope';
    	coordString = geomString;
	     var drawCallbackString = redlineVectorCallbackFunctionString;
	     toolMode = 'VectorMode='+type;

	    var argument = toolMode +'&EventArg=DeleteRedline&coords='+geomString+'&VectorAction=finish';
	    var context = this;
	   eval(drawCallbackString);
   }

   function processRedlineDelete(foundShp)
    {
        if (foundShp) {
               window.setTimeout("DeleteAllConfirm()", 500);
        } else
            alert("No redline graphics where found");
    }
    function DeleteAllConfirm()
    {
        if(confirm("Are you sure you want to delete all selected redlines?"))
        {
            var argument="EventArg=DoDeletion";
            var context="Map";
            var drawCallbackString = redlineVectorCallbackFunctionString;
	        eval(drawCallbackString);
        } 
        else
        {
            var argument="EventArg=cancelDeleteShape";
            var context="Map";
            var drawCallbackString = redlineVectorCallbackFunctionString;
	        eval(drawCallbackString);
        }
    }

    // Handler for MeasurePoint clicks
function RedlineComplete(geom, evtArgs) {
	var geomString = '';
	var type = '';
    var style = null; 
    var OutlineColor = document.getElementById('OutlineColor');
    var FillColor = document.getElementById('FillColor');
    var FillType = document.getElementById('FillType');
    var lineColor = "red";//OutlineColor.options[OutlineColor.selectedIndex].value;
    var fillColor = "none";//FillColor.options[FillColor.selectedIndex].value;
    var fillType = "none";//FillType.options[FillType.selectedIndex].value;
    var textString = "";
	if(ESRI.ADF.Geometries.Point.isInstanceOfType(geom)) {
	    geomString = geom.toString(':');
        if (currentTool == 'TextTool'){
            type="text";
            var textString = prompt('Enter Text To Draw', '');

            if ( textString == null || textString.trim() == "" )
            {
                alert("No text was entered");
                return false;
            }
        }else{
		    
		    type = 'point';
		    style = new ESRI.ADF.Graphics.MarkerSymbol("images/crosshair.png",6,6);
		 }
	}
	else if(ESRI.ADF.Geometries.Polyline.isInstanceOfType(geom)) {
		geomString = geom.getPath(0).toString('|',':');
		type = 'polyline';
		
		style = new ESRI.ADF.Graphics.LineSymbol(lineColor,2);
	}
	else if(ESRI.ADF.Geometries.Polygon.isInstanceOfType(geom)) {
		geomString = geom.getRing(0).toString('|',':');
		type = 'polygon';
		//fillsymbol(color, outlinecolor)
		style = new ESRI.ADF.Graphics.FillSymbol(fillColor,lineColor,2);	
		style.set_opacity(0.2);	
	}
	
	
	var randomnumber=Math.floor(Math.random()*100001);
    var newID = "Redline" + randomnumber;

//	RedlineGraphicFeature = $create(ESRI.ADF.Graphics.GraphicFeature,
//		        {"id": newID,"geometry":geom,"symbol":style});
//	map.addGraphic(RedlineGraphicFeature);        
//   
	coordString = geomString;
	  	
	m_measureLastCoords = m_measureCoords;
	m_measureCoords = "";
	//var argument = 'ControldID='+map.get_id()+'&EventArg='+type+'&coords='+geomString+'&VectorMode=measure';	
	 var drawCallbackString = redlineVectorCallbackFunctionString;
	 toolMode = 'VectorMode='+type+'&outline=' + lineColor;
     toolMode += '&fill=' + fillColor;
     toolMode += '&filltype=' + fillType;
     toolMode +='&text='+textString+"&name="+newID;

	var argument = toolMode +'&EventArg=Redline&coords='+geomString+'&VectorAction=finish';
	var context = this;
	eval(drawCallbackString);
}

function removeRedlineGraphic() {
    if (RedlineGraphicFeature!=null) {
        map.removeGraphic(RedlineGraphicFeature);
        RedlineGraphicFeature.dispose();
        RedlineGraphicFeature = null;
    }

}


function FindElement(elemID)
{
   var element = null;
    var elems = document.getElementsByTagName('*');
        if (elems != null && elems.length > 0) {
            for (var i=0; i<elems.length; i++) {
                if (elems[i].id.indexOf(elemID) > -1) {
                        var name ='_' + elemID;
                        if ((elems[i].id.length - elems[i].id.indexOf(name)) == (name.length)) {
                            element = elems[i];
                            break;
                    }
                 }
            }
        }
        if (element != null)
            lineColor  =  element.title;
    return element;
}
    function StartDrawing() {
        var map = Maps[mapBuddyId];
        var drawCallbackString = redlineVectorCallbackFunctionString;
        var lineColorPicker= FindElement("OutlineColorPicker_ChosenColor");
        var lineColor = "Red";
        if (lineColorPicker != null)
            lineColor= lineColorPicker.title;
        var fillColor = "black";
        var fillType = "solid";
        toolMode = currentTool;
        if (currentTool == 'PolylineTool') {
		    map.getGeometry(ESRI.ADF.Graphics.ShapeType.Path,RedlineComplete,null,lineColor,fillColor,'crosshair', true);
        }
        else if (currentTool == 'PolygonTool') {
		    map.getGeometry(ESRI.ADF.Graphics.ShapeType.Ring,RedlineComplete,null,lineColor,fillColor,'crosshair', true);
        }
        else if (currentTool == 'CircleTool') {
		    map.getGeometry(ESRI.ADF.Graphics.ShapeType.Circle,RedlineComplete,null,lineColor,fillColor,'crosshair', true);
        }
        else if (currentTool == 'OvalTool') {
		    map.getGeometry(ESRI.ADF.Graphics.ShapeType.Oval,RedlineComplete,null,lineColor,fillColor,'crosshair', true);
        }
        else if (currentTool == 'PointTool') {
		    map.getGeometry(ESRI.ADF.Graphics.ShapeType.Point,RedlineComplete,null,lineColor,fillColor,'crosshair', true);
        }
        else if (currentTool == 'TextTool') {
           map.getGeometry(ESRI.ADF.Graphics.ShapeType.Point,RedlineComplete,null,lineColor,fillColor,'crosshair', true);
        }
        else if (currentTool == 'DeleteTool')
        {
            map.getGeometry(ESRI.ADF.Graphics.ShapeType.Envelope,RedlineDeleteComplete,null,'blue','red','crosshair', true);
        }
    }
    
    function Export()
    {
         var argument = 'ControlID=' + map.controlName + '&EventArg=ExportRedline&ControlType=Map';
         var context = "<%=MapBuddyId %>";

        eval(redlineExportCallbackFunctionString);
    }
    
    //Callback for Export returns to this function:
    function processRedlineExport(result, context)
    {
        if (result.toUpperCase() == "TRUE") {
            var width = 150;
            var height = 50;
            var left = parseInt((screen.availWidth / 2) - (width));
            var top = parseInt((screen.availHeight / 2) - (height));
            //window.open('RedlineDownload.aspx', 'DownloadWin', 'left=' + left + ',top=' + top + ',menubar=0,resizable=0,width=' + width + ',height=' + height);
            var elem = $get("downloadDiv");
            elem.innerHTML = "<a href='javascript:{}' onclick='window.open(\"RedlineDownload.aspx\", \"DownloadWin\",menubar=0,resizable=0);'>Download</a>";
        } else
            alert("No redline graphics where found");
    }
    
    function ClearSelectedGraphic()
    {
        var lst = FindElement("ListBox1");
        if (lst){
            var selIDs = "";
            for(var z = 0; z < lst.options.length; ++z)    
            { 
                if (lst.options[z].selected == true){
                    if (selIDs!="")
                        selIDs += ",";
                    selIDs+=lst.options[z].value;
                }
             }
             var argument = 'ControlID=' + map.controlName + '&EventArg=ClearSelectedGraphics&ControlType=Map';
             argument +='&IDList='+selIDs;
	        var context = "<%=MapBuddyId %>";

        eval(redlineVectorCallbackFunctionString);
        }
    }
    
    function ClearGraphics() {
   
        var argument = 'ControlID=' + map.controlName + '&EventArg=ClearGraphics&ControlType=Map';
	    var context = "<%=MapBuddyId %>";

        eval(redlineVectorCallbackFunctionString);
    }
    
    function SetProperty(elem) {
        var argument = 'ControlID=' + map.controlName + '&EventArg=SetProperty&ControlType=Map';
        argument += '&propname=' + elem.id + '&propval=' + elem.value;
	    var context = "<%=MapBuddyId %>";

        eval(redlineVectorCallbackFunctionString);
    }
    
   //Close Redline Box with the x in the corner - need to reset tool on toolbar
   function CloseRedline()
   {
        CancelRedline();
        ResetMapPanTool("Map1","toolbarNav","toolbarNav")   
        map.cancelGetGeometry();
   } 
    
   //close the redline toolbox - this is when the user selects another tool
   function CancelRedline()
   {
        var id ="RedlineTools";
        hideRedlineTool(id);
        map.cancelGetGeometry();
   }
   
    function hideRedlineTool(id) {
        m_redlineToolbar = $get(id);
        if (m_redlineToolbar!=null) {
            m_redlineToolbar.style.display = "none";
        }
    } 
// event handler for starting to drag toolbar around... mouse down
function dragRedlineToolbarStart(e) {
    m_redlineToolbar = $get("RedlineTools");
    if (m_redlineToolbar!=null) {
        var box = calcElementPosition(m_redlineToolbar.id);
        m_redlineXOffset =e.clientX - box.left;
        m_redlineYOffset = e.clientY - box.top;
    }
    $addHandler(document, "mousemove", dragRedlineToolbarMove);
    $addHandler(document, "mouseup", dragRedlineToolbarStop);  
    e.preventDefault();
    e.stopPropagation();
}

// event handler for toolbar drag movement... mousemove
function dragRedlineToolbarMove(e) {
    m_redlineToolbar.style.left = (e.clientX-m_redlineXOffset) + "px";;
    m_redlineToolbar.style.top = (e.clientY-m_redlineYOffset) + "px";
    e.preventDefault();
    e.stopPropagation();
}

// event handler for end of toolbar drag movement... mouseup
function dragRedlineToolbarStop(e) {
    $removeHandler(document, "mousemove", dragRedlineToolbarMove);
    $removeHandler(document, "mouseup", dragRedlineToolbarStop);  
    e.preventDefault();
    e.stopPropagation();
}