﻿// map vars
var viewerBean = null;
var maximized = false;
var theme = "PirsNormalView";
var moveImageX = 0;
var moveImageY = 0;
var needsPngFilter = /(MSIE 6.0)|(MSIE 5.5)/.test(navigator.userAgent) && navigator.platform == "Win32";
var transparentTiles = (needsPngFilter == false) && false; // if this is false -> runs faster on ff and IE7, but not so sophisticated :-)
var showTLayerCnt = 0;
var disableTransparentLayer = false;
var initialZL = 9;

var mapAreaSearchEnabled = false;

var previousPositions = new Array(3);
previousPositions[0] = { 'x': 462210, 'y': 112371, 'z': 1 };
previousPositions[1] = { 'x': 462210, 'y': 112371, 'z': 1 };
previousPositions[2] = { 'x': 462210, 'y': 112371, 'z': 1 };
var prevPosIdx = 2;
var firstPos = true;

String.prototype.trim = function() { return this.replace(/(^\s+)|\s+$/g, "") }

glbEncoding = "SI";

var xmlHttp = false;
var xmlHttp2 = false;
var xmlHttp3 = false;

// create XMLhttpRequest objects
try {
    xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttp2 = new ActiveXObject("Msxml2.XMLHTTP");
    xmlHttp3 = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
    try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        xmlHttp2 = new ActiveXObject("Microsoft.XMLHTTP");
        xmlHttp23 = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e2) {
        xmlHttp = new XMLHttpRequest();
        xmlHttp2 = new XMLHttpRequest();
        xmlHttp3 = new XMLHttpRequest();
    }
}

var markerWorldX = 0;
var markerWorldY = 0;
var markerImageX = 0;
var markerImageY = 0;
var transparentXOffSet = 0;
var transparentYOffSet = 0;
var startWorldX = 0;
var startWorldY = 0;

var hotspotArray = new Array(); // Array of hotspots returned by WebService (commercials).
var hotspotcount = 0;

var hitsArray = new Array(); // Array of hits, which are also hot spots. Managed on client
var hitscount = 0;

var areaSearch = null;

function addNewLocation(xx, yy, n, a, p, t) {
    addNewLocation(xx, yy, n, a, p, t, 0);
}


function setOtherCoords(xx, yy, n, a, p, t) {
    setOtherCoords(xx, yy, n, a, p, t, 0);
}


function setCoords(xx, yy, n, a, p, t) {
    setCoords(xx, yy, n, a, p, t, 0);
}


function addNewLocation2(pid, action) {
    if (action == 1) {
        document.getElementById(glbrelayedPostbackContextControlId).value = 'AddFirstLocation|' + pid;
        doRelayedPostBack(glbrelayedPostbackTriggerControlId);
    } else if (action == 2) {
        document.getElementById(glbrelayedPostbackContextControlId).value = 'AddLastLocation|' + pid;
        doRelayedPostBack(glbrelayedPostbackTriggerControlId);
    }
}


function addNewLocation(xx, yy, n, a, p, t, option) {
    // TODO add to hitsarray

    if (option == 0)
        moveMapToZ(xx, yy, 9);

    // TODO optional UpdateSessionLocation(xx,yy,n,a,p,t,"ADD",option);
}


function removeLocation(xx, yy, option) {
    // TODO remove from hitsarray

    // TODO optional UpdateSessionLocation(xx, yy, '', '', '', '', "DELETE", null);	// option parameter irrelevant
}


function resetIcons() {
    hotspotcount = 0;
    hotspotArray = new Array();
}


function setIcon(wx, wy, xx, yy, hw, hotspotId, name, dataSource, iname) {
    hotspotArray[hotspotcount] = new Object();
    hotspotArray[hotspotcount].id = hotspotId;
    hotspotArray[hotspotcount].WX = parseInt(wx);
    hotspotArray[hotspotcount].WY = parseInt(wy);
    hotspotArray[hotspotcount].X = parseInt(xx);
    hotspotArray[hotspotcount].Y = parseInt(yy);
    hotspotArray[hotspotcount].HW = parseInt(hw);
    hotspotArray[hotspotcount].dataSource = dataSource;
    hotspotArray[hotspotcount].name = name;
    hotspotArray[hotspotcount].iconName = iname;

    hotspotcount++;
}


function resetAreaSearch() {
    areaSearch = null;
    var a = viewerBean.getCenterWorldCoord();
    showTransparentLayer(a.x, a.y);
}

function setAreaSearchRadius(r) {
    if (areaSearch == null)
        areaSearch = new Object();
    areaSearch.Radius = r;
    var a = viewerBean.getCenterWorldCoord();
    showTransparentLayer(a.x, a.y);
}

function setAreaSearchCenter(x, y) {
    if (!mapAreaSearchEnabled) {
        return;
    }

    if (areaSearch == null) {
        areaSearch = new Object();
        areaSearch.Radius = 5000;
    }
    areaSearch.x = x;
    areaSearch.y = y;
    var a = viewerBean.getCenterWorldCoord();
    showTransparentLayer(a.x, a.y);

    setPirsAreaSearchCoordinates(areaSearch);
    
    //alert('ax:' + areaSearch.x + 'ay:' + areaSearch.y + 'ar:' + areaSearch.Radius); 
}

function resetHits() {
    hitscount = 0;
    hitsArray = new Array();
}


function setHit(wx, wy, xx, yy, hw, hotspotId, name, iname) {
    hitsArray[hitscount] = new Object();
    hitsArray[hitscount].id = hotspotId;
    hitsArray[hitscount].WX = parseInt(wx);
    hitsArray[hitscount].WY = parseInt(wy);
    hitsArray[hitscount].X = parseInt(xx);
    hitsArray[hitscount].Y = parseInt(yy);
    hitsArray[hitscount].HW = parseInt(hw);
    hitsArray[hitscount].name = name;
    hitsArray[hitscount].iconName = iname;
    hitsArray[hitscount].enabled = true;

    hitscount++;
}




var cmname;
var cmaddress;
var cmstreet;
var cmpost;
var cmtel;
var cmhnr;
var cmx;
var cmy;
var cmscreenx;
var cmscreeny;

/*function _drawSpot(x, y, d, i) {
    var _drawOffsetX = 198;
    var _drawOffsetY = 395;
    var body = window.document.getElementsByTagName("body")[0];
    var div = window.document.createElement("div");

    div.style.position = "absolute";
    div.style.borderStyle = "solid";
    div.style.borderWidth = "1px";
    div.style.borderColor = "red";
    div.style.left = (x + _drawOffsetX) + "px";
    div.style.top = (y + _drawOffsetY) + "px";
    div.style.width = div.style.height = d * 2 + "px";
    div.style.zIndex = 1000;
    div.innerHTML = i;
    body.appendChild(div);
}*/


function checkIconPosition(xx, yy) {
    var info = "";
    var joindIdx = -1;

    for (i = 0; i < hotspotcount; i++) {
        //_drawSpot(hotspotArray[i].X, hotspotArray[i].Y, hotspotArray[i].HW, i);

        if (hotspotArray[i].X + transparentXOffSet - hotspotArray[i].HW < xx &&
			hotspotArray[i].X + transparentXOffSet + hotspotArray[i].HW > xx &&
			hotspotArray[i].Y + transparentYOffSet - hotspotArray[i].HW < yy &&
			hotspotArray[i].Y + transparentYOffSet + hotspotArray[i].HW > yy)
		{
            var text = hotspotArray[i].name;
            var hsid = hotspotArray[i].id;
            var hshw = hotspotArray[i].HW;

            var ok = true;

            //alert(text + "-"+ hsid + "-"+ hshw);
            //alert(hotspotArray[i].dataSource);
            if (hotspotArray[i].dataSource == "tmapcomm") {
                //alert(hsid);
                DisableMapSpots();
                if (hotspotArray[i].iconName == 191)	// oka
                    showOKx("OKA", hsid, (hotspotArray[i].X + transparentXOffSet) - 5, (hotspotArray[i].Y + transparentYOffSet) - 5);
                else if (hotspotArray[i].iconName == 192)	// okb
                    showOKx("OKB", hsid, (hotspotArray[i].X + transparentXOffSet) - 5, (hotspotArray[i].Y + transparentYOffSet) - 5);
                else if (hotspotArray[i].iconName == 193)	// okc
                    showOKx("OKC", hsid, (hotspotArray[i].X + transparentXOffSet) - 5, (hotspotArray[i].Y + transparentYOffSet) - 5);
                else {
                    info += hsid + ";";
                    joindIdx = i;
                    ok = false;
                }
            }

            if (ok) {
                return true;
            }
        }
    }

    if (info != "") {
        showOKx("OKX", info, (hotspotArray[joindIdx].X + transparentXOffSet) - 5, (hotspotArray[joindIdx].Y + transparentYOffSet) - 5);
        return true;
    }

    curiconindex = 0;

    //pointerHolder(xx + viewerBean.left, yy + viewerBean.top);
    // find in markers
    for (var i = 0; i < hitscount; i++) {
        var screenCoord = viewerBean.getScreenCoord(hitsArray[i].WX, hitsArray[i].WY);

        /*stickFlag(screenCoord.x + viewerBean.left, screenCoord.y + viewerBean.top);
        writeHere(viewerBean.width + " x " + viewerBean.height +
            "<br />tl: " + viewerBean.left + ", " + viewerBean.top +
            "<br />xy: " + viewerBean.x + ", " + viewerBean.y +
            "<br />Cxy:" + viewerBean.currentX + ", " + viewerBean.currentY);*/

        if (screenCoord.x - hitsArray[i].HW < xx &&
			screenCoord.x + hitsArray[i].HW > xx &&
			screenCoord.y - hitsArray[i].HW < yy &&
			screenCoord.y + hitsArray[i].HW > yy &&
			hitsArray[i].enabled == true)
		{
            //alert(hotspotcount);
		    //alert(hitsArray[i].iconName);
		    moveMapToZ(hitsArray[i].WX, hitsArray[i].WY, viewerBean.zoomLevel);
		    screenCoord = viewerBean.getScreenCoord(hitsArray[i].WX, hitsArray[i].WY);
		    showOKx(hitsArray[i].iconName /*"HIT"*/, hitsArray[i].id, screenCoord.x, screenCoord.y);

            return true;
        }
    }

    return false;
}


