/*
City of Saint Paul Open Source License

LICENSE

Copyright © 2006 City of Saint Paul, Minnesota. 

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

1.The above copyright notice and this permission notice shall be included in all copies of this Software or works derived from this Software.
2.Whenever a Recipient distributes or redistributes the Software, a copy of this agreement must be included with each copy of the Software
3.If Recipient distributes or redistributes the Software in any form other than source code, Recipient must also make the source code freely available, and must provide with each copy of the Software information on how to obtain the source code in a reasonable manner on or through a medium customarily used for software exchange
4.A Recipient may not make any representation in the Software or in any promotional, advertising or other material that may be construed as an endorsement by the City of Saint Paul of any product or service provided by Recipient, or that may seek to obtain commercial advantage by the fact of the City of Saint Paul’s participation in this Agreement.

DISCLAIMER OF WARRANTIES AND LIABILITIES; WAIVER AND INDEMNIFICATION

No Warranty:  The Software is provided “as is” without any warranty of any kind, either expressed, implied, or statutory, including, but not limited to, any warranty that the Software will conform to specifications, any implied warranties of merchantability, fitness for a particular purpose, or freedom from infringement, any warranty that the Software will be error free, or any warranty that documentation, if provided, will conform to the Software. This agreement does not, in any manner, constitute an endorsement by the City of Saint Paul or any prior recipient of any results, resulting designs, hardware, software products or any other applications resulting from use of the Software. Further, the City of Saint Paul disclaims all warranties and liabilities regarding third-party software, if present in the original Software, and distributes it “as is.”

Waiver and Indemnity:  Recipient agrees to waive any and all claims against the City of Saint Paul, its contractors and subcontractors, as well as any prior recipient.  If recipient's use of the Software results in any liabilities, demands, damages, expenses or losses arising from such use, including any damages from products based on, or resulting from, recipient's use of the Software, recipient shall indemnify and hold harmless the City of Saint Paul, it’s contractors and subcontractors, as well as any prior recipient, to the extent permitted by law. Recipient's sole remedy for any such matter shall be the immediate, unilateral termination of this agreement.

SUPPORT STATEMENT 

The Software is freely provided by the City of Saint Paul as a public service.  The recipient is herby notified that the provision and distribution of the Software should in no way be construed to mean that the City of Saint Paul is obligated to provide any level of support for the Software, now or in the future.  Support in this context shall be construed to mean providing coordination, technical assistance, responding to questions, releasing bug fixes, providing future releases, or otherwise obligating the City of Saint Paul to commit resources to maintain this Software or assist in its implementation by any person or entity.  The City of Saint Paul may, at it’s sole option, and without notice or obligation to the recipients, provide varying levels of support for the Software or terminate the agreement.  Provision of such support shall not alter the condition that the Software is provided without support as stated above.
*/

/*
 * Useful Javascript Functions
 */

function trim(str) {
	while(str.substring(0,1).match(/\s/)) {
		str = str.substring(1, str.length);
	}
	while(str.substring(str.length-1,1).match(/\s/)) {
		str = str.substring(0, str.length-1);
	}
	str = str.replace(/\x0A/,'');
	return str;
}
function doNadda() { return false; }


function clearSelection () {
	if (document.selection)
	document.selection.empty();
	else if (window.getSelection)
	window.getSelection().removeAllRanges();
}

function roundUp(n) {
	var noDecimals = Math.round(n);
	if(n - noDecimals > 0) {
		noDecimals++;
	}
	return noDecimals;
}

/*
 * Truncates a number to a specific number of digits
 */
function round(number,X) {
	X = (!X ? 2 : X);

	var n = new String(number);
	var loc = n.indexOf('.');
	var whole = n.substring(0,loc);
	var decimal = n.substring(loc+1, loc+1+X);
	return (whole+'.'+decimal);
}

function getKeyCode(event) {
	var KeyString = '';
	if(event.ctrlKey) {
		KeyString = KeyString + 'CTRL+';
	}
	if(event.shiftKey) {
		KeyString = KeyString + 'SHIFT+';
	}
	var key;
	if(event.which) {
		key = event.which;
	}
	if(event.keyCode) {
		key = event.keyCode;
	}
	return KeyString = KeyString + String.fromCharCode(key);
}


function stripCommas(v) {
	v = new String(v);
	while(v.match(/\,/)) {
		v = v.replace(',','');
	}
	return v;
}

