/*********************************************************************************
 Copyright (c) 2002-2005 Armin Burger
 
 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 AUTHOR OR 
 COPYRIGHT HOLDER 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.
**********************************************************************************/


// Global for resize timer/setTimeout
var resize_timer;



/**************************************************** 
 * LOAD MAP IMAGE INTO PARENT WINDOW MAP DIV
 * Reset parameters of some DIV's
 ****************************************************/
function loadMapImg(mapImgSrc) {
    // SWAP MAP IMG
    var theMapImg = $("mapImg");
    theMapImg.src = mapImgSrc;
}

function resetMapImgParams() {
    var theMapImgL = $("mapimgLayer");
    var theMapImg = $("mapImg");
    
    theMapImg.style.width = mapW+"px";
    theMapImg.style.height = mapH+"px";
    
    theMapImgL.style.top  = 0+"px";  
    theMapImgL.style.left = 0+"px";
    theMapImgL.style.width = mapW+"px";
    theMapImgL.style.height = mapH+"px";
    
    theMapImgL.style.clip = 'rect(auto auto auto auto)';  // NEEDED TO RESET DIV TO NON-CLIPPED AND ORIGINAL SIZE
    
    $("zoombox").style.visibility = 'hidden';
    $('loading').style.visibility = 'hidden';
    
    maploading = false;
}


/**
 * Initialize function; called by 'onload' event of map.phtml
 * initializes several parameters by calling other JS function
 */
function init() {
    // Add Resize Event to main window, using initResize() because of IE (see below)
    //window.onresize = function(){initResize();}
    window.onresize = function(){resizeDiv();}
    
    // Add properties to mapImg
    var imgTmpMap = $("mapImg");
    imgTmpMap.onload = resetMapImgParams;
    imgTmpMap.onmouseover = startUp;
    
    // Resize all layout DIV's with respect to window size
    resizeDiv();
    
    // Initialize TOC/legend
    initToc();
    
    // Set zoombox class for Opera and Konqueror to non-semitransparent
    if (navigator.userAgent.match(/Opera|Konqueror/i)) {
        $("zoombox").className = 'zoombox_nontransp';
    }
    
    createZSlider('zslider');
    createSearchOptions();
    domouseclick('zoomin');
    setTbTDButton('zoomin');
    
}   


/**
 * Resize all layout DIV's with respect to window size
 * needs to be adpated when default layout is modified
 */


