
/******************************************************************************
 *
 * Purpose: core p.mapper functions (init, user interaction, open popups) 
 * Author:  Armin Burger
 *
 ******************************************************************************
 *
 * Copyright (c) 2003-2006 Armin Burger
 *
 * This file is part of p.mapper.
 *
 * p.mapper is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version. See the COPYING file.
 *
 * p.mapper 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with p.mapper; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 ******************************************************************************/


// Global for resize timer/setTimeout
var resize_timer;


/*
myScalebar = new ScaleBar(1);
myScalebar.divisions = 3;
myScalebar.subdivisions = 2;
myScalebar.minLength = 150;
myScalebar.maxLength = 250;
myScalebar.place('scalebar');
*/


/**************************************************** 
 * 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 loadScaleBarImg(scalebarSrc){
	var theScaleBarImg = _$("scalebarImg");
	theScaleBarImg.src = scalebarSrc;

}

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;
    
    var varformMode = _$("varform").mode.value;
    if (varformMode == 'measure') {
        resetMeasure();
        polyline = toPxPolygon(geoPolyline);
        if (polyline.getPointsNumber()>0) {
            drawPolyline(jg,polyline);
        }
    }
}


/**
 * Initialize function; called by 'onload' event of map.phtml
 * initializes several parameters by calling other JS function
 */
function pm_init() {
    // Add Resize Event to main window   
    window.onresize = function(){initLayout();};
    initLayout();

    // Add properties to mapImg
    var imgTmpMap = _$("mapImg");
    imgTmpMap.onload = resetMapImgParams;
    imgTmpMap.onmouseover = startUp;
    //_$('map').onmouseout = hideIQL;
    
    // Initialize TOC/legend
    initToc();
	getListMenu();
	
    // 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('identify');
    setTbTDButton('identify');

	pm_startEvent();
    
}

function pm_startEvent(){
	// specific Map 
	var anch = _$("MIPRAnchSpecific");
	if (anch != null)
		anch.onclick = openLog4AuthDialog;
	var anchlog = _$("MIPRAnchLogout");
	if (anchlog != null)
		anchlog.onclick = openLogout4AuthDialog;
	var anchsearch = _$("MIPRAnchSearch");
	if (anchsearch != null)
		anchsearch.onclick = openSearchDialog;
		
	var helpcontrolbutton = _$("helpMessageControlButton");
	if (helpcontrolbutton != null)
		helpcontrolbutton.onclick = collapseExpandHelpContainer;
}

function pm_reload() {
    initToc();
	setAllLayers();
    //initLayout();
	//getListMenu();
}   



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


function pMap_setMapScale(scale) {
    //alert (scale);
    this.scale = scale;
}

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


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');
    var arrtool = new Array('zoomin','zoomout','pan','identify','select','poi','measure','auto_identify','addpoint');
	for (var i = 0; i < tdarr.length; i++) {
        var tdid = tdarr[i].id;
	    if (arrtool.inArray(tdid)){
			if (tdid != button) {
                rmHighlTD(tdid)
            } else {
                highlTD(tdid);
            }
        }
    }
}


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

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

function setFloatButton(button,styleHL,styleRHL) {
    //var tdarr = document.getElementsByName('tbtd');  //!!!!! DOES NOT WORK WITH CRAPPY IE !!!!
    var tdarr = document.getElementsByTagName('div');
	var arrtool = new Array('zoomin','zoomout','pan','identify','select','poi','measure','auto_identify','addpoint');
    for (var i = 0; i < tdarr.length; i++) {
		//alert(tdarr[i].id);
        var tdid = tdarr[i].id;
		if (arrtool.inArray(tdid)){
            if (tdid != button) {
                rmHighlButton(tdid,styleRHL)
            } else {
                highlButton(tdid,styleHL);
            }
        }
    }
}

function highlButton(elId,StyleHL) {
    var but = _$(elId);
    if (but) but.className=StyleHL;
}

function rmHighlButton(elId,StyleRHL) {
    //alert(elId);
    var but = _$(elId);
    if (but) but.className=StyleRHL;
}


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

function buttonOverOut(elId,styleOn,styleOff,styleDown,status){
    var but = _$(elId);
    if (but) {
		if (but.className != styleDown) {
			if (status == 'on') {
				but.className= styleOn;
			} else {
				but.className= styleOff;
			}
		}

    }
}

function buttonDownUp(elId,styleDown,styleUp,status){
    var but = _$(elId);
    if (but) {
		if (status == 'd') {
			but.className= styleDown;
		} else {
			but.className= styleUp;
		}
    }
}