function checkIconClick(xx, yy) {
    for (i = 0; i < hotspotcount; i++) {
        if (hotspotArray[i].X + transparentXOffSet - hotspotArray[i].HW < xx &&
			hotspotArray[i].X + transparentXOffSet + hotspotArray[i].HW > xx &&
			hotspotArray[i].Y + transparentYOffSet - hotspotArray[i].HW < yy &&
			hotspotArray[i].Y + transparentYOffSet + hotspotArray[i].HW > yy)
		{
            return iconClick(hotspotArray[i].X, iconarray[i].Y, hotspotArray[i].dataSource, hotspotArray[i].id);
            //return true;
        }
    }

    return false;
}


function iconClick(xx, yy, dataSource, hotspotId) {
    if (dataSource == "tmapcomm") {
        return false;
    } else {
        link = getSite() + "MapShowHotSpot.aspx?" + ("dataSource=" + dataSource + "&hotspotId=" + hotspotId);
    }

    if (window.opener) {
        try {
            window.opener.location = link;
            window.opener.focus();
        } catch (e) {
            xwin = window.open(link); // fix this!
            if (xwin)
                xwin.focus();
        }
    } else {
        xwin = window.open(link); // fix this!
        if (xwin)
            xwin.focus;
    }

    return true;
}


function printThisLocation(x, y, name, address, post, tel) {
    addNewLocation(x, y, name, address, post, tel, 1);
    printCurrentView();
}


function printCurrentView() {
    var markers = "";

    // get points from hitsarray
    if (hitsArray != null) {
        for (i = 0; i < hitscount; i++) {
            markers += hitsArray[i].WX + "," + hitsArray[i].WY + "," + hitsArray[i].iconName;
            if (i + 1 < hitscount)
                markers += ";";
        }
    }

    oTheme = _miniMapHandler.selectedMapViewType;
    var curZoom = getCurrentRealZoom();
    var a = viewerBean.getCenterWorldCoord();
    xwin = window.open(pirsApplicationPath + "PrintMap.aspx?" + "size=" + viewerBean.width + "&x=" + a.x + "&y=" + a.y + "&zoom=" + curZoom + "&theme=" + oTheme + "&RouteID=" + MapPath.RouteID + "&markers=" + markers + "&printPicture=0"), "mapprint", 'toolbar=no,location=no,scrollbars=yes,status=yes,width=980,height=720';
    if (xwin)
        xwin.focus();
}


function getMapLink2(publicationIDs, pathIDs) {
    // TODO page file

    oTheme = _miniMapHandler.selectedMapViewType;

    var curZoom = getCurrentRealZoom();
    var a = viewerBean.getCenterWorldCoord();
    var url = "dl=1&x=" + a.x + "&y=" + a.y + "&zl=" + viewerBean.zoomLevel + "&theme=" + oTheme;

    var hfPathIds = document.getElementById(pathIDs);
    var hfIds = document.getElementById(publicationIDs);

    if (hfPathIds != null) {
        if (hfPathIds.value.toString().length > 0) {
            if (MapPath.RouteID != null && MapPath.RouteID != "")
                url += "&path=1";
            url += "&markers=" + hfPathIds.value.toString();
        }
    } else if ((hfIds != null) && (hfIds.value.toString().length > 0)) {
        url += "&ids=" + hfIds.value.toString();
    }

    this.location = getSite() + "Page_Map.aspx?" + url;
}



var contextMenuDataCoord;
var contextMenuDataEvent;
function showContextMenu(coord, e) {
    //hideNearBySearchForm();

    contextMenuDataCoord = coord;
    contextMenuDataEvent = e;
    //document.getElementById('rightClickMenu').style.display = 'block';
    //document.getElementById('rightClickMenu').style.top = (coord.y - 10) + "px";
    //document.getElementById('rightClickMenu').style.left = (coord.x - 10) + "px";

    var wcoord = viewerBean.getCurrentWorldCoord(contextMenuDataCoord.x, contextMenuDataCoord.y);

    setAreaSearchCenter(wcoord.x, wcoord.y);

    e.cancelBubble = true;
    e.returnValue = false;

    return false;
}


function hideContextMenu() {
    //document.getElementById('rightClickMenu').style.display = 'none';
    //document.getElementById('rightClickMenu').style.top = -100 + "px";
    //document.getElementById('rightClickMenu').style.left = -100 + "px";
    //hideNearBySearchForm();
    closeCloudMessage();
}


function hideNearBySearchForm() {
    document.getElementById('nearBySearch').style.display = 'none';
    document.getElementById('nearBySearch').style.top = -100 + "px";
    document.getElementById('nearBySearch').style.left = -100 + "px";
}


function startNearBySearch() {
    hideNearBySearchForm();
    var wcoord = viewerBean.getCurrentWorldCoord(contextMenuDataCoord.x, contextMenuDataCoord.y);

    if (document.getElementById('inputNearBySearchWhat').value == "") {
        alert("Polje Kaj je obvezno!");

        return;
    }

    alert("koordinate izhodišča: x " + wcoord.x + " y " + wcoord.y + " - radij " + document.getElementById('inputNearBySearchRadij').value);
    //findNearBy(document.getElementById('inputNearBySearchWhat').value, document.getElementById('inputNearBySearchRadij').value, wcoord.x, wcoord.y);
}


function contextMenuAction(action) {
    hideContextMenu();

    if (action == 1) {
        viewerBean.zoom(getZoomStep(-1));
    } else if (action == 2) {
        viewerBean.zoom(getZoomStep(1));
    } else if (action == 3) {
        var wcoord = viewerBean.getCurrentWorldCoord(contextMenuDataCoord.x, contextMenuDataCoord.y);
        ResolveCoordinate(wcoord.x, wcoord.y, 1);
    } else if (action == 4) {
        var wcoord = viewerBean.getCurrentWorldCoord(contextMenuDataCoord.x, contextMenuDataCoord.y);
        ResolveCoordinate(wcoord.x, wcoord.y, 2);
    } else if (action == 5) {
        var wcoord = viewerBean.getCurrentWorldCoord(contextMenuDataCoord.x, contextMenuDataCoord.y);
        ResolveCoordinate(wcoord.x, wcoord.y, 3);
    } else if (action == 6) {
        document.getElementById('nearBySearch').style.display = 'block';
        document.getElementById('nearBySearch').style.top = (contextMenuDataCoord.y + 20) + "px";
        document.getElementById('nearBySearch').style.left = (contextMenuDataCoord.x - 10) + "px";
    } else if (action == 7) {
        var wcoord = viewerBean.getCurrentWorldCoord(contextMenuDataCoord.x, contextMenuDataCoord.y);
        ResolveCoordinate(wcoord.x, wcoord.y, 4);
    }
}


function showCloudMessage(x, y, entry) {
    // TODO map popup
}


function closeCloudMessage() {
    // TODO close map popup
}


