/**********************************************************************
 *
 * $Id: startUp.js,v 1.2 2006/08/11 19:39:30 lbecchi Exp $
 *
 * purpose: start up code to bootstrap initialization of kaMap within
 *          the sample interface.  Examples of using many parts of
 *          the kaMap core api.
 *
 * author: Lorenzo Becchi and Andrea Cappugi
 *
 * contributions by Paul Spencer (pspencer@dmsolutions.ca)
 *
 * TODO:
 *
 **********************************************************************
 *
 * Copyright (c) 2005, DM Solutions Group Inc.
 *
 * 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.
 *
 **********************************************************************/

/******************************************************************************
 *
 * To customize startUp:
 *
 * 1) modify toolbar Layout
 *  act on screen.css file and modify the funcion myMapInitialized().
 *  If you change pan and identifyer images edit switchMode() function too.
 *
 *****************************************************************************/

var myKaMap = myKaNavigator = myKaQuery = myScalebar = null;
var queryParams = null;
var bDebug = true;
var sDebug = '';
/**
 * parse the query string sent to this window into a global array of key = value pairs
 * this function should only be called once
 */
function parseQueryString() {
    queryParams = {};
    var s=window.location.search;
    if (s!='') {
        s=s.substring( 1 );
        var p=s.split('&');
        for (var i=0;i<p.length;i++) {
            var q=p[i].split('=');
            queryParams[q[0]]=q[1];
        }
    }
}

/**
 * get a query value by key.  If the query string hasn't been parsed yet, parse it first.
 * Return an empty string if not found
 */
function getQueryParam(p) {
    if (!queryParams) {
        parseQueryString();
    }
    if (queryParams[p]) {
        return queryParams[p];
    } else {
        return '';
    }
}

function myOnLoad() {
	initDHTMLAPI();

	window.onresize=drawPage;

	myKaMap = new kaMap( 'viewport' );

	var szProgetto = getQueryParam('progetto');
	var szMap = getQueryParam('map');
	var layer = getQueryParam('layer');
    var szExtents = getQueryParam('extents');
    var szCPS = getQueryParam('cps');
    var szEpsg = getQueryParam('epsgMap');

    var legendOptions = {};
    legendOptions.visibility = typeof gbLegendVisibilityControl != 'undefined' ? gbLegendVisibilityControl : true;
    legendOptions.opacity = typeof gbLegendOpacityControl != 'undefined' ? gbLegendOpacityControl : true;
    legendOptions.order = typeof gbLegendOrderControl != 'undefined' ? gbLegendOrderControl : true;
    legendOptions.query = typeof gbLegendQueryControl != 'undefined' ? gbLegendQueryControl : true;
    
    var myKaLegend = new kaLegend( myKaMap, 'legend', false, legendOptions);
//    var myKaKeymap = new kaKeymap( myKaMap, 'keymap' );
    myKaNavigator = new kaNavigator( myKaMap );
    myKaNavigator.activate();
    myKaQuery = new kaQuery( myKaMap, KAMAP_RECT_QUERY );
    myKaRubberZoom = new kaRubberZoom( myKaMap );
    myKaTracker = new kaMouseTracker(myKaMap);
    myKaTracker.activate();
    
    myKaMap.registerForEvent( KAMAP_INITIALIZED, null, myInitialized );
    myKaMap.registerForEvent( KAMAP_MAP_INITIALIZED, null, myMapInitialized );
    myKaMap.registerForEvent( KAMAP_SCALE_CHANGED, null, myScaleChanged );
    myKaMap.registerForEvent( KAMAP_EXTENTS_CHANGED, null, myExtentChanged );
    myKaMap.registerForEvent( KAMAP_LAYERS_CHANGED, null, myLayersChanged );
    myKaMap.registerForEvent( KAMAP_LAYER_STATUS_CHANGED, null, myLayersChanged );
    myKaMap.registerForEvent( KAMAP_QUERY, null, myQuery );
    myKaMap.registerForEvent( KAMAP_GRANO_SEARCH, null, myGranoSearch );
    myKaMap.registerForEvent( KAMAP_MAP_CLICKED, null, myMapClicked );
    myKaMap.registerForEvent( KAMAP_MOUSE_TRACKER, null, myMouseMoved );

    myScalebar = new ScaleBar(1);
    myScalebar.divisions = 3;
    myScalebar.subdivisions = 2;
    myScalebar.minWidth = 150;
    myScalebar.maxWidth = 200;
    myScalebar.place('scalebar');

	//toolTip = new kaToolTip( myKaMap );

	getRawObject('mapLegend').style.display = 'none';
	getRawObject('mapInfo').style.display = 'none';
	getRawObject('print').style.display = 'none';
	getRawObject('identifier').style.display = 'none';
	getRawObject('curtain').style.display = '';
	getRawObject('link').style.display = 'none';
	getRawObject('search').style.display = 'none';
//	getRawObject('wms').style.display = 'none';


//	myKaSearch = new kaSearch( myKaMap );
	drawPage();
    myKaMap.initialize( szProgetto, szMap, szExtents, szCPS , layer, szEpsg);
}

/**
 * event handler for KAMAP_INITIALIZED.
 *
 * at this point, ka-Map! knows what map files are available and we have
 * access to them.
 */
function myInitialized() {
    //myMapInitialized( null, myKaMap.getCurrentMap().name );
}

/**
 * event handler for KAMAP_MAP_INITIALIZED
 *
 * the scales are put into a select ... this will be used for zooming
 */