// 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 = 'url("' +rootPath + 'images/cursors/zoomin.cur"),crosshair';
			if (is_opera)
				usedCursor = "default";
			//var usedCursor = (internalCursor) ? 'crosshair' : 'url("' +rootPath + 'images/cursors/zoomin.ani")';	
			break;
        
        case "zoomout" :
			var usedCursor = 'url(' +rootPath + 'images/cursors/zoomout.cur),e-resize';
			if (is_opera)
				usedCursor = "default";			
			//var usedCursor = (internalCursor) ? 'e-resize' : 'url(' +rootPath + 'images/cursors/zoomout.cur)';	
			break;
        
        case "identify" :
			var usedCursor = 'url(' +rootPath + 'images/cursors/identify.cur),help';
			//var usedCursor = (internalCursor) ? 'help' : 'url(' +rootPath + 'images/cursors/identify.cur)';	
			if (is_opera)
				usedCursor = "help";	
            break;
        
        case "auto_identify" :	
			var usedCursor = 'pointer';	
            break;

        case "pan" :
			//var usedCursor = (internalCursor) ? 'move' : 'url(' +rootPath + 'images/cursors/pan.cur)';	
            var usedCursor = 'url(' +rootPath + 'images/cursors/pan.cur),move';
			if (is_opera)
				usedCursor = "hand";			
			//var usedCursor = 'move';
			break;
            
        case "select" :
			//var usedCursor = (internalCursor) ? 'help' : 'url(' +rootPath + 'images/cursors/select.cur)';
            var usedCursor = 'url(' +rootPath + 'images/cursors/select.cur),help';
			//var usedCursor = (internalCursor) ? 'help' : 'help';
			if (is_opera)
				usedCursor = "default";			
			break;
            
        case "measure" :
			//var usedCursor = (internalCursor) ? 'crosshair' : 'url(' +rootPath + 'images/cursors/measure.cur)';	
			var usedCursor = 'url(' +rootPath + 'images/cursors/measure2.cur),crosshair';
			if (is_opera)
				usedCursor = "crosshair";			
			break;

		case "ruler" :
			//var usedCursor = (internalCursor) ? 'crosshair' : 'url(' +rootPath + 'images/cursors/measure.cur)';	
			var usedCursor = 'url(' +rootPath + 'images/cursors/measure.cur),crosshair';
			if (is_opera)
				usedCursor = "crosshair";
			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() {
    showProcDialog("Print Option Window","MIPRPrintPanel","printZone");
	var printUrl = PM_XAJAX_LOCATION + 'x_print.php?' +SID + '&format=map';
	getQueryPrint(printUrl, '');
	//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() {
    showProcDialog("Download Option Window","MIPRDownloadPanel","downloadZone");
	var downloadUrl = PM_XAJAX_LOCATION + 'x_download.php?' +SID + '&format=map';    
	getQueryDownload(downloadUrl, '');
	//window.open("downloaddlg.phtml?"+SID, "dldlg","width=300,height=200,status=no,resizable=no");
}

function openLog4AuthDialog(){
	showProcDialog("Login For Access Specific Map ","MIPRLog4AuthPanel","log4AuthZone");
	var log4AuthUrl = PM_XAJAX_LOCATION + 'x_log4authproc.php?' +SID + '&log=true';
	getLog4Auth(log4AuthUrl,'');
}

function openLogout4AuthDialog(){
	showProcDialog("Logout For Access Specific Map ","MIPRLog4AuthPanel","log4AuthZone");
	var log4AuthUrl = PM_XAJAX_LOCATION + 'x_log4authproc.php?' +SID + '&log=false';
	getLog4Auth(log4AuthUrl,'');
}

function openSearchDialog(){
	var objprnt = _$("MIPRAnchSearch");
	showProcDialogPos("Search Dialog",objprnt,"MIPRSearchPanel","SearchZone");
	var searchUrl = PM_XAJAX_LOCATION + 'x_search.php?' +SID + '&get=frm';
	getSearch(searchUrl,'');
}

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

function openPrintReport(url,input){
  var inp  = document.getElementById(input);
  printwindow = window.open (url+'?'+input+'='+inp.value, "Report Information Print Window","location=no,status=yes,scrollbars=1,  width=600,height=600");
  printwindow.moveTo(0,0);
  return false;
} 


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';
}


function slider_mover() {
    _$('sliderArea').className = "sliderAreaOver";
}

function slider_mout() {
    _$('sliderArea').className = "sliderAreaOut";
}