function resizeDiv() {
    // Margins in application window
    var lMargin  = 15; // LEFT 
    var mMargin  = 10; // MIDDLE, between map and toc 
    var rMargin  = 15; // RIGHT
    var tMargin  = 10; // TOP
    var bMargin  = 10; // BOTTOM
    var m2Margin = 10; // MIDDLE, between TOC and refmap

    var winix = 0, winiy = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
      //Non-IE
      winix = window.innerWidth;
      winiy = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
      //IE 6+ in 'standards compliant mode'
      winix = parseInt(document.documentElement.clientWidth);
      winiy = parseInt(document.documentElement.clientHeight) - 2;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
      //IE 4 compatible
      winix = document.body.clientWidth;
      winiy = document.body.clientHeight;
    }

    // Element definitions
    var top             = $('top');
    var bottom          = $('bottom');
    var mapFrame        = $('mapFrame');
    var mapimgLayer     = $('mapimgLayer');
    var mapImg          = $('mapImg');
    var zoombox         = $('zoombox');
    var toolBar         = $('toolBar');
    var topMapFrame     = $('topMapFrame');
    var botMapFrame     = $('bottomMapFrame');
    var toc             = $('toc');
    var refmap          = $('refmap');
    var refmapBG        = $('refmapBG');
    var loading         = $('loading');
        
    
    // Position (T, L) and sizes (W, H) of elements
    var mapFrameL       = objLeft(mapFrame);
    var tocW            = objW(toc);
    var toolBarW        = objW(toolBar);
    var mapimgLayerW    = objW(mapimgLayer);
    var mapimgLayerL    = objLeft(mapimgLayer);
    var bottomW         = objW(bottom);
    var topW            = objW(top);
    
    var topH            = objH(top);
    var bottomH         = objH(bottom);
    var mapFrameT       = objTop(mapFrame);
    var tocH            = objH(toc);
    var refmapH         = objH(refmap);
    var toolBarH        = objH(toolBar);
    var mapimgLayerH    = objH(mapimgLayer);
    var mapimgLayerT    = objTop(mapimgLayer);
    var topMapFrameH    = objH(topMapFrame);
    var botMapFrameH    = objH(botMapFrame);
    
    
    // NEW sizes
    var newImgLayerW    = winix - lMargin - mMargin - rMargin - tocW - toolBarW;
    //alert(winix+" - "+lMargin+" - "+mMargin+" - "+rMargin+" - "+tocW+" - "+toolBarW);
    var newImgLayerH    = winiy - tMargin - bMargin - topH - bottomH - topMapFrameH - botMapFrameH;
    //alert(winiy+" - "+tMargin+" - "+bMargin+" - "+topH+" - "+bottomH+" - "+topMapFrameH+" - "+botMapFrameH);
    var newToolBarL     = mapimgLayerL + newImgLayerW;
    var newTocL         = mapFrameL + newImgLayerW + toolBarW + mMargin;
    var newTocH         = newImgLayerH + topMapFrameH + botMapFrameH - refmapH - m2Margin;

    
    // RESIZE elements
    mapW = newImgLayerW;
    mapH = newImgLayerH;
    //alert("mapW = "+mapW+" , mapH = "+mapH);
    
    mapFrame.style.width        = newImgLayerW + 'px';
    mapFrame.style.height       = newImgLayerH + topMapFrameH + 'px';
    mapFrame.style.top          = topH + tMargin + 'px';
    mapFrame.style.left         = lMargin + 'px';
    
    mapimgLayer.style.width     = newImgLayerW + 'px';
    mapimgLayer.style.height    = newImgLayerH + 'px';
    
    mapImg.style.width          = newImgLayerW + 'px';
    mapImg.style.height         = newImgLayerH + 'px';
    
    zoombox.style.width         = newImgLayerW + 'px';
    zoombox.style.height        = newImgLayerH + 'px';
    
    topMapFrame.style.width     = newImgLayerW + 'px';
    botMapFrame.style.width     = newImgLayerW + 'px';
    botMapFrame.style.top       = mapimgLayerT + topMapFrameH + newImgLayerH + 'px';
    
    toolBar.style.left          = newToolBarL + 'px';
    toolBar.style.height        = topMapFrameH + botMapFrameH + newImgLayerH + 'px';
    
    toc.style.left              = newTocL + 'px';
    toc.style.height            = newTocH + 'px';
    toc.style.top               = topH + tMargin + 'px';
    
    refmap.style.left           = newTocL + 'px';
    refmap.style.top            = mapFrameT + newTocH + m2Margin + 'px';
    refmapBG.style.left         = newTocL + 'px';
    refmapBG.style.top          = mapFrameT + newTocH + m2Margin + 'px';
    
    top.style.width             = winix + 'px';
    bottom.style.width          = winix + 'px';
    
    loading.style.left          = mapW/2 - 60 + 'px';
    loading.style.top           = mapH/2 - 20 + 'px';

    
    // Update Slider
    updateSlider_s1(newImgLayerW, newImgLayerH) ;
    
    // RELOAD MAP!!!
    var mapurl = PM_XAJAX_LOCATION + 'x_load.php?'+SID+ '&mapW=' + newImgLayerW + '&mapH=' + newImgLayerH + '&zoom_type=zoompoint';

    // Timer-controlled resize of map for stupid IE resize event behaviour
    if (navigator.appName.indexOf("Microsoft")!=-1) {
        clearTimeout(resize_timer);
        resize_timer = setTimeout("updateMap('" + mapurl + "', '')",500);     
    } else {
        updateMap(mapurl, '');   
    }
}



/**
 * Update s1 value for slider settings
 */