function myMapInitialized( eventID, mapName ) {
	//get list of maps and populate the maps select box
/*
	var aMaps = myKaMap.getMaps();


	// Update map selection list if one is available
    var oSelect = document.forms[0].maps;
    if (oSelect)
    {
        var j = 0;
        //var opt = new Option( 'select a map', '', true, true );
        //oSelect[j++] = opt;
        for(var i in aMaps) {
          oSelect[j++] = new Option(aMaps[i].title,aMaps[i].name,false,false);
        }

        //make sure the map is selected ...
        var oSelect = document.forms[0].maps;
        if (oSelect.options[oSelect.selectedIndex].value != mapName) {
            for(var i = 0; i < oSelect.options.length; i++ ) {
                if (oSelect.options[i].value == mapName) {
                    oSelect.options[i].selected = true;	
                    break;
                }
           }
        }
    } 
*/
	CreateTreeViste(mapName)
//	SelectVista(mapName);


	//update the scales select
    var currentMap = myKaMap.getCurrentMap();
    var scales = currentMap.getScales();
    var currentScale=myKaMap.getCurrentScale();


	oSelect = document.forms[0].scales;
	if(oSelect){
		while( oSelect.options[0] ) oSelect.options[0] = null;
	    j=0;
	    for(var i in scales)
	    {
			var opt = new Option("1 : "+FormatNumber(scales[i],0,false,false,3),scales[i],false,false);
			if ( i == currentMap.currentScale ) opt.selected = true;
	        oSelect.options[j++] = opt
	    }
	}
    
    //Activate query button
    switchMode('toolPan');
    
    //Activate service box
    switchService('toolLegend');
    
	// set title and subtitle
    switchTitle();
    
	
	/* handle request for layer visibility */
	var layers = getQueryParam('layers');
	if (layers != '') {
		var map = myKaMap.getCurrentMap();
		//turn off all layers
		var allLayers = map.getAllLayers();
		for (var i=0; i<allLayers.length; i++) {
			allLayers[i].setVisibility(false);
		}
		aLayers = layers.split(',');
		for (var i=0;i<aLayers.length; i++) {
			map.setLayerVisibility (unescape(aLayers[i]), true);
		}
	}
}

function CreateTreeViste(mapName){
	var oText = document.forms[0].TextMap;
	var MapsList = getRawObject('MapsList');
	var MapsListContent = getRawObject('MapsListContent');

	if ( MapsList ) {
		var aMaps = myKaMap.getMaps();
		if ( MapsListContent && MapsListContent.childNodes.length == 0 ){
			for(var i in aMaps) {
	//Debug('CreateTreeViste: '+i+' - '+aMaps[i].title)
				var aTmp = aMaps[i].title.split('#');
				d = document.createElement( 'div' );
				d.id = aMaps[i].name;
				d.className = 'MapListElement';
				if ( aMaps[i].name == mapName ){
					oText.value =  HtmlDecode(aTmp[aTmp.length-1]) //aMaps[i].title
					d.className+=' MapListElementSelected';
				}
				d.onmouseover = function(){this.className+=' MapListElementOver';}
				d.onmouseout = function(){this.className=this.className.replace(/ MapListElementOver/gi,'')}
				if ( aMaps[i].name != mapName )
//					d.onclick = function(){ToggleViste(false);mySetMap(this.id);}
					d.onclick = function(){
						var url = 'index.html'
								 +'?progetto='+myKaMap.GuidProgetto
								 +'&map='+this.id
//						alert(url)
						document.location = url;
					}
				
				if ( aTmp.length == 1 ){
					d.innerHTML = aMaps[i].title
				}else{
					for ( u=0; u<aTmp.length; u++ ) {
						if ( u == aTmp.length-1 ) {
							d.style.paddingLeft = 18 * u+'px';
							d.innerHTML = aTmp[u];
						}
					}
				}
				MapsListContent.appendChild( d );
			}
		}else{
			for(var i in aMaps) 
				if ( aMaps[i].name == mapName ) 
					oText.value = aMaps[i].title;
			aDiv = MapsListContent.getElementsByTagName('DIV')
			for(d=0;d<aDiv.length;d++){
				if( aDiv[d].id == mapName )
					aDiv[d].className+=' MapListElementSelected';
				else
					aDiv[d].className=aDiv[d].className.replace(/ MapListElementSelected/gi,'')
			}
		}
	} 
}

function ToggleViste( b ){
	var MapsList = getRawObject('MapsList');
	MapsList.style.display = b ? '' : 'none';
}

/**
 * handle the extents changing by updating a link in the interface that links
 * to the current view
 */
function myExtentChanged( eventID, extents ) {
	updateLinkToView();
}

function myMouseMoved( eventID, position) {
	var currentMap = myKaMap.getCurrentMap();
	var geopos = document.getElementById('geoPosition');
    if(geopos) {
		if (currentMap.units == 5 ){
			geopos.innerHTML = 'lon: ' + DecimalTodegree(position.x) + '&nbsp; lat: ' + DecimalTodegree(position.y);
		}else{
			geopos.innerHTML = 'x: ' + Math.round(position.x) + '&nbsp; y: ' + Math.round(position.y);
//			geopos.innerHTML = 'x: ' + roundIt(position.x,2) + '&nbsp; y: ' + roundIt(position.y,2);
		}
	}
}

function DecimalTodegree( dec ){
	sign = dec < 0 ? -1 : 1;
	decAbs = Math.abs( dec );

	Deg = Math.floor(decAbs);
	Min = Math.floor((decAbs-Deg)*60);
	Sec =  (((decAbs - Deg) - (Min/60)) * 60 * 60) ;

	Deg = (Deg>=10 ? (Deg>=100 ? '' : '&nbsp;' ) : '&nbsp;&nbsp;') + (Deg*sign); 
	Min = (Min>=10 ? ' ' : ' 0') + Min; 
	Sec = (Sec>=10 ? ' ' : ' 0') + FormatNumber(Sec,2,true,false,3); 
	t = Deg + '&deg;' + Min + '\'' + Sec + '&quot;'
//Debug('DecimalTodegree: '+ escape(t));	
	return t
}



function myLayersChanged(eventID, map) {
	updateLinkToView();
}

