/* em_map_xml.js
* created: 20060216
* author: jmknab@cattco.org
*/

/* 20071011
 * request has changed after SDE change
<LAYER type="featureclass" name="Ranches" visible="false" id="4">
<DATASET name="sde.SDE.Cattaraugus_Farms_Ranches" type="point" workspace="sde_ws-8" />
<SIMPLERENDERER>
<RASTERMARKERSYMBOL url="http://maps.cattco.org/images/Tourism/horseriding.gif" image="C:\Inetpub\wwwroot\images\Tourism\horseriding.gif" />
</SIMPLERENDERER>
</LAYER>
*/


var aXHR_points = new Array();
var aBusy_points = new Array();
var bGetPoints = 0;

/* use prototype.js Ajax Class instead of previously written xml handling methods
var myAjax = new Ajax.Request( url, { method: 'get', parameters: pars, onComplete: showResponse, onFailure: x });
function showResponse(originalRequest)
{
//put returned XML in the textarea
$('result').value = originalRequest.responseText;
}
*/


/* xml.js
* correct any problems in the XML with the
* correct entities to make it well-formed
*/

/*
Entity Reference  	Character Represented
&amp; 	Ampersand (&)
&lt; 	Less Than (<)
&gt; 	Greater Than (>)
&apos; 	Apostrophe (')
&quot; 	Quote (")
*/

