/*********************************************************************************
 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.
**********************************************************************************/

 /* 
 *Modified By : Radhika Dubey; radhikadubey@infobase.in
 * Modified on : 29 MArch 2007
 *Change Description : Customizing application for mapsofindia.com
*/

/**************************************************** 
 * LOAD MAP IMAGE INTO PARENT WINDOW MAP DIV
 * Reset parameters of some DIV's
 ****************************************************/
function loadMapImg(mapImgSrc) {
    // SWAP MAP IMG
    var theMapImg = document.getElementById("mapImg");
	//alert(mapImgSrc);
    theMapImg.src = mapImgSrc;
	
}
function writeext(geo_scale,minx_geo,maxy_geo,xdelta_geo,ydelta_geo)
{
	global_ext = geo_scale;
	//alert(global_ext);
	    
}
function resetMapImgParams() {
    var theMapImgL = document.getElementById("mapimgLayer");
    var theMapImg = document.getElementById("mapImg");
    
    theMapImg.style.width = mapW+"px";
    theMapImg.style.height = mapH+"px";
    
    theMapImgL.style.top  = 23+"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
    
    document.getElementById("zoombox").style.visibility = 'hidden';
    document.getElementById('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();}
    
    // Add properties to mapImg
    var imgTmpMap = document.getElementById("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)) {
        document.getElementById("zoombox").className = 'zoombox_nontransp';
    }
    
    createZSlider('zslider');
    createSearchOptions();
	//createSearchInput();
    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  = 190; // LEFT 
    var mMargin  = -14; // MIDDLE, between map and toc 
    var rMargin  = 1; // RIGHT
    var tMargin  = 210; // TOP
    //var bMargin  = -435; // BOTTOM
    var bMargin  = -480; // BOTTOM
    var m2Margin = 30; // MIDDLE, between TOC and refmap

    var winix = 0, winiy = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
      //Non-IE
      winix = window.innerWidth - 140;
      winiy = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
      //IE 6+ in 'standards compliant mode'
      winix = document.documentElement.clientWidth - 120;
      winiy = document.documentElement.clientHeight;
	  if(winix > 883)
		{
         winix = 883;
		}
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
      //IE 4 compatible
      winix = document.body.clientWidth - 120;
      winiy = document.body.clientHeight;
	  if(winix > 883)
		{
         winix = 883;
		}
    }
   
    // Element definitions
    var top             = document.getElementById('top');
    var bottom          = document.getElementById('bottom');
	var distance        = document.getElementById('distance');
    var mapFrame        = document.getElementById('mapFrame');
    var mapimgLayer     = document.getElementById('mapimgLayer');
    var mapImg          = document.getElementById('mapImg');
    var zoombox         = document.getElementById('zoombox');
    var toolBar         = document.getElementById('toolBar');
    var topMapFrame     = document.getElementById('topMapFrame');
    var botMapFrame     = document.getElementById('bottomMapFrame');
	var maplegendon     = document.getElementById('maplegendon');
	var maplegend       = document.getElementById('maplegend');
    var toc             = document.getElementById('toc');
    var refmap          = document.getElementById('refmap');
    var refmapBG        = document.getElementById('refmapBG');
    var loading         = document.getElementById('loading');
    var info         = document.getElementById('info');
    var feed       = document.getElementById('feedback');
var frame       = document.getElementById('infoFrame');
var footer       = document.getElementById('footer');
var dist      = document.getElementById('dist');
    //var under         = document.getElementById('under');    
    
    // 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);
    var infoH    = objH(info);
    
    
    // NEW sizes

	var newImgLayerW    = winix - lMargin - mMargin - rMargin - tocW - toolBarW;
   // var newImgLayerW    = winix - lMargin - mMargin - rMargin - tocW - toolBarW + 200;
    //alert(winix+" - "+lMargin+" - "+mMargin+" - "+rMargin+" - "+tocW+" - "+toolBarW);

    var newImgLayerH    = winiy - tMargin - bMargin - topH - bottomH - topMapFrameH ;
    //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;
    //newImgLayerW = 618;
	//newImgLayerH = 538;
    //alert(newImgLayerW);
    // RESIZE elements
    mapW = 501;
    mapH = 535;
	//alert(topMapFrame.style.top);
    //alert("mapW = "+mapW+" , mapH = "+mapH);
      //alert(topH + tMargin);
    mapFrame.style.width        = newImgLayerW + 'px';
    mapFrame.style.height       = newImgLayerH +23+ 'px';
    mapFrame.style.top          = topH + tMargin + 'px';
    mapFrame.style.left         = lMargin + 'px';
   //mapimgLayer.style.top     =  0+ 'px';
    mapimgLayer.style.width     = newImgLayerW + 'px';
    mapimgLayer.style.height    = newImgLayerH  +23+ 'px';
    
    mapImg.style.width          = newImgLayerW + 'px';
    mapImg.style.height         = newImgLayerH +23 + 'px';
    
    zoombox.style.width         = newImgLayerW + 'px';
    zoombox.style.height        = newImgLayerH +23+ 'px';
    
    topMapFrame.style.width     = newImgLayerW   + 'px';
    botMapFrame.style.width     = newImgLayerW  + 'px';
 botMapFrame.style.left    = -3+ 'px';
	//alert(mapimgLayerT + topMapFrameH + newImgLayerH);
    botMapFrame.style.top       = newImgLayerH  +23+'px';
    info.style.left           = newImgLayerW  +lMargin +m2Margin+10+ 'px';
    info.style.height           = newImgLayerH +33 + 'px';
   frame.style.left           = newImgLayerW  +lMargin +m2Margin+10+ 'px';
   frame.style.height           = newImgLayerH+2  + 'px';
   footer.style.top = newImgLayerH +890+  'px';
   maplegendon.style.left = newImgLayerW  +lMargin +m2Margin+10+ 'px';
    //maplegendon.style.top       = mapimgLayerT + topMapFrameH + newImgLayerH - infoH +'px';
    maplegend.style.top         = mapimgLayerT + topMapFrameH + newImgLayerH + 'px';
//under.style.top         = mapimgLayerT + topMapFrameH + newImgLayerH  -2 + 'px';
	dist.style.top = newImgLayerH + 385+'px';
    //info.style.left =  501 +toolBarW  + 'px';
//maplegendon.style.left = 501 +toolBarW  + 'px';
    toolBar.style.left          = newToolBarL +  'px';
    toolBar.style.height        = newImgLayerH  +10 +23+ 'px';
    feed.style.top              = newImgLayerH +385+  'px';
    toolBar.style.top         =  -3+'px';
    //toc.style.left              = newTocL + 168 + 'px';
     toc.style.left              = 653 + 168 + 'px';
    toc.style.height            = newTocH + 'px';
    
    //refmap.style.left           = newTocL + 177 + 'px';
	refmap.style.left           = 653 + 177 + 'px';
    //refmap.style.top            = mapFrameT + newTocH + m2Margin + (385) + 'px';
    refmap.style.top            = topH + tMargin + newImgLayerH + topMapFrameH - (newImgLayerH - newTocH )-11 + 'px';
    //refmapBG.style.left         = newTocL + 168 + 'px';
    refmapBG.style.left         = 653 + 168 + 'px';
    //refmapBG.style.top          = mapFrameT + newTocH + m2Margin + (375) + 'px';
    refmapBG.style.top          = topH + tMargin + newImgLayerH + topMapFrameH - (newImgLayerH - newTocH )- 22 + 'px';
    
    top.style.width             = winix + 'px';
    bottom.style.width          = winix -55+ 'px';
	//bottom.style.top          =   newImgLayerH + 280 +'px';
	bottom.style.top            =   300 +'px';
    bottom.style.left           =  170+'px';

	distance.style.top          =   310 +'px';

    loading.style.left          = mapW/2 - 60 + 'px';
    loading.style.top           = mapH/2 - 20 + 'px';
    //alert(newTocL);
	//google.style.top         =  mapH - 5 + 'px'
    
    // Update Slider
    updateSlider_s1(newImgLayerW, newImgLayerH) ;

    document.getElementById("mapFrame").style.visibility = 'visible';
    document.getElementById("topMapFrame").style.visibility = 'visible';
	document.getElementById("sliderArea").style.visibility = 'visible';
	document.getElementById("map").style.visibility = 'visible';
	document.getElementById("mapimgLayer").style.visibility = 'visible';
	document.getElementById("toolBar").style.visibility = 'visible';
	document.getElementById("bottomMapFrame").style.visibility = 'visible';
	document.getElementById("toc").style.visibility = 'hidden';
	document.getElementById("refmap").style.visibility = 'hidden';
	document.getElementById("refmapBG").style.visibility = 'hidden';
	document.getElementById("bottom").style.visibility = 'visible';
    document.getElementById("feedback").style.visibility = 'visible';

	if(document.getElementById('assembly')!=null)
	{
		document.getElementById("assembly").style.visibility = 'visible';
	}
	
    // RELOAD MAP!!!
    var mapurl = 'x_load.php?'+SID+ '&mapW=' + newImgLayerW + '&mapH=' + newImgLayerH + '&zoom_type=zoompoint';
    updateMap(mapurl, ''); 
	swapToInfoView();
}