function updateLinkToView()  {
	var port = (window.location.port)? window.location.port : 80;
	var url = window.location.protocol+'/'+'/'+window.location.host +':'+ port +''+window.location.pathname+'?';
	var extents = myKaMap.getGeoExtents();
	var cx = (extents[2] + extents[0])/2;
	var cy = (extents[3] + extents[1])/2;
	var cpsURL = 'cps='+cx+','+cy+','+myKaMap.getCurrentScale();
	var mapURL = 'map=' + myKaMap.currentMap;
    var theMap = myKaMap.getCurrentMap();
	var aLayers = theMap.getLayers();
	var layersURL = 'layers=';
	var sep = '';
	for (var i=0;i<aLayers.length;i++) {
		layersURL += sep + aLayers[i].name;
		sep = ',';
	}

	var link = getRawObject('linkToView');
	if(link) link.href = url + mapURL + '&' + cpsURL + '&' + layersURL;
	
	var linkContent = getRawObject('linkContent');
	if(linkContent) linkContent.value = myUrlEncode('This is a link:\n-------\n'+ url + mapURL + '&' + cpsURL + '&' + layersURL +'\n-------\n\nRemember to copy the entire link string.');


	//this should stay in an independant function
	var geoExtent = getRawObject('geoExtent');
	
	if(geoExtent) {
		geoExtent.innerHTML = 'minx: ' + roundIt(extents[0],2) +'&nbsp;' +
							'miny: ' + roundIt(extents[1],2) +'&nbsp;' +
							'maxx: ' + roundIt(extents[2],2) +'&nbsp;' +
							'maxy: ' + roundIt(extents[3],2) +'&nbsp;';
	}
}


function sendLinkToView(email,body) {
	
	var mySubject = myUrlEncode('Authomatic ka-Map mail');
	var myBody = myUrlEncode(body);
		
	location.replace( 'mailto:' + email + '?subject=' + mySubject + '&body=' + body);
}



/**
 * called when kaMap tells us the scale has changed
 */
function myScaleChanged( eventID, scale ) {

	var oSelect = document.forms[0].scales;
	if(oSelect){
	    for (var i=0; i<oSelect.options.length; i++)
	    {
	        if (oSelect.options[i].value == scale)
	        {
	            oSelect.options[i].selected = true;
	            //document.forms[0].zoomout.disabled = (i==0);
	            //document.forms[0].zoomin.disabled = (i==oSelect.options.length - 1);
	        }
	    }
    }
    //todo: update scale select and enable/disable zoomin/zoomout
    var currentMap = myKaMap.getCurrentMap();
    var scales = currentMap.getScales();
    for(var i in scales){
        var imgString = 'img'+scales[i];
        var scaleString = 'img'+scale;
        if(getRawObject(imgString)) {
            if(imgString == scaleString) {
                getRawObject(scaleString).src = 'images/pixel-red.png';
            } else {
                getRawObject(imgString).src = 'images/pixel-blue.png';
            }
        }
    }


	myScalebar.update(scale);
   
   
    /*
    if (scale >= 1000000) {
        scale = scale / 1000000;
        scale = scale + " Million";
    }
    var outString = 'current scale 1:'+ scale;
    getRawObject('scale').innerHTML = outString;
    */
}

/**
 * called when the user changes scales.  This will cause the map to zoom to
 * the new scale and trigger a bunch of events, including:
 * KAMAP_SCALE_CHANGED
 * KAMAP_EXTENTS_CHANGED
 */
function mySetScale( scale ) {
    myKaMap.zoomToScale( scale );
}

/**
 * called when the map selection changes due to the user selecting a new map.
 * By calling myKaMap.selectMap, this triggers the KAMAP_MAP_INITIALIZED event
 * after the new map is initialized which, in turn, causes myMapInitialized
 * to be called
 */
function mySetMap( name ) {
//Debug('mySetMap: '+name);	
    myKaMap.selectMap( name );
}


function myQuery( eventID, queryType, coords ) {

    var Map = myKaMap.getCurrentMap();
	var layers = Map.getQueryableLayers();
    var IdMap = Map.name;
    var Epsg = Map.epsg;
	var scale = Map.aScales[Map.currentScale];

	if(layers.length==0) {
//		alert("Nessun layer interrogabile. Selezionare un layer visibile e riprovare.");
		var params='map='+IdMap+'&epsgMap='+Epsg+'&s='+scale+'&coords='+coords;
		WOOpenWin( 'Query', 'showLayerData.php?'+params, 'resizable=yes,scrollbars=yes,width=500,height=500' );
	} else {
		var Layer = layers[0];
		if ( !Layer.queryable ){
			alert("Impossibile interrogare questo livello. Operazione non consentita.");
		} else if ( Layer.wms_server ){
			coords = myKaMap.geoToPix(coords[0],coords[1]);
			var params='map='+IdMap
				+ '&epsgMap='+Epsg
				+ '&layer='+Layer.wms_layers
				+ '&l='+coords[0]
				+ '&t='+coords[1]
				+ '&s='+scale
				+ '&wms=' + escape(Layer.wms_server)
				+ '&version=' + Layer.wms_version
				+ '&epsg=' + Layer.wms_srs.split(':')[1]
				+ '&format=' + Layer.wms_imageformat
				+ '&title='+escape(Layer.name)
			WOOpenWin( 'Query', 'tools/wms/wmsFeatureInfo.php?'+params, 'resizable=yes,scrollbars=yes,width=400,height=400' );
		} else if ( Layer.wfs_server ){
			coords = myKaMap.geoToPix(coords[0],coords[1]);
			var params='map='+IdMap
				+ '&epsgMap='+Epsg
				+ '&layer='+Layer.wfs_layer
				+ '&type='+Layer.type
				+ '&l='+coords[0]
				+ '&t='+coords[1]
				+ '&s='+scale
				+ '&wfs=' + escape(Layer.wfs_server)
				+ '&version=' + Layer.wfs_version
				+ '&epsg=' + Layer.wfs_srs.split(':')[1]
				+ '&title='+escape(Layer.name)
			WOOpenWin( 'Query', 'tools/wfs/wfsFeatureInfo.php?'+params, 'resizable=yes,scrollbars=yes,width=400,height=400' );
		} else {
			szLayer = Layer.id;
			if ( Layer.highlight != '' )	szLayer = szLayer.replace(Map.prefixHighLight,''); 
			var params='map='+IdMap+'&epsgMap='+Epsg+'&layer='+szLayer+'&s='+scale+'&coords='+coords;
			WOOpenWin( 'Query', 'showLayerData.php?'+params, 'resizable=yes,scrollbars=yes,width=500,height=500' );
		}
//		w.focus();
	}

}