/*
var mousePressed = false;
var pressedCoord = null;
function muMapCommercial(event) {
    mousePressed = false;
    document.getElementById('mapCommercial').style.cursor = GSIV.GRAB_MOUSE_CURSOR;
}


function mdMapCommercial(e) {
    mousePressed = true;
    pressedCoord = {'x': e.clientX, 'y': e.clientY};
    document.getElementById('mapCommercial').style.cursor = GSIV.GRABBING_MOUSE_CURSOR;
}


function moveMapCommercial(e) {
    if (mousePressed) {
        var dx = pressedCoord.x - e.clientX;
        var dy = pressedCoord.y - e.clientY;

        tmpstr = document.getElementById('mapCommercial').style.top;
        tmpstr.replace("px", "");
        var cy = parseInt(tmpstr);
        tmpstr = document.getElementById('mapCommercial').style.left;
        tmpstr.replace("px", "");
        var cx = parseInt(tmpstr);

        document.getElementById('mapCommercial').style.top = (cy - dy) + "px";
        document.getElementById('mapCommercial').style.left = (cx - dx) + "px";
        pressedCoord = {'x': e.clientX, 'y': e.clientY};
    }
}


function clearMapCommercialTimeout() {
    if (mapCommercialTID) {
        clearTimeout(mapCommercialTID);
        mapCommercialTID = null;
    }
}


function setMapCommercialTimeout() {
    clearMapCommercialTimeout();

    if (document.getElementById('mapCommercial').style.display != 'none') {
        mapCommercialTID = setTimeout("closeMapCommercial();", 100);
    }
}


function closeMapCommercial() {
    document.getElementById('mapCommercial').style.display = 'none';
    document.getElementById('mapCommercial').style.top = -100 + "px";
    document.getElementById('mapCommercial').style.left = -100 + "px";
    document.getElementById('mapCommercialText').innerHTML = "";
}


function muMapCommercialOKA(event) {
    mousePressed = false;
    document.getElementById('mapCommercialOKA').style.cursor = GSIV.GRAB_MOUSE_CURSOR;
}

function mdMapCommercialOKA(e) {
    mousePressed = true;
    pressedCoord = {'x': e.clientX, 'y': e.clientY};
    document.getElementById('mapCommercialOKA').style.cursor = GSIV.GRABBING_MOUSE_CURSOR;
}

function moveMapCommercialOKA(e) {
    if (mousePressed) {
        var dx = pressedCoord.x - e.clientX;
        var dy = pressedCoord.y - e.clientY;

        tmpstr = document.getElementById('mapCommercialOKA').style.top;
        tmpstr.replace("px", "");
        var cy = parseInt(tmpstr);
        tmpstr = document.getElementById('mapCommercialOKA').style.left;
        tmpstr.replace("px", "");
        var cx = parseInt(tmpstr);

        document.getElementById('mapCommercialOKA').style.top = (cy - dy) + "px";
        document.getElementById('mapCommercialOKA').style.left = (cx - dx) + "px";

        pressedCoord = {'x': e.clientX, 'y': e.clientY};
    }
}


function clearMapCommercialOKATimeout() {
    if (mapCommercialOKATID) {
        clearTimeout(mapCommercialOKATID);
        mapCommercialOKATID = null;
    }
}


function setMapCommercialOKATimeout() {
    clearMapCommercialOKATimeout();

    if (document.getElementById('mapCommercialOKA').style.display != 'none') {
        mapCommercialOKATID = setTimeout("closeMapCommercialOKA();", 200);
    }
}


function closeMapCommercialOKA() {
    document.getElementById('mapCommercialOKA').style.display = 'none';
    document.getElementById('mapCommercialOKA').style.top = -100 + "px";
    document.getElementById('mapCommercialOKA').style.left = -100 + "px";
    document.getElementById('mapCommercialOKAText').innerHTML = "";
}
*/


// Map initialization
function getCurrentRealZoom() {
    return getRealZoom(viewerBean.zoomLevel);
}


function getRealZoom(zoomLevel) {
    return 1000 * Math.pow(2, 12 - zoomLevel);
}


function getZoomLevel(realZoom) {
    return 12 - Math.ceil(Math.log(realZoom / 1000) / Math.log(2));
}


function viewerZoomed(ze) {
    // page global object of type MapZoomGauge
    _mapZoomGauge.zoomToLevel(ze.level);
    document.getElementById("scaleImage").src = pirsApplicationPath + "map/assets/gfx/scale" + ze.level + ".gif";

    viewerZoom();
}


function viewerZoom() {
    CloseAllMapCloudBaloons();
    DisableMapSpots();

    var b = viewerBean.getImageCoord(markerWorldX, markerWorldY);
    var c = viewerBean.getScreenCoord(markerWorldX, markerWorldY);

    markerImageX = b.x;
    markerImageY = b.y;

    var a = viewerBean.getCenterWorldCoord();
    showTransparentLayer(a.x, a.y);
}


function viewerMoved(me) {
    //CloseAllMapCloudBaloons();
    DisableMapSpots();

    var newmarkerX = viewerBean.width / 2 - viewerBean.currentX;
    var newmarkerY = viewerBean.height / 2 - viewerBean.currentY;

    if (transparentTiles == false) {
        document.getElementById('transparent').style.top = parseInt(document.getElementById('transparent').style.top) + (moveImageY - newmarkerY) + "px";
        document.getElementById('transparent').style.left = parseInt(document.getElementById('transparent').style.left) + (moveImageX - newmarkerX) + "px";
    }

    document.getElementById('cloudMessageBox').style.top = parseInt(document.getElementById('cloudMessageBox').style.top) + (moveImageY - newmarkerY) + "px";
    document.getElementById('cloudMessageBox').style.left = parseInt(document.getElementById('cloudMessageBox').style.left) + (moveImageX - newmarkerX) + "px";
    
    transparentXOffSet += (moveImageX - newmarkerX);
    transparentYOffSet += (moveImageY - newmarkerY);

    moveImageX = newmarkerX;
    moveImageY = newmarkerY;
}


function viewerMoveStoped(me) {
    var a = viewerBean.getCenterWorldCoord();
    showTransparentLayer(a.x, a.y);
}


function initializeGraphic(e) {
    // opera triggers the onload twice
    if (viewerBean == null) {
        var maxZoomS = 12;

        viewerBean = new GSIV('viewer', {
            tileBaseUri: pirsApplicationPath + 'GetMap.ashx',
            tileSize: 256,
            tilePrefix: '',
            tileExtension: 'png', //jpg
            maxZoom: maxZoomS,
            initialZoom: 1,
            blankTile: pirsApplicationPath + 'map/assets/gfx/blank.gif',
            loadingTile: pirsApplicationPath + 'map/assets/gfx/blank.gif' //'map/assets/gfx/greenBk.gif'//#CEF2BF //'map/assets/gfx/progress.gif'
        });

        document.getElementById('viewer').style.height = document.documentElement.clientHeight - 95 + "px"; //'600px';
        document.getElementById('surfaceImg').style.height = document.documentElement.clientHeight - 95 + "px";
        document.getElementById('surfaceImg').style.width = document.documentElement.clientWidth - glb_ViewerBeanWidthOffset + "px"; //270

        //viewerBean.fitToWindow(0);
        viewerBean.init();
        //viewerBean.recenter({'x':400 ,'y':800}, true);

        viewerBean.addViewerZoomedListener(this);
        viewerBean.addViewerMovedListener(this);
        viewerBean.addViewerMoveStopedListener(this);

        var offset = 125;
        //if (window.document.getElementById("DropDownListCityMaps") == null)
        //	offset = 110;
        var zoompos = parseInt(offset - 3 * 7.7);

        AfterInitialization();

        if (markerWorldX != 0) {
            moveMapToZ2(markerWorldX, markerWorldY, initialZL, true);
        }

        if (startWorldX != 0 && startWorldX != markerWorldX)
            moveMapToZ2(startWorldX, startWorldY, initialZL, true);

    }
}


function isUserAgent(distinctUserAgentNameSubstring) {
    return (navigator.userAgent.toLowerCase().indexOf(distinctUserAgentNameSubstring.toLowerCase()) != -1);
}