/**
 * Timer-controlled resize of map for stupid IE resize event behaviour
 */
var resize_timer; 
function initResize() {
    if (navigator.appName.indexOf("Microsoft")!=-1) {
        clearTimeout(resize_timer);
        resize_timer = setTimeout("resizeDiv()",500); 
    } else {
        resizeDiv();
    }
}



/**
 * 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);
	//s1 = 320000;
	s1 = 340070;
	//alert(s1);
}


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 = document.getElementById('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;
    //alert(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') {
            if (tdid != button) {
                rmHighlTD(tdid)
            } else {
                highlTD(tdid);
            }
        }
    }
}

function highlTD(elId) {
    var but = document.getElementById(elId);
    if (but) but.className='TOOLBARTD_ON';
}

function rmHighlTD(elId) {
    //alert(elId);
    var but = document.getElementById(elId);
    if (but) but.className='TOOLBARTD';
}


// Functions for MouseOver/Out
function TbOverOut(elId, status){
    var but = document.getElementById(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 = document.getElementById(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 = document.getElementById(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 = document.getElementById("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)";
    
    document.getElementById('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 = (internalCursor) ? 'help' : 'help';	
            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 = (internalCursor) ? 'crosshair' : 'crosshair';	
			break;
            
        default:
            var usedCursor = 'default';
    }
    
    document.getElementById('mapimgLayer').style.cursor = usedCursor;
    
}




/*
 * OPEN RESULT WINDOW FOR IDEBNTIFY AND SEARCH
 ***********************************************/