var IdW;
var myGranoSearchInterval;
function myGranoSearch( eventID ) {

	var layers = myKaMap.getCurrentMap().getQueryableLayers();
    var IdMap = myKaMap.getCurrentMap().name;

	if(layers.length==0) {
		alert("Nessun layer interrogabile. Selezionare un layer visibile e riprovare.");
	} else {
		if ( layers[0].type != 'raster' ){
			var W = window.screen.width-50;//1000;
			var H = window.screen.height-150;//670
			var Left=(window.screen.width-W)/2;
			var Top=(window.screen.height-H)/2-45;
	
			var url = '/GranoGis/PageDefault.aspx?';
			url += 'IdPortale=wf3PH4y%2bbcq2125Aro1RqUkz23HM0cAobv8%2bMFw2drXAVNYQZQUshxjpRboLtvNXKTd18tml7zl5bDULe3eMwLn%2bBGM%2f5pri';
			url += '&DBTarget='+layers[0].guid;
			url += '&Height='+W;
			url += '&Width='+H;
	
	
			IdW = window.open(url,'Search')//,'left='+Left+',top='+Top+',width='+W+',height='+H+',resizable=yes,scrollbars=yes' );
//			IdW = window.open('TestPopUp.htm','Search','width='+400+',height='+200+',resizable=yes,scrollbars=yes,location=yes' );
			IdW.focus();
//			myGranoSearchInterval = setInterval(TestGRANO,1000);
		} else  {
			alert("Il layer selezionato non è vettoriale.\nSelezionarne uno e riprovare");
		}
	}
}

var TestCounter = 0;
function TestGRANO(){
	if ( IdW.closed ) {
		clearInterval(myGranoSearchInterval);
//		window.status = '';
		return;
	}
		IdW.opener = self;
//		window.status = IdW.location.href;
//		window.status = IdW.closed + ' , '+(TestCounter++)+' , '+IdW.location;
}

function myQueryOutput (szText){
	getRawObject('queryOut').innerHTML=szText;
}


function myMapClicked( eventID, coords ) {
    //alert( 'myMapClicked('+coords+')');
	//myKaMap.zoomTo(coords[0],coords[1]);
}

function myZoomIn() {
    myKaMap.zoomIn();
}

function myZoomOut() {
    myKaMap.zoomOut();
}

function myPrint(output_type) {
    var szLayers = '';
    
    var layers = myKaMap.getCurrentMap().getLayers();
    for (var i=0;i<layers.length;i++) {
        szLayers = szLayers + "," + layers[i].name;
    }
	
    var extent = myKaMap.getGeoExtents();
    var scale = myKaMap.getCurrentScale();
    var cMap = myKaMap.getCurrentMap().name;
    var Epsg = myKaMap.getCurrentMap().epsg;

	var img_width = '600';// pixel dimension. max_img_width set inside print_map.php
    
    //output_type
	var params='output_type='+output_type+'&map='+cMap+'&epsgMap='+Epsg+'&scale='+scale+'&img_width='+img_width+'&groups='+szLayers+'&extent='+extent[0]+'|'+extent[1]+'|'+extent[2]+'|'+extent[3];
 	
 	//create and download the output file
 	//location.href='tools/print/print_map.php?'+params;
 
    WOOpenWin( 'Print', 'tools/print/print_map.php?'+params, 'resizable=yes,scrollbars=yes,width=600,height=400' );
    
}

/**
 * drawPage - calculate sizes of the various divs to make the app full screen.
 */
function drawPage() {
	var browserWidth = getInsideWindowWidth();
    var browserHeight = getInsideWindowHeight();

    var viewport = getRawObject('viewport');
    var page = getRawObject('page');
    var layoutFrame = getRawObject('layoutFrame');
    var explorer = getRawObject('explorer');
    var service = getRawObject('service');
    var toolbar = getRawObject('toolbar');

    var identifier = getRawObject('identifier');
	var print = getRawObject('print');
	
	var mapInfo = getRawObject('mapInfo');
	var legend = getRawObject('legend');
	var keymap = getRawObject('keymap');
	var link = getRawObject('link');
	var search = getRawObject('search');
//	var wms = getRawObject('wms');

	var mapLegend = getRawObject('mapLegend');
	var content = getRawObject('content');
	var contentBackground = getRawObject('contentBackground');
	var contentText = getRawObject('contentText');
	var geoPosition = getRawObject('geoPositionReference');
		
	//Set Viewport Width
    if(myKaMap.isIE4) {
        //terrible hack to avoid IE to show scrollbar
        page.style.width = (browserWidth -2) + "px";
    } else {
        page.style.width = browserWidth + "px";
    }
    
     if(myKaMap.isIE4) {
        //terrible hack to avoid IE to show scrollbar
        page.style.height = (browserHeight -2) + "px";
    } else {
        page.style.height = browserHeight + "px";
    }
	
	//layoutFrame
	layoutFrame.style.width = parseInt(page.style.width) + "px";
	layoutFrame.style.height = parseInt(page.style.height) -parseInt(getObjectHeight(explorer)) + "px";
	layoutFrame.style.top= parseInt(getObjectHeight(explorer)) + "px";
	layoutFrame.style.left="0";
	layoutFrame.style.right="0";
	
	//VIEWPORT
	viewport.style.width = parseInt(getObjectWidth(layoutFrame)) - parseInt(getObjectWidth(service))-2 + "px";
	viewport.style.height = parseInt(getObjectHeight(layoutFrame)) -1  + "px";
	viewport.style.top="0px";
	viewport.style.left= parseInt(getObjectWidth(service)) + "px";
	viewport.style.right="0px";
	
	//CONTENT
	//content.style.top = viewport.style.top;
	content.style.left = parseInt(viewport.style.left) +10  + "px";
	content.style.width = parseInt(viewport.style.width) -20  + "px";
	content.style.height = parseInt(viewport.style.height) -20  + "px";
	contentBackground.style.height = parseInt(viewport.style.height) -20  + "px";
	contentText.style.height = parseInt(viewport.style.height) -65  + "px";
	contentText.style.width = parseInt(viewport.style.width) -50  + "px";
	
	//SERVICE - left space


	mapLegend.style.height = parseInt(getObjectHeight(layoutFrame)) -2 + "px"; 
	mapInfo.style.height = parseInt(getObjectHeight(layoutFrame)) -2  + "px"; 
	print.style.height = parseInt(getObjectHeight(layoutFrame)) -2  + "px"; 
	identifier.style.height = parseInt(getObjectHeight(layoutFrame)) -2  + "px"; 
	link.style.height = parseInt(getObjectHeight(layoutFrame)) -2  + "px"; 
	search.style.height = parseInt(getObjectHeight(layoutFrame)) -2  + "px"; 
//	wms.style.height = parseInt(getObjectHeight(layoutFrame)) -2  + "px"; 

	service.style.height = parseInt(getObjectHeight(layoutFrame)) -2  + "px";
	geoPosition.style.top = parseInt(viewport.style.height) - 20  + "px";

    myKaMap.resize();

}

