//*********** COnfigure Page Instructions *************
/*
    1) Make sure XML document is configured first.
    2) Batch Replace "Parcels" with name of your tool.
    3) Change path to XML document (if necessary).

*/
//********** ENd Instructions *************************/



//***** Checks global variables and initialize if they don't exist already from other tools **********
if(gToolbar){}	
else{var gToolbar;
     var gToolbarRequire = dojo.require("esri.toolbars.draw");
     }

if(gDojoIdentifyTask){}	
else{var gDojoIdentifyTask = dojo.require("esri.tasks.identify");}

if(gMapToLocalVar){}
else {var gMapToLocalVar;}

if(httpRequest){}
else {var httpRequest;}

//***** Local file global variables to store values from XML config file *****
var g_Parcels_identifyTask;
var g_Parcels_identifyParams;
var g_Parcels_IdentifyURL = new Array();
var g_Parcels_IdentifyLayer = new Array();
var g_Parcels_Color;

//***** Initial function that fires this script *****
function Parcels_parseXML()
{
    gMapToLocalVar = myMap; //tranfers map name from main to local page variable in case map name changes, just change this one spot.

    dojo.disconnect(vMapEvents);
    dojo.disconnect(vMapClickEvent);
    dojo.byId("WidgetResults").innerHTML = "&nbsp;";
    
 	var ShowIdentifyResult = "";
	ShowIdentifyResult = ShowIdentifyResult + "<div id='IdentifyResults' style='position:relative; left:100px; top:-1600px; width:200px; height:75px; display:block;'>";
    ShowIdentifyResult = ShowIdentifyResult + "<img src='javascript/widget_Parcels/ResultBG.png' style='opacity:0.9;filter:alpha(opacity=90)' width=320 height=75>";
	ShowIdentifyResult = ShowIdentifyResult + "<div id='dentifyResults' style='position:relative; left:10px; top:-75px; z-index:92; display:block; font-size:8pt; width:310px; height:75px; color:white;'>";
	ShowIdentifyResult = ShowIdentifyResult + "<table width=290><tr><td width=250 valign=top style='color:white; font-size:12pt;'>Parcels</td>";
	ShowIdentifyResult = ShowIdentifyResult + "<td width=40 valign=top><img src='images/Move.png' width=20 onmousedown=dragStart(event,'IdentifyResults');><img src='javascript/widget_Parcels/Close.png' onclick='Parcels_ClearPanel();'></td></tr></table>";	 
    ShowIdentifyResult = ShowIdentifyResult + "<table cellpadding='0' cellspacing='0'><tr><td id='Parcel Tools' style='color:white; font-size:8pt;'>";
    ShowIdentifyResult = ShowIdentifyResult + "<a style='color:white; font-weight:bold;'>Tool activated, click on parcel to identify or</a><br>";
    ShowIdentifyResult = ShowIdentifyResult + "<input type='button' value='Draw Boundary' onclick='Parcels_CreateToolbar();'>";
    //ShowIdentifyResult = ShowIdentifyResult + "<input type='button' value='Highlight' onclick='Parcels_ActivateColorParcels();'>";
    ShowIdentifyResult = ShowIdentifyResult + "</td></tr>";
    ShowIdentifyResult = ShowIdentifyResult + "<tr><td colspan=2><div id='DivColorPicker'></div></td></tr>";
    ShowIdentifyResult = ShowIdentifyResult + "</table>";
    ShowIdentifyResult = ShowIdentifyResult + "</div></div>";
    
    dojo.byId("WidgetResults").innerHTML = ShowIdentifyResult;     
    
    
    dojo.byId("tdHelpTip").innerHTML = "Help: Click on a parcel to get information!";    

    try //Internet Explorer
        {xmlDoc=new ActiveXObject("Microsoft.XMLDOM");}
    catch(e)
    {
        try //Firefox, Mozilla, Opera, etc.
        {xmlDoc=document.implementation.createDocument("","",null);}
        catch(e)
        {
        alert(e.message);
        return;
        }
    }

    xmlDoc.async=false;
    xmlDoc.load("javascript/widget_Parcels/Parcels.xml");
    
    x=xmlDoc.getElementsByTagName('identifyURL');
    for (i=0;i<x.length;i++)
    {
        g_Parcels_IdentifyURL[i] = x[i].childNodes[0].nodeValue;
    }

    x=xmlDoc.getElementsByTagName('featureLayer');
    for (i=0;i<x.length;i++)
    {
        var descfieldnode = Parcels_getNextSibling(x[i]);
        var linkfieldnode = Parcels_getNextSibling(descfieldnode);
        g_Parcels_IdentifyLayer[i] = new Array();
        g_Parcels_IdentifyLayer[i][0] = x[i].childNodes[0].nodeValue;
        g_Parcels_IdentifyLayer[i][1] = descfieldnode.childNodes[0].nodeValue;
        g_Parcels_IdentifyLayer[i][2] = linkfieldnode.childNodes[0].nodeValue; 
    }

    Parcels_InitIdentify();

}