// (un)maximizes map
//var skipNextIEResizeEvent = false;  // for skipping IE redundant resize sub-events
function toggleMapSize(e) {
    // skip redundant resize sub-event
    /*if (glb_browserIsIE && skipNextIEResizeEvent && e != null && e.type == "resize" && !maximized) {
        skipNextIEResizeEvent = false;
        maximized = false;
        reinitializeGraphic(e);
        return;
    }

    // detect precondition for skipping redundant resize sub-event
    if (glb_browserIsIE && !skipNextIEResizeEvent && e == null && maximized) {
        skipNextIEResizeEvent = true;
    }*/

    var sidePanel = window.document.getElementById("sidePanelPath");
    var mapContainer = window.document.getElementById("mapContainer");

    if (maximized) {
        if (sidePanel) {
            sidePanel.style.display = "block";
        }

        SetMapSize(650, 678);

        maximized = false;

        if (glb_browserIsIE)
            mapContainer.style.marginTop = "";

        reinitializeGraphic(e);
    } else {
        if (sidePanel) {
            sidePanel.style.display = "none";
        }

        /*var calcWidth = 0;
        var calcHeight = 0;
        if (window.innerWidth) {
            calcWidth = window.innerWidth;
            calcHeight = window.innerHeight;
        } else {
            calcWidth = (document.compatMode == 'CSS1Compat' ? document.documentElement.clientWidth : document.body.clientWidth);
            calcHeight = (document.compatMode == 'CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight);
        }

        calcHeight -= 20;
        calcWidth -= 24;

        if (calcWidth % 2)
            calcWidth--;

        if (calcHeight % 2)
            calcHeight--;

        // compensate for possible scroll bars
        calcWidth -= (document.documentElement.scrollLeft || document.body.scrollLeft);
        calcHeight -= (document.documentElement.scrollTop || document.body.scrollTop);

        SetMapSize(calcWidth, calcHeight);*/
        SetMapSize(904, 678);
        viewerZoom();

        /*if (glb_browserIsIE)
            mapContainer.style.marginTop = "8px";*/

        maximized = true;
    }


    CloseAllMapCloudBaloons();
}



/*************
Map navigation
*************/

function zoomMapTo(z) {
    if (viewerBean != null) {

        if (z > viewerBean.maxZoomLevel)
            z = viewerBean.maxZoomLevel;

        var zoomdir = z - viewerBean.zoomLevel;
        viewerBean.zoom(zoomdir);
    }
}


function moveMapToZ2(x, y, z, disableSlide) {
    if (viewerBean == null) {
        if (MapPath.RefreshPathRequested == null && x != 0 && y != 0) {	// coordinates must be different than (0,0)
            // issue show hit request on first load (handled sometime during page load event)
            MapPath.RefreshPathRequested = "moveMapToZ2(" + x + ", " + y + ", " + z + ", " + disableSlide + ");";
        }

        return;
    }

    if (viewerBean != null) {
        disableTransparentLayer = true;
        viewerBean.moveToPosition(x, y, z, disableSlide);

        disableTransparentLayer = false;
        showTransparentLayer(x, y);
    }
}


function moveMapToZ(x, y, z) {
    // Disabled slide because of problems in IE
    moveMapToZ2(x, y, z, true);
}


function moveMapTo(x, y) {
    if (viewerBean != null)
        viewerBean.moveToPosition(x, y, viewerBean.zoomLevel, false);
}


function reloadMap() {
    moveMapTo(markerWorldX, markerWorldY);
}


function moveMapBack() {
    var pos = previousPositions[prevPosIdx - 1];

    moveMapToZ2(pos.x, pos.y, pos.z, true);
}


function getZoomStep(zs) {
    if (zs > 0) {
        return 1;
    } else {
        return -1;
    }
}


function showTransparentLayer(x, y) {
    var prevPos = previousPositions[prevPosIdx];
    if (!(prevPos.x == x && prevPos.y == y)) {
        if (firstPos) {
            firstPos = false;
        } else if (y > 28000 && y < 200000 && x > 370000 && x < 630000) {
            previousPositions[prevPosIdx - 2] = previousPositions[prevPosIdx - 1];
            previousPositions[prevPosIdx - 1] = previousPositions[prevPosIdx];

            previousPositions[prevPosIdx] = { 'x': x, 'y': y, 'z': viewerBean.zoomLevel };
        }
    }

    UpdateMiniMap(x, y);
    if (disableTransparentLayer)
        return;

    var markersstr = "";
    // zakodiramo informacijo o tipku ikone v koordinato
    for (i = 0; i < hitscount; i++) {
        markersstr += hitsArray[i].WX + "," + hitsArray[i].WY + "," + hitsArray[i].iconName;
        if (i + 1 < hitscount)
            markersstr += ";";
    }

    hotspotEnabled = markersstr != "" && viewerBean.zoomLevel >= 0;
    
    if (hotspotEnabled) {
        try {
            GetHotSpotData(x, y);
        } catch (eee) {
        }
    } else {
        resetIcons();
    }

    transparentXOffSet = 0;
    transparentYOffSet = 0;

    if (transparentTiles == false && (hotspotEnabled || MapPath.RouteID != "" || areaSearch != null)) {
        var curZoom = getCurrentRealZoom();

        // show buslines & peaks
        var addlstr = ";"; // additional layers

        var asp = "";
        if (areaSearch != null && areaSearch.Radius > 0) {
            asp = "&ASP=" + areaSearch.x + "," + areaSearch.y + ',' + areaSearch.Radius;
        }

        var params = "nocrop=1&zoom=" + curZoom + "&x=" + x + "&y=" + y + "&sizex=" + viewerBean.width + "&sizey=" + viewerBean.height + "&theme=TransparentViewS:Tile" + addlstr + "&RouteID=" + MapPath.RouteID + "&markers=" + markersstr + asp;

        //alert(params);

        var address = pirsApplicationPath + "GetMap.ashx?" + "type=map&" + params;
        
        document.getElementById('transparentImage').style.width = viewerBean.width + "px";
        document.getElementById('transparentImage').style.height = viewerBean.height + "px";

        if (needsPngFilter) {
            document.getElementById('transparentImage').style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + address + "', sizingMethod='scale', enabled='true')";
            ShowTransparentImg();
        } else {
            document.getElementById('transparentImage').src = address;
        }
    } else {
        document.getElementById('transparent').style.display = 'none';
    }

    moveImageX = viewerBean.width / 2 - viewerBean.x;
    moveImageY = viewerBean.height / 2 - viewerBean.y;
}


function ShowTransparentImg() {
    document.getElementById('transparent').style.top = '0px';
    document.getElementById('transparent').style.left = '0px';
    document.getElementById('transparent').style.display = 'block';
}


function GetHotSpotData(x, y) {
    DisableMapSpots();

    var curZoom = getCurrentRealZoom();
    var params = "nocrop=1&zoom=" + curZoom + "&x=" + x + "&y=" + y + "&sizex=" + viewerBean.width + "&sizey=" + viewerBean.height + "&theme=TransparentViewS:Tile&RouteID=" + MapPath.RouteID;
    var address = pirsApplicationPath + "GetMap.ashx?" + "type=hotspots2&" + params;
    
    if (xmlHttp.readyState == 2 || xmlHttp.readyState == 3)
        xmlHttp.abort();

    xmlHttp.open("GET", address, true);

    // Setup a function for the server to run when it's done
    xmlHttp.onreadystatechange = ProcessDataHS;
    xmlHttp.send(null);

    return true;
}


function ProcessDataHS() {
    // data must be in the following form:
    DisableMapSpots();

    if (xmlHttp.readyState == 4) {
        for (hitsi = 0; hitsi < hitscount; hitsi++) {
            hitsArray[hitsi].enabled = true;
        }

        resetIcons();

        var response = new String();
        response = xmlHttp.responseText;
        var p1 = response.indexOf("<hotspots>");
        if (p1 == 0)
            p1 += 10;
        //alert(response);

        p1 = response.indexOf("<hotspot>", p1);
        while (p1 > 0) {
            p1 += 9;
            var p2 = response.indexOf("</hotspot>", p1);
            var hsl = response.substr(p1, p2 - p1);

            p1 = p2 + 10;
            p1 = response.indexOf("<hotspot>", p1);

            hsinfo = hsl.split("|");
            setIcon(hsinfo[0], hsinfo[1], hsinfo[2], hsinfo[3], hsinfo[4], hsinfo[5], hsinfo[6], hsinfo[7], hsinfo[8]);

            for (hitsi = 0; hitsi < hitscount; hitsi++) {
                if (hitsArray[hitsi].WX == hsinfo[0] && hitsArray[hitsi].WY == hsinfo[1]) {
                    hitsArray[hitsi].enabled = false;
                    //alert(hitsArray[hitsi]);
                }
            }
        }

        DisableMapSpots();
    }
}