function showContent(url) {
	var content = getRawObject('content');
	var viewport = getRawObject('viewport');
	content.style.top = parseInt(viewport.style.top) + 10 + "px";
	content.style.display = 'block';	
	if (url!='') call(url,this, setContent);
}
function setContent(szContent){
	var contentText = getRawObject('contentText');
	contentText.innerHTML = szContent;
}
function hideContent() {
	var content = getRawObject('content');
	var viewport = getRawObject('viewport');
	content.style.top = parseInt(viewport.style.top) + parseInt(viewport.style.height) + "px";
	content.style.display = 'none';	
}
function Debug(szContent){
	if ( bDebug ) {
		var d = new Date();
		if ( szContent != '' ) 
			sDebug += d.getSeconds()+'.'+d.getMilliseconds()+'\t'+szContent+'<br>';
		setContent('<span style="font-size:9px;white-space:nowrap; ">'+sDebug+'</span>');
	}
}
/**
 * getFullExtent
 * ...
 */
function getFullExtent() {
    var exStr = myKaMap.getCurrentMap().defaultExtents.toString();
    var ex = myKaMap.getCurrentMap().defaultExtents;
    myKaMap.zoomToExtents(ex[0],ex[1],ex[2],ex[3]);
}

/**
 * switchMode
 * ...
 */
function switchMode(id) {
    if (id=='toolQuery') {
        myKaQuery.activate();
        getRawObject('toolQuery').style.backgroundImage = 'url(images/icon_set_explorer/tool_query_2.png)';
        getRawObject('toolPan').style.backgroundImage = 'url(images/icon_set_explorer/tool_pan_1.png)';
        getRawObject('toolZoomRubber').style.backgroundImage = 'url(images/icon_set_explorer/tool_rubberzoom_1.png)';
    } else if (id=='toolPan') {
        myKaNavigator.activate();
        getRawObject('toolQuery').style.backgroundImage = 'url(images/icon_set_explorer/tool_query_1.png)';
        getRawObject('toolPan').style.backgroundImage = 'url(images/icon_set_explorer/tool_pan_2.png)';
        getRawObject('toolZoomRubber').style.backgroundImage = 'url(images/icon_set_explorer/tool_rubberzoom_1.png)';
    } else if (id=='toolZoomRubber') {
        myKaRubberZoom.activate();
        getRawObject('toolQuery').style.backgroundImage = 'url(images/icon_set_explorer/tool_query_1.png)';
        getRawObject('toolPan').style.backgroundImage = 'url(images/icon_set_explorer/tool_pan_1.png)';
        getRawObject('toolZoomRubber').style.backgroundImage = 'url(images/icon_set_explorer/tool_rubberzoom_2.png)';
    } else {
        myKaNavigator.activate();
    }
}


/**
 * switchMode
 * ...
 */