function updateSlider_s1(pixW, pixH) {
    var maxScale1 = ((dgeo_x * dgeo_c) / pixW) / (0.0254 / 96);
    var maxScale2 = ((dgeo_y * dgeo_c) / pixH) / (0.0254 / 96);
    s1 = Math.max(maxScale1, maxScale2);
}


function pMap () {
    //this.setMapProperties = pMap_setMapProperties;
    //this.getMapProperties = pMap_getMapProperties;
    this.getMapScale = pMap_setMapScale;
    this.RefMapW = pMap_getRefMapW;
    this.RefMapH = pMap_getRefMapH; 
}

function pMap_setMapProperties(width, height, scale) {
    var mapimgLayer = $('mapimgLayer');
    
    mapimgLayer.style.width = width;
    mapimgLayer.style.height = height;
    
    this.width  = width;
    this.height = height;
    this.scale  = scale;
}


function pMap_getMapProperties() {
    var width = this.width;
    var height = this.height; 
    //alert(width + ' - ' + height);
    //loadMapImg0();
}


/**
 * SCALE OF CURRENT MAP
 */
function pMap_setMapScale(scale) {
    //alert (scale);
    this.scale = scale;
}

function pMap_getMapScale() {
    //alert(this.scale);
    return this.scale;
}


/**
 * REFERENCE MAP WIDTH/HEIGHT
 */
function pMap_setRefMapW(refW) {
    this.RefMapW = refW;
}

function pMap_setRefMapH(refH) {
    this.RefMapH = refH;
}

function pMap_getRefMapW() {
    return this.RefMapW;
}

function pMap_getRefMapH() {
    return this.RefMapH;
}






/*****************************************************************************
 * SWAP FUNCTIONS FOR TOOLBAR TD -> USE ALTERNATIVELY TO IMAGE SWAP
 * Changes TD class (default.css -> .TOOLBARTD...) in toolbar
 ********************************************************************/
// Function for state buttons (CLICKED TOOLS: zoomin, pan, identify, select, measure)
function setTbTDButton(button) {
    //var tdarr = document.getElementsByName('tbtd');  //!!!!! DOES NOT WORK WITH CRAPPY IE !!!!
    var tdarr = document.getElementsByTagName('td');
    for (var i = 0; i < tdarr.length; i++) {
        var tdid = tdarr[i].id;
        //alert(tdid);
        //if (tdid != 'tsep') {
        
        //!!!!! WORKAROUND FOR CRAPPY IE !!!!
        if (tdid == 'zoomin' || tdid == 'zoomout' || tdid == 'pan' || tdid == 'identify' || tdid == 'select' || tdid == 'measure' || tdid == 'poi' || tdid == 'auto_identify') {
            if (tdid != button) {
                rmHighlTD(tdid)
            } else {
                highlTD(tdid);
            }
        }
    }
}

function highlTD(elId) {
    var but = $(elId);
    if (but) but.className='TOOLBARTD_ON';
}

function rmHighlTD(elId) {
    //alert(elId);
    var but = $(elId);
    if (but) but.className='TOOLBARTD';
}


// Functions for MouseOver/Out
function TbOverOut(elId, status){
    var but = $(elId);
    if (but) {
        if (but.className != 'TOOLBARTD_ON') {
            if (status == 'on') {
                but.className='TOOLBARTD_OVER';
            } else {
                but.className='TOOLBARTD';
            }
        }
    }
}

// MouseDown/Up, only set for stateless buttons
function TbDownUp(elId, status){
    var but = $(elId);
    if (status == 'd') {
        but.className='TOOLBARTD_ON';
    } else {
        but.className='TOOLBARTD';
    }
}

function changeButtonClr(myObj, myAction) {
    switch (myAction) {
        case 'over':
            myObj.className = 'button_on';
            break;
            alert(myAction);
            
        case 'out':
            myObj.className = 'button_off';
            break;
    }
}




/*****************************************************************************
 * IMAGE SWAP FUNCTIONS FOR TOOLBAR
 * swaps images from imgname_on.gif to imgname_off.gif and vice versa
 *********************************************************************/