function UpdateSessionLocation(x, y, n, a, p, t, method, option) {
    rndNum = Math.random();
    if (method == "ADD")
        strLink = "newMapAjaxHelper.aspx?" + ("method=ADDLOC&X=" + x + "&Y=" + y + "&n=" + n + "&a=" + a + "&p=" + p + "&t=" + t + "&r=" + rndNum + "&op=" + option); // option represents point of insertion (1 - first, 2 - last, 3 - before last if more than 2 locations in list)
    else if (method == "DELETE")
        strLink = "newMapAjaxHelper.aspx?" + ("method=REMLOC&X=" + x + "&Y=" + y + "&n=" + n + "&a=" + a + "&p=" + p + "&t=" + t + "&r=" + rndNum);
    else if (method == "MOVE")
        strLink = "newMapAjaxHelper.aspx?" + ("method=MOVELOC&X=" + x + "&Y=" + y + "&n=" + n + "&a=" + a + "&p=" + p + "&t=" + t + "&r=" + rndNum + "&op=" + option); // option represents move direction of object in list (1 up, -1 down)

    if (xmlHttp2.readyState == 2 || xmlHttp2.readyState == 3)
        xmlHttp2.abort();

    xmlHttp2.open("GET", strLink, true);

    // Setup a function for the server to run when it's done
    xmlHttp2.onreadystatechange = ProcessDataUSL;
    xmlHttp2.send(null);

    return true;
}


function ProcessDataUSL() {
    if (xmlHttp2.readyState == 4) {
    }
}


function ResolveCoordinate(x, y, action) {
    rndNum = Math.random();
    strLink = "newMapAjaxHelper.aspx?" + ("method=RESOLVECOORD&TIS=1&ACT=" + action + "&X=" + x + "&Y=" + y + "&r=" + rndNum);

    if (xmlHttp3.readyState == 2 || xmlHttp3.readyState == 3)
        xmlHttp3.abort();

    xmlHttp3.open("GET", strLink, true);

    // Setup a function for the server to run when it's done
    xmlHttp3.onreadystatechange = ProcessDataRCoord;
    xmlHttp3.send(null);

    return true;
}


function ProcessDataRCoord() {
    if (xmlHttp3.readyState == 4) {
        var response = new String();
        response = xmlHttp3.responseText;
        //alert(response);

        address = response.split(" -*- ");
        if (address.length > 5) {
            var action = address[0];
            if (action == "1") {	// insert first
                //addNewLocation(address[5], address[6], address[4], address[2] + ' ' + address[3], address[1], '', 1);
                document.getElementById(glbrelayedPostbackContextControlId).value = 'AddFirstLocation|' + address[8];
                doRelayedPostBack(glbrelayedPostbackTriggerControlId);
            } else if (action == "2") {	// append last
                //addNewLocation(address[5], address[6], address[4], address[2] + ' ' + address[3], address[1], '', 2);
                document.getElementById(glbrelayedPostbackContextControlId).value = 'AddLastLocation|' + address[8];
                doRelayedPostBack(glbrelayedPostbackTriggerControlId);
            } else if (action == "3") {
                findInTis(address[2], address[3], address[1], address[7])
            } else if (action == "4") {	// insert before last if more than 2 in list
                addNewLocation(address[5], address[6], address[4], address[2] + ' ' + address[3], address[1], '', 3);
            }
        }
    }

}


function getSite() {
    return "";

    var loc = new String();
    loc = window.location.href;
    pos2 = loc.lastIndexOf("/");
    if (pos2 > 0)
        loc = loc.substring(0, pos2 + 1);
    else
        loc = "";

    return loc;
}




function findNearBy(what, radius, x, y) {
    link = "FROMMAP=3&what=" + what + "&x=" + x + "&y=" + y + "&rad=" + radius;

    link = getSite() + "default.aspx?" + (link);

    if (window.opener) {
        try {
            window.opener.location = link;
            window.opener.focus();
        } catch (e) {
            xwin = window.open(link); // fix this!
            if (xwin)
                xwin.focus();
        }
    } else {
        xwin = window.open(link); // fix this!
        if (xwin)
            xwin.focus;
    }
}

// -- Map navigation -- end



/**********************
Map's zoom gauge object
**********************/

// constants
MapZoomGauge.ZOOM_LEVEL_MAX = 12;
MapZoomGauge.ZOOM_LEVEL_MIN = 1;

// properties
MapZoomGauge.zoomLevel = MapZoomGauge.ZOOM_LEVEL_MIN;
MapZoomGauge.zoomSliderControlID = "";
MapZoomGauge.zoomSliderInitialTopOffset = 0;
MapZoomGauge.zoomSliderStepHeight = 0;
MapZoomGauge.debugElementID = null;

// constructors
function MapZoomGauge(initialZoomLevel, zoomSliderControlID, zoomSliderInitialTopOffset, zoomSliderStepHeight, debugElementID) {
    this.zoomLevel = initialZoomLevel;
    this.zoomSliderControlID = zoomSliderControlID;
    this.zoomSliderInitialTopOffset = zoomSliderInitialTopOffset;
    this.zoomSliderStepHeight = zoomSliderStepHeight;
    this.debugElementID = debugElementID;
}

// methods
MapZoomGauge.prototype.zoomToLevel = function(level) {
    this.zoomLevel = level;
    window.document.getElementById(this.zoomSliderControlID).style.top = Math.floor(this.zoomSliderInitialTopOffset + (MapZoomGauge.ZOOM_LEVEL_MAX - level) * this.zoomSliderStepHeight) + "px";

    // debug
    if (this.debugElementID) {
        window.document.getElementById(this.debugElementID).innerHTML = "zoom: " + this.zoomLevel;
    }
}

// -- MapZoomGauge -- end



var OKxReqX = -10;
var OKxReqY = -10;
var forceOpenBaloon = false;
var BaloonOpenedFromHit = false;

var inOKXSearch = false;
function showOKx(typeOKx, id, x, y) {
    if (inOKXSearch)
        return;

    CloseAllMapCloudBaloons();
    forceOpenBaloon = false;
    BaloonOpenedFromHit = false;
    //inOKXSearch = true;
    mapHit(id, x, y);
    //PIRSSearch.FindOKx(typeOKx, id, SucceededShowOKxCallback);
    OKxReqX = x;
    OKxReqY = y;
}


function showOKxFromList(typeOKx, id) {
    CloseAllMapCloudBaloons();
    forceOpenBaloon = true;
    BaloonOpenedFromHit = false;
    //PIRSSearch.FindOKx(typeOKx, id, SucceededShowOKxCallback);
}


function showOKxFromHit(typeOKx, id) {
    CloseAllMapCloudBaloons();
    forceOpenBaloon = true;
    BaloonOpenedFromHit = true;
    OKxReqX = viewerBean.width / 2 - 4;
    OKxReqY = viewerBean.height / 2;
    //PIRSSearch.FindOKx(typeOKx, id, SucceededShowOKxCallback);

}


function CleanPhone(ph) {
    posokl = ph.indexOf(')', 0);
    ph = ph.substring(posokl + 1);
    ph = ph.replace(' ', '');
    ph = ph.replace(' ', '');
    ph = ph.replace(' ', '');

    return ph;
}


function SucceededShowOKxCallback(result) {
    inOKXSearch = false;

    if (result == null)
        return;

    cmname = result.miniTisRecord.name;
    cmaddress = result.miniTisRecord.street + " " + result.miniTisRecord.hnr;
    cmstreet = result.miniTisRecord.street;
    cmhnr = result.miniTisRecord.hnr;
    cmpost = result.miniTisRecord.postnr;
    cmtel = result.miniTisRecord.telephone;
    cmx = result.miniTisRecord.x;
    cmy = result.miniTisRecord.y;
    cmscreenx = OKxReqX;
    cmscreeny = OKxReqY;

    if (result.presentation.cloudType == "")
        result.presentation.cloudType = "HIT";

    _mapCloudsHandler.setContent(result.presentation.cloudType,
						OKxReqX,
						OKxReqY,
						result.presentation.id,
						result.presentation.info,
						result.presentation.contacts,
						result.presentation.activities,
						result.presentation.logo,
						result.presentation.videoOKCOnly,
						result.presentation.imageOKBOnly,
						result.presentation.promotion,
						result.presentation.tool1,
						result.presentation.tool2,
						result.presentation.tool3,
						result.presentation.tool4,
						result.presentation.tool5);

    if (forceOpenBaloon) {
        window.document.getElementById("mapCloud" + result.presentation.cloudType + "Baloon").style.display = "block";
        window.setTimeout('BaloonOpenedFromHit = false;', 500);
    }
}


function DisableMapSpots() {
    // TODO mappopup
}


function CloseAllMapCloudBaloons() {
    var cloudMessageBoxElement = document.getElementById('cloudMessageBox');
    if (cloudMessageBoxElement) {
        cloudMessageBoxElement.style.display = 'none';
    }
}



/*************************
Map's cluds handler object
*************************/

// constants
MapCloudsHandler.OFFSET_CORRECTION_X = 38;
MapCloudsHandler.OFFSET_CORRECTION_Y = -91;
MapCloudsHandler.BALOON_HIDE_TIMEOUT = 500;