function switchService(id) {
	var service = getRawObject('service');

    if (id=='toolQuery') {
		myKaQuery.activate();
/*        getRawObject('toolQuery').style.backgroundImage = 'url(images/icon_set_explorer/tool_query_2.png)';
        getRawObject('toolLegend').style.backgroundImage = 'url(images/icon_set_explorer/tool_legend_1.png)';
        getRawObject('toolMapinfo').style.backgroundImage = 'url(images/icon_set_explorer/tool_mapinfo_1.png)';
        getRawObject('toolPrint').style.backgroundImage = 'url(images/icon_set_explorer/tool_print_1.png)';
        getRawObject('toolZoomRubber').style.backgroundImage = 'url(images/icon_set_explorer/tool_rubberzoom_1.png)';
		getRawObject('toolLink').style.backgroundImage = 'url(images/icon_set_explorer/tool_link_1.png)';
		getRawObject('toolSearch').style.backgroundImage = 'url(images/icon_set_explorer/tool_search_1.png)';
        
 		getRawObject('mapInfo').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('mapLegend').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('print').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('identifier').style.top = '0';
		getRawObject('curtain').style.top =  parseInt(getObjectHeight(service)) + "px";
		getRawObject('link').style.top =  parseInt(getObjectHeight(service)) + "px";
		getRawObject('search').style.top =  parseInt(getObjectHeight(service)) + "px";
*/		
    } else if (id=='toolLegend') {
        myKaNavigator.activate();
        getRawObject('toolQuery').style.backgroundImage = 'url(images/icon_set_explorer/tool_query_1.png)';
//        getRawObject('toolMapinfo').style.backgroundImage = 'url(images/icon_set_explorer/tool_mapinfo_1.png)';
        getRawObject('toolLegend').style.backgroundImage = 'url(images/icon_set_explorer/tool_legend_2.png)';
        getRawObject('toolPrint').style.backgroundImage = 'url(images/icon_set_explorer/tool_print_1.png)';
        getRawObject('toolPan').style.backgroundImage = 'url(images/icon_set_explorer/tool_pan_2.png)';
        getRawObject('toolZoomRubber').style.backgroundImage = 'url(images/icon_set_explorer/tool_rubberzoom_1.png)';
		//getRawObject('toolLink').style.backgroundImage = 'url(images/blank.gif)';
		getRawObject('toolSearch').style.backgroundImage = 'url(images/icon_set_explorer/tool_search_1.png)';
//        getRawObject('toolWMS').style.backgroundImage = 'url(images/icon_set_explorer/tool_wms_1.png)'; 

		getRawObject('mapLegend').style.display = '';
		getRawObject('mapInfo').style.display = 'none';
		getRawObject('print').style.display = 'none';
		getRawObject('identifier').style.display = 'none';
		getRawObject('curtain').style.display = 'none';
		getRawObject('link').style.display = 'none';
		getRawObject('search').style.display = 'none';
//		getRawObject('wms').style.display = 'none';

/*
		getRawObject('mapLegend').style.top = '0';
		getRawObject('mapLegend').style.height = parseInt(getObjectHeight(service)) -2 + "px"; 
		
		getRawObject('mapInfo').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('print').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('identifier').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('curtain').style.top =  parseInt(getObjectHeight(service)) + "px";
		getRawObject('link').style.top =  parseInt(getObjectHeight(service)) + "px";
		getRawObject('search').style.top =  parseInt(getObjectHeight(service)) + "px";
*/		
		
    } else if (id=='toolPrint') {
        myKaNavigator.activate();
        getRawObject('toolQuery').style.backgroundImage = 'url(images/icon_set_explorer/tool_query_1.png)';
        getRawObject('toolLegend').style.backgroundImage = 'url(images/icon_set_explorer/tool_legend_1.png)';
//        getRawObject('toolMapinfo').style.backgroundImage = 'url(images/icon_set_explorer/tool_mapinfo_1.png)';
        getRawObject('toolPrint').style.backgroundImage = 'url(images/icon_set_explorer/tool_print_2.png)'; 
        getRawObject('toolPan').style.backgroundImage = 'url(images/icon_set_explorer/tool_pan_2.png)';
        getRawObject('toolZoomRubber').style.backgroundImage = 'url(images/icon_set_explorer/tool_rubberzoom_1.png)';
		//getRawObject('toolLink').style.backgroundImage = 'url(images/blank.gif)';
		getRawObject('toolSearch').style.backgroundImage = 'url(images/icon_set_explorer/tool_search_1.png)';
//        getRawObject('toolWMS').style.backgroundImage = 'url(images/icon_set_explorer/tool_wms_1.png)'; 

		getRawObject('mapLegend').style.display = 'none';
		getRawObject('mapInfo').style.display = 'none';
		getRawObject('print').style.display = '';
		getRawObject('identifier').style.display = 'none';
		getRawObject('curtain').style.display = 'none';
		getRawObject('link').style.display = 'none';
		getRawObject('search').style.display = 'none';
//		getRawObject('wms').style.display = 'none';
/*        
        getRawObject('mapLegend').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('mapInfo').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('print').style.top = '0';
		getRawObject('identifier').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('curtain').style.top =  parseInt(getObjectHeight(service)) + "px";
		getRawObject('link').style.top =  parseInt(getObjectHeight(service)) + "px";
		getRawObject('search').style.top =  parseInt(getObjectHeight(service)) + "px";
*/		
/*    } else if (id=='toolWMS') {
        myKaNavigator.activate();
        getRawObject('toolQuery').style.backgroundImage = 'url(images/icon_set_explorer/tool_query_1.png)';
        getRawObject('toolLegend').style.backgroundImage = 'url(images/icon_set_explorer/tool_legend_1.png)';
//        getRawObject('toolMapinfo').style.backgroundImage = 'url(images/icon_set_explorer/tool_mapinfo_1.png)';
        getRawObject('toolPrint').style.backgroundImage = 'url(images/icon_set_explorer/tool_print_1.png)'; 
        getRawObject('toolPan').style.backgroundImage = 'url(images/icon_set_explorer/tool_pan_2.png)';
        getRawObject('toolZoomRubber').style.backgroundImage = 'url(images/icon_set_explorer/tool_rubberzoom_1.png)';
		//getRawObject('toolLink').style.backgroundImage = 'url(images/blank.gif)';
		getRawObject('toolSearch').style.backgroundImage = 'url(images/icon_set_explorer/tool_search_1.png)';
        getRawObject('toolWMS').style.backgroundImage = 'url(images/icon_set_explorer/tool_wms_2.png)'; 

		getRawObject('mapLegend').style.display = 'none';
		getRawObject('mapInfo').style.display = 'none';
		getRawObject('print').style.display = 'none';
		getRawObject('identifier').style.display = 'none';
		getRawObject('curtain').style.display = 'none';
		getRawObject('link').style.display = 'none';
		getRawObject('search').style.display = 'none';
		getRawObject('wms').style.display = '';
*/		
/*        
        getRawObject('mapLegend').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('mapInfo').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('print').style.top = '0';
		getRawObject('identifier').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('curtain').style.top =  parseInt(getObjectHeight(service)) + "px";
		getRawObject('link').style.top =  parseInt(getObjectHeight(service)) + "px";
		getRawObject('search').style.top =  parseInt(getObjectHeight(service)) + "px";
*/		
    } else if (id=='toolLink') {
        myKaNavigator.activate();
        getRawObject('toolQuery').style.backgroundImage = 'url(images/icon_set_explorer/tool_query_1.png)';
        getRawObject('toolLegend').style.backgroundImage = 'url(images/icon_set_explorer/tool_legend_1.png)';
//        getRawObject('toolMapinfo').style.backgroundImage = 'url(images/icon_set_explorer/tool_mapinfo_1.png)';
        getRawObject('toolPrint').style.backgroundImage = 'url(images/icon_set_explorer/tool_print_1.png)'; 
        getRawObject('toolPan').style.backgroundImage = 'url(images/icon_set_explorer/tool_pan_2.png)';
        getRawObject('toolZoomRubber').style.backgroundImage = 'url(images/icon_set_explorer/tool_rubberzoom_1.png)';
		//getRawObject('toolLink').style.backgroundImage = 'url(images/blank.gif)';
		getRawObject('toolSearch').style.backgroundImage = 'url(images/icon_set_explorer/tool_search_1.png)';
//        getRawObject('toolWMS').style.backgroundImage = 'url(images/icon_set_explorer/tool_wms_1.png)'; 

		getRawObject('mapLegend').style.display = 'none';
		getRawObject('mapInfo').style.display = 'none';
		getRawObject('print').style.display = 'none';
		getRawObject('identifier').style.display = 'none';
		getRawObject('curtain').style.display = 'none';
		getRawObject('link').style.display = '';
		getRawObject('search').style.display = 'none';
//		getRawObject('wms').style.display = 'none';
/*
		getRawObject('mapInfo').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('mapLegend').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('print').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('identifier').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('curtain').style.top =  parseInt(getObjectHeight(service)) + "px";
		getRawObject('link').style.top =   "0px";
		getRawObject('search').style.top =  parseInt(getObjectHeight(service)) + "px";
*/	

	} else if (id=='toolSearch') {
        myKaNavigator.activate();
        getRawObject('toolQuery').style.backgroundImage = 'url(images/icon_set_explorer/tool_query_1.png)';
        getRawObject('toolLegend').style.backgroundImage = 'url(images/icon_set_explorer/tool_legend_1.png)';
        getRawObject('toolMapinfo').style.backgroundImage = 'url(images/icon_set_explorer/tool_mapinfo_1.png)';
        getRawObject('toolPrint').style.backgroundImage = 'url(images/icon_set_explorer/tool_print_1.png)'; 
        getRawObject('toolPan').style.backgroundImage = 'url(images/icon_set_explorer/tool_pan_2.png)';
        getRawObject('toolZoomRubber').style.backgroundImage = 'url(images/icon_set_explorer/tool_rubberzoom_1.png)';
		//getRawObject('toolLink').style.backgroundImage = 'url(images/blank.gif)';
		getRawObject('toolSearch').style.backgroundImage = 'url(images/icon_set_explorer/tool_search_2.png)';
//        getRawObject('toolWMS').style.backgroundImage = 'url(images/icon_set_explorer/tool_wms_1.png)'; 


		getRawObject('mapLegend').style.display = 'none';
		getRawObject('mapInfo').style.display = 'none';
		getRawObject('print').style.display = 'none';
		getRawObject('identifier').style.display = 'none';
		getRawObject('curtain').style.display = 'none';
		getRawObject('link').style.display = 'none';
		getRawObject('search').style.display = '';
//		getRawObject('wms').style.display = 'none';
/*        
		getRawObject('mapLegend').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('mapInfo').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('print').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('identifier').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('curtain').style.top =  parseInt(getObjectHeight(service)) + "px";
		getRawObject('link').style.top =   parseInt(getObjectHeight(service)) + "px";
		getRawObject('search').style.top =  "0px";
*/

/*		
    } else if (id=='toolMapinfo') {
		myKaNavigator.activate();
        getRawObject('toolQuery').style.backgroundImage = 'url(images/icon_set_explorer/tool_query_1.png)';
        getRawObject('toolLegend').style.backgroundImage = 'url(images/icon_set_explorer/tool_legend_1.png)';
        getRawObject('toolMapinfo').style.backgroundImage = 'url(images/icon_set_explorer/tool_mapinfo_2.png)';
        getRawObject('toolPrint').style.backgroundImage = 'url(images/icon_set_explorer/tool_print_1.png)'; 
        getRawObject('toolPan').style.backgroundImage = 'url(images/icon_set_explorer/tool_pan_2.png)';
        getRawObject('toolZoomRubber').style.backgroundImage = 'url(images/icon_set_explorer/tool_rubberzoom_1.png)';
		//getRawObject('toolLink').style.backgroundImage = 'url(images/blank.gif)';
		getRawObject('toolSearch').style.backgroundImage = 'url(images/icon_set_explorer/tool_search_1.png)';
		//parseInt(getObjectHeight(service)) +		
		getRawObject('mapInfo').style.top = "0";
		getRawObject('mapLegend').style.top =  "210px";		
		
		//alert(getRawObject('mapInfo').style.height);
		getRawObject('mapLegend').style.height = (parseInt(getRawObject('mapInfo').style.height,10) - 210) + 'px' ;
		
		getRawObject('print').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('identifier').style.top = parseInt(getObjectHeight(service)) + "px";
		getRawObject('curtain').style.top =  parseInt(getObjectHeight(service)) + "px";
		getRawObject('link').style.top =   parseInt(getObjectHeight(service)) + "px";
		getRawObject('search').style.top =  parseInt(getObjectHeight(service)) + "px";
*/		
    } else {
        myKaNavigator.activate();
    }
}