// SWITCH IMAGE OF CLICKED TOOL TO 'ON', ALL OTHERS TO 'OFF'
function setButton(button) {
    var imgarr = document.getElementsByTagName('img');
    for (var i = 0; i < imgarr.length; i++) {
        var butid = imgarr[i].id;
        if (butid != 'sep') {
            if (butid != button) {
                setImg(butid, 'off');
            } else {
                setImg(butid, 'on');
            }
        }
    }
}

// set image to ON or OFF
function setImg(obj, status){
    var source = 'images/buttons/' + obj + '_' + status + '.gif';
    imgobj = $(obj);
    imgobj.src = source;
}




/**************************************************
 * Set cursor symbol according to tool selection
 *************************************************/
// return root path of application
function getRootPath() {
	var theLoc = document.location.href;
	var theLastPos = theLoc.lastIndexOf('/');
	var RootPath = theLoc.substr(0,theLastPos) + '/';
	
	return RootPath;
}

/** 
 * set the cursor to standard internal cursors
 * or special *.cur url (IE6+ only)
 */
function setCursor(rmc) {	
    if (!rmc) {
    	var varform = $("varform");
        if (varform) {
            var toolType = varform.tool.value;
        } else {
            var toolType = 'zoomin';
        }
    } else {
        toolType = 'pan';
    }

    
    /* Define settings for cursor to be used for tools
       set to true if you want to use the same cursors for all browsers (incl. IE) */
    var internalCursor = ((navigator.version < 6) || (navigator.appName == 'Netscape'));
    //var internalCursor = true; 
    
    var rootPath = getRootPath();
    var usedCursor = (internalCursor) ? toolType : "url(" +rootPath + "images/cursors/zoomin.cur)";
    
    $('mapimgLayer').style.cursor = usedCursor;
    
    switch (toolType) {
		case "zoomin" :
			var usedCursor = (internalCursor) ? 'crosshair' : 'url("' +rootPath + 'images/cursors/zoomin.ani")';	
			break;
        
        case "zoomout" :
			var usedCursor = (internalCursor) ? 'e-resize' : 'url(' +rootPath + 'images/cursors/zoomout.cur)';	
			break;
        
        case "identify" :
			//var usedCursor = (internalCursor) ? 'help' : 'url(' +rootPath + 'images/cursors/identify.cur)';	
			var usedCursor = 'help';	
            break;
        
        case "auto_identify" :	
			var usedCursor = 'pointer';	
            break;

        case "pan" :
			//var usedCursor = (internalCursor) ? 'move' : 'url(' +rootPath + 'images/cursors/pan.cur)';	
            var usedCursor = 'move';
			break;
            
        case "select" :
			//var usedCursor = (internalCursor) ? 'help' : 'url(' +rootPath + 'images/cursors/select.cur)';
            var usedCursor = (internalCursor) ? 'help' : 'help';	            
			break;
            
        case "measure" :
			var usedCursor = (internalCursor) ? 'crosshair' : 'url(' +rootPath + 'images/cursors/measure.cur)';	
			break;
            
        case "digitize" :
			var usedCursor =  'crosshair';	
			break;
            
        default:
            var usedCursor = 'default';
    }
    
    $('mapimgLayer').style.cursor = usedCursor;
    
}




/*
 * OPEN RESULT WINDOW FOR IDEBNTIFY AND SEARCH
 ***********************************************/
function openResultwin(winurl) {
    try {
        if (queryResultLayout == 'tree') {
            var winw = 300;
            var winh = 450;
        } else {
            var winw = 500;
            var winh = 200;
        }
    } catch(e) {
        var winw = 500;
        var winh = 200;
    }
    
    var w = window.open(winurl, 'resultwin', 'width=' + winw + ',height=' + winh + ',status=yes,resizable=yes,scrollbars=yes');
    return w;
}


/*****************************************************************************
 * SEARCH
 **********/
// CLOSE SEARCH PAGE
function searchClose() {
    parent.searchFrame.location = "blank.html";
}