//***** Transverse the XML document for siblings (for FireFox line break bug) *****
function Parcels_getNextSibling(startBrother){
  endBrother=startBrother.nextSibling;
  while(endBrother.nodeType!=1){
    endBrother = endBrother.nextSibling;
  }
  return endBrother;
} 

//***** Setup up the identify URl and params (done automatically after reading XML file, no user interaction) *****
function Parcels_InitIdentify() {

	var vLayerList = "";
	vMapClickEvent = dojo.connect(gMapToLocalVar, "onClick", Parcels_doIdentify);

	g_Parcels_identifyTask = new esri.tasks.IdentifyTask(g_Parcels_IdentifyURL[0]);
	g_Parcels_identifyParams = new esri.tasks.IdentifyParameters();
	g_Parcels_identifyParams.tolerance = 3;
	g_Parcels_identifyParams.returnGeometry = false;
	g_Parcels_identifyParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_ALL;	
	//String together list of layer IDs
	for (i=0;i<g_Parcels_IdentifyLayer.length;i++)
	{
	    if(i == (g_Parcels_IdentifyLayer.length - 1))
	        vLayerList = vLayerList + g_Parcels_IdentifyLayer[i][0];
	    else
	        vLayerList = vLayerList + g_Parcels_IdentifyLayer[i][0] + ",";
	}
	g_Parcels_identifyParams.layerIds = [vLayerList];
}

//***** This function actually fires the identify task after the user has clicked on a spot *****
function Parcels_doIdentify(evt) {

	gMapToLocalVar.graphics.clear();
	
	var symbol = new esri.symbol.SimpleMarkerSymbol();
        symbol.setStyle(esri.symbol.SimpleMarkerSymbol.STYLE_DIAMOND);
        symbol.setColor(new dojo.Color([255,0,0,0.75]));
    var graphic = new esri.Graphic(evt.mapPoint, symbol);
    gMapToLocalVar.graphics.add(graphic);		
 	
	g_Parcels_identifyParams.geometry = evt.mapPoint;
	g_Parcels_identifyParams.mapExtent = gMapToLocalVar.extent;
	g_Parcels_identifyTask.execute(g_Parcels_identifyParams, function(IdentifyResult) { Parcels_ShowResults(IdentifyResult); });

}