// properties
MapCloudsHandler.baloonClosingTimerID = null;
MapCloudsHandler.debugElementID = null;

// constructors
function MapCloudsHandler(debugElementID) {
    this.debugElementID = debugElementID;
}

function showOKxOrMoveMap(cloudType) {
    var prefix = "mapCloud" + cloudType;
    var cloudElement = window.document.getElementById(prefix);
    var baloonElement = window.document.getElementById(prefix + "Baloon");

    if (cmscreeny < 100 || cmscreeny > (viewerBean.height - 200) || cmscreenx > (viewerBean.width - 200)) {
        a = viewerBean.getCenterWorldCoord();

        moveMapToZ2(cmx, cmy, viewerBean.zoomLevel, false);

        //cloudElement.style.top = posY + MapCloudsHandler.OFFSET_CORRECTION_Y + "px";
        //cloudElement.style.left = posX + MapCloudsHandler.OFFSET_CORRECTION_X + "px";
        a = viewerBean.getCenterWorldCoord();
    } else {
        baloonElement.style.display = 'block';
    }
}

// methods
// cloudType: OKC, OKB, OKA, HIT
MapCloudsHandler.prototype.setContent = function(cloudType, posX, posY, id, info, contacts, activities, logo, videoOKCOnly, imageOKBOnly, promotion, tool1, tool2, tool3, tool4, tool5) {
    var prefix = "mapCloud" + cloudType;
    var cloudElement = window.document.getElementById(prefix);
    var baloonElement = window.document.getElementById(prefix + "Baloon");

    // do not redisplay visible control
    if (baloonElement != null && baloonElement.style.display != "none") {
        return;
    }

    var tagElement = window.document.getElementById(prefix + "Tag");
    var infoElement = window.document.getElementById(prefix + "Info");
    var contactsElement = window.document.getElementById(prefix + "Contacts");
    var activitiesElement = window.document.getElementById(prefix + "Activities");
    var logoElement = window.document.getElementById(prefix + "Logo");
    var videoElement = window.document.getElementById(prefix + "Video");
    var imageElement = window.document.getElementById(prefix + "Image");
    var promotionElement = window.document.getElementById(prefix + "Promotion");
    var tool1Element = window.document.getElementById(prefix + "Tool" + 1);
    var tool2Element = window.document.getElementById(prefix + "Tool" + 2);
    var tool3Element = window.document.getElementById(prefix + "Tool" + 3);
    var tool4Element = window.document.getElementById(prefix + "Tool" + 4);
    var tool5Element = window.document.getElementById(prefix + "Tool" + 5);

    if (cloudElement != null) {
        cloudElement.style.top = posY + MapCloudsHandler.OFFSET_CORRECTION_Y + "px";
        cloudElement.style.left = posX + MapCloudsHandler.OFFSET_CORRECTION_X + "px";
    }

    if (tagElement != null) {
        tagElement.innerHTML = id;
    }

    if (infoElement != null) {
        infoElement.innerHTML = info;
    }

    if (contactsElement != null) {
        contactsElement.innerHTML = contacts;
    }

    if (activitiesElement != null) {
        activitiesElement.innerHTML = activities;
    }

    if (logoElement != null) {
        if (logo != "") {
            logoElement.src = glbMapServerBaseURL + "/_uploads/logos/" + logo + ".jpg";
            logoElement.style.display = "";
        } else {
            logoElement.style.display = "none";
        }
    }

    if (videoElement != null) {
        //alert(".flv");
        if (videoOKCOnly != "") {
            videoElement.style.display = "";
            this.prepareVideo(videoOKCOnly).write(videoElement.id);
        } else {
            videoElement.style.display = "none";
        }
    }

    if (imageElement != null) {
        if (imageOKBOnly != "")
            imageElement.innerHTML = "<img class='logo' src='" + glbMapServerBaseURL + "/_uploads/logos/" + imageOKBOnly + ".jpg' alt='' />";
        else
            imageElement.innerHTML = "";
    }

    if (promotionElement != null) {
        promotionElement.innerHTML = promotion;
    }

    if (tool1Element != null) {
        if (tool1 != null) {
            tool1Element.href = tool1;
            tool1Element.style.display = "";
        } else {
            tool1Element.href = "";
            tool1Element.style.display = "none";
        }
    }

    if (tool2Element != null) {
        if (tool2 != null) {
            tool2Element.href = tool2;
            tool2Element.style.display = "";
        } else {
            tool2Element.href = "";
            tool2Element.style.display = "none";
        }
    }

    if (tool3Element != null) {
        if (tool3 != null) {
            tool3Element.href = tool3;
            tool3Element.style.display = "";
        } else {
            tool3Element.href = "";
            tool3Element.style.display = "none";
        }
    }

    if (tool4Element != null) {
        if (tool4 != null) {
            tool4Element.href = tool4;
            tool4Element.style.display = "";
        } else {
            tool4Element.href = "";
            tool4Element.style.display = "none";
        }
    }

    if (tool5Element != null) {
        if (tool5 != null) {
            tool5Element.href = tool5;
            tool5Element.style.display = "";
        } else {
            tool5Element.href = "";
            tool5Element.style.display = "none";
        }
    }

    //baloonElement.style.display = "block";

    // debug
    if (this.debugElementID) {
        window.document.getElementById(this.debugElementID).innerHTML = "setContent(" + cloudType + ", " + posX + ", " + posY + ", " + id + ", " + baloon + ", " + info + ", " + contacts + ", " + activities + ", " + logo + ", " + videoOKCOnly + ", " + imageOKBOnly + ", " + promotion + ", " + tool1 + ", " + tool2 + ", " + tool3 + ", " + tool4 + ", " + tool5 + ")";
    }
}

MapCloudsHandler.prototype.prepareVideo = function(videoAndImageNamePrefix) {
    var s1 = new SWFObject(glbMapServerBaseURL + "/JWPlayer/player.swf", "mpl", "225", "125", "9", "#ffffff");
    s1.addParam("allowfullscreen", "true");
    s1.addParam("allowscriptaccess", "always");
    s1.addParam("wmode", "opaque");
    s1.addParam("flashvars", "file=" + glbMapServerBaseURL + "/_uploads/ok_videos/" + videoAndImageNamePrefix + ".flv&stretching=fill&image=" + glbMapServerBaseURL + "/_uploads/ok_images/" + videoAndImageNamePrefix + ".jpg");

    return s1;
}

MapCloudsHandler.prototype.hideBaloonAfterTimeout = function(leftElement, event, baloonElementNameToClose) {
    if (event == null)
        event = window.event;
    var toElement = (event.relatedTarget != null) ? event.relatedTarget : event.toElement; // element that has been entered upon mouseout event
    while (toElement != leftElement && toElement != null)	// leads to either leftElement (which is predecessor of toElement) or beyond body element
        toElement = toElement.parentNode
    if (toElement == leftElement)	// if not stepped outside leftElement
        return;

    // cursor really left outermost element handling onmouseout event
    this.baloonClosingTimerID = setTimeout("window.document.getElementById('" + baloonElementNameToClose + "').style.display = 'none';", MapCloudsHandler.BALOON_HIDE_TIMEOUT);
}

MapCloudsHandler.prototype.cancelHideBaloonAfterTimeout = function() {
    if (this.baloonClosingTimerID != null) {
        clearTimeout(this.baloonClosingTimerID);
        this.baloonClosingTimerID = null;
    }
}

// -- MapCloudsHandler -- end



/****************
Zoom & Move tools
*****************/

function PlaceZoomAndMoveGauges(moveGaugeElementName, zoomGaugeElementName, areToolsOpened) {
    var moveGaugeElement = window.document.getElementById(moveGaugeElementName);
    var zoomGaugeElement = window.document.getElementById(zoomGaugeElementName);

    if (areToolsOpened) {
        moveGaugeElement.style.left = "270px";
        zoomGaugeElement.style.left = "283px";
    } else {
        moveGaugeElement.style.left = "10px";
        zoomGaugeElement.style.left = "23px";
    }
}


function toggleZoomAndMoveGauges(collapseOrExpand) {
    var divGaugesBackground = window.document.getElementById("divGaugesBackground");
    var divMoveGauge = window.document.getElementById("divMoveGauge");
    var divZoomGauge = window.document.getElementById("divZoomGauge");
    var divZoomQuick = window.document.getElementById("divZoomQuick");
    var divCollapseNavigationAndZoomGauge = window.document.getElementById("divCollapseNavigationAndZoomGauge");
    var divExpandNavigationAndZoomGauge = window.document.getElementById("divExpandNavigationAndZoomGauge");

    if (collapseOrExpand == "collapse") {
        divGaugesBackground.style.height = "50px";
        divMoveGauge.style.display = "none";
        divZoomGauge.style.display = "none";
        divZoomQuick.style.display = "none";
        divCollapseNavigationAndZoomGauge.style.display = "none";
        divExpandNavigationAndZoomGauge.style.display = "block";
    } else {
        divGaugesBackground.style.height = "183px";
        divMoveGauge.style.display = "block";
        divZoomGauge.style.display = "block";
        divZoomQuick.style.display = "block";
        divCollapseNavigationAndZoomGauge.style.display = "block";
        divExpandNavigationAndZoomGauge.style.display = "none";
    }
}