function openResultwin(winurl) {
    var w = window.open(winurl, "resultwin", "width=500,height=200,status=no,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");
   window.open("http://mapxl.com/india/help.html","win1","menubar=0, location=0, status=no, directories=no, toolbar=0, width=550 height=500,scrollbars=1,resizable=no,alwaysRaised=yes,cen,cen");
}
function shortpath() {
   // window.open("help.phtml", "help","width=400,height=500,status=no,resizable=yes");
   window.open("http://localhost/maplab/php/dist.php","win1","menubar=0, location=0, status=no, directories=no, toolbar=0, width=550 height=500,scrollbars=1,resizable=no,alwaysRaised=yes,cen,cen");
}

function openFeedback() {
   // window.open("help.phtml", "help","width=400,height=500,status=no,resizable=yes");
   window.open("http://mapxl.com/india/feedback/fetchfeedback.php","win1","menubar=0, location=0, status=no, directories=no, toolbar=0, width=600 height=670,scrollbars=0,resizable=no,alwaysRaised=yes,cen,cen");
}



/************************************************************************************
 * 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");
}



/************************************************************************** 
 * DISPLAY COORDINATES IN MORE THAN ONE COORDIMNATE SYSTEM
 **************************************************************************/
function showCoords(imgxy) {
    window.open("showcoords.phtml?"+SID + "&imgxy="+imgxy, "coords","width=280,height=130,status=no,resizable=no");
}

function openProjection() {
    window.open("projection.phtml", "projection","width=320,height=180,status=no,resizable=yes");
}





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) ? '' : (mpoint.x);
    var py = isNaN(mpoint.y) ? '' : (mpoint.y);
    
    var inserttxt = prompt(localeList['addLocation'], '');
    
    if (inserttxt) {
        //alert(inserttxt + ' --- ' + px + ' -- ' + py);
        //var ul = + px + ',' + py + ',' + inserttxt;
        var digitizeurl = 'x_poi.php?' +SID + '&up=' + px + '@@' + py + '@@' + escape(inserttxt);
        //alert(digitizeurl);
        addPOI(digitizeurl, '');
    }
    
}