// OPEN SEARCH PAGE
function searchOpen() {
    parent.searchFrame.location = "search.phtml?"+SID;
}



/******************************************************************************
 * PRINT FUNCTIONS
 *******************/
function openPrintDlg() {
    var pwin = window.open("printdlg.phtml?"+SID,"printdlg","width=300,height=180,status=no,resizable=no");
}

function printMap() {
    var w = window.open("printmap.phtml?"+SID,"printdlg","width=300,height=180,status=no,resizable=no");
}



/*
 * OPEN HELP WINDOW 
 *************************************/
function openHelp() {
    window.open("help.phtml", "help","width=400,height=500,status=no,resizable=yes");
}



/************************************************************************************
 * DOWNLOAD FUNCTIONS
 * get image with higher resolution for paste in othet programs
 ****************************************************************/
function openDownloadDlg() {
    window.open("downloaddlg.phtml?"+SID, "dldlg","width=300,height=180,status=no,resizable=no");
}

function openDownload() {
    window.open("download.phtml?"+SID, "download");
}




function openPoiDlg(imgxy) {
    //alert(imgxy);
    var coordsList = imgxy.split('+');
    var mpoint = getCoords(coordsList[0], coordsList[1], false);
    
    // Round values (function 'roundN()' in 'measure.js')
    var rfactor = 4;
    var px = isNaN(mpoint.x) ? '' : roundN(mpoint.x, rfactor);
    var py = isNaN(mpoint.y) ? '' : roundN(mpoint.y, rfactor);
    
    var inserttxt = prompt(localeList['addLocation'], '');
    
    if (inserttxt) {
        //alert(inserttxt + ' --- ' + px + ' -- ' + py);
        //var ul = + px + ',' + py + ',' + inserttxt;
        var digitizeurl = PM_XAJAX_LOCATION + 'x_poi.php?' +SID + '&up=' + px + '@@' + py + '@@' + escape(inserttxt);
        //alert(digitizeurl);
        addPOI(digitizeurl, '');
    }
}








/**
 * DOM window functions using dragresize.js
 *
 */

function initDOMWin(resizeable, wid) {    
    var dragresize = new DragResize('dragresize',
        { handles: ['tm', 'br'], minWidth: 50, minHeight: 50, minLeft: 2, minTop: 2, elmW: 20 });
    
    dragresize.isElement = function(elm)
    {
        if (elm.className && elm.className.indexOf('drsElement') > -1) return true;
    };
    
    dragresize.isHandle = function(elm)
    {
        if (elm.className && elm.className.indexOf('drsMoveHandle') > -1) return true;
    };

    dragresize.apply(document);
}


function createDOMWin(wid, W, H, T, L, oCl ) {
    var win_div = document.createElement('div');
    win_div.id = wid + '_domwin';
    win_div.className = 'drsElement';
    win_div.style.width  = W + 'px';
    win_div.style.height = H + 'px';
    win_div.style.top    = T + 'px';
    win_div.style.left   = L + 'px';
    win_div.style.visibility = 'hidden';
    
    var mh_div = document.createElement('div');
    mh_div.id = wid + '_mhandle';
    mh_div.className = 'drsMoveHandle';
    win_div.appendChild(mh_div);
    
    var con_div = document.createElement('div');
    con_div.id = wid + '_content';
    con_div.className = 'drsContent';
    win_div.appendChild(con_div);
    
    var clb_div = document.createElement('div');
    clb_div.id = wid + '_closebutton';
    clb_div.className = 'drsClosebutton';
    clb_div.onclick = oCl;
    con_div.appendChild(clb_div);
       
    document.body.appendChild(win_div);
    
    initDOMWin();
}


function createAllDOMWindows() {
    createDOMWin('query', 600, 200, 100, 100, domWinClose ) ;
    createDOMWin('print',  200, 150, 100, 100, domWinClose ) ;
    createDOMWin('download',  200, 150, 100, 100, domWinClose ) ;
}


function domWinClose() {
    var winId = this.id.split('_')[0] + '_domwin';
    document.getElementById(winId).style.visibility = 'hidden';
}