function ToggleHeader(){
    var viewport = getRawObject('viewport');
    var page = getRawObject('page');
    var layoutFrame = getRawObject('layoutFrame');
    var explorer = getRawObject('explorer');
    var service = getRawObject('service');
    var toolbar = getRawObject('toolbar');
	var HdTitle = getRawObject('HeaderTitle');
	var HdSubTitle = getRawObject('HeaderSubTitle');
    var ShowHideHeader = getRawObject('ShowHideHeader');

    var identifier = getRawObject('identifier');
	var print = getRawObject('print');
	
	var mapInfo = getRawObject('mapInfo');
	var legend = getRawObject('legend');
	var keymap = getRawObject('keymap');
	var link = getRawObject('link');
	var search = getRawObject('search');
//	var wms = getRawObject('wms');

	var mapLegend = getRawObject('mapLegend');
	var content = getRawObject('content');
	var contentBackground = getRawObject('contentBackground');
	var contentText = getRawObject('contentText');
	var geoPosition = getRawObject('geoPositionReference');
		
	if ( document.HeaderOFF ){
		h=112;
		HdTitle.style.display = '';
		HdSubTitle.style.display = '';
		document.HeaderOFF=false;
		ShowHideHeader.src='images/arrow_up.png'

		explorer.style.height = "144px";
		toolbar.style.top = "112px";

	}else{
		h=-112;
		HdTitle.style.display = 'none';
		HdSubTitle.style.display = 'none';
		document.HeaderOFF=true;
		ShowHideHeader.src='images/arrow_down.png'

		explorer.style.height = "31px";
		toolbar.style.top = "0px";

	}

//	explorer.style.height = parseInt(getObjectHeight(explorer)) + h - 1 + "px";
//	toolbar.style.top = parseInt(getObjectTop(toolbar)) + h + "px";

	//layoutFrame
	layoutFrame.style.height = parseInt(page.style.height) -parseInt(getObjectHeight(explorer)) + "px";
	layoutFrame.style.top= parseInt(getObjectHeight(explorer)) + "px";
	
	//VIEWPORT
	viewport.style.height = parseInt(getObjectHeight(layoutFrame)) -1  + "px";
	viewport.style.top="0px";
	
	//CONTENT
	content.style.height = parseInt(viewport.style.height) -20  + "px";
	contentBackground.style.height = parseInt(viewport.style.height) -20  + "px";
	contentText.style.height = parseInt(viewport.style.height) -65  + "px";
	
	//SERVICE - left space
	mapLegend.style.height = parseInt(getObjectHeight(layoutFrame)) -2 + "px"; 
	mapInfo.style.height = parseInt(getObjectHeight(layoutFrame)) -2  + "px"; 
	print.style.height = parseInt(getObjectHeight(layoutFrame)) -2  + "px"; 
	identifier.style.height = parseInt(getObjectHeight(layoutFrame)) -2  + "px"; 
	link.style.height = parseInt(getObjectHeight(layoutFrame)) -2  + "px"; 
	search.style.height = parseInt(getObjectHeight(layoutFrame)) -2  + "px"; 
//	wms.style.height = parseInt(getObjectHeight(layoutFrame)) -2  + "px"; 

	service.style.height = parseInt(getObjectHeight(layoutFrame)) -2  + "px";
	geoPosition.style.top = parseInt(viewport.style.height) - 20  + "px";

    myKaMap.resize();

	return false;
}

