/**********************************************************************
 *
 * $Id: startUp.js,v 1.19 2006/02/07 14:09:38 pspencer 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 = myXmlOverlay = null;
var queryParams = null;
var qp='';
var pid = null;

/**
 * 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 = new Array();
    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 mapParam = getQueryParam('mapName');
	if(!mapParam || mapParam==''){
		if (mapName!=''){
			mapParam = mapName;
		}
		else{
			mapParam = 'gmap_p';
		}
	}
    var extents = getQueryParam('extents');
    var cps = getQueryParam('cps');

    pid = getQueryParam('pid');
    if(!cid){
	    cid = getQueryParam('cid');
	}
    

    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, myExtentsChanged );
    myKaMap.registerForEvent( KAMAP_QUERY, null, myQuery );
    myKaMap.registerForEvent( KAMAP_ADDQUERY, null, addQueryHandler );
    
    myKaNavigator = new kaNavigator( myKaMap );
    myKaNavigator.activate();
    
    //myKaQuery = new pimQuery( myKaMap, null );
    myAddQuery = new addQuery( myKaMap, null );
    
    myScalebar = new ScaleBar(1);
    myScalebar.divisions = 3;
    myScalebar.subdivisions = 2;
    myScalebar.minLength = 150;
    myScalebar.maxLength = 220;
    myScalebar.place('scalebar');

	drawPage();
	
//	deba(mapParam);
	
    myKaMap.initialize( mapParam, extents, '', cps );
    
}

/**
 * event handler for KAMAP_INITIALIZED.
 *
 * at this point, ka-Map! knows what map files are available and we have
 * access to them.
 */
function myInitialized() {

}

/**
 * event handler for KAMAP_MAP_INITIALIZED
 *
 * the scales are put into a select ... this will be used for zooming
 */ 