function commifyNumber(number) {
	var numberOrig = new String(number);
	var numberArr = new String(number).split('.');
	number = numberArr[0];
 number = '' + number;
 if (number.length > 3) {
  var mod = number.length % 3;
  var output = (mod > 0 ? (number.substring(0,mod)) : '');
  for (i=0 ; i < Math.floor(number.length / 3); i++) {
   if ((mod == 0) && (i == 0))
    output += number.substring(mod+ 3 * i, mod + 3 * i + 3);
   else
    output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
  }
 } else {
   output=number;
 }
 if(numberOrig.match('.') && numberArr[1]) {
 	output = output + '.' + numberArr[1];
 }
 return output;
}

function parseBoolean(s, def) {
	if (!s) return def;
	s = s.toString().toLowerCase();
	return s == "true" || s == "yes" || parseInt(s) > 0;
}

/*
 * Ground Unit Translations
 */
var UNITS_STRINGS = new Array();
UNITS_STRINGS['M'] = 'Meters';
UNITS_STRINGS['IN'] = 'Inches';
UNITS_STRINGS['MI'] = 'Miles';
UNITS_STRINGS['FT'] = 'Feet';

var UNITS_SQ_STRINGS = new Array();
UNITS_SQ_STRINGS['SQIN'] = 'Square Inches';
UNITS_SQ_STRINGS['SQFT'] = 'Square Feet';
UNITS_SQ_STRINGS['SQMI'] = 'Square Miles';
UNITS_SQ_STRINGS['SQM'] = 'Square Meters';
UNITS_SQ_STRINGS['SQACRE'] = 'Acres';

var UNIT_CONVERSION = new Array();

UNIT_CONVERSION['IN'] = new Array();
UNIT_CONVERSION['IN']['FT'] = 0.083333333; // f(x) where x = inches and f(x) = feet
UNIT_CONVERSION['IN']['MI'] = 0.000015783;
UNIT_CONVERSION['IN']['M'] = 0.0254;
UNIT_CONVERSION['IN']['IN'] = 1;

UNIT_CONVERSION['FT'] = new Array();
UNIT_CONVERSION['FT']['IN'] = 12;
UNIT_CONVERSION['FT']['MI'] = 0.000189394;
UNIT_CONVERSION['FT']['M'] = 0.3048;
UNIT_CONVERSION['FT']['FT'] = 1;

UNIT_CONVERSION['MI'] = new Array();
UNIT_CONVERSION['MI']['IN'] = 63360;
UNIT_CONVERSION['MI']['FT'] = 5280;
UNIT_CONVERSION['MI']['M'] = 1609.344;
UNIT_CONVERSION['MI']['MI'] = 1;

UNIT_CONVERSION['M'] = new Array();
UNIT_CONVERSION['M']['FT'] = 3.280839895;
UNIT_CONVERSION['M']['MI'] = 0.000621371;
UNIT_CONVERSION['M']['IN'] = 39.37007874;
UNIT_CONVERSION['M']['M'] = 1;

UNIT_CONVERSION['SQIN'] = new Array();
UNIT_CONVERSION['SQIN']['SQIN'] = 1;
UNIT_CONVERSION['SQIN']['SQFT'] = 0.006944;
UNIT_CONVERSION['SQIN']['SQMI'] = .000000000249;
UNIT_CONVERSION['SQIN']['SQM'] = 0.000645;
UNIT_CONVERSION['SQIN']['SQACRE'] = 0.000000159422;

UNIT_CONVERSION['SQFT'] = new Array();
UNIT_CONVERSION['SQFT']['SQIN'] = 144;
UNIT_CONVERSION['SQFT']['SQFT'] = 1;
UNIT_CONVERSION['SQFT']['SQMI'] = .0000000358;
UNIT_CONVERSION['SQFT']['SQM'] = 0.092903;
UNIT_CONVERSION['SQFT']['SQACRE'] = 0.000022957;

UNIT_CONVERSION['SQMI'] = new Array();
UNIT_CONVERSION['SQMI']['SQIN'] = 4014489600;
UNIT_CONVERSION['SQMI']['SQFT'] = 27878288.486594;
UNIT_CONVERSION['SQMI']['SQMI'] = 1;
UNIT_CONVERSION['SQMI']['SQM'] = 2589988.110336;
UNIT_CONVERSION['SQMI']['SQACRE'] = 640;

UNIT_CONVERSION['SQM'] = new Array();
UNIT_CONVERSION['SQM']['SQIN'] = 1550.0031;
UNIT_CONVERSION['SQM']['SQFT'] = 10.763867;
UNIT_CONVERSION['SQM']['SQMI'] = .0000003861;
UNIT_CONVERSION['SQM']['SQM'] = 1;
UNIT_CONVERSION['SQM']['SQACRE'] = 0.000247105;