function switchTitle(){
	var HdTitle = getRawObject('HeaderTitle');
	var HdSubTitle = getRawObject('HeaderSubTitle');
	// titolo e sottotitolo
	var oMap = myKaMap.getCurrentMap();
	HdTitle.innerHTML = oMap.comune
	HdSubTitle.innerHTML = oMap.progetto
	
}

/*
 *  applyPNGFilter(o)
 *
 *  Applies the PNG Filter Hack for IE browsers when showing 24bit PNG's
 *
 *  var o = object (this png element in the page)
 *
 * The filter is applied using a nifty feature of IE that allows javascript to
 * be executed as part of a CSS style rule - this ensures that the hack only
 * gets applied on IE browsers :)
 */
function applyPNGFilter(o) {
    var t="images/a_pixel.gif";
    if( o.src != t ) {
        var s=o.src;
        o.src = t;
        o.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+s+"',sizingMethod='scale')";
    }
}

//functions to open popup

function WOFocusWin( nn ) {
	eval( "if( this."+name+") this."+name+".moveTo(50,50); this."+name+".focus();" );
}

function WOOpenWin( name, url, ctrl ) {
	param = ctrl.split(',');
	W=H=0;
	for (p in param){
		t = param[p].split('=');
		if (t[0]=='width') W=t[1];
		if (t[0]=='height') H=t[1];
	}

	var Left=(window.screen.width-W)/2;
	var Top=(window.screen.height-H-50)/2;

	ctrl+=',left='+Left+',top='+Top

	eval( "this."+name+"=window.open('"+url+"','"+name+"','"+ctrl+"');" );
	eval( "this."+name+".focus()" );
    /*IE needs a delay to move forward the popup*/
    // window.setTimeout( "WOFocusWin(nome);", 300 );
}

function WinOpener() {
    this.openWin=WOOpenWin;
	this.focusWin=WOFocusWin;
}

function SynchronizeWindowReference(o){
	this.SynchronizeWindowReferenceTimer=function(){
		try{
			//window.status = opener+' , '+opener.K.WinRef+' , '+o.DefaulMap
			if (opener.G2K.WinRef==null) opener.G2K.WinRef=window
		}catch(e){
			clearInterval(this.SynchronizeInterval)
		}finally{
		}
	}
	var _self = this
	this.SynchronizeInterval=setInterval(function(o){_self.SynchronizeWindowReferenceTimer(o)},1000)
}



//URL SYNTAX ENCODING
function myUrlEncode(string) {
  encodedHtml = escape(string);
  encodedHtml = encodedHtml.replace("/","%2F");
  encodedHtml = encodedHtml.replace(/\?/g,"%3F");
  encodedHtml = encodedHtml.replace(/=/g,"%3D");
  encodedHtml = encodedHtml.replace(/&/g,"%26");
  encodedHtml = encodedHtml.replace(/@/g,"%40");
  return encodedHtml;
};
  
function myUrlDecode(sz){
	return unescape(sz).replace(/\+/g," ");
};

//MATH FUNCTIONs
function roundIt(number,decimals){
	var base10 = 10;
	for(var i=0;i<decimals-1;i++)
		base10 = base10 *10;
	 
	return Math.round(number * base10)/base10;
}

function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	FormatNumber(Expression, NumDigitsAfterDecimal, IncludeLeadingDigit, UseParensForNegativeNumbers, GroupDigits)

	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.
 
	RETVAL:
		The formatted number!
 **********************************************************************/
{ 
        if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);
	
	if (decimalNum) {
		var ZeroAdd = 0
		p = tmpNumStr.indexOf(".");
		if (p<0) {
			ZeroAdd=decimalNum;
			tmpNumStr+='.';
		}else{
			p=tmpNumStr.indexOf(".") + 1;
			ZeroAdd = decimalNum - (tmpNumStr.length - p)
		}
		for (i=0;i<ZeroAdd;i++) tmpNumStr+='0'
	}
	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "." + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	return tmpNumStr;		// Return our formatted string!
}


