//$HeadURL: svn+ssh://jwilden@svn.wald.intevation.org/deegree/apps/igeoportal-standard/branches/2.5_testing/modules/digitizer/digitizer_utils.js $
/*----------------------------------------------------------------------------
 This file is part of deegree, http://deegree.org/
 Copyright (C) 2001-2009 by:
 - Department of Geography, University of Bonn -
 and
 - lat/lon GmbH -

 This library is free software; you can redistribute it and/or modify it under
 the terms of the GNU Lesser General Public License as published by the Free
 Software Foundation; either version 2.1 of the License, or (at your option)
 any later version.
 This library is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 details.
 You should have received a copy of the GNU Lesser General Public License
 along with this library; if not, write to the Free Software Foundation, Inc.,
 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

 Contact information:

 lat/lon GmbH
 Aennchenstr. 19, 53177 Bonn
 Germany
 http://lat-lon.de/

 Department of Geography, University of Bonn
 Prof. Dr. Klaus Greve
 Postfach 1147, 53001 Bonn
 Germany
 http://www.geographie.uni-bonn.de/deegree/

 e-mail: info@deegree.org
----------------------------------------------------------------------------*/

function reloadProxy(){
	var proxyDoc = document.getElementById( 'geomCheckerProxy' );
	if( proxyDoc != null ){
		proxyDoc.src = "geom_checker_proxy.jsp";
	}
}

function updateGUI( mesg, isValidGeom ){

	reloadProxy();
	var b = document.getElementById( 'saveButton' );
	
	if( b == null ){
		alert( 'Missing "Save" button with id "saveButton".');
		return;
	}
			
	if( isValidGeom ){
		b.removeAttribute( 'disabled' );
	} else {
		b.setAttribute( 'disabled', 'disabled' );
	}
	if( mesg != null ){
		//this
		//alert(mesg);
		//or that
		var style = isValidGeom ? 'background-color:yellow' : 'background-color:#FF6666';
		updateMesgField( mesg, style );
	}	
}

function updateMesgField( mesg, style ){
	var mesgField = document.getElementById( 'messageField' );
	if( mesgField != null ){
		var c = mesgField.firstChild;
		if( c != null ){
			mesgField.removeChild( c );
		}
		var txt = document.createTextNode( mesg );

		mesgField.setAttribute( 'style', style);
		mesgField.appendChild( txt );
	} else {
		alert('Mo mesg field to update.');
	}
}

function getGeometryType(){
	return geomType;		
}

function isPointGeometry(){
	return geomType == "POINT";
}

function setGeometryType( inputElement ){
	geomType = inputElement.value;		
	digitizer.init();
    isFirstPoint = true;
	digitizer.setPointMode( isPointGeometry() );
}

function resetArea(){
   geometry = false;
   isFirstPoint = true;
   digitizer.clear();
}

// stolen from imapview.html
function initEventHandling() {

//UT this must be tested with IE
    detectBrowser();
    if ( isNav ) {
        onmousedown = mouseDown;
        onmouseup = mouseUp;
        onmousemove = mouseMove;
        ondblclick = doubleClicked;
    } else {
        var layer = window.document.all[0];
        document.onmousedown = mouseDown;
        document.onmousemove = mouseMove;
        document.ondblclick = doubleClicked;
        layer.onmouseup = mouseUp;
        window.document.onmousemove = mouseMove;
    }
}

// stolen from imapview.html
function detectBrowser() {
	isNav = (navigator.appName.indexOf("Netscape")>=0);
}

// also copied and wasted
function getEventCoordinates(e) {
	var x = 0;
	var y = 0;
	if ( this.isNav ) {
		x = e.layerX;
		y = e.layerY;
	} else {
		x = window.event.offsetX;
		y = window.event.offsetY;
	}		
	return new Array( x, y);
}

function mouseDown(e){
	var xy = getEventCoordinates(e);
	if( isPointGeometry() ){
	
	} else {
		if( isFirstPoint ){
            digitizer.startDigitize( xy[0], xy[1] );
			isFirstPoint = false;
			updateMesgField( '', 'background-color:#FFFFFF');
		} else {
			digitizer.chkMouseUp();
		}
	}
}
	
function mouseMove(e){
	var xy = getEventCoordinates(e);
	if( isPointGeometry() ){
	
	} else {
        digitizer.getMouse( xy[0], xy[1] );	
	}
}
		