// -- Zoom & Move tools -- end



/******
MiniMap
******/

// constants
MiniMapHandler.VIEW_TYPE_BUTTON_IDS = ["btnNormalView", "btnOrtophotoView", "btnHybridView", "btnRoadMapView"];
MiniMapHandler.VIEW_LAYERS_CHECKBOX_IDS = ["cbArchitectureLayer", "cbBusLinesLayer", "cbHillsPeaksLayer"];

// properties
MiniMapHandler.selectedMapViewType = null; // should normaly return value "NormalView"
MiniMapHandler.selectedLayers = null; // should normaly return values (e.g. "000", "100", ...) that depict layers selection (where value: 0 - unselected, 1 - selected); layers have same ordering as MiniMapHandler.VIEW_LAYERS_CHECKBOX_IDS array

// constructors
function MiniMapHandler(selectedMapViewType, selectedLayers) {
    this.selectedMapViewType = selectedMapViewType;
    this.selectedLayers = selectedLayers;
}

// methods
MiniMapHandler.prototype.selectMapViewType = function(clickedButtonId) {
    for (i = 0; i < MiniMapHandler.VIEW_TYPE_BUTTON_IDS.length; i++) {
        var buttonsParent = window.document.getElementById(MiniMapHandler.VIEW_TYPE_BUTTON_IDS[i]).parentNode;
        if (buttonsParent != null) {
            if (MiniMapHandler.VIEW_TYPE_BUTTON_IDS[i] == clickedButtonId) {
                buttonsParent.className = "sel";
                this.selectedMapViewType = clickedButtonId.substring(3);
            } else {
                buttonsParent.className = "";
            }
        }
    }
}

MiniMapHandler.prototype.modifyLeyersSelection = function() {
    var layers = "";
    for (i = 0; i < MiniMapHandler.VIEW_LAYERS_CHECKBOX_IDS.length; i++) {
        var cb = window.document.getElementById(MiniMapHandler.VIEW_LAYERS_CHECKBOX_IDS[i]);
        if (cb != null) {
            layers += (cb.checked ? "1" : "0");
        }
    }
    this.selectedLayers = layers;
}

// -- MiniMap -- end



/************
MiniMap tools
*************/

function toggleMiniMap(collapseOrExpand) {
    var divMiniMap = window.document.getElementById("divMiniMap");
    var divCollapseMiniMap = window.document.getElementById("divCollapseMiniMap");
    var imgMiniMap = window.document.getElementById("imgMiniMap");
    var divMiniMapWindow = window.document.getElementById("divMiniMapWindow");
    var divExpandMiniMap = window.document.getElementById("divExpandMiniMap");

    if (collapseOrExpand == "collapse") {
        divMiniMap.style.width = "45px";
        divMiniMap.style.height = "35px";
        divCollapseMiniMap.style.display = "none";
        imgMiniMap.style.display = "none";
        divMiniMapWindow.style.display = "none";
        divExpandMiniMap.style.display = "block";
    } else {
        divMiniMap.style.width = "102px";
        divMiniMap.style.height = "69px";
        divCollapseMiniMap.style.display = "block";
        imgMiniMap.style.display = "block";
        divMiniMapWindow.style.display = "block";
        divExpandMiniMap.style.display = "none";
    }
}


var selectionWindow = new Array();
selectionWindow.push({ width: 320, height: 249 }); // at zoom level 0
selectionWindow.push({ width: 160, height: 125 }); // at zoom level 1
selectionWindow.push({ width: 80, height: 63 }); // at zoom level 2
selectionWindow.push({ width: 40, height: 32 }); // at zoom level 3
selectionWindow.push({ width: 20, height: 16 }); // at zoom level 4
selectionWindow.push({ width: 10, height: 8 }); 	// at zoom level 5
selectionWindow.push({ width: 6, height: 4 }); 	// at zoom level 6
selectionWindow.push({ width: 3, height: 2 }); 	// at zoom level 7
selectionWindow.push({ width: 2, height: 1 }); 	// at zoom level 8
selectionWindow.push({ width: 1, height: 1 }); 	// at zoom level 9
selectionWindow.push({ width: 1, height: 1 }); 	// at zoom level 10
selectionWindow.push({ width: 1, height: 1 }); 	// at zoom level 11
selectionWindow.push({ width: 1, height: 1 }); 	// at zoom level 12
/*for (i = 0; i < selectionWindow.length; i++) {
    // for zoom level i
    alert(selectionWindow[i].width + " x " + selectionWindow[i].height);
}*/
function UpdateMiniMap(worldX, worldY) {
    var divMiniMapWindow = window.document.getElementById("divMiniMapWindow");
    // coordinate system origin: bottom left
    // approximate world map border coordinates - left: 375242, right: 624196, top: 193239, bottom: 30747
    // approximate mini map border coordinates (includes image padding) - left: 8, right: 92, top: 59, bottom: 4
    // mini map selection window (includes image padding) - max width: 100, max height: 67

    if (worldX < 375242 && 624196 < worldX || worldY < 30747 && 193239 < worldY) {
        worldX = (375242 + 624196) / 2;
        worldY = (193239 + 30747) / 2;
    }

    // detailed calculation:
    // var selCenterX = ((worldX - 375242) / (624196 - 375242) * (92 - 8)) + 8;
    // var selCenterY = ((worldY - 30747) / (193239 - 30747) * (59 - 4)) + 4;
    var selCenterX = (worldX - 375242) / 2963.7381 + 8;
    var selCenterY = (worldY - 30747) / 2954.4000 + 4;

    var selLeft = selCenterX - selectionWindow[viewerBean.zoomLevel].width / 2;
    var selRight = selCenterX + selectionWindow[viewerBean.zoomLevel].width / 2;
    var selTop = selCenterY + selectionWindow[viewerBean.zoomLevel].height / 2;
    var selBottom = selCenterY - selectionWindow[viewerBean.zoomLevel].height / 2;

    // set selection window outer bounds
    selLeft = Math.round(Math.max(0, selLeft));
    selRight = Math.round(Math.min(100, selRight));
    selTop = Math.round(Math.min(67, selTop));
    selBottom = Math.round(Math.max(0, selBottom));

    //alert(worldX + "," + worldY + " : " + selLeft + "," + selRight + " / " + selTop + "," + selBottom);

    // selection at least 1px thick in any direction (+ border)
    divMiniMapWindow.style.left = Math.min(selLeft, 99) + "px";
    divMiniMapWindow.style.bottom = Math.min(selBottom, 66) + "px";

    divMiniMapWindow.style.width = Math.max(1, selRight - selLeft) + "px";
    divMiniMapWindow.style.height = Math.max(1, selTop - selBottom) + "px";
}

// -- MiniMap tools -- end



/************
MapPath tools
************/

// path / route related global variables initialization
MapPath.RouteID = "";
MapPath.RefreshPathRequested = null;

function MapPath() {
    throw "Can not create new instance. MapPath is static utility class.";
}

// locationIndex: 0 - start location, 1 - finnish location

MapPath.setLocation = function(locationIndex, streetAndSettlement, houseNumber, title, x, y) {
    var locationStreetAndSettlement = window.document.getElementById("locationStreetAndSettlement" + locationIndex);
    locationStreetAndSettlement.value = streetAndSettlement;
    locationStreetAndSettlement.title = streetAndSettlement;
    window.document.getElementById("locationHouseNumber" + locationIndex).value = houseNumber;
    window.document.getElementById("locationCoordinateX" + locationIndex).value = x;
    window.document.getElementById("locationCoordinateY" + locationIndex).value = y;
    window.document.getElementById("locationTitle" + locationIndex).innerHTML = title;
    resizePathWindow();
}

MapPath.clearLocation = function(locationIndex) {
    MapPath.setLocation(locationIndex, "", "", "", "", "", "")
}