function myMapInitialized( eventID, mapName ) {
    
	var map = getQueryParam('mapName');
    var extents = getQueryParam('extents');
    var cps = getQueryParam('cps');
    var mid = getQueryParam('mid');
    
//    alert('params:\n' + pid + '\n' + cid);
//    if(cps!='' && pid==''){
//    	myKaQuery.byCoords(cps);
//    }
    
    if(pid!=''){
    	myKaNavigator.byPoint(pid);
    }

    if(mid!=''){
    	myKaNavigator.byMeta(mid);
    }
    
    if(cid=='weather'){
    	myKaNavigator.weather();
    }

	
    //get list of maps and populate the maps select box
/*
    var aMaps = myKaMap.getMaps();
    var oSelect = document.forms.toolbar.maps;
    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.toolbar.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;
            }
        }
    }
    //update the scales select
    var currentMap = myKaMap.getCurrentMap();
    var scales = currentMap.getScales();
    var currentScale=myKaMap.getCurrentScale();

    //Insert tools into zoomer div
    
    var iWidth = 6;//width of the zoom to scale item
    var iMaxHeight = 10;//width of the zoom to scale item
    var iMinHeight = 20;//width of the zoom to scale item
    var zoomer="<span style='width:"+(scales.length*iWidth)+"'>";
    for(var i=0; i<scales.length; i++) {
//        var zoomTo = 'mySetScale(' +scales[i]+')';
        //var iHeight =  parseInt(i)*2.5+10;
//        var iHeight =  iMaxHeight - parseInt((iMaxHeight - iMinHeight) *i/scales.length);

//        var zoomImg = '';
        if (scales[i]==currentScale) {
        	getRawObject('img'+scales[i]).src='/images/pixel-red.png';
//            zoomImg = '<img src="images/pixel-red.png" width="' + iWidth + '" height="' + iHeight + 'px" border="0" onclick="'+zoomTo+'"  title="Zoom to 1:'+scales[i]+'" alt="Zoom to 1:'+scales[i]+'"  id="img'+scales[i]+'"/>';
//        } else {
//            zoomImg = '<img src="images/pixel-blue.png" width="' + iWidth + '" height="' + iHeight + 'px" border="0" onclick="'+zoomTo+'"  title="Zoom to 1:'+scales[i]+'" alt="Zoom to 1:'+scales[i]+'" id="img'+scales[i]+'"/>';
        }
//        zoomer = zoomer  + zoomImg ;
    }
//    zoomer=zoomer+"</span>";
//    getRawObject('zoomer').innerHTML = zoomer;

    //Activate query button
    switchMode('toolPan');

}

/**
 * called when kaMap tells us the scale has changed
 */
function myScaleChanged( eventID, scale )
{
    //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 = '1:'+ scale;
    getRawObject('scale').innerHTML = outString;
    getRawObject('leftscale').innerHTML = outString;

}


/**
 * called when kaMap tells us the extents has changed
 */
function myExtentsChanged( eventID, extent )
{
    var scale = myKaMap.getCurrentScale();
    var map = myKaMap.getCurrentMap().name;
    var center = myKaMap.getCenter()
    var coords = myKaMap.pixToGeo(-center[0],-center[1]);
    
    qp = coords + ',' + scale;

/*    getRawObject('permalink').href = '/map/?mapName=' + map + '&extents=' + extent + '&cps=' + qp + '&pid=' + pid;*/
    getRawObject('permalink').href = '/map/?mapName=' + map + '&cps=' + qp + '&pid=' + pid;
}

/**
 * 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 )
{
    myKaMap.selectMap( name );
}

function myQuery( eventID, coords, p ){
    var extent = myKaMap.getGeoExtents();
    var scale = myKaMap.getCurrentScale();
    var cMap = myKaMap.getCurrentMap().name;

//    qp = coords + ',' + scale;
    
    //alert(coords + ' ' + p);
    
    pid = p;

    getRawObject('permalink').href = '/map/?mapName=' + cMap + '&cps=' + qp + '&pid=' + pid;
    
//   	deba(p);
    if(p){
		updateLeftObjects(coords);
	}
    
}

function myZoomIn()
{
    myKaMap.zoomIn();
}

function myZoomOut()
{
    myKaMap.zoomOut();
}

function toggleToolbar(obj)
{
    if (obj.style.backgroundImage == '')
        obj.isOpen = true;
        
    if (obj.isOpen)
    {
        obj.title = 'show toolbar';
        obj.style.backgroundImage = 'url(/images/arrow_down.png)';
        var bValue = getObjectTop(obj);;
        var d = getObject('toolbar');
        d.display = "none";
        obj.isOpen = false;
        obj.style.top = "3px";
    }
    else
    {
        obj.title = 'hide toolbar';
        obj.style.backgroundImage = 'url(/images/arrow_up.png)';
        var d = getObject('toolbar');
        d.display="block";
        obj.isOpen = true;
        var h = getObjectHeight('toolbar');
        obj.style.top = (h + 3) + "px";
    }
}

function toggleKeymap(obj)
{
    if (obj.style.backgroundImage == '')
        obj.isOpen = true;
        
    if (obj.isOpen)
    {
        obj.title = 'show keymap';
        obj.style.backgroundImage = 'url(/images/arrow_left.png)';
        var bValue = getObjectTop(obj);;
        var d = getObject('keymap');
        d.display = "none";
        obj.isOpen = false;
    }
    else
    {
        obj.title = 'hide keymap';
        obj.style.backgroundImage = 'url(/images/arrow_right.png)';
        var d = getObject('keymap');
        d.display="block";
        obj.isOpen = true;
    }
}

function toggleReference(obj)
{
    if (obj.style.backgroundImage == '')
        obj.isOpen = true;
        
    if (obj.isOpen)
    {
        obj.title = 'show reference';
        obj.style.backgroundImage = 'url(/images/arrow_up.png)';
        var d = getObject('reference');
        d.display = 'none';
        obj.isOpen = false;
        obj.style.bottom = '3px';
    }
    else
    {
        obj.title = 'hide reference';
        obj.style.backgroundImage = 'url(/images/arrow_down.png)';
        var d = getObject('reference');
        d.display = 'block';
        obj.isOpen = true;
        obj.style.bottom = (getObjectHeight('reference') + 3) + 'px';
    }
}

function dialogToggle( href, szObj )
{
    var obj = getObject(szObj);
    if (obj.display == 'none')
    {
        obj.display = 'block';
        href.childNodes[0].src = '/images/dialog_shut.png';
        
    }
    else
    {
        obj.display = 'none';
        href.childNodes[0].src = '/images/dialog_open.png';
    }
}

/**
 * drawPage - calculate sizes of the various divs to make the app full screen.
 */
function drawPage(){
    var browserWidth = $(window).innerWidth();
    var browserHeight = $(window).innerHeight();
    
    var $viewport = $('#viewport');
    var siteframew = $('#siteframe').innerWidth();
    $viewport.css({width : $('#content').innerWidth() + 'px',height : (browserHeight - 171) + 'px'});

    myKaMap.resize();
}

/**
 * getFullExtent
 * ...
 */
function getFullExtent() {
    var exStr = myKaMap.getCurrentMap().defaultExtents.toString();
    var ex = myKaMap.getCurrentMap().defaultExtents;
    myKaMap.zoomToExtents(ex[0],ex[1],ex[2],ex[3]);
}

function extentFullScreen() {
    var siteframe = getRawObject('siteframe');
	if(myKaMap.isIE4) {
		var browserWidth = getInsideWindowWidth()-5;
	} else {
		var browserWidth = getInsideWindowWidth();
	}    
    var browserHeight = getInsideWindowHeight();
    var viewport = getRawObject('viewport');
	var foot = getRawObject('foot');
//	alert(siteframe.style.width);
//	alert(browserWidth);
	if(browserWidth==parseInt(siteframe.style.width)){
		siteframe.style.width = '875px';
		foot.style.width = '875px';
		
		viewport.style.display = 'none';
		viewport.style.display = 'block';
	}else{
	    //Set Viewport Width
	    if(myKaMap.isIE4) {
	        siteframe.style.width = browserWidth + "px";
	        foot.style.width = browserWidth + "px";
	        siteframe.style.height = (browserHeight - 110) + "px";
	    } else {
	        siteframe.style.width = browserWidth + "px";
	        siteframe.style.height = browserHeight + "px";
	        foot.style.width = browserWidth + "px";
	    }
	    
    }   
    drawPage();
}

/*
 *  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')";
    }
}

function showPoint(pid){
    var extent = myKaMap.getGeoExtents();
    var scale = myKaMap.getCurrentScale();
    var cMap = myKaMap.getCurrentMap().name;

    myXmlOverlay.removePoint(null);
    myXmlOverlay.loadXml('dbquery.php?pid='+pid+'&extent='+extent+'&scale='+scale);
    
    getRawObject('permalink').href = '/map/?mapName=' + cMap + '&extents=' + extent + '&pid=' + pid;
    
}

var toolname=null;
function makeClickable(){
	toolname = myKaMap.currentTool.name;
	myKaNavigator.activate();
}
function restoreTool(){
	if(toolname){
	    if(toolname=='pimQuery'){
	        myKaNavigator.activate();
	        //getRawObject('toolQuery').style.backgroundImage = 'url(images/tool_query_2.png)';
	        //getRawObject('toolPan').style.backgroundImage = 'url(images/tool_pan_1.png)';
	    }else{
	        myKaNavigator.activate();
	        //getRawObject('toolQuery').style.backgroundImage = 'url(images/tool_query_1.png)';
	        //getRawObject('toolPan').style.backgroundImage = 'url(images/tool_pan_2.png)';
	    }
	}
}

function showObject(pid){
    myKaNavigator.xmlOverlay.loadXml('dbquery.php?pid='+pid);
}


function showCObject(pid){
    myKaNavigator.xmlOverlay.loadXml('dbquery.php?client=true&pid='+pid);
}