function mouseUp(e){
	var xy = getEventCoordinates(e);
	if( isPointGeometry() ){
		digitizer.clear();
        digitizer.startDigitize( xy[0], xy[1] );
		geometry = digitizer.getAsPoint(geoTrans);
		geometry = toWKT( geomType, geometry );
		updateGUI( null, true );
	} 
}
		
function doubleClicked(){
	
	if( isPointGeometry() ){
		return;
	}
	if( geomType == 'LINESTRING' ){
		geometry = digitizer.getAsLineString(geoTrans);
	} else if( geomType == 'POLYGON' ){
		geometry = digitizer.getAsPolygon(geoTrans);
	} else {
		//ignore
	}

	geometry = toWKT( geomType, geometry );
	doCheckGeometry();
	// reset digitizer
	digitizer.setDigitizingComplete( true );
	digitizer.setPointMode( isPointGeometry() );
    isFirstPoint = true;
}

function toWKT( geomType, geom ){
	g = '';
	if( geomType == 'POINT' ){
		g = geomType + '( ' + geom.x +  ' ' + geom.y +')';
	} else if( geomType == 'LINESTRING' || geomType == 'POLYGON' ){
		g += geomType;
		g += geomType == 'LINESTRING' ? '( ' : '(( ';

		var points = geom.points;
		// UT HACK! double-click is reacting too late and it's causing the last
		// point to be doubled removed is here see also doubleClicked()
		for( var i = 0; i < points.length; i++ ){
			//if( i != points.length - 2){ // this is da HACK
			// but it's off, not quite OK with IE
				g+=points[i].x + ' ' + points[i].y;		
				
				if( i < points.length - 1 ){
					g+= ', ';						
				}							
			//}
		}
		
		g += geomType == 'LINESTRING' ? ' ) ' : ' ))';
	} else {
		alert('Geometry type ' + geomType + ' is not supported.' );
		g = null;
	}
	return g;
}

/* Map stuff */
function initMap(){

    var mm = opener.parent.controller.mapModel;
    var lGroups = mm.getLayerList().getLayerGroups();

    for( var i = 0; i < lGroups.length; i++ ){
        var elem = document.createElement("img");
        elem.setAttribute("id", "image" + i);
        elem.style.position = "absolute";
        elem.style.top = mapTop + "px";
        elem.style.left = mapLeft + "px";
        elem.style.zIndex = (lGroups.length + 10) - i; // change order to decreasing
        elem.setAttribute("border", "0");
        
        // UT HACK! double-click is reacting too late and it's causing the last
        // point to be doubled removed is here see also toWKT() ind digitizer_utils.js
        /*
        do not see any effect!
        elem.ondblclick = doubleClicked;
        elem.onmousemove = mouseMove;
        elem.onmouseup = mouseUp;
        elem.onmousedown = mouseDown;
        */
        
        //JM: change order of images: images will have the same order as the layergroups.
        var lastImg = document.getElementById( "image" + (i-1) );
        if ( lastImg == null ) {
            document.getElementsByTagName("body")[0].appendChild( elem );
        } else {        
            document.getElementsByTagName("body")[0].insertBefore( elem, document.getElementById( "image" + (i-1) ) );
        }
    }
}
	
//shamelssly stolen from mapcontroller.js
function ensureAspectRatio( bbox, width, height ) {
    var xmin = bbox.minx;
    var ymin = bbox.miny;
    var xmax = bbox.maxx;
    var ymax = bbox.maxy;
	var dx = xmax - xmin;
	var dy = ymax - ymin;
	
	var W = width;
	var H = height;
	var R = H/W;
	
	if ( dx >= dy ){
		var normCoords = getNormalizedCoords(dx, R, ymin, ymax);
		ymin = normCoords[0];
		ymax = normCoords[1];
	}else{
		R = W/H;
		var normCoords = getNormalizedCoords(dy, R, xmin, xmax);
		xmin = normCoords[0];
		xmax = normCoords[1];
	}
	
	return new Envelope( xmin, ymin, xmax, ymax );
}
	
function getNormalizedCoords(normLen, ratio, min, max){
	var mid = (max - min)/2 + min;
	min = mid - (normLen/2)*ratio;
	max = mid + (normLen/2)*ratio;
	var newCoords = new Array(min,max);
	return newCoords;
}