function xml_to_html(vXML) {
	vXML = vXML.replace(/&/g, "&amp;"); // replace & with &amp;

	vXML.replace(/</g, "&lt;");
	vXML.replace(/>/g, "&gt;");
	
	vXML = vXML.replace(/\"/g, "&#34;");
	vXML = vXML.replace(/\'/g, "&#39;");
	return vXML;
}

function xml_entities(vXML) {
	/* please note that to replace the Ampersand
	* make sure that the (&) is not appended with
	* any of the entity replacements
	* &amp;, &lt; and etc.
	*/
	// replace XML entities
	//regex

	vXML = vXML.replace(/&/g, "&amp;"); // replace & with &amp;
	//vXML = vXML.replace(/&\s/g, "&amp; "); // replace '& ' with '&amp; '
	//vXML.replace(/</g, "&lt;")
	vXML = vXML.replace(/\#/g, ""); // replace # with nothing
	vXML = vXML.replace(/&amp\;34\;/g, "&#34;"); // replace &amp;34; with &#34;
	vXML = vXML.replace(/&amp\;39\;/g, "&#39;"); // replace &amp;39; with &#39;
	/*
	vXML = vXML.replace(/"/g, "\"");
	vXML = vXML.replace(/'/g, "&apos;");
	*/
	return vXML;
}
/*
 * =entitiesToValues
 * @replaces some HTML entities with regular values
 */
function entitiesToValues(tmpValue) {
	tmpValue = tmpValue.replace(/&amp\;/g, "&"); // replace &amp; with &
	tmpValue = tmpValue.replace(/&\#34;/g, '"'); // replace &#34; with ";
	tmpValue = tmpValue.replace(/&\#39;/g, "'"); // replace &#39; with ';
	return tmpValue;
}

/*
* pass an array of nodes
*/
function xml_info(aNodes, tmpPrefix) {
	if (tmpPrefix == null) {
		tmpPrefix = "";
	}
	for (var a=0;a<aNodes.length;a++) {
		var node = aNodes[a];
		if (node.nodeType != 1) {
			info (tmpPrefix + " " + a + "Not a tag");
			continue; //skip if it isn't a tag
		}
		info(tmpPrefix + " " + a + " Node: " + node.nodeName + ", Attributes: " + node.attributes.length + ", Children: " + node.childNodes.length);
		// check for attributes
		if (node.attributes.length != 0) {
			for (var attrib=0;attrib<node.attributes.length;attrib++) {
				info(tmpPrefix + " " + node.nodeName + ": Attribute_" + attrib + " " + node.attributes[attrib].name + " " + node.attributes[attrib].value);
			}
		}
		// check for childNodes
		if (node.childNodes.length != 0) {
			xml_info(node.childNodes, tmpPrefix + "-");
		}
	}

}

function xml_getAttributes(node) {
	/* !xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx!
	 * switch to Object ... don't use array for an associative array .. use object
	 */
	var otmpReturn = new Object();
	info("Node "+node);
	if (node == null) {
		return -1;
	} else {
		info("Node Name = "+node.nodeName+", Attributes="+node.attributes.length);
		if (node.attributes.length != 0) {
			var tmpAttribName = "";
			for (var attrib=0;attrib<node.attributes.length;attrib++) {
				info("-Attribute_" + attrib + " " + node.attributes[attrib].name + " " + node.attributes[attrib].value);
				tmpAttribName = (node.attributes[attrib].name).toLowerCase();
				tmpAttribName = tmpAttribName.substring(tmpAttribName.lastIndexOf('.')+1);
				otmpReturn[tmpAttribName] = node.attributes[attrib].value;
			}
		}
		return otmpReturn;
	}
}

// thank you foldblog.blogspot.com for this and theupdater fixes for multiple requests
function http_updater_points(pointLayer) {
	this.index = pointLayer;
	this.status = 'inprogress';
	this.xmlHttp = null;
}
//gets all visible layers points
function em_getPointsWithCurrentExtent() {
	var env = '<ENVELOPE minx="' + minx + '" miny="' + miny +'" maxx="' + maxx +'" maxy="' + maxy + '" />';
	em_getPoints(env);
}


function em_getPointsLayer (tmpLayerID) {
	bGetPoints = 1; // points has started
	//points_clear();
	var envelope = '<ENVELOPE minx="' + minx + '" miny="' + miny +'" maxx="' + maxx +'" maxy="' + maxy + '" />';
	//get visible layers & point layers
	/*
	 * !xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx!
	 * needs to check the proper array item for the layer ID
	 */
	//if ((LayerVisible[i]==1) && (LayerType[i] == "point")) {
	    var axl_p = em_getRequestPoints(LayerID[tmpLayerID], envelope);
	info(axl_p);
	xhr_points(LayerID[tmpLayerID], axl_p);
	//}
	bGetPoints = 0; // done getting points
	debug("em_getPoints:done");
}

function em_getPoints () {
	bGetPoints = 1; // points has started
	points_clear();
	var envelope = '<ENVELOPE minx="' + minx + '" miny="' + miny +'" maxx="' + maxx +'" maxy="' + maxy + '" />';

	//get visible layers
	for (var i=0;i<layerCount;i++) {
		// exclude certain layers
		if ((LayerVisible[i]==1) && (LayerType[i] == "point")) {
			debug('Layer # = '+i+', layerID='+LayerID[i]+', LayerType='+LayerType[i]);
			if ((LayerID[i] == 27) || (LayerID[i] == 47)) {
				debug('Skipped Layer(s) Causing problems = '+LayerID[i]+' ('+LayerName[i]+')');
			} else {
				var axl_p = em_getRequestPoints(LayerID[i], envelope);
				info(axl_p);
				xhr_points(LayerID[i], axl_p);
			}
		}
	}
	bGetPoints = 0; // done getting points
	debug("em_getPoints:done");
}

function em_testGetPoints () {
	//
	debug('em_testGetPoints');
	bGetPoints = 1; // points has started
	points_clear();
	var envelope = '<ENVELOPE minx="' + minx + '" miny="' + miny +'" maxx="' + maxx +'" maxy="' + maxy + '" />';

	// get visible layers
	var tmpLayersVisible = new Array("0","1","47");
	for (var i=0;i<tmpLayersVisible.length;i++) {
		//
		if (LayerType[tmpLayersVisible[i]] == "point") {
			//alert(LayerName[tmpLayersVisible[i]]+" is a "+LayerType[tmpLayersVisible[i]]);
			var axl_p = em_getRequestPoints(LayerID[tmpLayersVisible[i]], envelope);
			info(axl_p);
			xhr_points(tmpLayersVisible[i], axl_p);
		} else {
			warn("em_testGetPoints: "+LayerName[tmpLayersVisible[i]] + " is not a point Layer. It is a "+LayerType[tmpLayersVisible[i]]+" layer");
		}
	}
	bGetPoints = 0; // points has ended
}

function em_getRequestPoints (iLayer, envelope) {
	var axl_p = '';
	axl_p += '<arcxml version="1.1">';
	axl_p += ' <request>';
	axl_p += '  <get_features';
	axl_p += '   featurelimit="200"';
	axl_p += '   beginrecord="0"';
	axl_p += '   outputmode="xml"';
	axl_p += '   attributes="true"';
	axl_p += '   geometry="true">';

	axl_p += '   <layer id="'+ iLayer +'" />';

	axl_p += '   <spatialquery subfields="#ALL#" where="" >';
	axl_p += '    <spatialfilter relation="area_intersection">';
	axl_p += envelope;
	axl_p += '    </spatialfilter>';
	axl_p += '   </spatialquery>';
	axl_p += '  </get_features>';
	axl_p += ' </request>';
	axl_p += '</arcxml>';
	return axl_p;
}



function xhr_points(tmpLayerID, tmpPostBody) {
	
	var req = xhr_create_instance(tmpLayerID);	

	aBusy_points[tmpLayerID] = true; // set to false after onreadystatechange function has completed
	
			//if(!isIE){aXHR_points[iXHR][1].overrideMimeType("text/xml")}
			debug('XHR:onreadystatechange');
			req.onreadystatechange = function() {
				points_xhr(tmpLayerID);
			};
			debug('XHR:open');
			req.open("post", query_url, true);

			debug('XHR:about to send');

			req.send(tmpPostBody);
			debug("XHR:sent");

}

/*function XHR_callInProgress() {
	for(var j=1;j<aXHR_points.length;j++) {
		if (aXHR_points[j][1] != null) {
		switch ( aXHR_points[j][1].readyState ) {
			case 1: case 2: case 3:
			debug('call in progress');
			return true;
			break;

			// Case 4 and 0
			default:
			return false;
			break;

		}
		}
	}
	return false;
}
*/

function XHR_current(){
	// get the active XmlHttpRequest from the QUEUE (really the Array)
    for (var x=0;x<aBusy_points.length;x++) {
    	if (aBusy_points[x] == true) {
    		return x;
    	}
    }
    return null;
}

function points_xhr(iTmpLayerID) {
	var tmpXHR = xhr_create_instance(iTmpLayerID);
	/*var iTmpXHR = XHR_current();
    if (iTmpXHR == null) {
    	alert("Done?");
    	return;
    } */
    //debug('XHR # '+iTmpXHR);
    debug('readyState='+tmpXHR.readyState);
    // check the state
	if (tmpXHR.readyState == 4 || tmpXHR.readyState == 'complete') {
		// check the status
		debug('readystate=4');
		if (tmpXHR.status == 200) {
			debug('status=200');
			var tmpResponseText = tmpXHR.responseText;
			xhr_done(iTmpLayerID); // done with xhr
			em_parseResponsePoints(tmpResponseText, iTmpLayerID);
		} else {
			// error
			alert('XHR:Error-Problem Retrieving information');
		}
	}
}

function em_parseResponsePoints(tmpResponseText,iTmpLayerID){

	debug("em_parseResponsePoints");
	debug('XHR info: layerID='+iTmpLayerID);
	//alert('ReponseText='+tmpResponseText);
	var result = tmpResponseText;
	result = xml_entities(result);
	//result = xml_entities(result);
	info("em_parseResponse:result = "+result);
	//strip out points and add them to ;
	/*
	* axl layer id, name, address, city, state, zip,
	* phone, web_site, email_addr,
	* x, y, latitude, longitude
	*/
	var xmlDocPoints;
	if(document.implementation && document.implementation.createDocument) {
		// MOZILLA
		xmlDocPoints = document.implementation.createDocument("", "", null);
		xmlDocPoints.async="false";
		//info("Response Header: "+http.GetResponseHeader("Content-Type"));
		//info("Result = "+result);
		xmlDocPoints.loadXML(result);
	} else if (window.ActiveXObject){
		//IE
		xmlDocPoints = new ActiveXObject("Microsoft.XMLDOM");
		xmlDocPoints.async="false";
		xmlDocPoints.loadXML(result);
	}
	debug("Completed xmlDoc.loadXML");
	var someNodeList = xmlDocPoints.getElementsByTagName('FEATURE');
	var nodes = $A(someNodeList);
	info("nodes.length="+nodes.length);
	xml_info(nodes);
	info("minX,minY = "+minx+", "+miny+" maxX,maxY = "+maxx+", "+maxy);
	/*
	var testConversion = convertPixelToMap(0,0);
	debug("Conversion map screen coords 0,0 " + testConversion[0] + ", " + testConversion[1]);
	var testConversionXY = convert_latitude_longitude(testConversion[0], testConversion[1]);
	createHotSpot(testConversionXY[0], testConversionXY[1]);

	var testMiddle = convertPixelToMap(mwidth/2, mheight/2);
	debug("Conversion map screen coords ("+mwidth/2+", "+mheight/2+") for middle of map "+testMiddle[0]+", "+testMiddle[1]);
	var testMiddleXY = convert_latitude_longitude(testMiddle[0],testMiddle[1]);
	createHotSpot(testMiddleXY[0], testMiddleXY[1]);

	var testQuarterWidth = convertPixelToMap(mwidth/4,mheight/2);
	debug("Conversion map screen coords ("+mwidth/4+", "+mheight/2+") for quarter width of map "+testQuarterWidth[0]+", "+testQuarterWidth[1]);
	var testQuarterWidthXY = convert_latitude_longitude(testQuarterWidth[0],testQuarterWidth[1]);
	createHotSpot(testQuarterWidthXY[0], testQuarterWidthXY[1]);

	var testQuarter = convertPixelToMap(mwidth/4, mheight/4);
	debug("Conversion map screen coords ("+mwidth/4+", "+mheight/4+") for quarter of map "+testQuarter[0]+", "+testQuarter[1]);
	var testQuarterXY = convert_latitude_longitude(testQuarter[0], testQuarter[1]);
	createHotSpot(testQuarterXY[0], testQuarterXY[1]);
	*/
    debug("Active Requests = "+iXHR +' nodes.length='+nodes.length);
	for (var iNode=0;iNode<nodes.length;iNode++) {
		node = nodes[iNode];
		info("Parsing Node: "+node.nodeName);
		if (node.childNodes.length != 0) {
			var atmpFields = node.getElementsByTagName('FIELDS');
			if (atmpFields) {
				var otmpFieldsAttributes = xml_getAttributes(atmpFields[0]);
			}
			var atmpPoints = node.getElementsByTagName('POINT');
			
			if (atmpPoints) {
				info("atmpPoints "+atmpPoints);
				var otmpPointsAttributes = xml_getAttributes(atmpPoints[0]);
				if (otmpPointsAttributes == -1) {
					xml_info(atmpPoints);
				} else {
					var pTmpInfo;
					/* !xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx!
					* check field attributes
					* otmpFieldsAttributes['name'],
					otmpFieldsAttributes['address'],
					otmpFieldsAttributes['city'],
					otmpFieldsAttributes['state'],
					otmpFieldsAttributes['zip'],
					otmpFieldsAttributes['phone'],
					otmpFieldsAttributes['website'],
					otmpFieldsAttributes['id'],
					otmpFieldsAttributes['hotlinks']
					*/
					
					if (!otmpFieldsAttributes['name']) {
						if (otmpFieldsAttributes['creek_name'] != null) {
							otmpFieldsAttributes['name'] = otmpFieldsAttributes['creek_name'];
						} else if (otmpFieldsAttributes['lake_name'] != null) {
							otmpFieldsAttributes['name'] = otmpFieldsAttributes['lake_name'];
						} else {
							otmpFieldsAttributes['name'] = "Unknown";
						}
					}
					if (!otmpFieldsAttributes['address']) {
						otmpFieldsAttributes['address'] = "";
					}
					if (!otmpFieldsAttributes['city']) {
						otmpFieldsAttributes['city'] = "";
					}
					if (!otmpFieldsAttributes['state']) {
						otmpFieldsAttributes['state'] = "";
					}
					if (!otmpFieldsAttributes['zip']) {
						otmpFieldsAttributes['zip'] = "";
					}
					if (!otmpFieldsAttributes['phone']) {
						otmpFieldsAttributes['phone'] = "";
					}
					if (!otmpFieldsAttributes['web_site']) {
						otmpFieldsAttributes['web_site'] = "";
					}
					if (!otmpFieldsAttributes['id']) {
						otmpFieldsAttributes['id'] = "";
					}
					if (!otmpFieldsAttributes['hotlinks']) {
						otmpFieldsAttributes['hotlinks'] = "";
					}

					if (otmpFieldsAttributes['items']) {
						pTmpInfo = "Types: "+otmpFieldsAttributes['items']+" like ";
						if (otmpFieldsAttributes['spec_items']) {
							pTmpInfo += otmpFieldsAttributes['spec_items'];
						}
					}
					if (otmpFieldsAttributes['type']) {
						pTmpInfo = otmpFieldsAttributes['type'];
					}
					if (otmpFieldsAttributes['creek_name']) {
						if (otmpFieldsAttributes['creek_name'] != '') {
							pTmpInfo = 'Creek Name: '+otmpFieldsAttributes['creek_name']+'\n';
						}
						if (otmpFieldsAttributes['lake_name'] != '') {
							pTmpInfo += 'Lake Name: '+otmpFieldsAttributes['lake_name']+'\n';
						}
						if (otmpFieldsAttributes['fish_type'] != '') {
							pTmpInfo += 'Fish: '+otmpFieldsAttributes['fish_type']+'\n';
						}
						if (otmpFieldsAttributes['season'] != '') {
							pTmpInfo += 'Season: '+otmpFieldsAttributes['season']+'\n';
						}
						if (otmpFieldsAttributes['stream_mil'] != '') {
							pTmpInfo += 'Stream Mile(s): '+otmpFieldsAttributes['stream_mil']+'\n';
						}
						if (otmpFieldsAttributes['lake_name'] != '') {
							pTmpInfo += 'Lake Name: '+otmpFieldsAttributes['lake_name']+'\n';
						}
						if (otmpFieldsAttributes['ice_fishin'] != '') {
							pTmpInfo += 'Ice Fishing: '+otmpFieldsAttributes['ice_fishin']+'\n';
						}
						if (otmpFieldsAttributes['pfr'] != '') {
							pTmpInfo += 'Public Fishing Rights: '+otmpFieldsAttributes['pfr'];
						}

					}
					point_add(
					iTmpLayerID, // LAYER that the point is related to

					otmpPointsAttributes['y'],
					otmpPointsAttributes['x'],

					otmpFieldsAttributes['name'],
					otmpFieldsAttributes['address'],
					otmpFieldsAttributes['city'],
					otmpFieldsAttributes['state'],
					otmpFieldsAttributes['zip'],
					otmpFieldsAttributes['phone'],
					otmpFieldsAttributes['website'],

					otmpFieldsAttributes['id'],
					otmpFieldsAttributes['hotlinks'],
					pTmpInfo
					);
				}
			}
		}

		//convert_latitude_longitude(1123404.88015903, 828441.290015045);

		//createHotSpot(300, 300);

		//var pointCount = xmlDocPoints.documentElement.getElementsByTagName("FEATURES").length;
		//item(0).getAttribute("count")
		//debug("Point Count = "+pointCount);
	}
	aBusy_points[iTmpLayerID] = false;
	if (XHR_current() == null) {
		
		// create points from points array using new function
		pointsScreenCreate();
		// apply behaviour
		Behaviour.apply();
		//alert("Points done");
		if (oPointFlagged['layerID'] != -1) {
			// find it and show it
			//alert(oPointFlagged['layerID']+':'+oPointFlagged['pointID'] +' is Flagged!');
			var tmpIndex = getPointIndex(oPointFlagged['layerID'], oPointFlagged['pointID']);
			if (tmpIndex != null) {
				pointShowClose(point_prefix+tmpIndex);
				oPointFlagged['layerID'] = -1;
				oPointFlagged['pointID'] = -1;
			}
		}
	}
	// hide loading layer
	hideLayer('loading');
	/*
	aXHR_points[iTmpXHR][1] = null; // clear the XHR object
	debug('cleared XHR object # '+iTmpXHR);
	*/
}
//alert("EM XML");