MapPath.findPath = function() {
    // clear "display"
    window.document.getElementById("pathLength").innerHTML = ""
    window.document.getElementById("pathDuration").innerHTML = "";
    window.document.getElementById("pathDescription").innerHTML = _glb_MSG_SEEKING_PATH; //"Iščem...";
    MapPath.hidePath();

    var travelOptionRouteType = window.document.getElementById("travelOptionRouteType");
    var travelOptionMeans = window.document.getElementById("travelOptionMeans");
    var travelOptions = "";
    travelOptions += travelOptionRouteType.options[travelOptionRouteType.selectedIndex].value;
    travelOptions += travelOptionMeans.options[travelOptionMeans.selectedIndex].value;
    travelOptions += window.document.getElementById("travelOptionUseHighway").checked ? 1 : 0;
    travelOptions += window.document.getElementById("travelOptionUseLocalRoads").checked ? 1 : 0;

    // possible formats for coordinates/addresses passed:
    // <x0>,<y0>;<x1>,<y1>
    // <x0>,<y0>;[<fulladdress1>]
    // [<fulladdress0>];<x1>,<y1>
    // [<fulladdress0>];[<fulladdress1>]
    var locationCoordinateX0 = window.document.getElementById("locationCoordinateX0");
    var locationCoordinateX1 = window.document.getElementById("locationCoordinateX1");
    var coords = "";
    if (locationCoordinateX0.value.length > 0) {	// if possible pass coordinates else full address
        coords += locationCoordinateX0.value;
        coords += "," + window.document.getElementById("locationCoordinateY0").value;
    } else {
        coords += "["
			+ window.document.getElementById("locationStreetAndSettlement0").value
			+ window.document.getElementById("locationHouseNumber0").value
			+ "]";
    }
    coords += ";";
    if (locationCoordinateX1.value.length > 0) {	// if possible pass coordinates else full address
        coords += locationCoordinateX1.value;
        coords += "," + window.document.getElementById("locationCoordinateY1").value;
    } else {
        coords += "["
			+ window.document.getElementById("locationStreetAndSettlement1").value
			+ window.document.getElementById("locationHouseNumber1").value
			+ "]";
    }
    coords = encodeURI(coords);

    //DisableMapSpots();

    if (xmlHttp.readyState == 2 || xmlHttp.readyState == 3)
        xmlHttp.abort();

    //alert("GetMapPath.ashx?options=" + travelOptions + "&coords=" + coords);
    xmlHttp.open("GET", "GetMapPath.ashx?options=" + travelOptions + "&coords=" + coords, true);

    // Setup a function for the server to run when it's done
    xmlHttp.onreadystatechange = MapPath.processPathData;
    xmlHttp.send(null);

    return true;
}

MapPath.processPathData = function() {
    // data must be in the following form:

    //DisableMapSpots();

    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        var response = xmlHttp.responseText;

        var error = MapPath.getXMLElementContent(response, "error");
        if (error != null) {
            //MapPath.clearPath();
            window.document.getElementById("pathDescription").innerHTML = error;
            MapPath.hidePath();

            return;
        }

        var windowBounds = MapPath.getXMLElementContent(response, "bounds").split("/");
        var northWestCorner = windowBounds[0].split(",");
        var southEastCorner = windowBounds[1].split(",");
        MapPath.returnPath(MapPath.getXMLElementContent(response, "routeid"),
			parseInt(northWestCorner[0]), parseInt(northWestCorner[1]),
			parseInt(southEastCorner[0]), parseInt(southEastCorner[1]));
        window.document.getElementById("pathLength").innerHTML = MapPath.getXMLElementContent(response, "length");
        window.document.getElementById("pathDuration").innerHTML = MapPath.getXMLElementContent(response, "duration");
        window.document.getElementById("pathDescription").innerHTML = MapPath.getXMLElementContent(response, "description");

        //DisableMapSpots();
    }
}

MapPath.getXMLElementContent = function(xmlSourceString, elementName) {
    var openingTag = "<" + elementName + ">";
    var closingTag = "</" + elementName + ">";

    if (xmlSourceString.indexOf(openingTag) == -1) {
        return null;
    }

    return xmlSourceString.substring(xmlSourceString.indexOf(openingTag) + openingTag.length, xmlSourceString.indexOf(closingTag));
}

MapPath.returnPath = function(routeID, northWestCornerX, northWestCornerY, southEastCornerX, southEastCornerY) {
    if (viewerBean == null) {
        if (MapPath.RefreshPathRequested == null) {
            // issue show path request on first load (handled sometime during page load event)
            MapPath.RefreshPathRequested = "MapPath.returnPath('" + routeID + "', " + northWestCornerX + ", " + northWestCornerY + ", " + southEastCornerX + ", " + southEastCornerY + ");";
        }

        return;
    }

    MapPath.RouteID = routeID;
    if (MapPath.RouteID != "") {
        var wX = Math.floor((northWestCornerX + southEastCornerX) / 2)
        var wY = Math.floor((northWestCornerY + southEastCornerY) / 2)

        var xdif = Math.abs(Math.floor(northWestCornerX - southEastCornerX));
        var ydif = Math.abs(Math.floor(northWestCornerY - southEastCornerY));
        var size = viewerBean.width;
        var numOfTiles = viewerBean.width / viewerBean.tileSize;
        var dxZoom = (xdif * 1000) / (GSIV.WORLDUNITCONST * numOfTiles);
        var dyZoom = (ydif * 1000) / (GSIV.WORLDUNITCONST * numOfTiles);
        var fZoom = getZoomLevel(Math.max(dxZoom, dyZoom))

        moveMapToZ2(wX, wY, fZoom, true);
    }
}

MapPath.clearPath = function() {
    MapPath.clearLocation(0);
    MapPath.clearLocation(1);
    window.document.getElementById("pathLength").innerHTML = "";
    window.document.getElementById("pathDuration").innerHTML = "";
    window.document.getElementById("pathDescription").innerHTML = "";

    MapPath.RouteID = "";
    var a = viewerBean.getCenterWorldCoord();
    showTransparentLayer(a.x, a.y);
}

MapPath.hidePath = function() {
    MapPath.RouteID = "";
    var a = viewerBean.getCenterWorldCoord();
    showTransparentLayer(a.x, a.y);
}

MapPath.clearCoordinatesForLocation = function(locationIndex) {
    window.document.getElementById("locationCoordinateX" + locationIndex).value = "";
    window.document.getElementById("locationCoordinateY" + locationIndex).value = "";
}

MapPath.verifyStreetAndSettlementExist = function(locationIndex) {
    // if street and settlement not specified or specified with coordinates then do not verify
    var trigger = window.document.getElementById("locationStreetAndSettlement" + locationIndex);
    if (window.document.getElementById("locationCoordinateX" + locationIndex).value.length != 0
		|| trigger.value.length == 0)
	{
        return true;
    }

    var sas = encodeURI(trigger.value);

    if (xmlHttp.readyState == 2 || xmlHttp.readyState == 3)
        xmlHttp.abort();

    xmlHttp.open("GET", pirsApplicationPath + "VerifyStreetAndSettlement.ashx?trigger=" + trigger.id + "&sas=" + sas, true);

    // Setup a function for the server to run when it's done
    xmlHttp.onreadystatechange = MapPath.processStreetAndSettlementData;
    xmlHttp.send(null);

    return true;
}

MapPath.processStreetAndSettlementData = function() {
    // data must be in the xml form; handle errors only
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        var response = xmlHttp.responseText;

        var error = MapPath.getXMLElementContent(response, "error");
        if (error != null) {
            var errorParts = error.split("/");
            alert(errorParts[0]);
            var field = window.document.getElementById(errorParts[1]);
            field.select();
            field.focus();
        }
    }
}

// -- MapPath tools -- end


/************
Misc Controls
************/

function toggleMiscControls(collapseOrExpand) {
    var divMiscControls = window.document.getElementById("divMiscControls");
    var divMiscControlsCollapse = window.document.getElementById("divMiscControlsCollapse");
    var divMiscControlsExpand = window.document.getElementById("divMiscControlsExpand");
    var divMiscControlsOptions = window.document.getElementById("divMiscControlsOptions");

    if (collapseOrExpand == "collapse") {
        divMiscControls.style.width = "15px";
        divMiscControlsCollapse.style.display = "none";
        divMiscControlsExpand.style.display = "block";
        divMiscControlsOptions.style.display = "none";
    } else {
        divMiscControls.style.width = "210px";
        divMiscControlsCollapse.style.display = "block";
        divMiscControlsExpand.style.display = "none";
        divMiscControlsOptions.style.display = "block";
    }
}

// -- Misc Controls -- end


function deWidthAutoCompletes() {
    window.document.getElementById("panel_SAS_ACE0").style.width = "";
    window.document.getElementById("panel_HN_ACE0").style.width = "";
    window.document.getElementById("panel_SAS_ACE1").style.width = "";
    window.document.getElementById("panel_HN_ACE1").style.width = "";
}
