/*
Copyright (c) 2009, Dan "Ducky" Little & GeoMOOSE.org

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 conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/


function startupMeasureLength(event) {
	startupMeasureTool('length');
}

function startupMeasureArea(event) {
	startupMeasureTool('area');
}

function startupMeasureTool(mType) {
	Tabs.showTab(CONFIGURATION.measure_tool.target_tab);

	var trans = {'length' : 'Length', 'area' : 'Area' };

	var p = document.getElementById(Tabs.getTab(CONFIGURATION.measure_tool.target_tab));

	p.innerHTML = '';

	var title = document.createElement('div');
	p.appendChild(title);
	title.appendChild(document.createTextNode('Measure '+trans[mType]));

	p.appendChild(document.createElement('br'));

	var infoTable = document.createElement('table');
	var infoTbody = document.createElement('tbody');
	p.appendChild(infoTable);
	infoTable.appendChild(infoTbody);

	var totalRow = document.createElement('tr');
	var totalTitle = document.createElement('th');
	var totalCell = document.createElement('td');

	infoTbody.appendChild(totalRow);
	totalRow.appendChild(totalTitle);
	totalRow.appendChild(totalCell);

	var segmentRow = document.createElement('tr');
	var segmentTitle = document.createElement('th');
	var segmentCell = document.createElement('td');

	infoTbody.appendChild(segmentRow);
	segmentRow.appendChild(segmentTitle);
	segmentRow.appendChild(segmentCell);

	var unitsRow = document.createElement('tr');
	var unitsTitle = document.createElement('th');
	var unitsCell = document.createElement('td');

	infoTbody.appendChild(unitsRow);
	unitsRow.appendChild(unitsTitle);
	unitsRow.appendChild(unitsCell);

	totalTitle.appendChild(document.createTextNode('Total '+trans[mType]+':'));
	
	var totalInput = document.createElement('input');
	totalInput.size = 14;
	totalInput.id = 'measuretool-input-total';
	totalCell.appendChild(totalInput);


	segmentTitle.appendChild(document.createTextNode('Segment '+trans[mType]+':'));
	var segmentInput = document.createElement('input');
	segmentInput.size = 14;
	segmentInput.id = 'measuretool-input-segment';
	segmentCell.appendChild(segmentInput);

	unitsTitle.appendChild(document.createTextNode('Units:'));

	var unitsDropdown = document.createElement('select');
	var units = {'Miles' : 'mi', 'Feet' : 'ft', 'Meters' : 'm'};

	unitsDropdown.id = 'measuretool-units';
	unitsCell.appendChild(unitsDropdown);
	for(var u in units) {
		var opt = document.createElement('option');
		opt.value = units[u];
		unitsDropdown.appendChild(opt);
		opt.appendChild(document.createTextNode(u));
		if(units[u] == CONFIGURATION.measure_tool.units) {
			opt.selected = true;
		}
	}

	var clearRow = document.createElement('tr');
	var blankCell = document.createElement('td');
	var clearCell = document.createElement('td');

	infoTbody.appendChild(clearRow);
	clearRow.appendChild(blankCell);
	clearRow.appendChild(clearCell);

	var clearButton = document.createElement('input');
	clearButton.type = 'button';
	clearButton.value = 'Clear';
	clearButton.onclick = measureToolClear;
	clearCell.appendChild(clearButton);

	var measureTable = document.createElement('table');
	var measureTbody = document.createElement('tbody');
	measureTbody.id = 'measuretool-tbody';

	p.appendChild(measureTable);
	measureTable.appendChild(measureTbody);
}

function measureToolClear(event) {
	var measureTable = document.getElementById('measuretool-tbody');
	measureTable.innerHTML = '';

	var measureTools = ['measure','measurearea'];
	for(var m = 0; m < measureTools.length; m++) {
		var tool = measureTools[m];
		Tools[tool].measure(new OpenLayers.Geometry.Point(), 'measure');
		if(Tools[tool].handler.layer) {
			Tools[tool].handler.layer.removeFeatures(Tools[tool].handler.layer.features);
		}
	}
}

function measureToolPartial(event) {
	var units = document.getElementById('measuretool-units');
	units = units.getElementsByTagName('option')[units.selectedIndex].value;

	var length = this.getLength(event.geometry, units);
	var total = document.getElementById('measuretool-input-total');
	var segment = document.getElementById('measuretool-input-segment');

	var t = document.getElementById('measuretool-tbody');

	var totalValue = stripCommas(total.value);

	if(length < totalValue) {
		while(t.firstChild) {
			t.removeChild(t.firstChild);
		}
		total.value = 0;
		segment.value = 0;
	}

	if(length > 0) {
		var rows = t.getElementsByTagName('tr');
		segment.value = commifyNumber((length - totalValue).toFixed(2));
		total.value = commifyNumber(length.toFixed(2));

		var newRow = document.createElement('tr');
		if(rows.length < 1) {
			t.appendChild(newRow);
		} else {
			t.insertBefore(newRow, rows[0]);
		}
		var segmentTitle = document.createElement('th');
		newRow.appendChild(segmentTitle);
		segmentTitle.appendChild(document.createTextNode(rows.length));

		var segmentLength = document.createElement('td');
		newRow.appendChild(segmentLength);
		segmentLength.appendChild(document.createTextNode(commifyNumber(length.toFixed(2))+' '+units));
	}
}

function measureToolLengthLog(event) {
	var units = document.getElementById('measuretool-units');
	units = units.getElementsByTagName('option')[units.selectedIndex].value;
	var segment = document.getElementById('measuretool-input-segment');
	var total = document.getElementById('measuretool-input-total');
	var length = this.getLength(event.geometry, units);
	length -= stripCommas(total.value);
	segment.value = commifyNumber(length.toFixed(2));
}

function measureToolAreaLog(event) {
	var units = document.getElementById('measuretool-units');
	units = units.getElementsByTagName('option')[units.selectedIndex].value;
	var segment = document.getElementById('measuretool-input-segment');
	var total = document.getElementById('measuretool-input-total');
	var area = this.getArea(event.geometry, units);
	area -= stripCommas(total.value);
	segment.value = commifyNumber(area.toFixed(2));
}

function measureToolAreaPartial(event) {
	var units = document.getElementById('measuretool-units');
	units = units.getElementsByTagName('option')[units.selectedIndex].value;

	var length = this.getArea(event.geometry, units);
	var total = document.getElementById('measuretool-input-total');
	var segment = document.getElementById('measuretool-input-segment');

	var t = document.getElementById('measuretool-tbody');

	var totalValue = stripCommas(total.value);

	/* count the number of points in the polygon, if they are less than 3
		then reset the counters */

	if(countPoints(event.geometry) < 3) {
		while(t.firstChild) {
			t.removeChild(t.firstChild);
		}
		total.value = '0.00';
		segment.value = '0.00';
	}

	if(length > 0) {
		var rows = t.getElementsByTagName('tr');
		segment.value = commifyNumber((length - totalValue).toFixed(2));
		total.value = commifyNumber(length.toFixed(2));

		var newRow = document.createElement('tr');
		if(rows.length < 1) {
			t.appendChild(newRow);
		} else {
			t.insertBefore(newRow, rows[0]);
		}
		var segmentTitle = document.createElement('th');
		newRow.appendChild(segmentTitle);
		segmentTitle.appendChild(document.createTextNode(rows.length));

		var segmentLength = document.createElement('td');
		newRow.appendChild(segmentLength);
		segmentLength.appendChild(document.createTextNode(commifyNumber(length.toFixed(2))+' '+units));
	}
}

function countPoints(g) {
	var points = 0;
	if(g.components) {
		for(var i = 0; i < g.components.length; i++) {
			if(g.components[i] instanceof OpenLayers.Geometry.Point) {
				points += 1;
			} else {
				points += countPoints(g.components[i]);
			}
		}
	}
	return points;

}