UNIT_CONVERSION['SQACRE'] = new Array();
UNIT_CONVERSION['SQACRE']['SQIN'] = 6272614.883;
UNIT_CONVERSION['SQACRE']['SQFT'] =  43559.825;
UNIT_CONVERSION['SQACRE']['SQMI'] = 0.0015625;
UNIT_CONVERSION['SQACRE']['SQM'] = 4046.856;
UNIT_CONVERSION['SQACRE']['SQACRE'] = 1;

/*
 * Conversion Dropdown population 
 */
function populateUnitConversionSelection(mType, obj) {
	var selectedArray;
	if(mType == 'area') {
		selectedArray = UNITS_SQ_STRINGS;
	} else {
		selectedArray = UNITS_STRINGS;
	}
	var options = obj.getElementsByTagName('option');
	for(var i = options.length - 1; i >= 0; i--) {
		obj.removeChild(options[i]);
	}
	
	for(var unit in selectedArray) {
		var opt = document.createElement('option');
		opt.value = unit;
//		if(unit == MAP_GROUND_UNITS || unit == 'SQ'+MAP_GROUND_UNITS) {
		if(unit == MEASURE_LENGTH_UNITS || unit == MEASURE_AREA_UNITS) {
			opt.setAttribute('selected', 'true');
			opt.selected = true;
		}
		opt.appendChild(document.createTextNode(selectedArray[unit]));
		obj.appendChild(opt);
		opt = null;
	}
	obj = null;
}

/*
 * Scale conversions that use the UNIT_CONVERSION table.
 */
function pixelScaleToInchScale(scMap, v) {
	var w = scMap.getMapSize().x;
	return ((v*w)/(w-1))*MAP_PIXELS_PER_INCH*UNIT_CONVERSION[MAP_GROUND_UNITS]['IN'];
}

function inchScaleToPixelScale(scMap, v) {
	var w = scMap.getMapSize().x;
	return ((v*(w-1))/w)*(1/MAP_PIXELS_PER_INCH)*(UNIT_CONVERSION['IN'][MAP_GROUND_UNITS])+.000001;
}


function LegendObj(id, legend) {
	this.id = id;
	this.legend = legend;
}


function getEventTarget(e) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	return targ;
}


function objectClientPosition(obj) {
	var position = new Point(obj.offsetLeft, obj.offsetTop);
	var parent = obj.parentNode;

	while(parent && parent.tagName == 'DIV') {
		if(parent.offsetLeft) {
			position.x += parent.offsetLeft;
		}
		if(parent.offsetTop) {
			position.y += parent.offsetTop;
		}
		parent = parent.parentNode;
	}
	return position;
}

function preventDefaultEvent(event) {
	if(window.event) { event = window.event; }
	event.returnValue = false;
	if(event.preventDefault) {
		event.preventDefault();
	}
	return false;
}

/* 
 * attachEvent()
 * Use Gecko style eventname's
 */

function attachEvent(obj, eventname, workingFn) {
	if(!obj) { return false; }
	if(document.all) {
		obj.attachEvent('on'+eventname, workingFn);
	} else {
		var retValue = true;
		if(eventname == 'mousewheel') { eventname = 'DOMMouseScroll'; retValue = false; }
		obj.addEventListener(eventname, workingFn, retValue);
	}
	obj = null;
}

function removeEvent(obj, eventname, workingFn) {
	if(!obj) { return false; }
	if (document.all) {
		obj.detachEvent("on"+eventname, workingFn);
	} else {
		obj.removeEventListener(eventname, workingFn, true);
	}
	obj = null;
}

function getBrowser() {
	return new String(navigator.appName).toLowerCase();
}

function getBrowserVersion() {
	return parseInt(navigator.appVersion);
}

/* Used to create layer controls */
function createIcon(EventManager, src,eventTrigger,mapTitle,iconTitle) {
	var newIcon = document.createElement('img');
	newIcon.setAttribute('src', src);
	newIcon.style.verticalAlign = 'middle';
	newIcon.EventManager = EventManager;
	newIcon.eventTrigger= eventTrigger;
	newIcon.mapTitle = mapTitle;
	if(iconTitle) {
		newIcon.title = iconTitle;
	}
	newIcon.onclick = triggerSelfEvent;
	return newIcon;
}

function getElementsByTagNameNS(obj, nameSpaceURI, nameSpacePrefix, tagName) {
	if(window.ActiveXObject) {
		if(nameSpacePrefix == '*') {
			return obj.getElementsByTagName(tagName);
		}
		return obj.getElementsByTagName(nameSpacePrefix+':'+tagName);
	} else { // Gecko, et. al, support actual namespace resolution
		return obj.getElementsByTagNameNS(nameSpaceURI, tagName);
	}
}