//***** After the identify function has run, it passes the result sets to this function. Mostly just formatting results *****
function Parcels_ShowResults(pIdentifyResult) {
	var ShowAtt = new Array();
	var AttribList = "";
	var AdditionalInfo = "";
	var vCounter = 0;
	
	//Store all results into a single string to output later.
	for(i=0; i<pIdentifyResult.length; i++)
	{
		ShowAtt[i] = pIdentifyResult[i].feature;
	    for(x=0; x<g_Parcels_IdentifyLayer.length; x++)
	    {
	        if(g_Parcels_IdentifyLayer[x][0] == pIdentifyResult[i].layerId) {
	            //handles the description part
	            if(g_Parcels_IdentifyLayer[x][1].indexOf(",") > 0) // more than one field in XML
	            {
                    var FieldSplit = g_Parcels_IdentifyLayer[x][1].split(",");//splitting the field names by a comma
                    for(z=0; z<FieldSplit.length; z++)
                    {

                        if((ShowAtt[i].attributes[FieldSplit[z]] != "") && (ShowAtt[i].attributes[FieldSplit[z]] != "Null"))//checking to make sure the field exists
                        {//AttribList = AttribList + FieldSplit[z] + ": " + ShowAtt[i].attributes[FieldSplit[z]] + "<br>";
                            switch (FieldSplit[z]) {
                                case 'Owner_Name': AttribList = AttribList + "Owner Name: " + ShowAtt[i].attributes[FieldSplit[z]] + "<br>"; break;
                                case 'Situs': AttribList = AttribList + "Address: " + ShowAtt[i].attributes[FieldSplit[z]] + "<br>"; break;
                                case 'Account_Nu': AttribList = AttribList + "Account #: " + ShowAtt[i].attributes[FieldSplit[z]] + "<br>"; break;
                                case 'PropID': AttribList = AttribList + "<a href='javascript/widget_Parcels/bcad.htm?bcad=" + ShowAtt[i].attributes[FieldSplit[z]] + "' target='_blank'>View BCAD details</a><br>"; break;
                                case 'PROP_ID': AttribList = AttribList + "Property ID: "+ ShowAtt[i].attributes[FieldSplit[z]]+ "</br>" + "<a href='javascript/widget_Parcels/wcad.htm?wcad=" + ShowAtt[i].attributes[FieldSplit[z]] + "' target='_blank'>View WCAD details</a><br>"; break;
                            }

                        }                                    
                    }

	            }
	            else // single field in XML
	            {
	                if(g_Parcels_IdentifyLayer[x][1] != "null")
	                {
	                    if((ShowAtt[i].attributes[g_Parcels_IdentifyLayer[x][1]] != "") && (ShowAtt[i].attributes[g_Parcels_IdentifyLayer[x][1]] != "Null"))
	                    {AttribList = AttribList + g_Parcels_IdentifyLayer[x][1] + ": " + ShowAtt[i].attributes[g_Parcels_IdentifyLayer[x][1]] + "<br>";}
	                }
	            }  
	            //end description part
	            
	            //handles the link part
	            if(g_Parcels_IdentifyLayer[x][2].indexOf(",") > 0) //More than one field in XML
	            {
                    var LinkSplit = g_Parcels_IdentifyLayer[x][2].split(",");
                    for(var y=0; y<LinkSplit.length; y++)
                    {
                        if((ShowAtt[i].attributes[LinkSplit[y]] != "") && (ShowAtt[i].attributes[LinkSplit[y]] != "Null"))  
                        { 
                            if(ShowAtt[i].attributes[LinkSplit[y]].indexOf("http") > -1)
                            {AttribList = AttribList + LinkSplit[y] + ": <a href='" + ShowAtt[i].attributes[LinkSplit[y]] + "' target=_blank>Link</a><br>"; }
                            else
                            {AttribList = AttribList + LinkSplit[y] + ": <a href='javascript/widget_Parcels/" + ShowAtt[i].attributes[LinkSplit[y]] + "' target=_blank>Link</a><br>";}  
                        }
                    }
	            }
	            else //single field in XML
	            {
	                if(g_Parcels_IdentifyLayer[x][2] != "null")
	                {
	                    if((ShowAtt[i].attributes[g_Parcels_IdentifyLayer[x][2]] != "") && (ShowAtt[i].attributes[g_Parcels_IdentifyLayer[x][2]] != "Null"))  
                        { 
	                        if(ShowAtt[i].attributes[g_Parcels_IdentifyLayer[x][2]].indexOf("http") > -1)
	                        {AttribList = AttribList + g_Parcels_IdentifyLayer[x][2] + ": <a href='" + ShowAtt[i].attributes[g_Parcels_IdentifyLayer[x][2]] + "' target=_blank>Link</a><br>";}
	                        else
	                        {AttribList = AttribList + g_Parcels_IdentifyLayer[x][2] + ": <a href='javascript/widget_Parcels/" + ShowAtt[i].attributes[g_Parcels_IdentifyLayer[x][2]] + "' target=_blank>Link</a><br>";}
	                    }
	                }
	            }  
	            //end link part	            

                //handle special cases
                    //place special cases here.
                //end special cases
	        }
		}
		AttribList = AttribList + "<br>";	
	}
	
	//sets up the background of the results window
	var ShowIdentifyResult = "";
	ShowIdentifyResult = ShowIdentifyResult + "<div id='IdentifyResults' style='position:relative; left:100px; top:-1550px; width:200px; height:250px; z-index:100; display:block;'>";
    ShowIdentifyResult = ShowIdentifyResult + "<img src='javascript/widget_Parcels/ResultBG.png' style='opacity:0.9;filter:alpha(opacity=90)'>";
	ShowIdentifyResult = ShowIdentifyResult + "<div id='dentifyResults' style='position:relative; left:10px; top:-482px; z-index:92; display:block; font-size:8pt; width:310px; height:465px; overflow-y: scroll; color:white;'>";
	ShowIdentifyResult = ShowIdentifyResult + "<table width=290><tr><td width=250 valign=top style='color:white; font-size:12pt;'>Parcels</td>";
	ShowIdentifyResult = ShowIdentifyResult + "<td width=40 valign=top><img src='images/Move.png' width=20 onmousedown=dragStart(event,'IdentifyResults');><img src='javascript/widget_Parcels/Close.png' onclick='Parcels_ClearPanel();'></td></tr></table>";	
    ShowIdentifyResult = ShowIdentifyResult + "<table cellpadding='0' cellspacing='0'><tr><td id='Parcel Tools' style='color:white; font-size:8pt;'>";
    ShowIdentifyResult = ShowIdentifyResult + "<a style='color:white; font-weight:bold;'>Tool activated, click on parcel to identify or</a> <br>";
    ShowIdentifyResult = ShowIdentifyResult + "<input type='button' value='Draw Boundary' onclick='Parcels_CreateToolbar();'>"; 
    //ShowIdentifyResult = ShowIdentifyResult + "<input type='button' value='Highlight' onclick='Parcels_ActivateColorParcels();'>";       
    ShowIdentifyResult = ShowIdentifyResult + "</td></tr></table><br><br>";	
	//write out the formatted identify results.
	if (AttribList != "")
	{
	ShowIdentifyResult = ShowIdentifyResult + AttribList + AdditionalInfo;
	}
	else
	{ShowIdentifyResult = ShowIdentifyResult + "Sorry, no results";}
	
	ShowIdentifyResult = ShowIdentifyResult + "</div></div>"; 
    //place the results in a hidden place holder on the website and show.
	dojo.byId("WidgetResults").innerHTML = ShowIdentifyResult;
}


function Parcels_CreateToolbar(map) { 
    gMapToLocalVar.graphics.clear();
   
    gToolbar = new esri.toolbars.Draw(gMapToLocalVar);
    dojo.connect(gToolbar, "onDrawEnd", addToMap);
    
    gToolbar.activate(esri.toolbars.Draw.FREEHAND_POLYGON);
    gMapToLocalVar.hideZoomSlider();
}

function addToMap(geometry) {
       switch (geometry.type) {
          case "polygon":
            var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_NONE, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_DASHDOT, new dojo.Color([255,0,0]), 2), new dojo.Color([255,255,0,0.25]));
            break;
        }
        var graphic = new esri.Graphic(geometry, symbol);
        gMapToLocalVar.graphics.add(graphic);
        Parcels_doIdentify2(geometry);
}


function Parcels_doIdentify2(evt) {
 	
	g_Parcels_identifyParams.geometry = evt;
	g_Parcels_identifyParams.mapExtent = gMapToLocalVar.extent;
	g_Parcels_identifyTask.execute(g_Parcels_identifyParams, function(IdentifyResult) { Parcels_ShowResults(IdentifyResult); });
	
	gMapToLocalVar.showZoomSlider();
	gToolbar.deactivate();

}

function Parcels_ActivateColorParcels()
{
    dojo.disconnect(vMapEvents);
    dojo.disconnect(vMapClickEvent);
    g_Parcels_identifyParams.returnGeometry = true;
    vMapClickEvent = dojo.connect(gMapToLocalVar, "onClick", Parcels_ShowColorPicker);
    
    dojo.byId("DivColorPicker").innerHTML = "<iframe id='fmColor' src='javascript/colorPicker/colorPicker.html' height='250'></iframe>";
    
}

function Parcels_ShowColorPicker(evt)
{
    g_Parcels_identifyParams.geometry = evt.mapPoint;
	g_Parcels_identifyParams.mapExtent = gMapToLocalVar.extent;
	g_Parcels_identifyTask.execute(g_Parcels_identifyParams, function(IdentifyResult) { Parcels_ColorParcels(IdentifyResult); });
    
}

function Parcels_ColorParcels(pResult)
{
   
        var R_val = parent.frames.fmColor.document.formColor.cp1_Red.value;
        var G_val = parent.frames.fmColor.document.formColor.cp1_Green.value;
        var B_val = parent.frames.fmColor.document.formColor.cp1_Blue.value;
        //alert(R_val);

    //for(i=0; i<pResult.length; i++)
	//{
		var temp = pResult[0].feature;
		var temp2 = temp.geometry;
		var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0,0,0]), 2), new dojo.Color([R_val,G_val,B_val,0.65]));
	    //var symbol = new esri.symbol.SimpleMarkerSymbol();
        //symbol.setStyle(esri.symbol.SimpleMarkerSymbol.STYLE_DIAMOND);
        //symbol.setColor(new dojo.Color([0,0,255,0.75]));
        var graphic = new esri.Graphic(temp2, symbol);
        gMapToLocalVar.graphics.add(graphic);		
    //}
}

//***** Clears the results window when user closes the window. *****
function Parcels_ClearPanel()
{
    dojo.byId("WidgetResults").innerHTML = "";			
}


