if ( (typeof(bIntegrated) == 'undefined' || bIntegrated == false) && typeof(document.attachEvent) != 'function' ) {
    
    document.events = [];
    document.attachEvent = function(type, reference) {
        var evt = this.events;
        if(!evt[type]){ evt[type] = []; }
        evt[type][evt[type].length] = reference;

        document[type] = function(e) { 
            document.executeEvents(type, e);        
        };
    };

    document.executeEvents = function(type, e) {
        for(var i in this.events[type]) {
            this.events[type][i](e);
        }    
    };
    window.onunload = function() { document.executeEvents('onunload'); };
    window.onload = function() { document.executeEvents('onload'); };
    window.onresize = function() { document.executeEvents('onresize'); };

}

var bFullScreen     = false;
var bMenuOpen       = true;
var bInfoPaneOpen   = false;
var bInfoPaneVisible= false;

function toggleFullScreen() {
    if(bFullScreen) {
        oGeoStart.util.getElementById("fullscreen_btn_off").style.display = 'block';
        oGeoStart.util.getElementById("fullscreen_btn_on").style.display  = 'none';
        oGeoStart.util.getElementById("menuHandle_img").src               = sBaseUrl + "GeoStart/images/menuHandle_open.gif";
        document.body.style.overflow = '';
        
        
        
        oGeoStart.util.getElementById('content').style.backgroundImage = '';
        oGeoStart.util.getElementById('topbar').style.backgroundImage = '';
        
        bFullScreen = false;
        bMenuOpen = true;
        
        
    } else {
        oGeoStart.util.getElementById("fullscreen_btn_off").style.display = 'none';
        oGeoStart.util.getElementById("fullscreen_btn_on").style.display  = 'block';
        oGeoStart.util.getElementById('content').style.backgroundImage = 'url(static/denhaagpresentation/images/bg_body_2.gif)';
        oGeoStart.util.getElementById('topbar').style.backgroundImage = 'url(static/denhaagpresentation/images/bg_body_2.gif)';
        bFullScreen = true;
        bMenuOpen = false;
        document.body.style.overflow = 'hidden';
        scroll(0,0);
    }
    
    resizer();
}


function windowOpen(sLink, iWidth, iHeight) {
    window.open(sLink, '_blank', 'location=0,statusbar=0,menubar=0,width='+iWidth+',height='+iHeight);
}


/**
*   Function for fluid design. 
**/
function resizer() {
      if(!oSettings.sMapMaker){
          var oCenter = oGeoStart.oMap.getCenter();
    
          var iHeaderHeight = parseInt(oSettings._HeaderHeight);
          
          var size = checkSize();      
          myWidth  = size[0];
          myHeight = size[1];
          
          // geen fullscreen
          if(!bFullScreen) {
            if(oSettings._bMenu !== false){ 
                oGeoStart.util.getElementById('header').style.display       = 'block';
                oGeoStart.util.getElementById('header').style.height = iHeaderHeight + 'px';
            }
            
            
            oGeoStart.util.getElementById('geoStart').style.marginTop       = (iHeaderHeight)+'px';
            oGeoStart.util.getElementById('geoStart').style.height          = (myHeight-iHeaderHeight-10)+'px';
            
            oGeoStart.util.getElementById('geoMapContainer').style.height   = (myHeight-iHeaderHeight-40-15)+'px';
            
            

            oGeoStart.util.getElementById('infoPane').style.height          = (myHeight-iHeaderHeight-40-15)+'px'; 
            
            oGeoStart.util.getElementById('geoMap').style.height            = (myHeight-iHeaderHeight-40-15)+'px';            
            oGeoStart.util.getElementById('menuContainer').style.height     = (myHeight-iHeaderHeight-40-14)+'px'; 

            
            /** menuhandle zetten **/
            oGeoStart.util.getElementById('menuHandle').style.height        = (myHeight-iHeaderHeight-40-15)+'px';
            oGeoStart.util.getElementById('menuHandle').style.display       = "none";          
            
            oGeoStart.util.getElementById('closeInfoPaneOverlay').style.top = 44 + 'px';
            oGeoStart.util.getElementById('leftPaneContainer').style.marginRight = '5px'; 
          } else {
            // wel fullscreen
            oGeoStart.util.getElementById('header').style.display           = 'none';
            
            oGeoStart.util.getElementById('geoStart').style.height          = (myHeight - 60)+'px';
            oGeoStart.util.getElementById('geoStart').style.marginTop       = '10px';
            
            oGeoStart.util.getElementById('infoPane').style.height          = (myHeight-40-15-10)+'px';
            oGeoStart.util.getElementById('geoMap').style.height            = (myHeight-40-15-10-24)+'px';

            oGeoStart.util.getElementById('menuContainer').style.height     = (myHeight-40-14-10)+'px';
            
            oGeoStart.util.getElementById('menuHandle').style.height        = (myHeight-40-15-10)+'px';
            oGeoStart.util.getElementById('menuHandle').style.display       = "block";
            
            oGeoStart.util.getElementById('leftPaneContainer').style.marginRight = '0px';
            
            if(oSettings.hoogte){
                oGeoStart.util.getElementById('geoMapContainer').style.height   = oSettings.hoogte + 'px';
            }
            else{
                oGeoStart.util.getElementById('geoMapContainer').style.height   = (myHeight-40-15-10)+'px';
            }
            
            oGeoStart.util.getElementById('closeInfoPaneOverlay').style.top = 44 + 'px';
            
          }

                
          if(bMenuOpen) {
            if(!bFullScreen) {
                oGeoStart.util.getElementById('geoMapContainer').style.width    = (myWidth-307)+'px';
            } else {
                // menu open & fullscreen

                oGeoStart.util.getElementById('geoMapContainer').style.width    = (myWidth-309)+'px';
            }
            
            oGeoStart.util.getElementById('mapMenuContainer').style.width   = (myWidth-305)+'px';
            oGeoStart.util.getElementById('menuContainer').style.display    = 'block';
            oGeoStart.util.getElementById('menuContainer').style.width      = 278+'px';
            oGeoStart.util.getElementById('menuHandle').style.left          = 290+'px';
            oGeoStart.util.getElementById('infoPane').style.left            = 296 + 'px';
            
          } else {
            if(oSettings.breedte){  
                oGeoStart.util.getElementById('geoMapContainer').style.width = oSettings.breedte - 2 + 'px';    
            } 
            else{ 
                if(!bFullScreen) {
                    oGeoStart.util.getElementById('geoMapContainer').style.width    = (myWidth-40)+'px';
                } else {
                    oGeoStart.util.getElementById('geoMapContainer').style.width    = (myWidth-28)+'px';
                }  
            }        
            oGeoStart.util.getElementById('menuContainer').style.display    = 'none';
            oGeoStart.util.getElementById('mapMenuContainer').style.width   = (myWidth-305)+'px';
          
            oGeoStart.util.getElementById('menuHandle').style.left          = 11 + 'px';        
            oGeoStart.util.getElementById('infoPane').style.left            = 17 + 'px';
          }
          
          oGeoStart.util.getElementById('mapMenu').style.width            = (myWidth-310-17)+'px';                
          oGeoStart.util.getElementById('geoStart').style.width           = (myWidth-20)+'px';
          
          /** menuhandle-img in het midden zetten **/

          oGeoStart.util.getElementById('menuHandle_img').style.top      = (oGeoStart.util.getElementById('geoMapContainer').clientHeight/2)-77 + 'px';
          oGeoStart.util.getElementById('infoPane_img').style.top        = (oGeoStart.util.getElementById('geoMapContainer').clientHeight/2)-24 + 'px'; 
          
          oGeoStart.util.getElementById('closeInfoPaneOverlay').style.left     = oGeoStart.util.getElementById('geoMapContainer').offsetLeft + 1 + 'px';
          oGeoStart.util.getElementById('closeInfoPaneOverlay').style.height   = oGeoStart.util.getElementById('geoMapContainer').clientHeight + 'px';
          oGeoStart.util.getElementById('closeInfoPaneOverlay').style.width    = oGeoStart.util.getElementById('geoMapContainer').clientWidth + 'px';
          
          // roep accordionobject aan om items goed te zetten:
          try {
              if(oSettings._bMenu !== true || typeof(oSettings._bMenu) != "undefined") {
                oGeoStart.oMenuEffects.checkResize();
              }
          } catch(e){ }

          /** Try/catch because this function is called before the creation of the map object **/
          try {
            oGeoStart.oMap.checkResize();
          } catch(e) { }
          /*
          try {
            oIntroScreen.checkResize();
          } catch(e) { }
           */         
          //oGeoStart.oMapMaker.checkResize();
          
          oGeoStart.oMap.panTo(oCenter);
          
      }
      
      if ( oGeoStart.util.getElementById('Loading_mapMaker') != null ) {
        oGeoStart.util.getElementById('Loading_mapMaker').style.display = 'none';
      }
      
};

/** Call the function on resize **/
//onresize = resizer;

var counter = 0;
function positionHelp(myHeight){
    var eHelp = oGeoStart.util.getElementById('help_draggable');
    

    counter++;
    iHeaderHeight = parseInt(oSettings._HeaderHeight);
    iHeight = checkSize()[1];
    if ( eHelp ) {
        var aPosition = findPos(oGeoStart.util.getElementById('help_draggable'));

        //var iTop = ( 0 - iHeaderHeight + ( ( iHeight - 579 - aPosition[1] ) / 2 ) );

        var currentTop = parseInt(eHelp.style.top.replace('px', ''));
        
        if ( iHeight > 600 ) {
            eHelp.style.top = ( ( ( iHeight - 579 ) / 2 ) - findPos(oGeoStart.util.getElementById("help_container"))[1] ) + "px";            
        } else {
            eHelp.style.top = ( 0 - findPos(oGeoStart.util.getElementById("help_container"))[1] ) + "px";
        }
    } else {
        setTimeout('positionHelp(' + myHeight + ')', 100);
    }
};

/**
*   In the main info tab, there are 3 divs. Use this to activate the correct div.
**/
function setInfoPaneContent(sBlock){
    var aBlocks = new Object();
    aBlocks['search'] = oGeoStart.util.getElementById('searchResultWrap');
    aBlocks['info'] = oGeoStart.util.getElementById('moreInfoWrap');
    aBlocks['list'] = oGeoStart.util.getElementById('listWrap');
    aBlocks['help'] = oGeoStart.util.getElementById('helpWrap');
    
    for ( var sId in aBlocks ) {
        
        aBlocks[sId].style.display = 'none';
    }
    
    aBlocks[sBlock].style.display = 'block';
    
    setTimeout('oGeoStart.util.getElementById("infoPaneContent").scrollTop = 0', 0);
    
};
 
/**
*   In the main info tab, there are 3 divs. Use this to activate the correct div.
**/
function setMoreInfoTab(sBlock, e){
    var aBlocks = new Object();
    aBlocks['location_description'] = oGeoStart.util.getElementById('location_description');
    aBlocks['location_images'] = oGeoStart.util.getElementById('location_images');
    aBlocks['location_address'] = oGeoStart.util.getElementById('location_address');
    aBlocks['location_cats'] = oGeoStart.util.getElementById('location_cats');
    aBlocks['location_link'] = oGeoStart.util.getElementById('location_link');
    
    var oTabs = oGeoStart.util.getElementById('infoPane_tabs');
   
    for(var i = 0; i < oTabs.childNodes.length; i++){
        if(oTabs.childNodes[i].className == "infoPane_tab"){
            oTabs.childNodes[i].firstChild.className = "";   
        }
        //oTabs.childNodes[i].firstChild.className = "";
    }
    
   // document.getElementsByClassName()
    
    e.className = "active";
    
    
    for ( var sId in aBlocks ) {
        aBlocks[sId].style.display = 'none';
    }    
    aBlocks[sBlock].style.display = 'block';
    
}; 
 
 
 
/**
*   Toggle help display on the map. 
*   eHC: Help Control element.
**/
function toggleHelp(){
    var eH = oGeoStart.util.getElementById('help');
    var eHC = oGeoStart.util.getElementById('Control_grey_help');
    if ( eH.style.display != 'block' ){
        eH.style.display = 'block';  
        eHC.style.fontWeight = 'bold';      
        pageHit('Google_Maps_Help');
    } else {
        eH.style.display = 'none';
        eHC.style.fontWeight = 'normal';
    }    
};

    /**
    *   Crossbrowser find position voor DOM object
    **/
    function findPos(obj) {
        var curleft = curtop = 0;
        if (obj.offsetParent) {
            curleft = obj.offsetLeft;
            curtop = obj.offsetTop;
            while (obj = obj.offsetParent) {
                curleft += obj.offsetLeft;
                curtop += obj.offsetTop;
            }
        }
        return [curleft,curtop];
    };




function checkSize() {
      var myWidth = 0, myHeight = 0;
      if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
        
      } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
      } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
      }      
      var retVal = [myWidth, myHeight];
      
      return retVal;
}


/** 
*   The tab title is dynamic and can contain 'Detail pagina' and 'Locatie overzicht' 
*   This function reads input#sCurTab.value to check what was loaded last.
**/
function tabTitleClick(){
    var sCurTab = oGeoStart.util.getElementById('sCurTab').value;
    
    setTabContent(sCurTab);
    activate('tabTitle');
    swap('tab', true);
};

function stopClick(e){
    if (!e){
        var e = window.event;
    }
    e.cancelBubble = true;
    if (e.stopPropagation){
        e.stopPropagation();
    }
};

function toggleDirForm(){
    if(oGeoStart.util.getElementById('infoWindow_route').style.display != "block"){
        oGeoStart.util.getElementById('infoWindow_route').style.display     = "block";
        oGeoStart.util.getElementById('infoWindow_location').style.display  = "none";
    }
    else{
        oGeoStart.util.getElementById('infoWindow_route').style.display     = "none";
        oGeoStart.util.getElementById('infoWindow_location').style.display  = "block";        
    }
    modifyButtons();
    
}

function changeRouteLabel(sSource){
    if(sSource == 'from'){        
        
        oGeoStart.util.getElementById('routeLabel').innerHTML = "Bestemming:";
    }
    else{
        oGeoStart.util.getElementById('routeLabel').innerHTML = "Vertrekpunt:";
    }
    
}

function togglePermLink(sLink){
   // if(!oSettings.sMapMaker){
        var permLinkDiv         = oGeoStart.util.getElementById('permLinkDiv'); 
        //var balloonHeight   = balloon.offsetHeight; 
        if(permLinkDiv.style.display != "block"){
             oGeoStart.util.getElementById('closeInfoPaneOverlay').style.display = 'block'; 
            permLinkDiv.style.display = "block";
            oGeoStart.util.getElementById('permLinkInput').value = ""+sLink;
            oGeoStart.util.getElementById('permLinkInput').select();
            var oRect = findPos(oGeoStart.util.getElementById("geoMap"));
            
            //permLinkDiv.style.left = (oRect[0] +  (oGeoStart.util.getElementById('geoMap').clientWidth / 2)) + "px";
            permLinkDiv.style.left = "520px";
            oGeoStart.util.getElementById('permLinkInput').select();
           // balloon.offsetHeight = balloonHeight + 20;
        }
        else{
            permLinkDiv.style.display = "none";
             oGeoStart.util.getElementById('closeInfoPaneOverlay').style.display = 'none'; 
            //balloon.offsetHeight = balloonHeight - 20;
        }
    //}
}
  
function modifyButtons(){
    var buttons = oGeoStart.util.getElementById('geoStart').getElementsByTagName('input');
    //alert(buttons[0].type); 
     
    for(var i = 0; i < buttons.length; i++){
        if((buttons[i].type == "submit" || buttons[i].type == "button" ) && buttons[i].className != "nostyle" && buttons[i].className != "hidden"){
           if(typeof(buttons[i]) != null){
               try{
                   var button       = buttons[i];  
                   var parent       = button.parentNode;
                   
                   if(parent.className != 'buttonWrap'){
                       parent.removeChild(button);
                       
                       var buttonWrap           = document.createElement('div');
                       buttonWrap.className     = 'buttonWrap';
                       button.className         = 'button';
                       buttonWrap.appendChild(button);
                       
                       parent.appendChild(buttonWrap);
                   }
               }
               catch(e){}
           }
           
            
              
        }
        //buttons[i].style.color = "lime"; 
         
        
        
    }
    
}   
/**
*   @desc Script to add javascript files dynamicly. Hard coded for controls.
**/
function cAddScript(){    
    
    this.load = function(sType){    
        this.s = document.createElement('script'); 
        this.s.type = 'text/javascript'; 
        this.s.src = this.getSrc(sType);
        document.getElementsByTagName('head')[0].appendChild(this.s);    
        
        this.s.onload = function(){
            oGeoStart.displayControls();
        };
        this.s.onreadystatechange = function(){
            oGeoStart.displayControls();
        };
    };
    
    
    this.getSrc = function(sType){
        switch ( sType ) {
            case 'small':
                return 'GeoStart/libs/mapcontrols/default_minicontrols.js';
            default:
                return 'GeoStart/libs/mapcontrols/default_greycontrols_terrain.js';
        }
    };
};/**
    cbsData klasse, verantwoordelijk voor het tonen van CBS-data en delegeren van listeners naar GMaps elements.
    
    @Author Hendrik Nijmeijer, SWIS BV
**/

function cCbsData() {
    
    this.sSelectedStatistiek = "";
    
    /** initfunctie **/
    this.init = function() {       
        
        this.oTileLayerOverlay = this.getCbsTileLayer();
        oGeoStart.oMap.addOverlay(this.oTileLayerOverlay);        
        
        if(oSettings.sMapMaker == "") {
            this.oLegendControl = new cCbsLegend(oGeoStart.oMap);
            oGeoStart.oMap.addControl(this.oLegendControl);    
        }       
        
        if(typeof(oGeoStart.oMenuEffects) != "undefined") {
            oGeoStart.oMap.addControl(new Cbs_Control(oGeoStart.oMap, 'CBS data'))
        }
        
        this.aStatRadios = document.getElementById("statistiek-content").getElementsByTagName("input");
        
        this.loadListeners();
    }
    
    /** Stel de listeners in op de verschillende map-element events**/
    this.loadListeners = function(){
        
        // Load listener voor de clickevent op de kaartlaag
        GEvent.addListener(oGeoStart.oMap, 'click', function(oOverlay, oPoint) { 
            if(oGeoStart.oCbsData.getStatistiek() != false && oPoint) {
                GDownloadUrl(sBaseUrl + "GeoStart/ajax/getPointInfo.php?stat=" + oGeoStart.oCbsData.getStatistiek() + "&lat=" + oPoint.lat() + "&lng=" + oPoint.lng() + "&zoom=" + oGeoStart.oMap.getZoom(), GEvent.callback(this, oGeoStart.oCbsData.showFeatureInfo ) );
            }
        });
        
        // Laat de zoomend listener om de legenda bij te werken met nieuwe minmaxwaarden
        GEvent.addListener(oGeoStart.oMap, 'zoomend', function() {
            if(oGeoStart.oCbsData.getStatistiek() != false) {
                oGeoStart.oCbsData.updateLegenda();
            }                
        });
        
        // Set de onclick listeners op de radiobtns in het menu
        for(var i = 0; i < this.aStatRadios.length; i++) {
            this.aStatRadios[i].onclick = new Function("oGeoStart.oCbsData.setStatistiek(this.value)");
        }
    }
    
    this.updateLegenda = function() {
        GDownloadUrl( "GeoStart/ajax/getLegendaRange.php?zoom=" + oGeoStart.oMap.getZoom() + "&stat=" + oGeoStart.oCbsData.getStatistiek(), GEvent.callback(this, oGeoStart.oCbsData.setLegendaData));
    }
    
    this.setLegendaData = function(sJson) {
        var oData = eval('(' + sJson + ')');                        
        if(oSettings.sMapMaker == "") {
            this.oLegendControl.setMinMax(oData.min, oData.max);
        } else {
            document.getElementById("stat_schaal_min").innerHTML = oData.min;
            document.getElementById("stat_schaal_max").innerHTML = oData.max;
        }
    }
    
    // opent extinfowindow op een niet-echt-bestaande marker met info over die plek
    this.showFeatureInfo = function(sJson) {
            var oData = eval('(' + sJson + ')');
            var oPoint = new GLatLng(parseFloat(oData.point.lat), parseFloat(oData.point.lng));
            var oIcon = new GIcon();
            oIcon.iconSize          = new GSize(0, 0);
            oIcon.iconAnchor        = new GPoint(0, 0);
            oIcon.infoWindowAnchor  = new GPoint(125, 0);
            
            var oMarker = new GMarker(oPoint, { icon: oIcon,
                                                hide: true});
            
            oMarker.g_type = 'tempmarker';
            
            oGeoStart.oMap.addOverlay(oMarker);
            oMarker.openExtInfoWindow(  oGeoStart.oMap, 
                                        'infoWindowBalloon_stats', 
                                        oData.html,
                                        {
                                            beakOffset: 3,
                                            paddingX:50,
                                            paddingY:30
                                        });
            
            oGeoStart.oMap.removeOverlay(oMarker);        
    }
    
    /** methode om de kaartlaag op te halen van de mapserver **/
    this.getCbsTileLayer = function() { 
        var oTileLayer = new GTileLayer(new GCopyrightCollection(), 0, 17);
        oTileLayer.getTileUrl = function(oTile, iZoom) {
            if(oGeoStart.oCbsData.getStatistiek() != false) {
                return "http://mt" + (oTile.y + oTile.x) % 6 + ".tile01.swis.nl/cbs/" + oGeoStart.oCbsData.getStatistiek() + "/"+oTile.x+"/"+oTile.y+"/"+iZoom+".gif";
            } else {
                return "";
            }
        };
        
        //@TODO: opacity in oSettings?
        oTileLayer.getOpacity = function() {return 0.6;}
        
        return new GTileLayerOverlay(oTileLayer);
    }

    
    /** Returned de geselecteerde statistiek (if any), anders FALSE **/
    this.getStatistiek = function() {
        if(this.sSelectedStatistiek != "") {
            return this.sSelectedStatistiek;
        } else {
            return false;
        }
    }
    
    /** Stel een statistiek in, doet ook een refresh op de tilelayer **/
    this.setStatistiek = function(sStatistiek) {

        this.sSelectedStatistiek = sStatistiek;
                
        document.getElementById("kaartlaag_verbergen_btn").disabled = false;
        
        if(this.oTileLayerOverlay.isHidden()){
            this.oTileLayerOverlay.show();
        }
       
        var oStatistiekData = this.getStatistiekData(sStatistiek);
        
        
        if(oSettings.sMapMaker == "") {
            this.oLegendControl.show();
                    
            if(oStatistiekData.type == "p"){
                this.oLegendControl.setPercentages(true);
            } else {
                this.oLegendControl.setPercentages(false);
            }
            
            this.oLegendControl.setTitel(oStatistiekData.rubriek + ": " + oStatistiekData.naam);
        } else {
            document.getElementById("stat_naam").innerHTML = oStatistiekData.rubriek + ": " + oStatistiekData.naam;
            if(oStatistiekData.type == "p"){
                document.getElementById("stat_schaal_min_p").style.display = "inline";
                document.getElementById("stat_schaal_max_p").style.display = "inline";
            } else {
                document.getElementById("stat_schaal_min_p").style.display = "none";
                document.getElementById("stat_schaal_max_p").style.display = "none";
            }            
        }
        this.updateLegenda();            
        
        this.oTileLayerOverlay.refresh();
        
        GEvent.trigger(this, 'cbsLayerChanged');
    }
    
    
    /** Geeft data terug over een statistiek **/
    this.getStatistiekData = function(sStatistiek) {
         for(var i in aKaartlagen) {
            
            for(var j in aKaartlagen[i].stats) {
                if(j == sStatistiek) {
                    return {    naam:       aKaartlagen[i].stats[j],
                                rubriek:    i,
                                type:       aKaartlagen[i].type };
                }          
            }
        }
    }        
    
    /** Remove de statistieklaag **/
    this.removeStatistieken = function() {
        this.oTileLayerOverlay.hide();
        
        if(oSettings.sMapMaker == "") {
            this.oLegendControl.hide();
        }        
        this.deselectRadioButtons();
        
        this.sSelectedStatistiek = "";
        
        document.getElementById("kaartlaag_verbergen_btn").disabled = true;
    }    
       
    // deselecteer alle radiobtns
    this.deselectRadioButtons = function() {
        
        for(var i = 0; i < this.aStatRadios.length; i++) {
            this.aStatRadios[i].checked = false;
        }
        
    }
    
    // haal de gegevens op van deze bron
    this.getStatistiekBron = function() {
        
        oGeoStart.oMenuEffects.openInfoPane();
        
        if(oGeoStart.oCrossSiteProxy){
            oGeoStart.oCrossSiteProxy.load('html.showHelp', sBaseUrl + 'GeoStart/ajax/getHelp.php');
            oGeoStart.oCrossSiteProxy.call(oGeoStart.oCbsData.showLayerBron);
        } else {
            GDownloadUrl(sBaseUrl + 'GeoStart/ajax/getBronInfo.php?stat=' + this.getStatistiek(), oGeoStart.oCbsData.showLayerBron);
        }
    
   }
   
   // laat de gegevens zien over de bron
   this.showLayerBron = function(data) {
       var aJson = eval('(' + data + ')');  
       document.getElementById('moreInfoWrap').innerHTML = aJson.html;
       setInfoPaneContent('info');            
   }
}
function Clusterer(){
    
    this.iMin = 0;
    this.iMax = 100;
    
    this.iMaxItemsToOpenList = 12;
    
    this.iMinSize = 20;
    this.iMaxSize = 40;
    
    this.iStopResizingAtMax = 50;
    
    this.fPixelPerAantal = 0;
    
    this.bEnableBounds = oSettings.use_cluster_bounds;
    
    this.oIconoptions = {};
    this.oIconoptions.width = 30;
    this.oIconoptions.height = 30;
    this.oIconoptions.primaryColor = "#F58220";
    this.oIconoptions.labelSize = 0;
    this.oIconoptions.labelColor = "#FFFFFF";
    this.oIconoptions.shape = "circle";
    this.oIconoptions.strokeColor = "#FF0000";
    //this.oIconoptions.shadowColor = "#000000";
    
    this.oIconoptions.label = 0;
    
    this.aBounds = [];        
    
}


Clusterer.prototype.drawBounds = function(){
    if(this.aBounds.length > 0){
        var i =    this.aBounds.length ;
        while(i--){
            oGeoStart.oMap.removeOverlay(this.aBounds[i]);
        }
        this.aBounds = [];
    }
    
    for(var key in oGeoStart.oPoints){
        if(oGeoStart.oPoints[key].type == 'CLUSTER'){
            
            
            var aInfo = oGeoStart.oPoints[key]._GeoInfo;
            
            
            if(aInfo.cluster_maxlat == aInfo.cluster_minlat || aInfo.cluster_maxlng == aInfo.cluster_minlng ) {
                continue;   
            }
            
            var aPoints = [
                            new GLatLng(parseFloat(aInfo.cluster_maxlat), parseFloat(aInfo.cluster_maxlng)),
                            new GLatLng(parseFloat(aInfo.cluster_minlat), parseFloat(aInfo.cluster_maxlng)),
                            new GLatLng(parseFloat(aInfo.cluster_minlat), parseFloat(aInfo.cluster_minlng)),
                            new GLatLng(parseFloat(aInfo.cluster_maxlat), parseFloat(aInfo.cluster_minlng)),
                            new GLatLng(parseFloat(aInfo.cluster_maxlat), parseFloat(aInfo.cluster_maxlng))
                          ];
            var oPoly = new GPolygon(aPoints, '#0000FF', 2, 0.5, '#FF0000', 0.2);
            this.aBounds.push(oPoly);
            oGeoStart.oMap.addOverlay(oPoly);
        }
    }
    
       
       
}

Clusterer.prototype.enableBounds = function(){
    if(oSettings.use_cluster_bounds){
        this.bEnableBounds = 1;   
    } else {
        alert('Je kan deze optie alleen gebruiken als use_cluster_bounds aan staat in GeoStart instellingen.');
    }
}

Clusterer.prototype.disableBounds = function(){
    this.bEnableBounds = 0;   
}

Clusterer.prototype.setMinMax = function(oMinMax){
    this.iMin = parseInt(oMinMax.iMin,10);
    this.iMax = parseInt(oMinMax.iMax,10);
    if(this.iMin == this.iMax){
        this.fPixelPerAantal = 0;
    } else {
        this.fPixelPerAantal = (this.iMaxSize - this.iMinSize) / (this.iMax - this.iMin);
    }
    
    
    if(this.bEnableBounds !== 0){
        oGeoStart._oQueuedCommand = function(){ oGeoStart.oClusterer.drawBounds(); }
    }
}


Clusterer.prototype.getMarker = function(aInfo){
    var oIcon = this.getClusterIcon(aInfo);
        
    oIcon.infoWindowAnchor = new GPoint(148 + (this.oIconoptions.width / 2), 15);
    
    
    var oMarker = new GMarker(new GLatLng(parseFloat(aInfo.lat), parseFloat(aInfo.lng)), oIcon);
    oMarker._GeoInfo = aInfo;
    oMarker.type = 'CLUSTER';
    
    var sClusterId = aInfo.id;
    if(aInfo.aantal_markers > this.iMaxItemsToOpenList){
        GEvent.addListener(oMarker, 'click', GEvent.callbackArgs(this, this.zoomToBounds, oMarker));
    } else {
        GEvent.addListener(oMarker, 'click', GEvent.callbackArgs(this, this.openInfoWindow, oMarker));
    }
        
    return oMarker;
    
}

Clusterer.prototype.openInfoWindow = function(oMarker){
    if ( typeof(oMarker._ClusterInfo) == 'object') {
        this.renderInfoWindow(oMarker._ClusterInfo);
    } else {
        GDownloadUrl(sBaseUrl + 'GeoStart/ajax/getClusteredInfo.php?action=markers&sClusterId=' + oMarker._GeoInfo['id'] + '&sMapMaker=' + oSettings.sMapMaker, GEvent.callback(this, this.renderInfoWindow));
    }
}

Clusterer.prototype.zoomToBounds = function(oMarker){
    GDownloadUrl(sBaseUrl + 'GeoStart/ajax/getClusteredInfo.php?action=bounds&sClusterId=' + oMarker._GeoInfo['id'] + '&sMapMaker=' + oSettings.sMapMaker, GEvent.callback(this, this.zoomToBoundsAction));
}

Clusterer.prototype.zoomToBoundsAction = function(sJson){
    if(typeof(oGeoStart.oMap.getExtInfoWindow()) != 'undefined' && oGeoStart.oMap.getExtInfoWindow() != null ) { oGeoStart.oMap.getExtInfoWindow().remove(); }
    
    var oJson = eval('(' + sJson + ')');
    
    oCluster = oJson.oMarkers[0];
    
    var oBounds = new GLatLngBounds();
    oBounds.extend(new GLatLng(parseFloat(oCluster.cluster_maxlat), parseFloat(oCluster.cluster_maxlng)));
    oBounds.extend(new GLatLng(parseFloat(oCluster.cluster_minlat), parseFloat(oCluster.cluster_minlng)));
    
    var iZoom = oGeoStart.oMap.getBoundsZoomLevel(oBounds);
    
    oGeoStart.oMap.setCenter(oBounds.getCenter(), iZoom);
}


Clusterer.prototype.renderInfoWindow = function(sJson){
    if(typeof(sJson) == 'string'){
        var oJson = eval('(' + sJson + ')');
    } else {
        var oJson = sJson;
    }
    
    var oMarkers = oJson.oMarkers;    
    var sClusterId = oJson.sClusterId
    
    if ( !oGeoStart.oTemplate ) {
        oGeoStart.oTemplate = new cTemplate();
        oGeoStart.oTemplate.sTemplateDir = sBaseUrl + 'GeoStart/templates/';
    }                
    
    for ( var key in oMarkers ) {
        // icononly/FF0000/child_friendly.png
        oMarkers[key].icon = 'icononly/' + oMarkers[key].icoonkleur + '/' + oIconmanager.get(oMarkers[key].sg_id).icon;
        
    }
    
    oGeoStart.oTemplate.loadTemplate('ballon_cluster.js.tpl');
    
    oGeoStart.oTemplate.assign('sClusterId', sClusterId);
    oGeoStart.oTemplate.assign('oMarkers', oMarkers);
    
    oGeoStart.oTemplate.assign('iMarkers', oGeoStart.oPoints[sClusterId]._GeoInfo.aantal_markers);
    
    oGeoStart.oPoints[sClusterId]._ClusterInfo = oJson;
        
    oGeoStart.oPoints[sClusterId].openExtInfoWindow(
            oGeoStart.oMap, 
            "infoWindowBalloon_cluster",
            oGeoStart.oTemplate.fetch(),
            {
                beakOffset: 3 ,
                paddingX:   50,
                paddingY:   30
            }
        );
    oGeoStart.oClusterer.oZoomListener = GEvent.addListener(oGeoStart.oMap, 'zoomend', function(){
        if(oGeoStart.oMap.getExtInfoWindow() !== null){
            oGeoStart.oMap.getExtInfoWindow().remove();
        }
        GEvent.removeListener(oGeoStart.oClusterer.oZoomListener);        
    });
                
    
}


Clusterer.prototype.getList = function(sClusterId, iPage){
    var iPage = iPage || 1;
    
    if(oGeoStart.oCrossSiteProxy){
        oGeoStart.oCrossSiteProxy.load('oGeoStart.oClusterer', sBaseUrl + "GeoStart/ajax/getClusteredItems.php?sClusterId="+sClusterId+"&iPage="+iPage + '&sMapMaker=' + oSettings.sMapMaker);
        oGeoStart.oCrossSiteProxy.call(oGeoStart.oClusterer.showItemList);
    } else {
        GDownloadUrl(sBaseUrl + "GeoStart/ajax/getClusteredItems.php?sClusterId="+sClusterId+"&iPage="+iPage + '&sMapMaker=' + oSettings.sMapMaker, oGeoStart.oClusterer.showItemList);
    }            
}
Clusterer.prototype.showItemList = function(sHtml){

    oGeoStart.oMenuEffects.openInfoPane();     
    
    oGeoStart.util.getElementById('listWrap').innerHTML = sHtml;
    
    setInfoPaneContent('list');
    
}

Clusterer.prototype.openMarkerInfoWindow = function(sClusterId, sMarkerId){
    
    var i = oGeoStart.oPoints[sClusterId]._ClusterInfo.oMarkers.length;
    
    while(i--){
        if(sMarkerId == oGeoStart.oPoints[sClusterId]._ClusterInfo.oMarkers[i].id){
            
                oGeoStart.oPoints[sClusterId]._ClusterInfo.oMarkers[i].parentCluster = sClusterId;
                
                var oMarker = oGeoStart.oPoints[sClusterId]._ClusterInfo.oMarkers[i];
                var oOverlay = new GMarker(new GLatLng(oMarker.lat, oMarker.lng), {hide:true, icon: oIconmanager.get(oMarker.sg_id)});
                oGeoStart.oMap.addOverlay(oOverlay);
                
                oOverlay.type = 'tempmarker';                

                
                
                oGeoStart.oClusterer.oListener = GEvent.addListener(oGeoStart.oMap, 'extinfowindowclose', function(){
                    if(oOverlay.type == 'tempmarker' ) {
                        GEvent.removeListener(oGeoStart.oClusterer.oListener);
                        oGeoStart.oMap.removeOverlay(oOverlay);                        
                    }
                   
                });                
                
                oOverlay.openExtInfoWindow(
                    oGeoStart.oMap, 
                    "infoWindowBalloon",
                    oGeoStart.htmlInfoWindow(oGeoStart.oPoints[sClusterId]._ClusterInfo.oMarkers[i]),
                    {
                        beakOffset: 3 ,
                        paddingX:   50,
                        paddingY:   30
                    }
                );
                
               
        }
    }
}

Clusterer.prototype.getIconSize = function(iNumber){
    
    if(this.iStopResizingAtMax >= this.iMax) { 
        return this.iMinSize;
    } else {
        return (this.iMaxSize - this.iMinSize) + Math.round(iNumber * this.fPixelPerAantal);
    }
}

Clusterer.prototype.getClusterIcon = function(aInfo){
    
    var iSize = this.getIconSize(aInfo.aantal_markers);
    
    this.oIconoptions.width = iSize;
    this.oIconoptions.height = iSize;
    this.oIconoptions.label = aInfo.aantal_markers;
    
    return MapIconMaker.createFlatIcon(this.oIconoptions);
    
};/**
*   @class cDirections v. 1.0
*   Class handling GDirections. 
*
*   Floris Lovink - Swis BV
**/
function cDirections(oMap, sDiv) {
    this._oMap = oMap;                              // GMap2 object
    
    this._eDiv = oGeoStart.util.getElementById(sDiv);                           // Element for showing direction results
    var self = this;
    this.aReasons=[];
    this.aReasons[200]   = "Success";
    this.aReasons[400]   = "Fout: Er is iets mis gegaan. Controleer je spelling.";
    this.aReasons[601]   = "Het adres mist.";
    this.aReasons[602]   = "Onbekend adres:  Controleer de ingevulde adressen.";
    this.aReasons[603]   = "Onmogelijk adres:  Helaas kan om contractuele redenen het adres niet worden weergegeven.";
    this.aReasons[604]   = "Geen route gevonden: Helaas kan er geen route gevonden tussen deze adressen.";
    this.aReasons[610]   = "Foute Key: Neem contact op met de systeem beheerder.";
    this.aReasons[500]   = "Server fout: De aanvraag kan op dit moment niet worden behandeld. Probeer het later nog eens.";
    
    this.init = function() {
        this._oDirections = new GDirections(oGeoStart.oMap);
            
        GEvent.addListener(this._oDirections, 'error', GEvent.callback(this,this.checkStatus));   
    };
    
    this.loadDirections = function(oForm, sMarkerLocation) {
        if(typeof(sMarkerLocation) != "undefined" && sMarkerLocation.substring(0, 6) == "LATLNG") {
            var aLatLng = sMarkerLocation.substring(7).split(",");
            var oLatLng = new GLatLng(aLatLng[0], aLatLng[1]);
            
            var oCoder = new GClientGeocoder();
            
            oCoder.getLocations(oLatLng, function(oResponse) {
                oGeoStart.oMenuEffects.openTab('route');  
                if(oResponse.Status.code == 200) {
                    oGeoStart.oDir.loadDirections(oForm, oResponse.Placemark[0].address);
                } else {
                    oGeoStart.oDir.routeError(oGeoStart.oDir.aReasons[oResponse.Status.code]);
                }
            });
        } else if(oForm.id == 'infoWindow_routeForm'){
            var sLocation   = oForm.infoWindow_routeInput.value;
            if(sLocation == ''){
                this.routeError('U heeft niet alle velden ingevuld.');
            }
            else{
                if(oForm.route_naar.checked){
                    oGeoStart.util.getElementById('routeInner').innerHTML = '';
                    
                    oGeoStart.oMenuEffects.openTab('route');
                    
                    oGeoStart.util.getElementById('source').value       = sLocation;
                    oGeoStart.util.getElementById('destination').value  = sMarkerLocation;
                    
                    self.getDirections(sLocation, sMarkerLocation);   
                }
                else{
                    oGeoStart.util.getElementById('routeInner').innerHTML = '';
                    
                    oGeoStart.oMenuEffects.openTab('route');
                    
                    oGeoStart.util.getElementById('source').value       = sMarkerLocation;
                    oGeoStart.util.getElementById('destination').value  = sLocation;
                    
                    self.getDirections(sMarkerLocation ,sLocation);
                }
            }
        }
        else{       
            var sLocation   = oForm.destination.value;
            var sHome       = oForm.source.value;

            

            if ( sLocation == '' || sHome == '' ) {
                this.routeError('U heeft niet alle velden ingevuld.');
            } else {
                oGeoStart.util.getElementById('routeInner').innerHTML = '';
                self.getDirections(sHome, sLocation);
            }
        }
    };
    
    this.swapRouteInput = function(){
        //console.log("komt in de functie");
        var source  = oGeoStart.util.getElementById('source').value;
        var dest    = oGeoStart.util.getElementById('destination').value;
        
        //console.log("SOURCE: " + source + " | DEST: " + dest);
        
        oGeoStart.util.getElementById('source').value         = dest;
        oGeoStart.util.getElementById('destination').value    = source;   
    };
    
    this.openPrintRoute = function(){
        var source  = oGeoStart.util.getElementById('source').value.replace(' ', '+');
        var dest    = oGeoStart.util.getElementById('destination').value.replace(' ', '+');
        
        var printLink = "http://maps.google.com/maps?f=d&hl=nl&geocode=&saddr=__SOURCE__&daddr=__DEST__&ie=UTF8&cd=1&om=1&pw=2";
        
        printLink = printLink.replace(/__SOURCE__/g, source);
        printLink = printLink.replace(/__DEST__/g, dest);
        
        window.open(printLink);
    };
    
    this.routeClear = function(){
        oGeoStart.oMap.closeInfoWindow();
        this._oDirections.clear();
        oGeoStart.util.getElementById('source').value = 'Straat, postcode, plaats';
        oGeoStart.util.getElementById('destination').value = 'Straat, postcode, plaats';
        oGeoStart.util.getElementById('routeInner').innerHTML = '';
    }
    
    this.getDirections = function(sFrom, sTo){
         this._oDirections.load('from: ' + sFrom + ', ' + oSettings._sCountryCode + ' to: ' + sTo + ', ' + oSettings._sCountryCode,{getSteps:true} );
         GEvent.addListener(this._oDirections, 'load', GEvent.callback(this,this.onGDirectionsLoad));
    };
    
    this.checkStatus = function(){
        
        var iCode = this._oDirections.getStatus().code;
        
        
        if ( iCode != 200 ){
            this.routeError(this.aReasons[iCode]);
        }
    };
    
    this.routeError = function (sText){
        oGeoStart.util.getElementById('routeInner').innerHTML = '<span style="color:red;font-weight:bold;">' + sText + '</span>';

    };
    
    this.onGDirectionsLoad = function (){
        var oRoute = this._oDirections.getRoute(0);
        
        //console.log(this._oDirections.getMarker(1));
        oGeoStart.util.getElementById('routeInner').innerHTML = oGeoStart.html.htmlDirectionSteps(oRoute);
       // oGeoStart.html.htmlDirectionSteps(oRoute);
    };
    
    
};/**
*   Class for GeoCode query and returning results.
*   @Notes: showPlace: Might need to put this function in cMapObjects and refer to cMapObjects from here.
*   @class 
**/
function cGeoSearch(){
    /**
    *   Initialize the object.
    *   @param Object GMap2 object.
    *   @param Element Element to load search results into
    **/
    this.init = function(oMap, eGeoSearch){
        this.iMaxResults = 2;
        
        this.oCoder = new GClientGeocoder();
        this._oMap = oMap;
        this._searchDiv     = eGeoSearch            ||  oGeoStart.util.getElementById('GeoCode_search') || null;
        this._sBaseCity     = oSettings._sBaseCity;
        // this._sBaseProvince = _sProvince            ||  'Zuid Holland';
        this._sCountryCode  = oSettings._sCountryCode.toLowerCase();
        this.oCoder.setBaseCountryCode(this._sCountryCode.toLowerCase());

    };
    
    /**
    *   Place temporary marker. Also add listener to marker to remove when infowindow is closed.
    *   @note: Shouldn't we put this in MapObjects
    *   @param i Placemark ID
    *   @private
    **/
    this.showPlace = function(i){
        // Open info window       
        var point = new GLatLng(this._oResult.Placemark[0].Point.coordinates[1], this._oResult.Placemark[0].Point.coordinates[0]);
        
        oGeoStart.checkZoom();
        this._oMap.setCenter(point, this._oMap.getZoom());
        this._oMap.openInfoWindowHtml(point, this._oResult.Placemark[i].address.split(',')[0]);
    };
    
    /**
    *   Asychronous call to GeoCoder.
    *   @param sSearch Search string
    **/
    this.getSearch = function(sSearch){
        var self = this;
        
        if ( sSearch.length > 2 ) {
            this.oCoder.getLocations(sSearch + ', ' + self._sBaseCity, function(oResult){
                if ( oResult.Status.code == G_GEO_SUCCESS ) {
                    oGeoStart.oSearch._oResult = oResult;
                    oGeoStart.oSearch.loadResult();
                } else {
                    oGeoStart.oSearch.cleanResult();
                }
            });
        } else {
            oGeoStart.oSearch.cleanResult();
        }
    };
    
    /**
    *   Load result into div.
    *   Currently uses strict layout, no template
    *   @private
    **/    
    this.loadResult = function(){
        var bGotResults = false;
        var sResult = '';
        var iLength = this._oResult.Placemark.length;
        
        if ( iLength > this.iMaxResults  ) {
            iLength = this.iMaxResults;
        }
        
        for (i=0; i<iLength; i++) { 
            var aInfo = this._oResult.Placemark[i].address.split(',');
            
            sResult += oGeoStart.html.htmlSingleSearchResult(i, aInfo);
            bGotResults = true;        
        }
        
        if ( bGotResults == true ) {

            this._searchDiv = oGeoStart.util.getElementById('GeoCode_search');            
            this._searchDiv.innerHTML = sResult;
        }
    };
    
    /**
    *   Clean up if empty set.
    *   @private
    **/
    this.cleanResult = function(){
        this._searchDiv = oGeoStart.util.getElementById('GeoCode_search');
        this._searchDiv.innerHTML = '';
    };
}


/** 
 * @fileoverview GeoStart klasse. Verantwoordelijk voor het sturen van alle functinaliteit.
 *
 * @author Bjorn Brala bjorn@swis.nl
 * @version 3.01b
 */

/**
 * Construct the MapObjects object
 * @class cGeoStart class
 * @constructor
 */
 function cGeoStart(){
     
        this.oCrossSiteProxy = false;
     
    /************************************************
    *                                               *
    *    Initialisation, listeners and settings.    *
    *                                               *
    ************************************************/
        /** 
        *   Initiazlize the map  
        *   @param {string} sMapid Name of map div
        *   @param {float} fLat latitute of startpoint
        *   @param {float} fLon longitute of startpoint
        *   @param {int} iZoom default zoom level
        **/     
        this.init = function(sMapId, fLat, fLong, iZoom){
            this.oMap = new GMap2(oGeoStart.util.getElementById(sMapId));
            
            cGeoStartPoly.apply(this, []); // Extend with poly objects
            
            /** Array met mapcontrols **/ 
            this.aControls      = [];
            
            /** Huigige lat **/
            this._fLat = parseFloat(fLat);                      // Start viewport
            /** Huigige long **/
            this._fLng = parseFloat(fLong);                     // |
            /** Huigige zoom**/
            this._iZoom = parseInt(iZoom, 10);                  // |
            
            this.bFirstLoad = true;
            if(!oSettings.sMapMaker && !bMapMakerWizard) {
                setTimeout("resizer()", 10);
            }
            
            this.oMap.checkResize();
            this.loadSettings();                                // Load map specific settings
            
            this.loadListeners();                               // Load map listeners

            
            if ( this._bPreloaderEnabled ){
                /** Preloader object {@link cPreloader} **/
                this.oPreloader = new cPreloader(this.oMap);    // Preloader
                this.oPreloader.init(this.oMap, 255);           // Bind to map object
            }
            
            /** Category state array. Filled with category visibility. **/
            this.aCategorystate = [];                  
            
            // Object contains all geometry objects
            this.oPoints        = {}; 
            
			if(typeof(oSettings._bMenu) == 'undefined' || (typeof(oSettings._bMenu) != 'undefined' && oSettings._bMenu !== false)){
                this.oMenuEffects   = new cMenuEffects("menuContainer");
            }

            /**Messagebox object for showing zoom message **/
            this.oMessageBox    = new cMessageBox();
            this.oMessageBox.init(this.oMap);                
            
            /** Directions object handles route directions**/
            this.oDir           = new cDirections(this.oMap);  
            this.oDir.init();
            
            /** mapMaker object handles the mapmaker. **/
            
            this.oMapMaker      = new cMapMaker('mapMaker_frame');
            this.oNewMapMaker   = new cNewMapMaker();

            /** Tooltip object ( {@link cTooltip} ) **/
            this._oTooltip = new cTooltip(this.oMap, 'GeoTooltip', 22, 22, -29, -3);
                        
            this._bUpdateWaiting    = false;                       // Set queue to clean
            this.bFirstUpdate       = true;
            this.loadObjects();                                 // Start loading of markers in current view
            this.aCategorystate     = this._oMenu.getCatStates();
            
            this.bMaxZoom   = false;
            this.bMinZoom   = false;
            
            if(oSettings._bTileServer){
                this.oTilePolyHandler = new cTilePolyHandler();
                this.oTileLayerOverlay = this.addTileLayer();
                this.oMap.addOverlay(this.oTileLayerOverlay);
            }
            
            
            /** boolean for not showing tooltips when mapmaker is open **/
            this.bMapMakerOpen = false;
        };
                
        this.addTileLayer = function() { 
            var tilelayer = new GTileLayer(new GCopyrightCollection(), 0, 17);
            tilelayer.getTileUrl = function(tile, zoom) {
                var sCats = oMenu.getCheckBoxDataString();
                if(sCats == "") {
                    sCats = -1;
                }
                if(oSettings.__bUseZoom){
                    var sUrl = "http://mt" + (tile.y + tile.x) % 10 + ".tile01.swis.nl/tile/" + oSettings.sDbKey + "/" + sCats +"/"+tile.x+"/"+tile.y+"/"+zoom+".gif";
                }else {
                    var sUrl = "http://mt" + (tile.y + tile.x) % 10 + ".tile01.swis.nl/tile/nozoom/" + oSettings.sDbKey + "/" + sCats +"/"+tile.x+"/"+tile.y+"/"+zoom+".gif";                    
                }
                return sUrl;
            };
            tilelayer.getOpacity = function() {return 0.5;}
            return new GTileLayerOverlay(tilelayer);
        }

        
        /**
        *   @desc Init geheel clean, zo min mogelijk laden. Geen data laden.
        *   @param sMapId Id van de map div
        *   @param fLat Start latitude
        *   @param fLong Start longlitude
        *   @param iZoom Start zoom niveau
        *   @param {Object} mapOptions Eventuele mapopties (<a target"_blank" href="http://code.google.com/intl/nl/apis/maps/documentation/reference.html#GMapOptions">GMapOptions</a>)
        **/
        this.cleanInit = function(sMapId, fLat, fLong, iZoom, mapOptions){
            var opts = mapOptions || {};
            /**
            *   GMap2 object, standard google map
            **/
            this.oMap = new GMap2(oGeoStart.util.getElementById(sMapId), mapOptions);
            
            this._fLat = fLat;                      // Start viewport
            this._fLng = fLong;                     // |
            this._iZoom = iZoom;                    // |
            
            this.oMap.setCenter(new GLatLng(this._fLat, this._fLng), this._iZoom); 
            
            this.oMap.enableContinuousZoom();
        };

        
        /**
        *    Load settings for the map.
        **/
        this.loadSettings = function(){
            // ms Interval per group of objects
            this._iLoadInterval    = 1;      
            // Objects per load 
            this._iLoadStep        = 10; 
            
            this._iLoadTimeout     = 750;       
            
            // Que next update call. True: update, False: do nothing
            this._bQueueLastRequest = true;     
                                                
            // Enable preloader
            this._bPreloaderEnabled = oSettings._bPreloaderEnabled;              
            // Enable hover (tooltips)
            this._bEnableHover      = oSettings._bEnableHover;                   
            // Enable balloon
            this._bEnableBalloon    = this._bEnableBalloon          || 'true';   
            
            // Preferred zoom level. Map will zoom here if a marker isnt loaded and the default zoom for the marker is below the treshhold defined here.            
            this._iPreferredZoom    = parseInt(oSettings._iPreferredZoom, 10);       
            
                                                
            // Category key in database
            this._sCategoryKey = 'sg_id';       
            
            // Wip 2.1 Filters
            // Initialize filter palceholders.
            // Use: 
            //      this.createFilter(sKey)
            //      this.removeFilter(sKey)
            //      this.addFilterItem(sKey, sValue)
            //      this.removeFilterItem(sKey, sValue)
            this._aGeoFilterKeys = [];   
                          
            // Wip 2.1 Filters
            // Initialize filter palceholders.
            // Use: 
            //      this.createFilter(sKey)
            //      this.removeFilter(sKey)
            //      this.addFilterItem(sKey, sValue)
            //      this.removeFilterItem(sKey, sValue)
            this._aGeoFilterState = [];
                        
            // Relative URL for GeoStart data requests            
            this._sDataUrl = sBaseUrl + 'GeoStart/ajax/getData.php';    
            
            /**
            *   Menu object {@link cMenu}
            **/
            this._oMenu = oMenu;                
            
            
            
            
            if(oSettings.sMapMaker == false) {
                this.oMap.setCenter(new GLatLng(parseFloat(this._fLat), parseFloat(this._fLng)), parseInt(this._iZoom, 10), eval(oSettings.map_default_type));
            } else {
                
                var aSw = oSettings.sw.split(",");
                var aNe = oSettings.ne.split(",");
                
                var aBounds = new GLatLngBounds(new GLatLng(parseFloat(aSw[0]), parseFloat(aSw[1])), new GLatLng(parseFloat(aNe[0]), parseFloat(aNe[1])));
                                
                this.oMap.setCenter(aBounds.getCenter(), this.oMap.getBoundsZoomLevel(aBounds)+1);
                

            }            

            this.oMap.enableScrollWheelZoom();    // Enable scroll wheel zoom.
            
            /**
            *   Powered by geostart
            **/            
            this.oMap.addControl(new powered_by_geostart(this.oMap));
            
            /**
            *   Load map controls.
            **/            
            var sMapControls = oSettings._sMapControls || "default";
            this.loadControls(sMapControls);
        

      };

            
            //this.oMap.enableContinuousZoom();
            
        
        /**
        *   Display different controls on the map.
        *   @param sSet Welke set met controls moet geladen worden
        **/
        this.loadControls = function(sSet){
            if ( this.sCurrentControlSet != sSet ) {
                this.sCurrentControlSet = sSet;
                
                this.displayControls();
            }        
        };
        
        
        /**
        *   @desc Add controls to the map and save the controls in {@link cGeoStart#aControls}
        *   @private
        **/
        this.displayControls = function(){                
        
                if ( this.aControls.length > 0 ) {
                    this.removeCurrentControls();
                }               
                
                switch ( this.sCurrentControlSet ) {        
                    case 'none':
                        break;
                    case 'small':
                        //var eZoomControl = new Mini_control_grey_zoom(this.oMap);
                        var eZoomControl = new GSmallZoomControl3D();
                        this.oMap.addControl(eZoomControl); 
                        this.aControls.push(eZoomControl);
                        /*
                        var eKaartControl = new Mini_control_grey_left(this.oMap);
                        this.oMap.addControl(eKaartControl);  
                        this.aControls.push(eKaartControl);                        
                        
                        var eSatControl = new Mini_control_grey_right(this.oMap);
                        this.oMap.addControl(eSatControl);  
                        this.aControls.push(eSatControl);                        
                        */
                
                        break;
                    default:

                        var extLargeMapControl = new GLargeMapControl3D();
                        this.oMap.addControl(extLargeMapControl);
                        this.aControls.push(extLargeMapControl);

                        var eKaartControl = new Control_grey_left(this.oMap, 'Kaart');
                        this.oMap.addControl(eKaartControl);  
                        this.aControls.push(eKaartControl);
                            
                        var eSatellietControl = new Control_grey_center(this.oMap, 'Satelliet');
                        this.oMap.addControl(eSatellietControl); 
                        this.aControls.push(eSatellietControl);
                        
                        var eBeideControl = new Control_grey_right(this.oMap, 'Beide');
                        this.oMap.addControl(eBeideControl); 
                        this.aControls.push(eBeideControl);                        
                        
                        var eTerreinControl = new Control_grey_right2(this.oMap, 'Terrein');
                        this.oMap.addControl(eTerreinControl); 
                        this.aControls.push(eTerreinControl);

                        if(oSettings.use_clusters == false){
                            this.oZoomArrow = new cZoomArrow();
                            this.oZoomArrow.init(this.oMap);
                        }
                        
                        
                        break;
                }
        };
        
        /**
        *   remove current controls from the map in preperation of loading new controls
        **/ 
        this.removeCurrentControls = function(){
            var i = this.aControls.length;
            while ( i-- ) {
                this.oMap.removeControl(this.aControls[i]);
            }            
        };

    
    /************************************************
    *                                               *
    *    Data handling.                             *   
    *                                               *
    ************************************************/
        /**
        *    Handle the loading of data.
        *        - Check if currently loading, if so set queued request to true.
        *        - Generate get string for bounds + zoom
        *        - Call GDownloadUrl for asynchronous data request
        **/
        this.loadObjects = function(bTimedTrigger){
            
            if (typeof(bTimedTrigger) == 'undefined') {
                clearTimeout(oGeoStart.oTimer);
                oGeoStart.oTimer = setTimeout('oGeoStart.loadObjects(true);', oGeoStart._iLoadTimeout);
                return;
            } else {
                clearTimeout(oGeoStart.oTimer);
            }
            
           
            if ( !oGeoStart.isBusy() ) {                     // If no update is running.
                
                GEvent.trigger(oGeoStart, "loadObjects");
                
                // Opslaan waar je nu update.
                this.setCurrentPlace();
            
            
                if( oSettings.sMapMaker
                    || 
                    (oMenu.getCheckBoxDataString().length > 0 || this.bFirstUpdate == true)
                ) {
                    oGeoStart.bRemoving  = true;                    // Update status, set object to busy removing
                    oGeoStart.bAdding    = true;                    // and adding.
                    
                    var bounds      = oGeoStart.oMap.getBounds();        // Save current bounds
                    var iZoom       = oGeoStart.oMap.getZoom();        // Save current zoom
                    
                    
                    if ( oMenu ) {
                    // Generate the $_GET string for _sDataUrl
                        
                        var sGet = "?nelng=" + ( bounds.getNorthEast().lng() ) + "&nelat=" + ( bounds.getNorthEast().lat() ) + "&swlng=" + ( bounds.getSouthWest().lng() ) + "&swlat=" + ( bounds.getSouthWest().lat() ) + "&iZoom=" + iZoom + "&sMapMaker=" + sMapMaker;
                        if(!oSettings.sMapMaker ) {  
                            if(this.bFirstUpdate == false) {
                                sGet += "&cats=" + oMenu.getCheckBoxDataString();
                            }
                            if(bMapMakerWizard == true) {
                                sGet += "&bMapmakerWizard=true";
                            }
                        }
                        
                    } else {
                        var sGet = "?cats=&nelng=" + ( bounds.getNorthEast().lng() ) + "&nelat=" + ( bounds.getNorthEast().lat() ) + "&swlng=" + ( bounds.getSouthWest().lng() ) + "&swlat=" + ( bounds.getSouthWest().lat() ) + "&iZoom=" + iZoom + "&sMapMaker=" + sMapMaker;
                    }
                    // Check if first load for session problems ( F5 reloads JS, but not PHP Session! )
                    sGet += '&oMapObjects=' + !oGeoStart.bFirstLoad;
                    
                    if(typeof(bUseGifImages) != 'undefined'){
                        sGet += '&bUseGifImages=' + bUseGifImages;   
                    }
                    
                    // Start the Asynchonous request
                    if(oGeoStart.oCrossSiteProxy) {
                        oGeoStart.oCrossSiteProxy.load('updateObjects', oGeoStart._sDataUrl + sGet);
                        oGeoStart.oCrossSiteProxy.call('updateObjects');
                    } else {
                        GDownloadUrl( oGeoStart._sDataUrl + sGet, GEvent.callback(oGeoStart, oGeoStart.updateObjects));
                    }
                    
                    oGeoStart.bFirstUpdate = false;   
                } else {
                    if(oMenu.getCheckBoxDataString().length == 0) {
                        if(typeof(oGeoStart.oZoomArrow)!='undefined'){
                            oGeoStart.oZoomArrow.hide();
                        }
                        
                        if(typeof(oGeoStart.oTileLayerOverlay) != 'undefined'){
                            oGeoStart.oTileLayerOverlay.refresh();
                        }
                        
                    }
                    oGeoStart.syncCategories();
                }
            } else {                                    // If an update is running
                if ( oGeoStart._bQueueLastRequest ){         // Check if queuing enabled.
                    oGeoStart._bUpdateWaiting = true;
                }
            }         

        };
        
        
        /**
        *    Check if MapObjects contains any geometry
        **/
        this.filled = function(){
            var i = 0; 
            for ( var x in this.oPoints ) { 
                if(typeof(this.oPoints[x]) != 'function'){
                    i += x; break;
                } 
            }  
            if ( i ) {  
                if(iMarkerId == i){
                    iMarkerId = 0;
                    return false;
                }
                return true; 
            } else {      
                return false; 
            }
        };
        
        this.firstLoad = function(){
            return this.bFirstLoad;
        }
        
        /**
        *    Check for queued commands and execuste appropiate commands if needed
        *   @private
        **/
        this.checkQueue = function(){
            if ( !oGeoStart.isBusy() ) {                          // If not busy
                GEvent.trigger(oGeoStart, "loadObjectsDone");
            
            
                if ( oGeoStart._bMenuUpdateWaiting ) {                   // If MENU update is waiting
                    oGeoStart._bMenuUpdateWaiting = false;         
                    oGeoStart.syncCategories();                   // Re-Synchronize category visiblity
                                                                    // Fix for: Click hide category when
                                                                    // updateing. Only the markers who
                                                                    // appear after the click are properly 
                                                                    // Hidden
                    oMenu.countOffItems('GeoCounter_visible'); // Recalculate the total visible markers.
                }
                                                                    // If viewport update is waiting
                if ( oGeoStart._bQueueLastRequest && this._bUpdateWaiting ) {
                    oGeoStart._bUpdateWaiting = false;                
                    oGeoStart.loadObjects();                      // Re-load objects based on current viewport
                }
                
                
                // Handle queues events like clicks ( currrently only used for clicks (4-7-2007) )
                if ( oGeoStart._oQueuedCommand !== null && typeof(oGeoStart._oQueuedCommand) == 'object' ){
                    oGeoStart.trigger(this._oQueuedCommand.iId, oGeoStart._oQueuedCommand.sEvent);
                    oGeoStart._oQueuedCommand = null;
                // Queued function
                } else if ( oGeoStart._oQueuedCommand !== null && typeof(oGeoStart._oQueuedCommand) == 'function' ){
                    oGeoStart._oQueuedCommand();
                    oGeoStart._oQueuedCommand = null;
                }
            }
        };
        
        /**
        *    Check if currently busy updating
        **/
        this.isBusy = function(){
            if ( ( oGeoStart.bRemoving || oGeoStart.bAdding ) ) { 
                if ( oGeoStart.bRemoving === null || oGeoStart.bAdding === null ) {
                    return false;   
                } else {
                    return true;    
                }
            } else { 
                return false;
            }
        };
                
        
        /**
        *   Update map objects. Parse data and send 
        *   requests to update functions for objects
        *   and the oMenu.
        *   @private
        *   @param json Json string with data from getData.php
        *   @private
        **/
        this.updateObjects = function (json){
                // console.time('updateObjects');
                // console.time('findHtml in string');
                var iHtmlIndex = json.indexOf('"sMenuHtml":"     ');
                if(iHtmlIndex !== -1 ){
                    sHtml = json.substring(iHtmlIndex-1, json.length - 2);
                    sNewJson = json.substring(0, iHtmlIndex-2) + '}}}';
                } else {
                    sNewJson = json;
                }

                // console.timeEnd('findHtml in string');
                // console.time('updateObjects:eval');
                var oData = eval('(' + sNewJson + ')');
                // console.timeEnd('updateObjects:eval');
                
            //** Update menu data. **/
                // console.time('updateObjects:oMenu.update');

                if(oSettings.use_clusters === true){
                    oGeoStart.oClusterer.setMinMax(oData.oMinMax);   
                }
                
                oGeoStart._oMenu.update(oData.oMenu);

                // console.timeEnd('updateObjects:oMenu.update');
                
                if(oSettings._bTileServer){
                    if(typeof(oGeoStart.oTileLayerOverlay) != 'undefined'){
                        oGeoStart.oTileLayerOverlay.refresh()   ;
                    }
                }
                

                
                if(oSettings.sMapMaker == false && typeof(oGeoStart.oZoomArrow)!='undefined'){
                    oGeoStart.oZoomArrow.checkHidden(oData.oMenu.iHidden, oData.oMenu.iVisible);
                }
            
            /** Category state **/
                oGeoStart.aCategorystate = oGeoStart._oMenu.getCatStates();
            
            /** Added Geometry data **/
                oGeoStart.aNewGeometry     = oData.aNewGeometry;
            /** Removed Geometry data **/
                oGeoStart.aRemoved         = oData.aRemovedGeometry;
                
            /** Organisatie data **/
                oGeoStart.aOrganisatieInfo = oData.organisatie_info;
                            
    
            /** Load preloader **/
                var iOperations = oData.aOverview.iRemoved + oData.aOverview.iNew; // Count of actions, (add+remove)
                
                if ( oGeoStart._bPreloaderEnabled ) {                // Check if preloader should be used.
                    oGeoStart.oPreloader.start(iOperations);            // Initialize the preloader 
                    //oGeoStart.oPreloader._iOperations = iOperations; // Initialize max counter
                }
            
            /** Start removal loader **/
                oGeoStart.iRemovedCounter = 0;                       
                oGeoStart.iRemoved       = oData.aOverview.iRemoved;
                
                // Start the interval to remove per batch.
                oGeoStart.oDelInterval = setInterval(function() { oGeoStart.removeBatch(); }, oGeoStart._iLoadInterval);    
            
            /** Start preloader and add loader. **/
                oGeoStart.iNewCounter = 0;
                oGeoStart.iNewGeometry = oData.aOverview.iNew;
                
                // Start the interval to add per batch
                oGeoStart.oAddInterval = setInterval(function() { oGeoStart.displayBatch(); }, oGeoStart._iLoadInterval);                
                    /*                        
                if((oMenu.iHidden > oMenu._iVisible) && this.oMessageBox._bDontShow === false && (oMenu.iHidden - oMenu._iVisible) > 0) {
                    if(typeof(oSettings._bMenu) == "undefined" || (typeof(oSettings._bMenu) != "undefined" &&  oSettings._bMenu == true)) {
                        this.oMessageBox.show(oMenu.iHidden - oMenu._iVisible);                    
                    }
                } */

                oGeoStart.bFirstLoad = false;
                            
                            
                // console.timeEnd('updateObjects');
        };
    
        
        /**
        *   Check visibility of object and hide if category isn't visible or filtered.
        *   @param oRef MapObject to check (marker/polygon/polyline)
        **/
        this.checkVisibility = function(oRef) {            
            if ( oRef._GeoInfo.id.indexOf("route") == -1 ) {
                // Nieuwe Regel: Bij beide zichtbaar dan laten zien
                if ( !this.checkVisibilityCategory(oRef) && !this.checkVisibilityFilter(oRef) ) {
                    if ( oRef.isHidden() ) {
                        oRef.show(); 
                    }
                } else {
                    oRef.hide();                
                }            
            } else {
                alert('itsa route!');
            }
        };
        
        /**
        *   Check category visibility for referenced object.
        *   @private
        *   @param oRef MapObject to check (marker/polygon/polyline)
        **/
        this.checkVisibilityCategory = function(oRef) {
            /** Categgory states for menu **/            
            if ( this.aCategorystate ) {
                /*if(typeof(oRef._GeoInfo.allcats) == 'string'){
                    oRef._GeoInfo.allcats = eval(oRef._GeoInfo.allcats);
                }                    
                */
                
                
                
                if(oRef.type == "CLUSTER" && parseInt(oRef._GeoInfo.aantal_markers,10) > 1 ){
                    aAllCats = oMenu.getVisibleSubCats();
                    if(aAllCats.length > 0){
                        oRef._GeoInfo.allcats = oMenu.getVisibleSubCats();
                    } else {
                        oRef._GeoInfo.allcats = [this.aCategorystate[0]];
                    }
                    
                    var i = this.aCategorystate.length;
                    var iHiddenCount = 0;
                    while ( i-- ) {
                        var j = oRef._GeoInfo.allcats.length;
                        while ( j-- ) {   
                            if ( oRef._GeoInfo.allcats[j] == parseInt(this.aCategorystate[i], 10) ) {
                                iHiddenCount++;
                            }
                            if ( iHiddenCount >= oRef._GeoInfo.allcats.length ) {
                                return true;
                            }
                        }                        
                    }
                    return false;
                }
                
                /** Check if point is in hidden category **/
                var i = this.aCategorystate.length;
                var iHiddenCount = 0;
                while ( i-- ) {
                    if(typeof(oMenu.oCatOf) != "undefined" && typeof(oMenu.oCatOf[oRef._GeoInfo.id]) != 'undefined'){
                        var j = oMenu.oCatOf[oRef._GeoInfo.id].length;
                        while ( j-- ) {   
                            if ( parseInt(oMenu.oCatOf[oRef._GeoInfo.id][j], 10) == parseInt(this.aCategorystate[i], 10) ) {
                                iHiddenCount++;
                            }
                            if ( iHiddenCount >= oMenu.oCatOf[oRef._GeoInfo.id].length ) {
                                return true;
                            }
                        }
                    // Extra controle als geen catof object er is
                    } else {
                        if( parseInt(oRef._GeoInfo.sg_id, 10) == parseInt(this.aCategorystate[i], 10) ) {
                            return true;
                        }
                    }
                }
                //console.log('if')
                return false;                
            } else {
                //console.log('else')
                return false;
            }
        };
            
            
        /**
        *   Check filter for referenced item
        *   @private
        *   @param oRef MapObject to check (marker/polygon/polyline)
        **/
        this.checkVisibilityFilter = function(oRef){
            if ( !this._aGeoFilterKeys ) {
                this._aGeoFilterKeys = [];
            }
            /** Check special filters **/           
            var j = this._aGeoFilterKeys.length;          // Initialize loop through filters
            
            while ( j-- ) { 
                // If filter contains 
                if ( this._aGeoFilterState[this._aGeoFilterKeys[j]] && this._aGeoFilterState[this._aGeoFilterKeys[j]].length > 0 ) { // Check if the filter has been filled
                    var k = this._aGeoFilterState[this._aGeoFilterKeys[j]].length;
                    while ( k-- ) { // Loop throught the filter states
                        if ( oRef._GeoInfo[this._aGeoFilterKeys[j]].indexOf(this._aGeoFilterState[this._aGeoFilterKeys[j]][k]) != -1 ) {
                            return true;
                        }
                    }                    
                }
            }
            return false;
        };
        
        /** 
        *   Add command to command queue. 
        *   @param sCommand String of the event to be triggered
        *   @param iSubject Id of the object on who the command should be triggered
        **/        
        this.queueCommand = function(sCommand, iSubject){
            this._oQueuedCommand         = {};
            this._oQueuedCommand.sEvent  = sCommand;
            this._oQueuedCommand.iId     = iSubject;
        };
        
        
    /************************************************
    *                                               *
    *    Filter functions                           *
    *                                               *
    ************************************************/
        /**
        *   Create filter for FIELD - Currently only suppport values to filter on, no ranges.
        *   @param sKey Fieldname for filter, field should be in oPoints[]._GeoInfo
        **/
        this.createFilter = function(sKey) {
            this._aGeoFilterKeys.push(sKey);
            this._aGeoFilterState[sKey] = [];
        };
        
        /**
        *   Remove filter for FIELD
        *   @param sKey Fieldname for filter
        **/
        this.removeFilter = function(sKey) {
            if ( this._aGeoFilterKeys ) {
                var i = this._aGeoFilterKeys.length;
                while( i-- ) {
                    if ( this._aGeoFilterKeys[i] == sKey ) {
                        delete(this._aGeoFilterKeys[i]);
                        break;
                    }
                }                
                if ( this._aGeoFilterState[sKey] ) {
                    delete(this._aGeoFilterState[sKey]);
                }
            }
        };
        
        /**
        *   Add value to filter 
        *   @param sKey Keyname of the filter/_GeoInfo field.
        *   @param sValue Value that should be shows on the map
        **/
        this.addFilterItem = function(sKey, sValue) {
            if ( this._aGeoFilterState[sKey] ) {
                this._aGeoFilterState[sKey].push(sValue);                
            }
        };
        
        /**
        *   Remove value from filter
        *   @param sKey Keyname of the filter/_GeoInfo field.
        *   @param sValue Value that should be shows on the map
        **/
        this.removeFilterItem = function(sKey, sValue) {
            if ( this._aGeoFilterState[sKey] ) {
                var i = this._aGeoFilterState[sKey].length;
                while ( i-- ) {
                    if ( this._aGeoFilterState[sKey][i] == sValue ) {
                        delete(this._aGeoFilterState[sKey][i]);
                        break;
                    }
                }
            }
        };
    


    /************************************************
    *                                               *
    *    MapObject functions. Front for all objects *
    *                                               *
    ************************************************/
        /**
        *   Trigger event on object.id. Contains logic for hover etc. Might need to move the logic to the listeners?
        *   @param iId Id of map object
        *   @param sEvent Event to be triggered on mapobject
        **/
        this.trigger = function(iId, sEvent){
            switch(sEvent){
                case 'mouseout':
                    if ( this._bEnableHover && !this.isBusy() ) {
                        GEvent.trigger(this.oPoints[iId], sEvent);                        
                    }
                    break;
                case 'mouseover':
                    if ( this._bEnableHover && !this.isBusy()) {
                        GEvent.trigger(this.oPoints[iId], sEvent);                        
                    }
                    break;
                case 'click':
                    if ( this._bEnableBalloon && !this.isBusy()) {
                        GEvent.trigger(this.oPoints[iId], sEvent);                        
                    }
                    break;
                case 'deleteObject':
                    if ( this.oPoints[iId] && ( this.oPoints[iId]._GeoInfo.g_type == 'POLYGON' || this.oPoints[iId]._GeoInfo.g_type == 'LINESTRING' ) ) {
                        if(typeof(this.aPolyBounds[iId]) != 'undefined'){
                            delete(this.aPolyBounds[iId]);   
                        }                        
                    }
                    GEvent.clearInstanceListeners(this.oPoints[iId]);
                    this.oMap.removeOverlay(this.oPoints[iId]);   // Remove object from the map.
                    delete(this.oPoints[iId]);                    // Remove object from map objects
                    break;
                default:
                    if ( !this.isBusy() ) {
                        GEvent.trigger(this.oPoints[iId], sEvent);
                    }
                    break;
            }
        };
        
        
        /**
        *   Open a hidden object. Uses json string with object data as argument.    callback function in this.gotoHiddenId
        *   @param json Hidden marker data.
        **/
        this.gotoHidden = function(json){
            if(typeof(oGeoStart.oMap.getExtInfoWindow()) != 'undefined' && oGeoStart.oMap.getExtInfoWindow() != null && typeof(oGeoStart.oMap.getExtInfoWindow().remove) == 'function' ){
                oGeoStart.oMap.getExtInfoWindow().remove();
            }
            
            
            var aInfo =  eval( '(' + json + ')');            
            
            // Check current zoom level
            if ( this.oMap.getZoom() < aInfo.zoom ) {
                if ( aInfo.iZoom < this.iPrefferedZoom ) {
                    var iZoom = this.iPrefferedZoom;
                } else {
                    var iZoom = aInfo.zoom;
                }
                
                if(iZoom > oGeoStart.oMap.getCurrentMapType().getMaximumResolution()) {
                    iZoom = oGeoStart.oMap.getCurrentMapType().getMaximumResolution();
                }
                this.oMap.setCenter(new GLatLng(parseFloat(aInfo.lat), parseFloat(aInfo.lng)), parseInt(iZoom, 10));
            }
            
            this.aCategorystate = this._oMenu.getCatStates();
            this.createPoint(aInfo);
            this.oPoints[aInfo.id].show();
            GEvent.trigger(this.oPoints[aInfo.id], 'click');            
        };
        
        /**
        *   Open a hidden object, new style uses ajax request to get data 
        *   @param iId MapObject id
        **/
        this.gotoHiddenId = function(iId){
            if ( !this.isBusy() ) {      // Check if an map update is running
                if (typeof(oGeoStart.oPoints[iId]) == 'object') {
                    GEvent.trigger(this.oPoints[iId], 'click');
                    oGeoStart.oMenuEffects.hideInfoPane();
                } else {
                    if ( !oGeoStart.oMap.getInfoWindow().isHidden() ) { // Close opened info window
                        oGeoStart.oMap.closeInfoWindow();
                    }
                    oGeoStart.oMenuEffects.hideInfoPane();
                    
                    if(this.oCrossSiteProxy){
                        this.oCrossSiteProxy.load('gotoHidden', sBaseUrl + 'GeoStart/ajax/getItemById.php?id='+iId);
                        this.oCrossSiteProxy.call('gotoHidden');
                    } else {
                        GDownloadUrl( sBaseUrl + 'GeoStart/ajax/getItemById.php?id='+iId, GEvent.callback( this, this.gotoHidden ) );
                    }
                } 
            } else {
                setTimeout('oGeoStart.gotoHiddenId('+iId+')', 100);
            }
        };
          
        
        
        /**
        *   Check zoom level and goto minimum zoom level. Returns true if no change.
        *   @private
        *   @return {boolean} Changed zoom level to preffere 
        **/
        this.checkZoom = function(){
            if ( this.oMap.getZoom() < this._iPreferredZoom ) {
                this.oMap.setZoom(this._iPreferredZoom);
                return false;
            } else {
                return true;
            }
        };
        
        
        /**
        *   Hide object.id
        *   @param iId object Id
        **/
        this.hide = function(iId){
            this.oPoints[iId].hide();
        };
        
        /**
        *   Show object.id
        *   @param iId object Id
        **/
        this.show = function(iId){
            this.oPoints[iId].show();
        };
        
        
        /**
        *   Hide category.id
        *   Uses this._sCategoryKey to identify category in oPoints[id].dbInfo
        *   @param int iId Id reference to MapObjects
        **/
        this.hideCategory = function(iId){
            // If busy remember to update categories after load.
            if ( this.isBusy() ) { this._bMenuUpdateWaiting = true; }

            for ( k in this.oPoints ) {
                if ( typeof(this.oPoints[k]) != 'function' && this.oPoints[k]._GeoInfo[this._sCategoryKey] == iId ) {
                    this.hide(k);
                }
            }            
        };
        
        /**
        *   Show category.id
        *   Uses this._sCategoryKey to identify category in oPoints[id].dbInfo
        *   @param int iId id of geomtry
        **/
        this.showCategory = function(iId){
            // If busy remember to update categories after load.
            if ( this.isBusy() ) { this._bMenuUpdateWaiting = true; }

            for ( var k in this.oPoints ) {
                if ( typeof(this.oPoints[k]) != 'function' && this.oPoints[k]._GeoInfo[this._sCategoryKey] == iId ) {
                    this.show(k);
                }
            }            
        };
        
        /**
        *   Show category.id by array 
        *   Uses this._sCategoryKey to identify category in oPoints[id].dbInfo
        *   @param array aInfo Array (NON ASSOCIATIVE) with the categories to be shown.
        **/
        this.showCategoryGroup = function(aInfo){
            // If busy remember to update categories after load.
            if ( this.isBusy() ) { this._bMenuUpdateWaiting = true; }
            
            var i = aInfo.length;
            for ( var k in this.oPoints ) {
                if(typeof(this.oPoints[k]) != 'function'){
                    var j = i;
                    while ( j-- ) {
                        if ( this.oPoints[k]._GeoInfo[this._sCategoryKey] == aInfo[j] ) {
                            this.show(k);
                        }
                    }
                }
            }            
        };

        /**
        *   Hide category.id by array 
        *   Uses this._sCategoryKey to identify category in oPoints[id].dbInfo
        *   @param array aInfo Array (NON ASSOCIATIVE) with the categories to be shown.
        **/
        this.hideCategoryGroup = function(aInfo){
            // If busy remember to update categories after load.
            if ( this.isBusy() ) { this._bMenuUpdateWaiting = true; }

            var i = aInfo.length;
            for ( var k in this.oPoints ) {
                if(typeof(this.oPoints[k]) != 'function'){
                    var j = i;
                    while ( j-- ) {
                        if ( this.oPoints[k]._GeoInfo[this._sCategoryKey] == aInfo[j] ) {
                            this.hide(k);
                        }
                    }
                }
            }            
        };
        
        /**
        *    Sync categorie and points
        *    Used for updateing map if categories got selected while updateing.
        *   @private
        **/
        this.syncCategories = function(){
            this.aCategorystate = this._oMenu.getCatStates();        // Get current state from Menu object
            var i = this.aCategorystate.length;
            
            for ( var k in this.oPoints ) {
                if(typeof(this.oPoints[k]) != 'function'){
                    this.checkVisibility(this.oPoints[k]);
                }
            }       
        };
        
        
        /**
        *   Show or hide ALL markers.
        *   @param {boolean} bVisibility
        **/
        this.setAll = function( bVisiblity ){
            // If busy remember to update categories after load.
            if ( this.isBusy() ) { this._bMenuUpdateWaiting = true; }
            
            if ( !bVisiblity ) { this.oMap.closeInfoWindow(); }
            
            for ( var k in this.oPoints ) {                
                if(typeof(this.oPoints[k]) != 'function'){
                    if ( bVisiblity ) {                
                        if ( this.oPoints[k].isHidden() ) {
                            this.show(k);
                        }
                    } else {
                        if ( !this.oPoints[k].isHidden() ) {
                            this.hide(k);
                        } 
                    }
                }
            }        
        };
        
        /**
        *   Generate counters for visible / invisible items.
        **/      
        this.getVisiblityCounters = function(){
            var iVisible = 0;
            var iTotal = 0;
            for ( k in this.oPoints ) {
                if(typeof(this.oPoints[k]) != 'function'){
                    iTotal++;
                    if ( !this.oPoints[k].isHidden() ) {
                        iVisible++;
                    }
                }
            }
            
            return  {
                        'iTotal':iTotal,
                        'iVisible':iVisible,
                        'iHidden':iTotal - iVisible
                    };                       
        };
        
        this.showOverlay = function() {
            oGeoStart.util.getElementById("closeInfoPaneOverlay").style.display = 'block';
        }
        
        this.hideOverlay = function() {
            oGeoStart.util.getElementById("closeInfoPaneOverlay").style.display = 'none';
        }
        

        
        
        this.checkZoomLevel = function(){
            try{                
                var oZoomInLink = oGeoStart.util.getElementById('zoomIn');
                var oZoomOutLink = oGeoStart.util.getElementById('zoomOut');
                
                //console.log(oZoomInLink )
                oZoomInLink.className = 'zoomAnchor';
                oZoomOutLink.className = 'zoomAnchor';
                
                if(oGeoStart.oMap.getZoom() == oGeoStart.oMap.getCurrentMapType().getMaximumResolution()){
                    oZoomInLink.className = 'zoomAnchor disabled';
                }
                else{
                    if(oGeoStart.oMap.getZoom() == oGeoStart.oMap.getCurrentMapType().getMinimumResolution()){
                        oZoomOutLink.className = 'zoomAnchor disabled';
                    }
                } 
            } catch(e) {}
        };


    /**
    *   Check if there is enough change to start an update
    */
    this.getIfChangedEnough = function(){
        var oCurrentXy = oGeoStart.oMap.fromLatLngToDivPixel(oGeoStart.oMap.getCenter());
        if(typeof(oGeoStart.oMap._oSavedXy) == 'undefined' || oGeoStart.oMap.getZoom() != oGeoStart.oMap._iSavedZoom ){
            return true;
        }
        var iChangeInPixels = Math.max(Math.abs(oGeoStart.oMap._oSavedXy.x - oCurrentXy.x), Math.abs(oGeoStart.oMap._oSavedXy.y - oCurrentXy.y));
        
        if(iChangeInPixels >= oSettings.pixels_voor_update){
            return true;            
        } else {
            return false;
        }
    }
    
    /**
    *   Set current X/Y, used after update
    */
    this.setCurrentPlace = function(){
        oGeoStart.oMap._oSavedXy   = oGeoStart.oMap.fromLatLngToDivPixel(oGeoStart.oMap.getCenter());
        oGeoStart.oMap._iSavedZoom = oGeoStart.oMap.getZoom();
    }    
}
/** 
* HTML namespace in cGeoStart 
* @extends cGeoStart  
* @namespace
**/
cGeoStart.prototype.html = function(){};       

    /************************************************
    *                                               *
    *    HTML generation functions.                 *
    *                                               *
    ************************************************/
        
        /**
        *   Make request for "Meer informatie"
        *   @param int Marker ID
        **/
        cGeoStart.prototype.html.htmlMeerInfoRequest = function(iMarkerId){
            // De inhoud van de informatie DIV alleen bijwerken als er een iMarkerID is opgegeven
            if(iMarkerId){
                if(oGeoStart.oCrossSiteProxy){
                    oGeoStart.oCrossSiteProxy.load('html.htmlMeerInfoLoad', sBaseUrl  + 'GeoStart/ajax/getMeerinfoHtml.php?id=' + iMarkerId + '&integrated=1');
                    oGeoStart.oCrossSiteProxy.call(oGeoStart.html.htmlMeerInfoLoad);
                } else {
                    GDownloadUrl(sBaseUrl  + 'GeoStart/ajax/getMeerinfoHtml.php?id=' + iMarkerId + '&bUseGif=' + bUseGifImages, oGeoStart.html.htmlMeerInfoLoad);                    
                }
            }
        };
    
    
        /**
        *   @desc Handle the "Meerinfo" request and load the data into the proper div.
        *   @param sJson Single location data based on ajax call
        *   @private
        **/
        cGeoStart.prototype.html.htmlMeerInfoLoad = function(sJson){
            aJson = eval('(' + sJson + ')');

            //InfoPane openenen
            oGeoStart.oMenuEffects.openInfoPane();
            
            //activate('tabTitle');
            

            // De naam van het informatie tabje veranderen
            //oGeoStart.util.getElementById('infoPaneTitleText').innerHTML = aJson.sTitel.substring(0,43); // de titel moet niet langer zijn als 43 tekens anders loopt ie het tabje uit
             
            // De informatie in de informatie div zetten
            oGeoStart.util.getElementById('moreInfoWrap').innerHTML = aJson.html;
            
            // In het hidden field het markers id zetten
            // oGeoStart.util.getElementById('iMarkerId').value = aJson.iId;
            
            // Statistieken bijhouden
            pageHit(aJson.permlink + '/meer_informatie');
            
            /** Activate and show the right content block **/
            setInfoPaneContent('info');
        };
        
        
        
        
        
        /**
        *   Make request for search in geostart
        *   @param sKeyword Search for this word
        *   @param iPage page of search results
        **/
        cGeoStart.prototype.html.showSearch = function(sKeyword, iPage){
            if ( !iPage ) { 
                /** 
                *   @default 1 
                **/
                var iPage = 1;
            }
            
            if ( !sKeyword ) { 
                var sKeyword = oGeoStart.util.getElementById('searchInput').value;
            }
        

            
            if(sKeyword != 'Zoek op locatie, trefwoord, adres, plaats'){
                oGeoStart.oMenuEffects.openInfoPane();
                setInfoPaneContent('search');
                if(iPage == 1){
                    oGeoStart.util.getElementById('searchResultWrap').innerHTML = '<div class="searchLoader"><img src="' +sBaseUrl + 'GeoStart/images/loading.gif" alt="loading"><br><br>Even geduld a.u.b. zoekresultaten worden opgehaald..</div>';
                }    
            } else {                
                return;
            }
            
            
            oGeoStart.html.sKeyword = sKeyword;
            
            if(oGeoStart.oCrossSiteProxy){
                oGeoStart.oCrossSiteProxy.load('html.showSearch', sBaseUrl + 'GeoStart/ajax/getSearchResults.php?keyword='+sKeyword+'&iPage='+iPage+ '&sMapMaker=' + sMapMaker);
                oGeoStart.oCrossSiteProxy.call(oGeoStart.html.loadSearch);
            } else {
                GDownloadUrl(sBaseUrl + 'GeoStart/ajax/getSearchResults.php?keyword='+sKeyword+'&iPage='+iPage+ '&sMapMaker=' + sMapMaker, oGeoStart.html.loadSearch);
            }

            
            
        };
        

        /**
        *   Display search result HTML into proper div.
        *   @param html Generated HTML
        *   @private
        **/
        cGeoStart.prototype.html.loadSearch = function(html){
            oGeoStart.util.getElementById('searchResultWrap').innerHTML = html;
            oGeoStart.util.getElementById('searchInput').value = oGeoStart.html.sKeyword;
            oGeoStart.util.getElementById('searchBox_searchInput').value = oGeoStart.html.sKeyword;                
            oGeoStart.oSearch.getSearch(oGeoStart.html.sKeyword);
        };
        
        
        /**
        *   @desc Single search result
        *   @param iId Id of the marker
        *   @param aInfo Array with information
        *   @private
        **/
        cGeoStart.prototype.html.htmlSingleSearchResult = function(iId, aInfo){
                if ( !oGeoStart.oTemplate ) {
                    oGeoStart.oTemplate = new cTemplate();
                    oGeoStart.oTemplate.sTemplateDir = sBaseUrl + 'GeoStart/templates/';
                }                
                if(aInfo)
                oGeoStart.oTemplate.loadTemplate('enkel_zoek_resultaat.js.tpl');
                
                oGeoStart.oTemplate.assign('sTitel', aInfo[0]);
                oGeoStart.oTemplate.assign('sStraat', aInfo[0]);
                oGeoStart.oTemplate.assign('sPlaats', aInfo[1]);
                oGeoStart.oTemplate.assign('iId', iId);
                
                return oGeoStart.oTemplate.fetch();
        };
        
        
        /**
        *   @desc show sport organisatie informatie
        *   @param iId Id of organisatie
        **/
        cGeoStart.prototype.html.showOrganisatieInfo = function(iId){
            //oGeoStart.html.sOrganisatieTitel = sTitel;
            if(oGeoStart.oCrossSiteProxy){
                oGeoStart.oCrossSiteProxy.load('html.loadOrganisatieInfo', sBaseUrl + 'GeoStart/ajax/getOrganisatieHtml.php?id='+iId);
                oGeoStart.oCrossSiteProxy.call(oGeoStart.html.loadOrganisatieInfo);
            } else {
                GDownloadUrl(sBaseUrl + 'GeoStart/ajax/getOrganisatieHtml.php?id='+iId, oGeoStart.html.loadOrganisatieInfo);
            }
        };
        
        /**
        *   @desc Load html into tab.
        *   @param sHtml Html to load into info tab
        *   @private
        **/
        cGeoStart.prototype.html.loadOrganisatieInfo = function(sHtml){
            //console.log(sHtml);
            
            oGeoStart.oMenuEffects.openInfoPane();
            setInfoPaneContent('info');
            
            // De naam van het informatie tabje veranderen
            // de titel moet niet langer zijn als 43 tekens anders loopt ie het tabje uit
            //oGeoStart.util.getElementById('tabTitleText').innerHTML = oGeoStart.html.sOrganisatieTitel.substring(0,43); 
            
            // De informatie in de informatie div zetten
            oGeoStart.util.getElementById('moreInfoWrap').innerHTML = sHtml;
            
        };
        
        
        /**
        *   Make request for Help
        **/
        cGeoStart.prototype.html.helpRequest = function(){
            oGeoStart.oMenuEffects.openInfoPane();
            
            if(oGeoStart.oCrossSiteProxy){
                oGeoStart.oCrossSiteProxy.load('html.showHelp', sBaseUrl + 'GeoStart/ajax/getHelp.php');
                oGeoStart.oCrossSiteProxy.call(oGeoStart.html.showHelp);
            } else {
                GDownloadUrl(sBaseUrl + 'GeoStart/ajax/getHelp.php', oGeoStart.html.showHelp);
            }

        };
        
        /**
        *   Show help in the infoPane
        *   @param sJson - the fetched data
        **/
        cGeoStart.prototype.html.showHelp = function(sJson){ 
            aJson = eval('(' + sJson + ')');  
            setInfoPaneContent('help');
            oGeoStart.util.getElementById('helpWrap').innerHTML = aJson.html;
        };
        
        /**
        *   Zoom in ballon als je te ver uitgezoomed bent.
        *   @param iId Id van marker
        *   @return string Html van ballon
        **/
        cGeoStart.prototype.html.htmlInfowindowZoomuit = function(iId){
            if ( !oGeoStart.oTemplate ) {
                oGeoStart.oTemplate = new cTemplate();
                oGeoStart.oTemplate.sTemplateDir = sBaseUrl + 'GeoStart/templates/';
            }
            oGeoStart.oTemplate.loadTemplate('ballon_zoomin.js.tpl');
            
            oGeoStart.oTemplate.assign('iId', iId);
            
            return oGeoStart.oTemplate.fetch();                        
        };

       /**
       *    generate InfoWindow with embed/link information for object
       *    @param sKey key ( keyfield type ) for marker.
       *    @param iId Marker object id
       *    @return sHtml Window containing link and embed information
       **/
       cGeoStart.prototype.html.htmlLinkEmbedWindow = function( sKey, iId ) {
            if ( !oGeoStart.oTemplate ) {
                oGeoStart.oTemplate = new cTemplate();
                oGeoStart.oTemplate.sTemplateDir = sBaseUrl + 'GeoStart/templates/';
            }
            
            oGeoStart.oTemplate.loadTemplate('ballon_link_embed.js.tpl');
           
            oGeoStart.oTemplate.assign('sTitelKey', oGeoStart.oPoints[iId]._GeoInfo['titel_key']);
            oGeoStart.oTemplate.assign('iId', iId );
            oGeoStart.oTemplate.assign('sKey', sKey );
            oGeoStart.oTemplate.assign('sIframeCode', oGeoStart.getMiniMapCode(sKey, 310, 257));
            
            return oGeoStart.oTemplate.fetch();          
       };
       
       
       /**
       *    Generate info window based on Array of information gotten from AJAX request
       *    @param array aInfo Information about the point
       *    @return string content String with info window html for marker
       **/
       cGeoStart.prototype.htmlInfoWindow = function(aInfo) {
            if ( !oGeoStart.oTemplate ) {
                oGeoStart.oTemplate = new cTemplate();
                oGeoStart.oTemplate.sTemplateDir = sBaseUrl + 'GeoStart/templates/';
            }
            
            if ( oSettings._bMenu !== false ) {
                if(!bMapMakerWizard) {
                    if(bIntegrated){
                        oGeoStart.oTemplate.loadTemplate('ballon_integrated.js.tpl');
                        oGeoStart.oTemplate.assign('sLinkUrl', sLinkUrl);
                    } else {
                        oGeoStart.oTemplate.loadTemplate('ballon.js.tpl');
                    }
                } else {
                    oGeoStart.oTemplate.loadTemplate('ballon_mapmakerwizard.js.tpl');
                }
            } else {
                oGeoStart.oTemplate.loadTemplate('ballon_mapmaker.js.tpl');
            }
            
            if(typeof(aInfo.organisaties) != 'undefined' && typeof(aInfo.organisaties[aInfo.id]) != 'undefined' && aInfo.organisaties[aInfo.id].length > 0){
                var aOrganisaties = aInfo.organisaties[aInfo.id];
            } else if(oGeoStart.aOrganisatieInfo[aInfo.id]){
                var aOrganisaties = oGeoStart.aOrganisatieInfo[aInfo.id];
            } else {
                var aOrganisaties = false;
            }
            
            var aOrganisatieLinksTemp = {};
            var aOrganisatieLinks = [];
            for(i in aOrganisaties) {
                
                if(typeof(aOrganisaties[i])!='function' && typeof(aOrganisatieLinksTemp[aOrganisaties[i].v_id]) == "undefined"){
                    aOrganisatieLinksTemp[aOrganisaties[i].v_id] = true;
                    var sHtml = "<a href='#' onclick=\"oGeoStart.html.showOrganisatieInfo('" + aOrganisaties[i].v_id + "');return false;\">" + aOrganisaties[i].v_naam + "</a>";
                    aOrganisatieLinks.push(sHtml);  
                    
                }
           }
           
           var sOrganisatiesHtml = aOrganisatieLinks.join(", ");

            if ( aOrganisaties !== false && typeof(aOrganisaties) != 'undefined' ) {                
                var bOrganisaties = 'true';
                oGeoStart.oTemplate.assign('iOrganisaties', aOrganisatieLinks.length);
                oGeoStart.oTemplate.assign('sOrganisatiesHtml', sOrganisatiesHtml);
            }    
            
            
            if ( aInfo.omschrijving  != '' || aOrganisaties !== false  ) {
                var bOmschrijvingEnOrganisaties = true;
            } 
                          
            var aSubgroepen = [];
            if (typeof(oMenu.oCatOf) != 'undefined' && typeof(oMenu.oCatOf[aInfo.id]) != "undefined" ) {
                var aSg = oMenu.oCatOf[aInfo.id] || [aInfo.sg_id];
            } else if ( aInfo.sg_id){
                var aSg = [aInfo.sg_id];
            } else {
                var aSg = [];
            }
            
            var i = aSg.length || 0;
            
            while ( i-- ) {       
                aSubgroepen[i]              = {};
                aSubgroepen[i].image        = oIconmanager.get(aSg[i]).image;
                aSubgroepen[i].icon         = oIconmanager.get(aSg[i]).icon;
                aSubgroepen[i].sg_titel     = oIconmanager.get(aSg[i]).sg_titel;
                aSubgroepen[i].sg_titel_key = oIconmanager.get(aSg[i]).sg_titel_key;
                aSubgroepen[i].hg_titel_key = oIconmanager.get(aSg[i]).hg_titel_key;
                aSubgroepen[i].sg_id        = aSg[i];
                aSubgroepen[i].color        = oIconmanager.get(aSg[i]).color;
                if(typeof(oMenu.oCounter) == 'undefined') {
                    aSubgroepen[i].counter      = '';
                } else {
                    aSubgroepen[i].counter      = "[" + oMenu.oCounter[aSg[i]] + "]";    
                }
                
            }          
            
            oGeoStart.oTemplate.assign('aSubgroepen', aSubgroepen);
            
            
            if ( bOmschrijvingEnOrganisaties === false && aInfo.website ) {
                var bWebsite = true;
                if ( aInfo.website.substring(0,7) != 'http://' && aInfo.website.substring(0,8) != 'https://') {
                    aInfo.website = 'http://' + aInfo.website;
                }
                if ( aInfo.website.length > 30 ) {
                    var sWebby = aInfo.website.substring(7, 28)+'...';
                } else {
                    var sWebby = aInfo.website + '...';
                }
                oGeoStart.oTemplate.assign('sWebsite', aInfo.website);
            }
            
            if(typeof(aInfo.parentCluster) != 'undefined' ){
                oGeoStart.oTemplate.assign('sParentCluster', aInfo.parentCluster);
            }
            
            oGeoStart.oTemplate.assign('id', aInfo.id);

            oGeoStart.oTemplate.assign('kleur', aInfo.icoonkleur);
            
            oGeoStart.oTemplate.assign('hg_titel', aInfo.hg_titel);
            oGeoStart.oTemplate.assign('sg_voorkeur', aInfo.sg_id);
            
            oGeoStart.oTemplate.assign('titel', aInfo.titel);
            oGeoStart.oTemplate.assign('adres', aInfo.adres);
            oGeoStart.oTemplate.assign('postcode', aInfo.postcode);
                            
            oGeoStart.oTemplate.assign('plaats', aInfo.plaats);
            var sRouteLocatie = "";
            
            if(aInfo.postcode || (aInfo.adres && aInfo.plaats ) ){
                sRouteLocatie = aInfo.adres + ", " + aInfo.postcode + ", " + aInfo.plaats;
            } else {
                sRouteLocatie = "LATLNG|" + aInfo.lat + "," + aInfo.lng;
            }
                
            oGeoStart.oTemplate.assign('route_locatie', sRouteLocatie)
            oGeoStart.oTemplate.assign('sMeerInfo', aInfo.id);

            oGeoStart.oTemplate.assign('titel_key', aInfo.titel_key);
            
            
            if ( bOmschrijvingEnOrganisaties ) {
                oGeoStart.oTemplate.assign('bOmschrijvingEnOrganisaties', 'true');            
            }        

            if ( bOrganisaties ) {
                oGeoStart.oTemplate.assign('bOrganisaties', 'true');
            }
            
            if ( bWebsite ) {
                oGeoStart.oTemplate.assign('bWebsite', 'true');                    
            }
            
            if(aInfo.g_type != "POLYGON"){
                oGeoStart.oTemplate.assign('bShowRouteLink', 'true');
            }
            
            oGeoStart.oTemplate.assign('sTitelSafe', aInfo.titel.replace("'", '&quot;').replace('"', ''));
            
            return oGeoStart.oTemplate.fetch();
       };
       
  
       /**
       *    Generate info window for minimap based on Array of information gotten from AJAX request
       *    @param array aInfo Information about the point
       *    @return string content String with info window html for marker
       **/
       cGeoStart.prototype.htmlMiniInfoWindow = function(aInfo) {
            if ( !oGeoStart.oTemplate ) {
                oGeoStart.oTemplate = new cTemplate();
                oGeoStart.oTemplate.sTemplateDir = sBaseUrl + 'GeoStart/templates/';
            }
            
            oGeoStart.loadTemplate('ballon_minimapinfo.js.tpl');
            
            
            oGeoStart.oTemplate.assign('id', aInfo.id);
            oGeoStart.oTemplate.assign('titel', aInfo.titel);
            
            oGeoStart.oTemplate.assign('titel_key', aInfo.titel_key);


            if ( aInfo.omschrijving == '' && aInfo.website ) {
                var bWebsite = true;
                if ( aInfo.website.substring(0,7) != 'http://') {
                    aInfo.website = 'http://' + aInfo.website;
                }
                if ( aInfo.website.length > 30 ) {
                    var sWebby = aInfo.website.substring(7, 28)+'...';
                } else {
                    var sWebby = aInfo.website + '...';
                }
                oGeoStart.oTemplate.assign('sWebsite', aInfo.website);
            } else {
                oGeoStart.oTemplate.assign('bOmschrijving', 'true');
            }
                
            return oGeoStart.oTemplate.fetch();
       };
       
       
       /**
       *    generate directions html
       *    @param oDirections object
       *    @return string content String with html for directions div
       **/ 
       cGeoStart.prototype.html.htmlDirectionSteps = function( oDirections ) {
            if ( !oGeoStart.oTemplate ) {
                oGeoStart.oTemplate = new cTemplate();
                oGeoStart.oTemplate.sTemplateDir = sBaseUrl + 'GeoStart/templates/';
            }
            
            oGeoStart.oTemplate.loadTemplate('route_directions.js.tpl');
                       
            sHome           = oDirections.getStartGeocode().address;
            
            sSummary        = oDirections.getSummaryHtml();
            sDestination    = oDirections.getEndGeocode().address;
            
            var iNumSteps =  oDirections.getNumSteps();
            
            var aDirections=[];
            
            for(i=0; i < iNumSteps; i++){            
                aDirections.push({nummer      : i+1,
                                    description : oDirections.getStep(i).getDescriptionHtml(),
                                    distance    : oDirections.getStep(i).getDistance().html,
                                    coord       : oDirections.getStep(i).getLatLng()});
            }
            
            oGeoStart.oTemplate.assign('sHome', sHome);
            oGeoStart.oTemplate.assign('sBaseUrl', sBaseUrl);
            oGeoStart.oTemplate.assign('sSummary', sSummary);
            oGeoStart.oTemplate.assign('aDirections', aDirections);
            
            oGeoStart.oTemplate.assign('sDestination', sDestination);
            
            return oGeoStart.oTemplate.fetch();
       };/**
*   Prototype for GeoStart listener.
*      
*   Maplistener and GeoMetry listeners
*
*   @extends cGeoStart
**/


        /**
        *    Load listeners needed on the oMap
        *   @private
        **/
        cGeoStart.prototype.loadListeners = function(){
            
            
            /** Update map objects on moveend ( also triggers on zooms ) **/
            GEvent.addListener(oGeoStart.oMap, 'moveend', function() {                 
                if(oGeoStart.getIfChangedEnough()){
                    oGeoStart.loadObjects();            
                }
            });
                        
            GEvent.addListener(oGeoStart.oMap, 'zoomend', function() {
                oGeoStart.checkZoomLevel();                 
                oGeoStart._oTooltip.hide(); 
            });
            
            GEvent.addListener(oGeoStart.oMap, 'maptypechanged', function() {
                oGeoStart.checkZoomLevel();
                if(typeof(oGeoStart.oZoomArrow)!='undefined'){
                    oGeoStart.oZoomArrow.checkHidden(oMenu.iHidden, oMenu._iVisible);
                }
            });
            
            GEvent.addListener(oGeoStart.oMap, 'extinfowindowopen', function() {
                oGeoStart.checkZoomLevel();
            });
            
            GEvent.addListener(oGeoStart.oMap, 'extinfowindowbeforeclose', function() {
                if(     typeof(oGeoStart.oMap.getExtInfoWindow().marker_) != "undefined" && 
                        typeof(oGeoStart.oMap.getExtInfoWindow().marker_._GeoInfo) != "undefined" &&
                        oGeoStart.oMap.getExtInfoWindow().marker_._GeoInfo.g_type == "POLYGON" && 
                        oSettings._bTileServer) {
                    oGeoStart.oPoints[oGeoStart.oMap.getExtInfoWindow().marker_._GeoInfo.id].hidePolygon();
                } else {
                    if(typeof(oGeoStart.oMap.getExtInfoWindow().marker_._GeoInfo) != "undefined"){
                        oGeoStart.checkVisibility(oGeoStart.oMap.getExtInfoWindow().marker_);
                    }
                }
            });
            if(oSettings._bTileServer) {                
                GEvent.addListener(oGeoStart.oMap, 'mousemove', function(latlng) { 
                    oGeoStart.oTilePolyHandler.handleMouseMove(latlng.lat(), latlng.lng());
                });
            }            
        };
          

        /**
        *   Load listeners for geometry. Currently supports only markers.
        *   @param object oRef Reference object to apply listeners to
        *   @private
        **/
        cGeoStart.prototype.loadGeometryListeners = function(oRef){
            //console.log('Start oRef');
            /** Onclick event. Hide tooltip ( looks bad on moving map ) and open info window **/
            GEvent.addListener(oRef, 'click', function(clickPoint) {
                var oRefLocal = oRef;
                /** Ajust lat/lng on poly object to facilitate infowindow opened at clickpoint **/
                if (    oRefLocal._GeoInfo['g_type'] == 'POLYGON' ||
                        oRefLocal._GeoInfo['g_type'] == 'MULTIPOLYGON' ||
                        oRefLocal._GeoInfo['g_type'] == 'LINESTRING' ){
                    if ( clickPoint ) { 
                        oRefLocal._GeoInfo['lat'] = clickPoint.lat();
                        oRefLocal._GeoInfo['lng'] = clickPoint.lng();
                    }
                }
                    
                oGeoStart._oTooltip.hide();
                oRefLocal.openExtInfoWindow(
                    oGeoStart.oMap, 
                    "infoWindowBalloon",
                    oGeoStart.htmlInfoWindow(oRefLocal._GeoInfo),
                    {
                        beakOffset: 3 ,
                        paddingX:   50,
                        paddingY:   30
                    }
                );

                
                if (oRefLocal._GeoInfo['g_type'] == 'POINT'){
                    oRefLocal.hide();
                } else {
                    oRefLocal.show();
                }
            });                            


            
            /** Mouseover event to facilitatie our tooltip **/
            
            GEvent.addListener(oRef, "mouseover", function() {
                var oRefLocal = oRef;
                //console.log(oRefLocal.type);
                if ( oRefLocal.type == "point" ) {
                    if ( oGeoStart._bEnableHover ) {
                        oGeoStart._hoveringMarker = true;
                        //oGeoStart._hoverListener.remove();
                        
                        // check if there is already an infowindow on this marker, if so, no need to display a tooltip.
                        var bThisMarker = false;
                        if(typeof(oGeoStart.oMap.getExtInfoWindow()) != "undefined" && oGeoStart.oMap.getExtInfoWindow() != null && typeof(oGeoStart.oMap.getExtInfoWindow().marker_._GeoInfo) != "undefined"){
                            if(oGeoStart.oMap.getExtInfoWindow().marker_._GeoInfo['id'] == oRefLocal._GeoInfo['id']) {
                                var bThisMarker = true;
                            }
                        }
                        
                        if ( oGeoStart._oTooltip.markerOnScreen(oRefLocal.getPoint()) && !bThisMarker && !  oGeoStart.bMapMakerOpen){                // Check if marker is onscreen
                            
                            oRefLocal.hide();
                            
                            oGeoStart._oTooltip.setMarker(oRefLocal);
                            oGeoStart._oTooltip.checkAlign(oRefLocal._GeoInfo['g_type']);
                            oGeoStart._oTooltip.setText(oRefLocal.tooltip);
                            if ( typeof(oMenu.oCatOf) != 'undefined' && typeof(oMenu.oCatOf[oRefLocal._GeoInfo['id']]) != 'undefined' )  {
                                oGeoStart._oTooltip.addContent(oMenu.oCatOf[oRefLocal._GeoInfo['id']]);
                            } else {                                 
                                oGeoStart._oTooltip.addContent(parseInt(oRefLocal._GeoInfo['sg_id'], 10));                                
                            }

                            oGeoStart._oTooltip.show(oRefLocal.getPoint());
                            
                            
                            var bFirst = true;
                            var event = GEvent.addListener(oGeoStart.oMap, 'mousemove', function(){
                                if(!bFirst){
                                    if(oGeoStart.oMap.getExtInfoWindow() == null || typeof(oGeoStart.oMap.getExtInfoWindow().marker_._GeoInfo) == 'undefined' || oGeoStart.oMap.getExtInfoWindow().marker_._GeoInfo['id'] != oRefLocal._GeoInfo['id']) {
                                        GEvent.removeListener(event);
                                        oGeoStart._oTooltip.hide();
                                    }
                                    
                                } else {
                                    bFirst = false;
                                }
                            });
                            
                            
                            GEvent.addDomListener(oGeoStart._oTooltip._eDiv, "click", function() {
                                // hide the tooltip
                                oGeoStart._oTooltip.hide();
                                
                                oGeoStart.trigger(oGeoStart._oTooltip.getMarker()._GeoInfo["id"], "click");
                               
                                GEvent.clearListeners(oGeoStart._oTooltip._eDiv, "click");
                            });                            
                            
                            // Add a listener to hide it again on mouseout
                            if (oRefLocal.isHidden() ) {                            // If marker is hidden show it
                                oRefLocal.bHoverShow = true;                             // Mark the marker as "shown by hover"
                                oRefLocal.show();                                        // Show the marker
                                
                                // Add a listener to hide it again on mouseout
                                oRefLocal.tempMouseoutListener = GEvent.addListener(oRefLocal, 'mouseout', function(){
                                    oRefLocal.hide();                                    // Hide the marker
                                    oGeoStart.checkVisibility(oRefLocal);
                                    //alert('mouse out');
                                    oRefLocal.tempMouseoutListener.remove();             // Remove self (listener)
                                });
                            }
                        }
                    }
                }
            });
        };/**
*   Marker cache extentie. 
*   
*   Vervangt de oude remove/add/createPoint voor nieuwe(betere). In 
*   plaats van altijd een nieuwe marker maken slaat hij de markers op en verbergd hij ze
*
*   @extends cGeoStart  
**/

        /**
        *   Remove a batch of markers
        *   @private
        **/
        cGeoStart.prototype.removeBatch = function(){
            
            var i = 0;
            
            if ( typeof(this.oMarkerCache) != 'object' ) {
                oGeoStart.oMarkerCache = [];
            }

            for ( var key in oGeoStart.aRemoved ) {                            // Loop trough global map objects.
                if(typeof(oGeoStart.aRemoved[key]) != 'function'){
                    if ( i < oGeoStart._iLoadStep && oGeoStart.iRemovedCounter <= oGeoStart.iRemoved ) { // Loop until max per batch (_iLoadStep) 
                                                                                          // and check if all updates were done.
                        
                        if ( oGeoStart.oPoints[key] && ( oGeoStart.oPoints[key]._GeoInfo['g_type'] == 'MULTIPOLYGON' || oGeoStart.oPoints[key]._GeoInfo['g_type'] == 'POLYGON' || oGeoStart.oPoints[key]._GeoInfo['g_type'] == 'LINESTRING' ) ) {
                            if(typeof(oGeoStart.aPolyBounds[key]) != 'undefined'){
                                delete(oGeoStart.aPolyBounds[key]);
                            }
                            oGeoStart.trigger(key, 'deleteObject');
                        } else if (oGeoStart.oPoints[key]._GeoInfo['g_type'] == 'CLUSTER') {
                        
                            oGeoStart.oMap.removeOverlay(oGeoStart.oPoints[key]);
                            delete(oGeoStart.oPoints[key]);
                            
                        } else {
                            oGeoStart.oMarkerCache.push(oGeoStart.oPoints[key]);
                            oGeoStart.oPoints[key].hide();
                            delete(oGeoStart.oPoints[key]);
                        }
                        
                        delete(oGeoStart.aRemoved[key]);                    // Remove object from remove data update array
                        oGeoStart.iRemovedCounter++;                                // Global counter to check if remval is done.
                    } else {
                        break;
                    }
                    i++;
                }
            }
            if ( oGeoStart._bPreloaderEnabled ) {                            // Only update preloader if enabled
                oGeoStart.oPreloader.updateLoader( i );
            }


            // Little update check counter thingie...
            if ( oMenu ) 
                oMenu.countOffItems('GeoCounter_visible');
            
            // Cleanup functions if done.
            if ( oGeoStart.iRemovedCounter >= oGeoStart.iRemoved ) {
                clearInterval(oGeoStart.oDelInterval);                 // Clear the loop.
                oGeoStart.iRemovedCounter = 0;
                oGeoStart.aRemoved = null;
                oGeoStart.iRemoved = null;
                oGeoStart.bRemoving = false;                            // Tell map objects hes done.
                
                oGeoStart.checkQueue();                               /// Call checkqueue to handle queued requests
            }
            
            //oGeoStart.util.getElementById('keyword_menu').value = 'Er zijn ' + this.oMarkerCache.length + ' marker gecached.';
        };
    
    
        /**
        *    Batch display of data. Updates mapobjects internal arrays.
        *    Comments added to lines different from this.removeBatch
        *   @private
        **/
        cGeoStart.prototype.displayBatch = function(){
            var i = 0;
            for ( var key in this.aNewGeometry ) {
                if(typeof(this.aNewGeometry[key]) != 'function'){
                    if ( i < this._iLoadStep && this.iNewCounter <= this.iNewGeometry ) {
                        if( typeof(this.oPoints[key]) != 'object' ) {
                            this.createPoint(this.aNewGeometry[key]);
                        }
                        delete(this.aNewGeometry[key]);                        // Remove from 'todo' object.
                        this.iNewCounter++;
                    } else { 
                        break; 
                    }
                    i++;
                }
            }
            if ( this._bPreloaderEnabled ) {
                this.oPreloader.updateLoader( i );                // Update preloader if enabled
            }
            
            // Little update check counter thingie...
            if ( oMenu ) 
                oMenu.countOffItems('GeoCounter_visible');
            
            // Cleanup functions if done.
            if ( this.iNewCounter >= this.iNewGeometry ) {
                clearInterval(this.oAddInterval);
                this.aNewGeometry = null;
                this.iNewGeometry = null;
                this.iNewCounter = 0;
                this.bAdding = false;
                if ( this._bPreloaderEnabled ) {
                    this.oPreloader.remove();             // Hide preloader again.
                }
                this.checkQueue();                        // Call checkqueue to handle queued requests
            }
            //oGeoStart.util.getElementById('keyword_menu').value = 'Er zijn ' + this.oMarkerCache.length + ' marker gecached.';
        };

        /**
        *    Create point (marker) on map. 
        *    Uses information from cGeoData::aVisible, add any fields from there.
        *    @param aInfo Array with information
        **/
        cGeoStart.prototype.createPoint = function(aInfo){
            
            if ( typeof(this.oMarkerCache) != 'object' ) {
                this.oMarkerCache = [];
            }
            
            
            if( typeof(this.oPoints[aInfo['id']]) != 'object' ) {
                switch ( aInfo.g_type ) {
                    case "POLYGON":
                        if(oSettings._bTileServer) {
                            var oPoly = new cTilePoly(); 
                            oPoly.titel = aInfo.titel;
                            oPoly.tooltip = aInfo[oSettings._sTooltipField];
                            oPoly.type = "polygon";
                            oPoly._GeoInfo  = aInfo;                // All information given by cGeoData(PHP!)
                            var id = aInfo.id;
                            // Add object to factories
                            this.oTilePolyHandler.oPolyIds[id] = true;                            
                        } else {
                            var oPoly = this.createPolygon(aInfo); 
                            this.oMap.addOverlay(oPoly);                       
                            oPoly.titel = aInfo.titel;
                            oPoly.tooltip = aInfo[oSettings._sTooltipField];
                            oPoly.type = "polygon";
                            //oPoly.content = this.htmlInfoWindow(aInfo);
                            oPoly._GeoInfo  = aInfo;                // All information given by cGeoData(PHP!)
                            this.loadGeometryListeners(oPoly);
                            var id = aInfo.id;                            
                        }
                        this.oPoints[id] = oPoly;               // Add object to factory
                        this.checkVisibility(oPoly);                        
                        break;
                        
                        
                    case "LINESTRING":
                        var oPoly = this.createPolyline(aInfo);
                        this.oMap.addOverlay(oPoly);
                        oPoly.titel = aInfo.titel;
                        oPoly.tooltip = aInfo[oSettings._sTooltipField];
                        oPoly.type = "linestring";
                        //oPoly.content = this.htmlInfoWindow(aInfo);
                        oPoly._GeoInfo  = aInfo;                // All information given by cGeoData(PHP!)
                        this.loadGeometryListeners(oPoly);
                        var id = aInfo.id;
                        this.oPoints[id] = oPoly;               // Add object to factory
                        this.checkVisibility(oPoly);
                        break;
                        
                    case "POINT":   
                        // console.log('Adding marker');
                        // console.log(aInfo);
                                        
                        // marker cache
                        if ( this.oMarkerCache.length > 0 ) {
                                                    
                            var oMarker = this.oMarkerCache.pop();
                                                        
                            oMarker.setPoint(new GLatLng( parseFloat(aInfo.lat), parseFloat(aInfo.lng) ));
                            var id = aInfo.id;
                            oMarker.title     = aInfo.titel;          // Define title
                            oMarker.tooltip   = aInfo[oSettings._sTooltipField];
                            oMarker.type        = "point";            // Set geometry type. Not used yet in 1.0
                            oMarker._GeoInfo  = aInfo;                // All information given by cGeoData(PHP!)
                            //oMarker.content = this.htmlInfoWindow(aInfo);
                            
                            oMarker.setImage(oIconmanager.get(aInfo.sg_id).image);
                            
                            this.oPoints[id] = oMarker;
                            
                            this.checkVisibility(oMarker);                            
                        
                        } else {
                            var point = new GMarker( new GLatLng( parseFloat(aInfo.lat), parseFloat(aInfo.lng) ), oIconmanager.get(aInfo.sg_id));    // Create object
                            var id = aInfo.id;
                            this.oPoints[id] = point;               // Add object to factory
                            
                            point.title     = aInfo.titel;          // Define title
                            point.tooltip   = aInfo[oSettings._sTooltipField];
                            point.type      = "point";            // Set geometry type. Not used yet in 1.0
                            point._GeoInfo  = aInfo;                // All information given by cGeoData(PHP!)

                            //point.content = this.htmlInfoWindow(aInfo);
                        
                            /** Default event listener for opening info window **/
                            /*console.log( 'Loading listeners');
                            console.log(this);
                            console.log(point);                            */
                            this.loadGeometryListeners(point);
                            
                            /** Add the overlay to the map **/
                            this.oMap.addOverlay(this.oPoints[aInfo.id]);
                            
                            this.checkVisibility(point);
                        }
                        break;
                    case "CLUSTER":
                        //console.log('adding '  + aInfo.id);
                        if(aInfo.id.indexOf('_') == -1) {
                            //console.log(aInfo);   
                        }
                        this.oPoints[aInfo.id] = oGeoStart.oClusterer.getMarker(aInfo);
                            
                        /** Add the overlay to the map **/
                        this.oMap.addOverlay(this.oPoints[aInfo.id]);
                        break;
                                             
                                                
                    case "MULTIPOLYGON":
                        if(oSettings._bTileServer){   
                                         
                            
                            var oPoly = new cTileMultiPoly();
                            oPoly.init(aInfo);
                            
                            //this.oMap.addOverlay(oPoly);        
                            //console.log(oPoly);
                            //this.loadGeometryListeners(oPoly);
                            var id = aInfo.id;                    
                            //this.aPolyBounds[id] = oPoly.getBounds();                    
                            this.oPoints[id] = oPoly;               // Add object to factory
                            this.checkVisibility(oPoly);
                            
                            
                        } else {
                        
                            var i = aInfo.aGeometry.length;
                            var aGeo = aInfo.aGeometry;
                            var aPolylines = [];
                            
                            var iPGWidth = 2;
                            var iPGOpacy = 1;
                            var iPGFillOpacy = 0.5;
                            
                            while ( i-- ) {
                                   //aPolylines.push(eval('({ color: "#'+sColor+'", weight: '+iPGWidth+', opacity: '+iPGOpacy+', points: "' + aGeo[i][0] + '",levels: "' + aGeo[i][1] + '", zoomFactor: 2, numLevels: 18 })'));
                                   aPolylines.push({ color: "#" + sColor, weight: iPGWidth, opacity: iPGOpacy, points: aGeo[i][0] ,levels: aGeo[i][1], zoomFactor: 2, numLevels: 18 });
                            }
                            var oEncoded = { 
                                polylines: aPolylines,
                                fill: true,
                                color:'#' + oIconmanager.get(aInfo.sg_id).color,
                                opacity: iPGFillOpacy,
                                outline: true
                            };
                                
                            //console.log(aInfo);
                                
                            var oPoly = new GPolygon.fromEncoded(oEncoded);
                            GMultiPolygon.apply(oPoly, []);                    
                            oPoly._gInitMulti(oEncoded);                    
                            oPoly.titel = aInfo.titel;
                            oPoly.tooltip = aInfo[oSettings._sTooltipField];
                            oPoly.type = "MULTIPOLYGON";
                            //oPoly.content = this.htmlInfoWindow(aInfo);
                            oPoly._GeoInfo  = aInfo;                // All information given by cGeoData(PHP!)
                            
                            this.oMap.addOverlay(oPoly);        
                            //console.log(oPoly);
                            this.loadGeometryListeners(oPoly);
                            var id = aInfo.id;                    
                            this.aPolyBounds[id] = oPoly.getBounds();                    
                            this.oPoints[id] = oPoly;               // Add object to factory
                            this.checkVisibility(oPoly);
                            break;
                        }
                }
            }
            return this.oPoints[id];
        };/** 
* @extends cGeoStart  
**/

    /************************************************
    *                                               *
    *    Minimap functions. Generate minimap code,  *
    *    load / init minimap                        *
    *                                               *
    ************************************************/

        /**
        *   Init a mini map. Clean map with one marker.
        *   Will callback this.loadMiniMap to load JSON data of marker.
        *   @param sMapId Name of the map div
        *   @param iId Id of the marker shown in the minimap
        **/
        cGeoStart.prototype.initMinimap = function(sMapId, iId){
            this.oMap = new GMap2(oGeoStart.util.getElementById(sMapId));
            
            this.oPoints = Object();
            cGeoStartPoly.apply(this, []); // Extend with poly objects
            
            GDownloadUrl( 'GeoStart/ajax/getItemById.php?id='+iId, GEvent.callback( this, this.loadMiniMap ) );
        };
        
        /**
        *   Callback function to load the minimap based on the init string.
        *   @param JSON string with single marker data array
        *   @note Highly customized function for use with minimap.tpl
        *   @private
        **/
        cGeoStart.prototype.loadMiniMap = function(JSON){
            aInfo = eval('(' + JSON + ')');
            
            this.oMap.setCenter(new GLatLng(aInfo.lat, aInfo.lng), aInfo.zoom);
            
            this.point = new GMarker( new GLatLng( parseFloat(aInfo.lat), parseFloat(aInfo.lng) ), oIconmanager.get(aInfo.sg_id));    // Create object
            this.point['_GeoInfo'] = aInfo;
            
            
            if ( aInfo.g_type == "point" ) {
                GEvent.addListener(this.point, 'click', function(){
                    oGeoStart.point.openInfoWindowHtml(oGeoStart.htmlMiniInfoWindow(oGeoStart.point._GeoInfo));
                });
            }
            
            this.oMap.addOverlay(this.point);
            
            oGeoStart.util.getElementById('miniTitel').innerHTML = aInfo.titel;
            
            // Delay needed. oMap needs a little while... buggy API :/
            setTimeout('oGeoStart.oMap.setZoom('+aInfo.zoom+');', 100);
        };
        
        /**
        *   Generate minimap iFrame code for inclusion in antoher webpage. 
        *   @param iMarkerId 
        *   @param iH Height in pixels.
        *   @param iW Width in pixels.
        **/
        cGeoStart.prototype.getMiniMapCode = function(iMarkerId, iH, iW){
            var sCode = '<iframe style="float:none;margin:2px;" src="' + sBaseUrl + '?minimap=1&marker_key=__MARKERID__&w=__WIDTH__&h=__HEIGHT__" width="__WIDTH2__" height="__HEIGHT__"></iframe>';
            
            /** Dynamicly replace variables. More of a proof of concept. Tho is makes changing a lot easier **/
            sCode = sCode.replace(/__HEIGHT__/g, iH);
            sCode = sCode.replace(/__WIDTH__/g, iW);
            sCode = sCode.replace(/__WIDTH2__/g, iW - 2);
            sCode = sCode.replace(/__MARKERID__/g, iMarkerId);
            
            return sCode;                        
        };
        
        
        /**
        *   Open embed InfoWindowHtml at place of current InfoWindow
        *   @param sKey Key of geometry/marker
        *   @param iId Id of the geometry/marker in the database
        *   @private
        **/
        cGeoStart.prototype.openEmbed = function(sKey, iId){
            var point = oGeoStart.oMap.getInfoWindow().getPoint();
            oGeoStart.oMap.closeInfoWindow();
            
            oGeoStart.oMap.openInfoWindowHtml(point, oGeoStart.html.htmlLinkEmbedWindow(sKey, iId));
        };
        
        /**
        *   Update the iFrame code based on inputs in cMapObjects::openEmbed
        *   @private
        **/
        cGeoStart.prototype.updateIframecode = function(){
            oGeoStart.util.getElementById('iframecode').value = this.getMiniMapCode( oGeoStart.util.getElementById('ifid').value, oGeoStart.util.getElementById('ifl').value, oGeoStart.util.getElementById('ifb').value );
        };cGeoStart.prototype.util = function(){};       


/**
* Todo caching implementeren, wat als HTML wordt weggehaald.
*/
cGeoStart.prototype.util.getElementById = function( sId ) {
    return document.getElementById(sId);
    
    if(typeof(this.oCache) == 'undefined'){
        this.oCache = {};   
    }
    
    this.oCache[sId] = document.getElementById(sId);
    
    return this.oCache[sId];    
}

/**
*   Extend on cGeoStart
*   Adds poly functinality
*   @extends cGeoStart  
*   @namespace cGeoStartPoly
*   @class
**/
function cGeoStartPoly(){
    this.bPolyLoaded = true;
    this.aPolyBounds = {};

    /**
    *   Create a polyline
    **/   
    this.createPolyline = function(aInfo){
        var aPoints = this.createPoints(aInfo);
        
        if ( aInfo.polykleur.length > 0 ){
            var oPoly = new GPolyline(aPoints, "#" + aInfo.polykleur, 4, 0.5);
        } else {
            var oPoly = new GPolyline(aPoints, "#" + oIconmanager.get(aInfo.sg_id).color, 4, 0.5);
        }
        oPoly._GeoInfo = aInfo;
        return oPoly;
    };
    
    /**
    *   Create a polyline
    **/   
    this.createPolygon = function(aInfo){        
        var aPoints = this.createPoints(aInfo);
        
        var sEdgecolor = "#" + sColor;
        if ( aInfo.polykleur.length > 0 ){
            var oPoly = new GPolygon(aPoints, "#"+sColor, 1, 1, '#' + aInfo.polykleur, 0.2);
        } else {
            var oPoly = new GPolygon(aPoints, "#"+sColor, 1, 1, '#' + oIconmanager.get(aInfo.sg_id).color, 0.2);
        }
        oPoly._GeoInfo = aInfo;
        
        this.aPolyBounds[aInfo.id] = oPoly.getBounds();
        //console.count('Polybound added')
        
        return oPoly;
    };
    
    /**
    *   Convert array of lat's and lng's to real GPoints()
    **/
    this.createPoints = function(aInfo){
        var aPoints = aInfo['aGeometry'];
        var iLength = aPoints.length;
        var aGPoints = [];
        for(var i=0; i<iLength; i++){
            point = new GLatLng( parseFloat(aPoints[i].lat), parseFloat(aPoints[i].lng) );
            aGPoints.push(point);
        }
        return aGPoints;
    };
    
    /**
    *   @desc Fills collection of bounds for polygones.
    **/    
    this.addPolyBound = function(iId, point){
        //this.aPolyBounds[iId].extend(point);
        
        alert('deprocated function, addPolybounds');
    };
    
    /**
    *   @desc Check if point is in polygon. Trigger click on item.
    *   @param point GPoint
    *   @return boolean Was an item found.
    **/
    this.checkClickedPoly = function(point){
        if ( point ) {
            for ( var i in this.aPolyBounds ){
                if (typeof(this.aPolyBounds[i]) != 'function' && this.aPolyBounds[i].contains(point)){                    
                    if (this.oPoints[i] && this.oPoints[i].Contains(point)){
                        return i;
                        break;
                    }
                }
            }
        }
        return false;
    };
};/**
*   GMultiPolygon extension. Single mapobject with multiple polygons as geometry
**/
function GMultiPolygon(){
    this._aPolys = Array();
    this._aPolyBounds = Array();
    
    /**
    *   Init, overwrites google functions
    *   @private
    **/
    this._gInitMulti = function(oArg){    
        var aPolyLines = oArg.polylines;
        var i = aPolyLines.length;
        while ( i-- ) {
            this._gAddPoly(GPolygon.fromEncoded({polylines:Array(aPolyLines[i]), fill:false, color:'#000000', opacity:100, outline:false}));
        }    
    };

    /**
    *   Add polygon and polybounds to list.
    *   @param oPoly <a target="_blank" href="http://code.google.com/intl/nl/apis/maps/documentation/reference.html#GPolygon">GPolygon</a> class
    *   @private
    **/ 
    this._gAddPoly = function(oPoly){
        this._aPolyBounds.push( oPoly.getBounds() );
        this._aPolys.push( oPoly );
    };

    /**
    *   Check if multipoly contains point.
    *   @param GPoint <a target="_blank" href="http://code.google.com/intl/nl/apis/maps/documentation/reference.html#GPoint">Google GPoint</a>
    **/
    this.Contains = function(point){
        var i = this._aPolyBounds.length;
        while ( i-- ) {
            if ( this._aPolyBounds[i].contains(point) ) {
                if ( this._gCheckPoly(i, point) ) {
                    return true;
                }
            }
        }
        return false;
    };
    
    /**
    *   @private
    **/
    this._gCheckPoly = function(index, point){
        return this._aPolys[index].Contains(point);
    };
    
    /**
    *   Get bounds of polygon
    **/
    this.getBounds = function() {
        if ( !this.oBounds ) {
            this.oBounds = new GLatLngBounds();
            var i = this._aPolyBounds.length;
            while ( i-- ) {
                this.oBounds.extend(this._aPolyBounds[i].getSouthWest());
                this.oBounds.extend(this._aPolyBounds[i].getNorthEast());
            }
        }
        return this.oBounds;
    };
};/**
*   @extends GPolygon
**/

/**
*   getPoint function for polygon
**/
GPolygon.prototype.getPoint = function(){
    return new GLatLng(parseFloat(this._GeoInfo['lat']), parseFloat(this._GeoInfo['lng']));
};

/**
*   Open InfoWindows for Polyline
**/    
GPolygon.prototype.openInfoWindowHtml = function(content){
    var oRef = this;    
    oGeoStart.oMap.openInfoWindowHtml(this.getPoint(), content, {onOpenFn:this.setUpListeners(this)});
};



GPolygon.prototype.setUpListeners = function(oRef){
    var closeEvent = GEvent.addListener(oGeoStart.oMap, 'infowindowclose', function(){
        GEvent.trigger(oRef, 'infowindowclose');
    });    
    this.handleInfoWindowClose();    
};

GPolygon.prototype.handleInfoWindowClose = function() { 
    var oRef = this;
    GEvent.addListener(oRef, 'infowindowclose', function(){
        try { closeEvent.remove(); } catch(e){}
        try { GEvent.removeListener(closeEvent);  } catch(e){}
    });
    GEvent.trigger(oRef, 'infowindowopen');
};
    
/**
*   @desc Check if polygon contains point.
*   @return boolean
**/    
GPolygon.prototype.Contains = function(point) {
    var j=0;
    var oddNodes = false;
    var x = point.lng();
    var y = point.lat();
    for (var i=0; i < this.getVertexCount(); i++) {
      j++;
      if (j == this.getVertexCount()) {j = 0;}
      if (((this.getVertex(i).lat() < y) && (this.getVertex(j).lat() >= y))
      || ((this.getVertex(j).lat() < y) && (this.getVertex(i).lat() >= y))) {
        if ( this.getVertex(i).lng() + (y - this.getVertex(i).lat())
        /  (this.getVertex(j).lat()-this.getVertex(i).lat())
        *  (this.getVertex(j).lng() - this.getVertex(i).lng())<x ) {
          oddNodes = !oddNodes;
        }
      }
    }
    return oddNodes;
};

GPolygon.prototype.openExtInfoWindow = function(map, cssId, html, opt_opts) {
  if (map == null) {
    throw 'Error in GPolygon.openExtInfoWindow: map cannot be null';
    return false;
  }
  if (cssId == null || cssId == '') {
    throw 'Error in GPolygon.openExtInfoWindow: must specify a cssId';
    return false;
  }
  
  map.closeInfoWindow();
  if (map.getExtInfoWindow() != null) {
    map.closeExtInfoWindow();
  }
  if (map.getExtInfoWindow() == null) {
    map.setExtInfoWindow_( new ExtInfoWindow(
      this,
      cssId,
      html,
      opt_opts
    ) );
    if (map.ClickListener_ == null) {
      //listen for map click, close ExtInfoWindow if open
      map.ClickListener_ = GEvent.addListener(map, 'click',
      function(event) {
          if( !event && map.getExtInfoWindow() != null ){
            map.closeExtInfoWindow();
          }
        }
      );
    }
    if (map.InfoWindowListener_ == null) {
      //listen for default info window open, close ExtInfoWindow if open
      map.InfoWindowListener_ = GEvent.addListener(map, 'infowindowopen', 
      function(event) {
          if (map.getExtInfoWindow() != null) {
            map.closeExtInfoWindow();
          }
        }
      );
    }
    map.addOverlay(map.getExtInfoWindow());
  }
};
GPolygon.prototype.getIcon = function(){
    var oIcon = new GIcon();
    oIcon.iconAnchor = new GPoint(0, 0);
    oIcon.iconSize = new GSize(0, 0);
    oIcon.infoWindowAnchor = new GPoint(120, 0);
    return oIcon;
}/**
* @extends GPolyline
**/

/**
*   getPoint function for polyline
**/
GPolyline.prototype.getPoint = function(){
    return new GLatLng(parseFloat(this._GeoInfo['lat']), parseFloat(this._GeoInfo['lng']));
};
    
/**
*   Open InfoWindows for Polyline
*   @param content Html content for infowindow
**/    
GPolyline.prototype.openInfoWindowHtml = function(content){
    var oRef = this;    
    oGeoStart.oMap.openInfoWindowHtml(this.getPoint(), content, {onOpenFn:this._setUpListeners(this)});
};

/**
*   Add event listeneners for inforwindowclose
*   @param oRef  Referenced mapobject
*   @private
**/    
GPolyline.prototype._setUpListeners = function(oRef){
    var closeEvent = GEvent.addListener(oGeoStart.oMap, 'infowindowclose', function(){
        GEvent.trigger(oRef, 'infowindowclose');
    });
    this._handleInfoWindowClose();    
};


/**
*   Handle close of infowindow
*   @private
**/
GPolyline.prototype._handleInfoWindowClose = function() { 
    var oRef = this;
    GEvent.addListener(oRef, 'infowindowclose', function(){
        try { closeEvent.remove(); } catch(e){}
        try { GEvent.removeListener(closeEvent);  } catch(e){}
    });
    GEvent.trigger(oRef, 'infowindowopen');
};

/**
*   @desc Check if polygon contains point. Hopefully works for polyline... *pray*
*   @param GPoint <a target="_blank" href="http://code.google.com/intl/nl/apis/maps/documentation/reference.html#GPoint">Google GPoint</a>
*   @return boolean
**/    
GPolyline.prototype.Contains = function(point) {
    var j=0;
    var oddNodes = false;
    var x = point.lng();
    var y = point.lat();
    for (var i=0; i < this.getVertexCount(); i++) {
      j++;
      if (j == this.getVertexCount()) {j = 0;}
      if (((this.getVertex(i).lat() < y) && (this.getVertex(j).lat() >= y))
      || ((this.getVertex(j).lat() < y) && (this.getVertex(i).lat() >= y))) {
        if ( this.getVertex(i).lng() + (y - this.getVertex(i).lat())
        /  (this.getVertex(j).lat()-this.getVertex(i).lat())
        *  (this.getVertex(j).lng() - this.getVertex(i).lng())<x ) {
          oddNodes = !oddNodes
        }
      }
    }
    return oddNodes;
};

GPolyline.prototype.openExtInfoWindow = function(map, cssId, html, opt_opts) {
  if (map == null) {
    throw 'Error in GPolygon.openExtInfoWindow: map cannot be null';
    return false;
  }
  if (cssId == null || cssId == '') {
    throw 'Error in GPolygon.openExtInfoWindow: must specify a cssId';
    return false;
  }
  
  map.closeInfoWindow();
  if (map.getExtInfoWindow() != null) {
    map.closeExtInfoWindow();
  }
  if (map.getExtInfoWindow() == null) {
    map.setExtInfoWindow_( new ExtInfoWindow(
      this,
      cssId,
      html,
      opt_opts
    ) );
    if (map.ClickListener_ == null) {
      //listen for map click, close ExtInfoWindow if open
      map.ClickListener_ = GEvent.addListener(map, 'click',
      function(event) {
          if( !event && map.getExtInfoWindow() != null ){
            map.closeExtInfoWindow();
          }
        }
      );
    }
    if (map.InfoWindowListener_ == null) {
      //listen for default info window open, close ExtInfoWindow if open
      map.InfoWindowListener_ = GEvent.addListener(map, 'infowindowopen', 
      function(event) {
          if (map.getExtInfoWindow() != null) {
            map.closeExtInfoWindow();
          }
        }
      );
    }
    map.addOverlay(map.getExtInfoWindow());
  }
};
GPolyline.prototype.getIcon = function(){
    var oIcon = new GIcon();
    oIcon.iconAnchor = new GPoint(0, 0);
    oIcon.iconSize = new GSize(0, 0);
    oIcon.infoWindowAnchor = new GPoint(120, 0);
    return oIcon;
}
/**
*   Extend on cGeoStart
*   Adds poly functinality
*   @extends cGeoStart  
*   @namespace cGeoStartPoly
*   @class
**/
function cTileMultiPoly(){
    this.bPolygonRendered = false;
    this.bHidden = true;
    this.oPolygon;
    
    GEvent.addListener(this, 'click', function() {
        this.renderPolygon();
        GEvent.trigger(this.oPolygon, "click");
    });
    
    this.init = function(aInfo){
        var iPGWidth = 2;
        var iPGOpacy = 1;
        var iPGFillOpacy = 0.5;
        
        var i = aInfo.aGeometry.length;
        var aGeo = aInfo.aGeometry;
        var aPolylines = [];                            
        while ( i-- ) {
               //aPolylines.push(eval('({ color: "#'+sColor+'", weight: '+iPGWidth+', opacity: '+iPGOpacy+', points: "' + aGeo[i][0] + '",levels: "' + aGeo[i][1] + '", zoomFactor: 2, numLevels: 18 })'));
               aPolylines.push({ color: "#"+sColor, weight: iPGWidth, opacity: iPGOpacy, points: aGeo[i][0] ,levels: aGeo[i][1], zoomFactor: 2, numLevels: 18 });
        }
        var oEncoded = { 
            polylines: aPolylines,
            fill: true,
            color:'#' + oIconmanager.get(aInfo.sg_id).color,
            opacity: iPGFillOpacy,
            outline: true
        };
            
        //console.log(aInfo);
            
        var oPoly = new GPolygon.fromEncoded(oEncoded);
        GMultiPolygon.apply(oPoly, []);                    
        oPoly._gInitMulti(oEncoded);                    
        oPoly.titel = aInfo.titel;
        oPoly.tooltip = aInfo[oSettings._sTooltipField];
        oPoly.type = "MULTIPOLYGON";
        //oPoly.content = this.htmlInfoWindow(aInfo);
        oPoly._GeoInfo  = aInfo;                // All information given by cGeoData(PHP!)
        this._GeoInfo = aInfo;

        this.oPolygon = oPoly;
        
        oGeoStart.oTilePolyHandler.oPolyIds[aInfo.id] = true;
        
        oGeoStart.loadGeometryListeners(this.oPolygon);

        
    }
    
    this.containsPoint = function(y, x) {
       return this.oPolygon.Contains(new GLatLng(parseFloat(y), parseFloat(x)));
    }
    
    
    this.inBounds = function(lat, lng) {
        var i = this.oPolygon._aPolyBounds.length;
        var oLatLng = new GLatLng(lat,lng);
        while(i--){
            if(this.oPolygon._aPolyBounds[i].contains(oLatLng)){
                return true;   
            }
        }
        return false;
    }

    this.renderPolygon = function() {
        if(!this.bPolygonRendered){
            oGeoStart.oMap.addOverlay(this.oPolygon);
            this.bPolygonRendered = true;
        }
    }
    
    this.hidePolygon = function() {
        if(this.bPolygonRendered) {
            oGeoStart.oMap.removeOverlay(this.oPolygon);
            this.bPolygonRendered = false;        
        }
    }
    
    this.hide = function() {
        this.bHidden = true;
        this.hidePolygon();
    }
    
    this.show = function() {
        this.bHidden = false;
    }    
        
        
    this.isHidden = function() {
        return this.bHidden;
    }
    
}
/**
*   Extend on cGeoStart
*   Adds poly functinality
*   @extends cGeoStart  
*   @namespace cGeoStartPoly
*   @class
**/
function cTilePoly(){
    this.bPolygonRendered = false;
    this.bHidden = true;
    this.oPolygon;
    
    GEvent.addListener(this, 'click', function() {
        this.renderPolygon();
        GEvent.trigger(this.oPolygon, "click");
    });
    
    this.containsPoint = function(y, x) {
        x = parseFloat(x);
        y = parseFloat(y);
        
        var oddNodes = false;
        
        for (var i=0; i < this._GeoInfo.aGeometry.length; i++) {

            j = i+1;
        
            if (j == this._GeoInfo.aGeometry.length) j = 0;
            
            var fLat = {    "i" : parseFloat(this._GeoInfo.aGeometry[i].lat),
                            "j" : parseFloat(this._GeoInfo.aGeometry[j].lat) };
            
            var fLng = {    "i" : parseFloat(this._GeoInfo.aGeometry[i].lng),
                            "j" : parseFloat(this._GeoInfo.aGeometry[j].lng) };
                            
           
            if (((fLat.i < y) && (fLat.j >= y)) || ((fLat.j < y) && (fLat.i >= y))) {

                if ( fLng.i + (y - fLat.i) / (fLat.j - fLat.i) * (fLng.j - fLng.i)<x ) {
                    oddNodes = !oddNodes;
                    
                }
            }
        }

        return oddNodes;

    }
    
    
    this.inBounds = function(lat, lng) {
        if(typeof(this._GeoInfo.aBounds) == 'undefined'){
            this._GeoInfo.aBounds = this._aGeoInfo.aGeometry.aBounds;
        }

        
        if( lat < this._GeoInfo.aBounds.ne.lat && lat > this._GeoInfo.aBounds.sw.lat &&
            lng < this._GeoInfo.aBounds.ne.lng && lng > this._GeoInfo.aBounds.sw.lng ) {
            return true;
        }
        
        return false;
    }

    this.renderPolygon = function() {
        if(!this.bPolygonRendered){

            if(typeof(this.oPolygon) == "undefined") {
                this.oPolygon = oGeoStart.createPolygon(this._GeoInfo);
                oGeoStart.loadGeometryListeners(this.oPolygon);
            }
            
            oGeoStart.oMap.addOverlay(this.oPolygon);

            this.bPolygonRendered = true;
        }
    }
    
    this.hidePolygon = function() {
        if(this.bPolygonRendered) {
            oGeoStart.oMap.removeOverlay(this.oPolygon);
            this.bPolygonRendered = false;        
        }
    }
    
    this.hide = function() {
        this.bHidden = true;
        this.hidePolygon();
    }
    
    this.show = function() {
        this.bHidden = false;
    }    
        
        
    this.isHidden = function() {
        return this.bHidden;
    }
    
}
/**
*   handle icons. Added to help handle errors in groups etc.
*   @class cIconManager manage icon data in the JS api
*   @constructor
**/
function cIconManager(){
    /**
    *   Get icon of subgroep
    *   @param iId Subgroep id
    *   @param sColor Optionsal color, only used when iId = route
    *   @return oIcon Modified <a href="http://code.google.com/intl/nl/apis/maps/documentation/reference.html#GIcon" target="_blank">GIcon</a>, sg_titel as extra, used by {@link cTooltip} to identify category name.
    **/
    this.get = function(iId, sColor) {
        
        /**
        var oIcon           = new GIcon(G_DEFAULT_ICON);
        oIcon.sg_titel = 'Testing icon speed';
        return oIcon;
        **/
        
        
        
        if( typeof(this.oIcons[iId]) == "object" ) {
            return this.oIcons[iId];
        } else if( typeof(iId) == 'number' ) {
            console.log('Didnt find: ' + iId);
            var oIcon           = new GIcon(G_DEFAULT_ICON);
            oIcon.sg_titel = 'Icoon niet gevonden';
            return oIcon;       
    
        } else if( iId.indexOf("poi") > -1 ){
            var oIcon           = new GIcon(this.oBaseIcon);
            oIcon.image         = sBaseUrl + "GeoStart/images/poi_icon.png";
            oIcon.sg_titel      = "Bezienswaardigheid";
            return oIcon;
        } else if ( iId.indexOf("route_start") > -1 ) {
            var oIcon           = new GIcon(this.oBaseIcon);
            oIcon.iconSize      = new GSize(10, 10);
            oIcon.iconAnchor    = new GPoint(5, 5);
            oIcon.image         = sBaseUrl + "GeoStart/images/route_start.png";
            oIcon.sg_titel      = "Start van de route";
            return oIcon;
        } else if ( iId.indexOf("route_end") > -1) {
            var oIcon           = new GIcon(this.oBaseIcon);
            oIcon.iconSize      = new GSize(10, 10);
            oIcon.iconAnchor    = new GPoint(5, 5);
            oIcon.image         = sBaseUrl + "GeoStart/images/route_end.png";
            oIcon.sg_titel      = "Einde van de route";
            return oIcon;
        } else if ( iId == 'route' ) {
            var oIcon           = new GIcon(this.oBaseIcon);
            oIcon.iconSize      = new GSize(15, 15);
            oIcon.iconAnchor    = new GPoint(8, 8);
            oIcon.infoWindowAnchor  = new GPoint(8, 8);
            oIcon.image         = sBaseUrl + "icon/" + sColor + "/trans/dot.gif.png";
            oIcon.sg_titel      = "Bezienswaardigheid";
            return oIcon;               
        } else {
            //GLog.write("No icon found for " + iId);
            for(var key in this.oIcons ){
                if(typeof(this.oIcons[key]) != 'function') return this.oIcons[key];                
            }
        }
    };
};
/**
*   @class cIntroScreen v. 1.0
*   Class showing Introscreen when visiting GeoStart
*
*   Floris Lovink - Swis BV
**/

function cIntroScreen(){
    this.init = function(){
        this.oContainer = oGeoStart.util.getElementById('introScreen');
        this.oContainer.style.display = "none";
        
        this.oStadsdelen  = {   "centrum" :         {   "lat" : 52.073176,
                                                        "lng" : 4.305611,
                                                        "z"   : 14 },
                                "haagsehout" :      {   "lat" : 52.088683,
                                                        "lng" : 4.33754,
                                                        "z"   : 14 },
                                "leidschenveen":    {   "lat" : 52.059879,
                                                        "lng" : 4.379768,
                                                        "z"   : 14 },
                                "scheveningen":     {   "lat" : 52.106294,
                                                        "lng" : 4.291534,
                                                        "z"   : 14 }, 
                                "escamp" :          {   "lat" : 52.048901,
                                                        "lng" : 4.272652,
                                                        "z"   : 14 },
                                "laak" :            {   "lat" : 52.064101,
                                                        "lng" : 4.330673,
                                                        "z"   : 14 },
                                "loosduinen" :      {   "lat" : 52.054602,
                                                        "lng" : 4.22905,
                                                        "z"   : 14 },
                                "segbroek" :        {   "lat" : 52.075497,
                                                        "lng" : 4.260635,
                                                        "z"   : 14 } };
       
        
        this.fillContainer();
    };
    this.checkResize = function() {
        var oRect = findPos(oGeoStart.util.getElementById("geoMap"));
        this.oContainer.style.left = parseInt( ( oRect[0] + parseInt(oGeoStart.util.getElementById("geoMap").clientWidth / 2, 10) ) - ( this.oContainer.clientWidth / 2 )  , 10) + 'px';
    };
        
    this.show = function(){
        this.oContainer.style.display = "block";
    };                     
    
    this.gotoStadsdeel = function(sStadsdeel) {
        this.hide();
                
        var oStadsDeel = this.oStadsdelen[sStadsdeel];
        oGeoStart.oMap.setCenter(new GLatLng(parseFloat(oStadsDeel.lat), parseFloat(oStadsDeel.lng)), parseInt(oStadsDeel.z, 10));
        
        return false;
    };
        
   
    this.hide = function(){                             
        if ( this.oContainer ) {
            this.oContainer.style.display = "none";    
        }
    };
    
    this.fillContainer = function(){
        var aHtml = new Array();
        aHtml.push('<a id="sluiten_btn" onclick="oIntroScreen.hide(); return false;" href="#">Sluiten <img src="' + sBaseUrl + 'GeoStart/images/ballon/ballon_close.gif" alt="sluiten" /></a>');
        aHtml.push('<h1>Den Haag op de Kaart</h1>');
        aHtml.push('<p id="intro">Den Haag op de kaart wijst u de weg langs meer dan 2.000 locaties waaronder <a onclick="oMenu.iPortal = 1; oMenu.iRubriek = 1; oMenu.setPortal(); oIntroScreen.hide(); return false" href="rubriek/cultuur/musea">musea</a>, <a onclick="oMenu.iPortal = 7; oMenu.setPortal(); oIntroScreen.hide(); return false" href="rubriek/sport">sportverenigingen</a>, <a onclick="oMenu.iPortal = 5; oMenu.setPortal(); oIntroScreen.hide(); return false" href="rubriek/onderwijs">scholen</a>, <a onclick="oMenu.iPortal = 6; oMenu.iRubriek = 18; oMenu.setPortal(); oIntroScreen.hide(); return false" href="rubriek/gemeente/stadsdeelkantoren">stadsdeelkantoren</a>, <a onclick="oMenu.iPortal = 2; oMenu.iRubriek = 2; oMenu.setPortal(); oIntroScreen.hide(); return false" href="rubriek/gezondheid/ziekenhuizen">ziekenhuizen</a> etc.</p>');
        
        aHtml.push('<div id="actionLinks">');
            aHtml.push('<h2>Direct naar een stadsdeel</h2>');
            
            aHtml.push('<ul>');
                aHtml.push('<li><a onclick="oIntroScreen.gotoStadsdeel(\'centrum\');" href="#"><img src="GeoStart/images/ballon/go.gif" alt="go" /> Centrum</a></li>');
                aHtml.push('<li><a onclick="oIntroScreen.gotoStadsdeel(\'haagsehout\');" href="#"><img src="GeoStart/images/ballon/go.gif" alt="go" /> Haagse Hout</a></li>');
                aHtml.push('<li><a onclick="oIntroScreen.gotoStadsdeel(\'leidschenveen\');" href="#"><img src="GeoStart/images/ballon/go.gif" alt="go" /> Leidschenveen - Ypenburg</a></li>');
                aHtml.push('<li><a onclick="oIntroScreen.gotoStadsdeel(\'scheveningen\');" href="#"><img src="GeoStart/images/ballon/go.gif" alt="go" /> Scheveningen</a></li>');
            aHtml.push('</ul>');
        
            aHtml.push('<ul>');
                aHtml.push('<li><a onclick="oIntroScreen.gotoStadsdeel(\'escamp\');" href="#"><img src="GeoStart/images/ballon/go.gif" alt="go" /> Escamp</a></li>');
                aHtml.push('<li><a onclick="oIntroScreen.gotoStadsdeel(\'laak\');" href="#"><img src="GeoStart/images/ballon/go.gif" alt="go" /> Laak</a></li>');
                aHtml.push('<li><a onclick="oIntroScreen.gotoStadsdeel(\'loosduinen\');" href="#"><img src="GeoStart/images/ballon/go.gif" alt="go" /> Loosduinen</a></li>');
                aHtml.push('<li><a onclick="oIntroScreen.gotoStadsdeel(\'segbroek\');" href="#"><img src="GeoStart/images/ballon/go.gif" alt="go" /> Segbroek</a></li>');
            aHtml.push('</ul>');
              
        aHtml.push('</div>');
        
        aHtml.push('<p><strong>Hoe werkt het?</strong><br>Gebruik het menu aan de linkerzijde om rubrieken te selecteren. Versleep de kaart met uw muis en gebruik de zoomfunctie om Den Haag te doorkruisen. Zoekt u iets specifieks? Gebruik dan de zoekfunctie links bovenin uw scherm. Voor nadere instructie kunt u de <a href="#" onclick="oGeoStart.html.helpRequest();oIntroScreen.hide();return false;">helpfunctie</a> raadplegen. </p>');
        
        
        var sHtml = aHtml.join("\n");

        this.oContainer.innerHTML = sHtml;  
    };
}var MapIconMaker={};MapIconMaker.createMarkerIcon=function(a){var b=a.width||32;var c=a.height||32;var d=a.primaryColor||"#ff0000";var e=a.strokeColor||"#000000";var f=a.cornerColor||"#ffffff";var g="http://chart.apis.google.com/chart?cht=mm";var h=g+"&chs="+b+"x"+c+"&chco="+f.replace("#","")+","+d.replace("#","")+","+e.replace("#","")+"&ext=.png";var j=new GIcon(G_DEFAULT_ICON);j.image=h;j.iconSize=new GSize(b,c);j.shadowSize=new GSize(Math.floor(b*1.6),c);j.iconAnchor=new GPoint(b/2,c);j.infoWindowAnchor=new GPoint(b/2,Math.floor(c/12));j.printImage=h+"&chof=gif";j.mozPrintImage=h+"&chf=bg,s,ECECD8"+"&chof=gif";h=g+"&chs="+b+"x"+c+"&chco="+f.replace("#","")+","+d.replace("#","")+","+e.replace("#","");j.transparent=h+"&chf=a,s,ffffff11&ext=.png";j.imageMap=[b/2,c,(7/16)*b,(5/8)*c,(5/16)*b,(7/16)*c,(7/32)*b,(5/16)*c,(5/16)*b,(1/8)*c,(1/2)*b,0,(11/16)*b,(1/8)*c,(25/32)*b,(5/16)*c,(11/16)*b,(7/16)*c,(9/16)*b,(5/8)*c];for(var i=0;i<j.imageMap.length;i++){j.imageMap[i]=parseInt(j.imageMap[i])}return j};MapIconMaker.createFlatIcon=function(b){var c=b.width||32;var d=b.height||32;var e=b.primaryColor||"#ff0000";var f=b.shadowColor||"#000000";var g=MapIconMaker.escapeUserText_(b.label)||"";var h=b.labelColor||"#000000";var i=b.labelSize||0;var j=b.shape||"circle";var k=(j=="circle")?"it":"itr";var l="http://chart.apis.google.com/chart?cht="+k;var m=l+"&chs="+c+"x"+d+"&chco="+e.replace("#","")+","+f.replace("#","")+"ff,ffffff01"+"&chl="+g+"&chx="+h.replace("#","")+","+i;var n=new GIcon(G_DEFAULT_ICON);n.image=m+"&chf=bg,s,00000000"+"&ext=.png";n.iconSize=new GSize(c,d);n.shadowSize=new GSize(0,0);n.iconAnchor=new GPoint(c/2,d/2);n.infoWindowAnchor=new GPoint(c/2,d/2);n.printImage=m+"&chof=gif";n.mozPrintImage=m+"&chf=bg,s,ECECD8"+"&chof=gif";n.transparent=m+"&chf=a,s,ffffff01&ext=.png";n.imageMap=[];if(k=="roundrect"){n.imageMap=[0,0,c,0,c,d,0,d]}else{var o=8;var p=360/o;var q=Math.min(c,d)/2;for(var a=0;a<(o+1);a++){var r=p*a*(Math.PI/180);var s=q+q*Math.cos(r);var t=q+q*Math.sin(r);n.imageMap.push(parseInt(s),parseInt(t))}}return n};MapIconMaker.createLabeledMarkerIcon=function(a){var b=a.primaryColor||"#DA7187";var c=a.strokeColor||"#000000";var d=a.starPrimaryColor||"#FFFF00";var e=a.starStrokeColor||"#0000FF";var f=MapIconMaker.escapeUserText_(a.label)||"";var g=a.labelColor||"#000000";var h=a.addStar||false;var i=(h)?"pin_star":"pin";var j="http://chart.apis.google.com/chart?cht=d&chdp=mapsapi&chl=";var k=j+i+"'i\\"+"'["+f+"'-2'f\\"+"hv'a\\]"+"h\\]o\\"+b.replace("#","")+"'fC\\"+g.replace("#","")+"'tC\\"+c.replace("#","")+"'eC\\";if(h){k+=d.replace("#","")+"'1C\\"+e.replace("#","")+"'0C\\"}k+="Lauto'f\\";var l=new GIcon(G_DEFAULT_ICON);l.image=k+"&ext=.png";l.iconSize=(h)?new GSize(23,39):new GSize(21,34);return l};MapIconMaker.escapeUserText_=function(a){if(a===undefined){return null}a=a.replace(/@/,"@@");a=a.replace(/\\/,"@\\");a=a.replace(/'/,"@'");a=a.replace(/\[/,"@[");a=a.replace(/\]/,"@]");return encodeURIComponent(a)};
/**
*   @class cMapMaker v. 1.0
*   Class handling the frontend MapMaker. 
*
*   Floris Lovink - Swis BV
**/

function cMapMaker(sMapMakerElement) {
    var self = this;
  
    this.bSaveStatic = false;
  
    this.oMapMakerElement   = oGeoStart.util.getElementById(sMapMakerElement);
        
    this.oMapMakerWidth = oGeoStart.util.getElementById('mapMaker_width');
    this.oMapMakerHeight = oGeoStart.util.getElementById('mapMaker_height');
        
    /*show or hide the mapmaker */
    this.toggle = function() {
        if(this.oMapMakerElement.style.display != 'block') {
            oGeoStart.oMapMaker.show();            
            oGeoStart.oMapMaker.initializeDraggabelObject();
        } else {
            oGeoStart.oMapMaker.hide();
        }
    }

    /*Show the mapMaker*/
    this.show = function(){
        oGeoStart.bMapMakerOpen = true;
        oGeoStart.oMapMaker.oMapMakerElement.style.display = 'block';
        if(typeof(oGeoStart.oZoomArrow)!='undefined'){
            oGeoStart.oZoomArrow.hide();
        }
        oGeoStart.oMapMaker.oMapMakerElement.style.visibility = 'visible';
        
        oGeoStart.oMapMaker.oMapMakerElement.style.left = Math.round((oGeoStart.oMap.getContainer().clientWidth / 2) - (398 / 2)) + 'px';
        
        oGeoStart.oMapMaker.oMapMakerElement.style.top = Math.round((oGeoStart.oMap.getContainer().clientHeight / 2) - (298 / 2)) + 'px';
        
        oGeoStart.oMapMaker.oMapMakerElement.style.width    = '398px';
        oGeoStart.oMapMaker.oMapMakerElement.style.height   = '298px';   

        
        oGeoStart.util.getElementById("mapMaker_width").innerHTML     = oGeoStart.oMapMaker.getSize().width;

        oGeoStart.util.getElementById("mapMaker_height").innerHTML    = oGeoStart.oMapMaker.getSize().height;        
        oGeoStart.util.getElementById('mapMaker_title').style.color    = '#494949';
    }
    
    /*Reset all inputs, width and height and then hide the mapMaker */
    this.hide = function () {
       oGeoStart.bMapMakerOpen = false;
       oGeoStart.oMapMaker.swapContent('mapMaker_step1');
       oGeoStart.util.getElementById('mapMaker_title').value          = 'Voer een titel in voor de kaart';
       
       oGeoStart.util.getElementById('mapMaker_embed').embedCode.value                  = '';
       
       oGeoStart.oMapMaker.oMapMakerElement.style.width    = '398px';
       oGeoStart.oMapMaker.oMapMakerElement.style.height   = '298px';   
       
       oGeoStart.oMapMaker.oMapMakerElement.style.display = 'none';
       
       if(typeof(oGeoStart.oZoomArrow)!='undefined'){
            oGeoStart.oZoomArrow.checkHidden(oMenu.iHidden, oMenu._iVisible);
       }
       
       oGeoStart.util.getElementById('mapMaker_title').style.color    = '#494949';
       
       oGeoStart.oMapMaker.swapContent('mapMaker_step1');
    }
    
    this.initializeDraggabelObject = function() {
        if(typeof(oGeoStart.oMapMaker.oDragResize) == 'undefined') {
            //<![CDATA[

            // Using DragResize is simple!
            // You first declare a new DragResize() object, passing its own name and an object
            // whose keys constitute optional parameters/settings:
            oGeoStart.oMapMaker.oDragResize = new DragResize('dragresize', { minWidth: 400, minHeight: 300, minLeft: 0, minTop: 0, maxLeft: 600, maxTop: 600 });

            // Optional settings/properties of the DragResize object are:
            //  enabled: Toggle whether the object is active.
            //  handles[]: An array of drag handles to use (see the .JS file).
            //  minWidth, minHeight: Minimum size to which elements are resized (in pixels).
            //  minLeft, maxLeft, minTop, maxTop: Bounding box (in pixels).

            // Next, you must define two functions, isElement and isHandle. These are passed
            // a given DOM element, and must "return true" if the element in question is a
            // draggable element or draggable handle. Here, I'm checking for the CSS classname
            // of the elements, but you have have any combination of conditions you like:

            oGeoStart.oMapMaker.oDragResize.isElement = function(elm) {
                if (elm.className && elm.className.indexOf('drsElement') > -1) return true;
            };
            oGeoStart.oMapMaker.oDragResize.isHandle = function(elm) {
                if (elm.className && elm.className.indexOf('drsMoveHandle') > -1) return true;
            };

            // You can define optional functions that are called as elements are dragged/resized.
            // Some are passed true if the source event was a resize, or false if it's a drag.
            // The focus/blur events are called as handles are added/removed from an object,
            // and the others are called as users drag, move and release the object's handles.
            // You might use these to examine the properties of the DragResize object to sync
            // other page elements, etc.

            oGeoStart.oMapMaker.oDragResize.ondragfocus = function() { };
            
            oGeoStart.oMapMaker.oDragResize.ondragstart = function(isResize) { 
                oGeoStart.oMapMaker.oDragResize.maxTop = oGeoStart.oMap.getSize().height;
                oGeoStart.oMapMaker.oDragResize.maxLeft = oGeoStart.oMap.getSize().width;
            };
            oGeoStart.oMapMaker.oDragResize.ondragmove = function(isResize) { 
                oGeoStart.oMapMaker.oMapMakerHeight.innerHTML = oGeoStart.oMapMaker.getSize().height;
                oGeoStart.oMapMaker.oMapMakerWidth.innerHTML = oGeoStart.oMapMaker.getSize().width;
            };
            oGeoStart.oMapMaker.oDragResize.ondragend = function(isResize) {
                oGeoStart.oMapMaker.oMapMakerHeight.innerHTML = oGeoStart.oMapMaker.getSize().height;
                oGeoStart.oMapMaker.oMapMakerWidth.innerHTML = oGeoStart.oMapMaker.getSize().width;
            };
            oGeoStart.oMapMaker.oDragResize.ondragblur = function() { };

            // Finally, you must apply() your DragResize object to a DOM node; all children of this
            // node will then be made draggable. 
            oGeoStart.oMapMaker.oDragResize.apply(oGeoStart.oMap.getContainer());

            //]]>
        } else {
            oGeoStart.oMapMaker.oMapMakerElement.style.width = '400px';
            oGeoStart.oMapMaker.oMapMakerElement.style.height = '300px';
            oGeoStart.oMapMaker.oDragResize.minHeight = 300;
            oGeoStart.oMapMaker.oDragResize.minWidth = 400;
            oGeoStart.oMapMaker.oDragResize.elmH = 300;
            oGeoStart.oMapMaker.oDragResize.elmW = 400;
            oGeoStart.oMapMaker.oDragResize.minLeft= 0;
            oGeoStart.oMapMaker.oDragResize.minTop = 0;
            
        }
    }

    /**
    *   Return de viewport-box van de mapmaker
    *
    *   @see http://code.google.com/apis/maps/documentation/reference.html#GLatLngBounds
    *
    *   @Return GLatLngBounds met de viewport
    */    
    this.getLatLngBounds = function() {
        if(oGeoStart.oMapMaker.oMapMakerElement.style.display == 'block') {
            
            var x = parseInt(oGeoStart.oMapMaker.oMapMakerElement.style.left.replace('px', ''), 10);
            var y = parseInt(oGeoStart.oMapMaker.oMapMakerElement.style.top.replace('px', '') ,10) + 39;
            
            var iWidth = parseInt(oGeoStart.oMapMaker.oMapMakerElement.style.width.replace('px', ''),10);
            var iHeight = parseInt(oGeoStart.oMapMaker.oMapMakerElement.style.height.replace('px', ''),10) - 46;
            
            var oReturn = new GLatLngBounds(
                oGeoStart.oMap.fromContainerPixelToLatLng(new GPoint(x, y + iHeight)),
                oGeoStart.oMap.fromContainerPixelToLatLng(new GPoint(x + iWidth, y))
            );
            
            return oReturn;
        }
    }

    /* Returns the width and height of the mapmaker */
    this.getSize = function(){
        var iWidth = oGeoStart.oMapMaker.oMapMakerElement.style.width.replace('px', '');
        var iHeight = oGeoStart.oMapMaker.oMapMakerElement.style.height.replace('px', '') - 46;
        
        if(iWidth == "") {
            iWidth = "400";
        }
        
        if(iHeight == "") {
            iHeight = "300";
        }
        
        
        
        var oSize =  {  'width':    iWidth,
                        'height':   iHeight }

        return oSize;
    }
    
    /* Swap the content of the mapmaker */
    this.swapContent = function(element){
        var aBlocks = new Object();
        aBlocks['mapMaker_step1'] = oGeoStart.util.getElementById('mapMaker_step1');
        aBlocks['mapMaker_step2'] = oGeoStart.util.getElementById('mapMaker_step2');
        
        if(element == 'mapMaker_step2' && ( oGeoStart.util.getElementById('mapMaker_title').value == '' || oGeoStart.util.getElementById('mapMaker_title').value =='Voer een titel in voor de kaart') ) {
            alert("Je hebt nog geen titel voor de kaart ingevoerd");
            oGeoStart.util.getElementById('mapMaker_title').value = '';
            oGeoStart.util.getElementById('mapMaker_title').focus();
        } else {
            if(element == "mapMaker_step2") {
                oGeoStart.util.getElementById('mapMaker_loading').style.display = 'block';
                oGeoStart.util.getElementById('mapMaker_embedForm').style.display = 'none';
                
                var oPos = findPos(oGeoStart.util.getElementById("mapMaker_step1"));
            
                var iTop = parseInt(oPos[1], 10);
                if(!bFullScreen) {
                    iTop -= parseInt(oSettings._HeaderHeight, 10);
                }
                
                oGeoStart.util.getElementById('mapMaker_frame').style.visibility = 'hidden';

            
                oGeoStart.util.getElementById("mapMaker_step2").style.left    = oPos[0] + 2 + 'px';
                
                oGeoStart.util.getElementById("mapMaker_step2").style.top     = iTop + 'px';
                oGeoStart.util.getElementById("mapMaker_step2").style.width   = oGeoStart.util.getElementById("mapMaker_frame").clientWidth + 'px';
                oGeoStart.util.getElementById("mapMaker_step2").style.height  = oGeoStart.util.getElementById("mapMaker_frame").clientHeight + 'px';
            }
            
            if(element == "mapMaker_step1"){
                oGeoStart.util.getElementById('mapMaker_frame').style.visibility = 'visible';                       
            }

            for ( var sId in aBlocks ) {
                if(typeof(aBlocks[sId]) != 'function'){
                    aBlocks[sId].style.display = 'none';
                }
            }    
            aBlocks[element].style.display = 'block';
            if(element != 'mapMaker_step1'){
                oGeoStart.oMapMaker.setMapData();
            }    

        }
    }
        
    this.getVisibleMarkersString = function() {
        var aMarkers = [];
        for(var i in oGeoStart.oPoints) {
            if(!oGeoStart.oPoints[i].isHidden()){
                aMarkers.push(i);
            }
        }
        
        return aMarkers.join("|");        
    }
    
    
    this.setMapMakerWizardData = function() {
        
        if(oGeoStart.oMap.getExtInfoWindow() != null) {
            oGeoStart.oMap.getExtInfoWindow().remove();
        }
        
        var sTitle = oGeoStart.util.getElementById("kaart_titel").value;
        if(sTitle == "") {
            alert("Je hebt de kaart nog geen titel gegeven.");
            oGeoStart.util.getElementById("kaart_titel").focus();
            return false;
        }
        
        var iZoom               = oGeoStart.oMap.getZoom();
        var sCenter             = oGeoStart.oMap.getCenter().toUrlValue();
        var sVisibleMarkers     = this.getVisibleMarkersString();
        
        var oBounds             = oGeoStart.oMap.getBounds();
        //var oMarkerPositions    = this.getMarkerPositions();    

        var iHeight             = oGeoStart.oMap.getContainer().clientHeight;
        var iWidth              = oGeoStart.oMap.getContainer().clientWidth;

        var sNorthEast          = oBounds.getNorthEast().toUrlValue();
        var sSouthWest          = oBounds.getSouthWest().toUrlValue();
        
        switch(oGeoStart.oMap.getCurrentMapType().getUrlArg()){
            case 'm':
                var sMapType = 1;
                break;
            case 'k':
                var sMapType = 2;
                break;
            case 'h':
                var sMapType = 3;
                break;
            case 'p':
                var sMapType = 4;
                break;
        }        
       
        var sArgs = '';
        
        sArgs +=  'zoom=' + iZoom + '&center=' + sCenter;
        
        sArgs += '&title=' + escape(sTitle);
  
        sArgs += '&sMapType=' + sMapType;
    
        if(iWidth) {
            sArgs += '&width=' + iWidth;
        }

        if(iHeight) {
            sArgs += '&height=' + iHeight;
        }
        
        sArgs += '&markers=' + sVisibleMarkers;
        
        sArgs += '&ne=' + sNorthEast;
        
        sArgs += '&sw=' + sSouthWest;
        
        if(oGeoStart.oCrossSiteProxy){
            oGeoStart.oCrossSiteProxy.load('createMapMaker', sBaseUrl + 'GeoStart/ajax/createMapMaker.php?' + sArgs);
            oGeoStart.oCrossSiteProxy.call(oGeoStart.oMapMaker.handleMapMakerWizardRequest);
        } else {
            GDownloadUrl(sBaseUrl + 'GeoStart/ajax/createMapMaker.php', GEvent.callback( oGeoStart.oMapMaker, oGeoStart.oMapMaker.handleMapMakerWizardRequest), sArgs );
        }
    }
    
    this.handleMapMakerWizardRequest = function(json) {
        aInfo = eval('('+json+')');

        if(aInfo.key != false){
            oGeoStart.oMapMaker.submitMapMakerWizard(aInfo.key, aInfo.width, aInfo.height, aInfo.id);
        }
    }
    
    this.submitMapMakerWizard = function(sKey, iWidth, iHeight, iId) {
        window.opener.Webbeheer.Modules.MapMaker.setNewKey(sKey, iWidth, iHeight, iId);
        window.close();
    }
   
    /*Get all the current conditions en save the created map in the db*/
    this.setMapData = function(){
        if(bMapMakerWizard) {
            return this.setMapMakerWizardData();
        }
        
        if ( this.bSaveStatic ) {
            this.oMarkerPositions = this.getMarkerPositions();    
        }

        
        var sArgs = '';
        
        var iZoom           = oGeoStart.oMap.getZoom();
        var sCenter         = oGeoStart.oMapMaker.getLatLngBounds().getCenter().toUrlValue();
        var sVisibleCats    = oMenu.getCheckBoxDataString();
        
        var iHeight         = oGeoStart.util.getElementById("mapMaker_height").innerHTML;
        var iWidth          = oGeoStart.util.getElementById("mapMaker_width").innerHTML;
        var sTitle          = oGeoStart.util.getElementById("mapMaker_title").value;
        
        
        var sNorthEast = oGeoStart.oMapMaker.getLatLngBounds().getNorthEast().toUrlValue();
        var sSouthWest = oGeoStart.oMapMaker.getLatLngBounds().getSouthWest().toUrlValue();
        
        switch(oGeoStart.oMap.getCurrentMapType().getUrlArg()){
            case 'm':
                var sMapType = 1;
                break;
            case 'k':
                var sMapType = 2;
                break;
            case 'h':
                var sMapType = 3;
                break;
            case 'p':
                var sMapType = 4;
                break;
        }
        
        
        
        sArgs +=  'zoom=' + iZoom + '&center=' + sCenter;
        
        sArgs += '&title=' + escape(sTitle);
  
        sArgs += '&sMapType=' + sMapType;
    
        if(iWidth) {
            sArgs += '&width=' + iWidth;
        }

        if(iHeight) {
            sArgs += '&height=' + iHeight;
        }
        
        sArgs += '&subcats=' + sVisibleCats;
        
        sArgs += '&ne=' + sNorthEast;
        
        sArgs += '&sw=' + sSouthWest;
        
        if(oSettings.show_cbs_data && oGeoStart.oCbsData.getStatistiek() != false) {
            sArgs += '&stat=' + oGeoStart.oCbsData.getStatistiek();
        }        
        
        if(oGeoStart.oCrossSiteProxy){
            oGeoStart.oCrossSiteProxy.load('setMapData', sBaseUrl + 'GeoStart/ajax/createMapMaker.php?' + sArgs);
            oGeoStart.oCrossSiteProxy.call(oGeoStart.oMapMaker.handleKeyRequest);
        } else {
            GDownloadUrl(sBaseUrl + 'GeoStart/ajax/createMapMaker.php', GEvent.callback( oGeoStart.oMapMaker, oGeoStart.oMapMaker.handleKeyRequest), sArgs );
        }
    }
    
    /* Handle the requested key, generated in createMapMaker.php */
    this.handleKeyRequest = function(json){
        aInfo = eval('('+json+')');

        if(aInfo.key != false){
            oGeoStart.oMapMaker.createEmbedLink(aInfo.key, aInfo.width, aInfo.height);
        }
        
        if ( this.bSaveStatic ) {
            var sGet = [];
            for(var key in this.oMarkerPositions){
                if(typeof(this.oMarkerPositions[key]) != 'function'){
                    // Get string opbouwn: id=x,y
                    sGet.push(key + '='  + this.oMarkerPositions[key].x + ',' + this.oMarkerPositions[key].y);
                }
            }
        }
        
    }
    
    /* Put the embedlinkTxt in de textarea of the mapmaker*/
    this.createEmbedLink = function(sKey, iWidth, iHeight){
        oGeoStart.util.getElementById('mapMaker_loading').style.display = 'none';
        oGeoStart.util.getElementById('mapMaker_embedForm').style.display = 'block';
        var sIframeHtml  = ''; 
        sIframeHtml      = '<iframe width="'+iWidth+'" height="'+iHeight+'" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="' + sBaseUrl + 'embed/' + sKey + '"></iframe>'; 

        oGeoStart.util.getElementById('mapMaker_embed').embedCode.value = sIframeHtml;
        
        if(iWidth > 640 || iHeight > 640){
            var warningDiv = oGeoStart.util.getElementById('mapMaker_warning');
            warningDiv.style.display    = "block";
            warningDiv.innerHTML        = "Let op: Deze kaart is te groot en zal niet getoond kunnen worden. De maximale afmetingen voor statische kaarten is 640 x 640px. De afmetingen van uw kaart zijn: " + iWidth + " x " + iHeight + "px.";
        } else {
            oGeoStart.util.getElementById('mapMaker_warning').style.display = "none";
        }        
        //oGeoStart.util.getElementById('embedCodeStatic').href = sBaseUrl + 'GeoStart/staticmap/staticmap.php?sMapMaker=' + sKey;
        
        oGeoStart.util.getElementById('embedCodePreviewLink').href = sBaseUrl + 'embed/' + sKey;

        oGeoStart.util.getElementById('mapMaker_embed').embedKey.value = sKey;
    }
        
    /**
    *   Get marker positions for all markers in the viewport of the mapmaker frame.
    **/ 
    this.getMarkerPositions = function(){
        if(bMapMakerWizard) {
            var oBounds = oGeoStart.oMap.getBounds();
        } else {
            var oBounds = this.getLatLngBounds();
        }
        
        var oXyBottomLeft = oGeoStart.oMap.fromLatLngToContainerPixel(oBounds.getSouthWest());
        var oXyTopRight   = oGeoStart.oMap.fromLatLngToContainerPixel(oBounds.getNorthEast());
        
        var oOffset = new GPoint(oXyBottomLeft.x, oXyTopRight.y);
        
        var oMarkerPositions = {};
        
        for ( var iId in oGeoStart.oPoints ) {
            if(typeof(oGeoStart.oPoints[iId])!='function'){
                if ( oBounds.contains(oGeoStart.oPoints[iId].getPoint()) ) {
                    oXy = oGeoStart.oMap.fromLatLngToContainerPixel(oGeoStart.oPoints[iId].getPoint());
                    oMarkerPositions[iId] = new GPoint(oXy.x - oOffset.x, oXy.y - oOffset.y);
                }
            }
        }
        
        return oMarkerPositions;
                        
    }
        
}

/**
*	Menu handler.
*	Responsible for menu operations like current status.
*   @class cMenu handle menu data and state's
*   @contructor
**/
function cMenu(){
    
    /** Array with states **/
	var aState;				// Stores open elements in menu. Reference by menuitem.id
	/** Array with base tree of menu **/
    var aTree;
	/** The menu element (dom) **/
    var oMenuElement;		// The menu element
    var oMenuItemsElement;
    
    /** Hoofdrubriek **/
    var iPortal;
    
    /** Subrubriek **/
    var iRubriek;
    
    
	
	/**
	*	Initialize menu class
    *   @param sMenuElement Name of the menu element
    *   @param sMenuItemsElement Name of the element to load HTML into
    *   @param sMenuCounterElement Name of the element to load counter data into
	**/
	this.init = function(sMenuElement, sMenuItemsElement, sMenuCounterElement ){
        
        this.oMenuElement = oGeoStart.util.getElementById(sMenuElement);
        
        this.oMenuElement.onclick = this.eventDelegationHandler;
        this.oMenuElement.onmouseover = this.eventDelegationHandler;
        this.oMenuElement.onmouseout = this.eventDelegationHandler;
        
        this.oMenuElement.oMenu = this;
        
        this.oMenuItemsElement = oGeoStart.util.getElementById(sMenuItemsElement);

		this.oMenuCounterElement = oGeoStart.util.getElementById(sMenuCounterElement);
		this.oStateMenu = {};
		this.oStateCB = {};
		this.oStateCategory = {};
		this.oTree = {};
        this.iPortal = 0;
        this.iRubriek = 0;
        
        this.oHoofdmenuLi = {};
                
        this.bFirstLoad = true;
	};
	
    /**
    * Events op het menu afhandlen
    */
    this.eventDelegationHandler =  function(e){
        if (!e) var e = window.event;
        eTarget = this.oMenu.getEventTarget(e);
        sType = e.type;
        
        switch(sType){
            case 'click':
                return this.oMenu.handleClickEvent(eTarget);                
            case 'mouseout':                
            case 'mouseover':
                this.oMenu.handleMouseEvent(eTarget, sType);                
        }        
    }
    
    this.handleMouseEvent = function(eTarget, sType){
        if(eTarget.className == 'location_icon' && eTarget.parentNode.className !== 'offscreen' ){
            if ( sType == 'mouseover' ) {
                oGeoStart.trigger(this.findMarkerId(eTarget.id), 'mouseover');   
            } else {
                oGeoStart._oTooltip.hide();
            }
        }
    }   
    
    this.getEventTarget = function(e){
      e = e || window.event;
      return e.target || e.srcElement;
    }
    
    /**
    * Click events afhandelen.
    * @param eTarget Element die target is.
    */
    this.handleClickEvent = function(eTarget){
        
        // Checkboxes
        if ( eTarget.tagName == 'INPUT' ) {
            if ( eTarget.id.indexOf('GeoMenu_hg') !== -1 ) {
                this.toggleParent(eTarget.id.replace('GeoMenu_hg_cb_', ''), eTarget.checked);
            } else if ( eTarget.id.indexOf('GeoMenu_sg') !== -1 ) {
                this.toggleCategory(eTarget.id.replace('GeoMenu_sg_cb_', ''), eTarget.checked);
            }        
        // Links
        } else if ( eTarget.tagName == 'A' ) {
            // Marker link
            if( eTarget.className == 'location_icon' ) {
                var iId = this.findMarkerId(eTarget.id);
                oGeoStart.gotoHiddenId(iId);                
            // Lijst van locaties van subgroep
            } else if( eTarget.className == 'go' ) {
                
                var iSg = eTarget.parentNode.parentNode.parentNode.id.replace('subCats_item_', '');
                this.getItemList(iSg);
                
            // Hoofd of subcategorie linkje
            }  else {
                eParent = eTarget.parentNode;
                if(eParent.id.indexOf('mainCats') !== -1){
                    var iHg = eParent.id.replace('mainCats_item_', '');
                    
                    this.closeRoot(iHg);
                    this.handleOpenHg(iHg);
                    this.toggleDisplay('mainCats_item_' + iHg);
                    
                } else if(eParent.id.indexOf('subCats') !== -1){
                    var iSg = eParent.id.replace('subCats_item_', '');
                    var iHg = eParent.parentNode.parentNode.id.replace('mainCats_item_', '');
                    
                    this.handleOpenSg(iHg, iSg);                    
                    
                } else {
                    
                    GLog.write('Onafgehandelde link geklikt: ' + eTarget.id);
                                                            
                }
            }
            return false;
        } else if ( eTarget.tagName == 'SPAN' ) {
            // Alles aan/uit
            if( eTarget.id == 'toggleOn' ) {
                oMenu.toggleAll(true);
            } else if( eTarget.id == 'toggleOff' ) {
                oMenu.toggleAll(false);
            } else if( eTarget.className == 'plus' ){
                return this.handleClickEvent(eTarget.parentNode);
            }               
        }
    }
    
    this.findMarkerId = function(sId){
        // m{iSg}_{iMarkerId}
        return sId.substring(sId.indexOf("_")+1)   
    }

	/**
	*	Call all load state functions
	**/
	this.loadState = function(){
        if ( oGeoStart.bFirstLoad && sMapMaker == '' ) {
            aInputs = oGeoStart.util.getElementById('location_menu').getElementsByTagName('input');        
            var i=aInputs.length;        
            while ( i-- ){
                oMenu.oStateCB[aInputs[i].id] = false;
            }
        }
        
        oMenu.loadDisplayState();
		oMenu.loadCbState();
	};

	/**
	*	Update menu
    *   @param oMenuData Eval-led data gotten from getData.php {@link cGeoStart#update()}
	*   @private
    **/
	this.update = function(oMenuData){
		GEvent.trigger(oMenu, 'beforeUpdate');
        
        // Als het menu moet worden getoond
        if ( typeof(oSettings) == 'undefined' || oSettings._bMenu !== false ) {
            
            // Controle wat er moet gebeuren
            if(oMenuData.sMenuHtml === false) {
                // Geen menu update nodig.
            } else if (typeof(oMenuData.sMenuHtml) == 'string') {
                // Hele menu invullen
                oMenu.oMenuItemsElement.innerHTML = oMenuData.sMenuHtml;

                if(oMenu.oMenuCounterElement != null){
                    oMenu.oMenuCounterElement.innerHTML = oMenuData.sCounterHtml;
                }
            } else if (typeof(oMenuData.sMenuHtml) == 'object') {
                // Is een array met veranderde hoofdgroepen
                for (var iHoofdgroep in oMenuData.sMenuHtml) {
                    if(typeof(this.oHoofdmenuLi[iHoofdgroep]) == 'undefined'){
                        this.oHoofdmenuLi[iHoofdgroep] = oGeoStart.util.getElementById('mainCats_item_'
                        +iHoofdgroep);
                    }
                    // Inner html optimalisatie
                    this.oHoofdmenuLi[iHoofdgroep].innerHTML = oMenuData.sMenuHtml[iHoofdgroep];     
                }
                                
            }
                
        }
        
        
        // Staat laden
        oMenu.loadState();
        oMenu.oTree = oMenuData.aTree;
		oMenu.oCounter = oMenuData.aMenu;
        oMenu._iVisible = oMenuData.iVisible;
        oMenu.oCatOf = oMenuData.oPointToCat;
        oMenu.iHidden = oMenuData.iHidden;
        


        
        
        var i = 0; 
        // Tel aantal hoofdmenu items
        for ( var x in this.oTree ) { if(typeof(this.oTree[x])!= 'function'){i++;} } 
        
        if ( oGeoStart.util.getElementById('GeoMenu_hg_route') != null ) {
            // Open / closed onthouden
            if ( oGeoStart.util.getElementById('GeoMenu_hg_route') != null && oGeoStart.util.getElementById('GeoMenu_hg_route').className.indexOf('closed') != -1 ) { var sExtra = 'cat_item_closed '; } else { var sExtra = ''; }
            
            // Even oneven bepalen
            if (i%2 == 0) { oGeoStart.util.getElementById('GeoMenu_hg_route').className = sExtra + "even"; } 
            else { oGeoStart.util.getElementById('GeoMenu_hg_route').className = sExtra + "uneven"; } 
        }
        
        if(this.bFirstLoad){
            oMenu.fillCbState();
            
            for ( var k in this.oTree ) {
                if(typeof(this.oTree[k])!='function'){
                    for ( var i in this.oTree[k] ) {
                        if(typeof(this.oTree[k][i])!='function'){
                            this.oStateCategory[i] = false;
                        }
                    }
                }
            }
            
            this.bFirstLoad = false;
        }
        
        // Link to cat/subcat afhandelen
        if ( this.iPortal > 0 ) {
            oMenu.setPortal();
        }
        
        
        GEvent.trigger(oMenu, 'updated');
             
	};
	
	/**
	*	Return category states, restructured object to array for quicker loops
    *   @return Array
	**/
	this.getCatStates = function(){
		var aReturn = []; // Redo object to array for speed.
		for ( var k in this.oStateCategory ) {            
			if ( typeof(this.oStateCategory) != 'function' && this.oStateCategory[k] == false ) {
				aReturn.push(k);
			}
		}
		return aReturn;	
	};

	/************************************************
	*												*
	*	Menu display/hide functions					*
	*												*
	************************************************/
		/**
		*	Toggle item referenced by id.
        *   @param sId String DOM id of element
		**/
		this.toggleDisplay = function(sId){
            var oItem = oGeoStart.util.getElementById(sId);
            var aClasses = oItem.className.split(' ');
            
            if ( typeof(aClasses[1]) == 'undefined' ) { aClasses[1] = ' '; }
            
            if ( aClasses[0] == 'cat_item_closed' ) {
                oItem.className = 'cat_item_open ' + aClasses[1];
                oItem.style.backgroundColor =  '#CECECE';
                oMenu.oStateMenu[sId] = aClasses[1];
            } else {
                oItem.className = 'cat_item_closed ' + aClasses[1];
                oItem.style.backgroundColor = "#FFFFFF";
                delete(oMenu.oStateMenu[sId]);
               
            }
		};
		
        
        
        
        /**
        *   Close all root categories.
        *   @param iClickedId Which element was clicked. This element will not be closed. This is used to be sure only 1 item is open
        **/
        this.closeRoot = function(iClickedId){
            
            for ( var k in this.oTree ){
                if ( typeof(this.oTree[k]) != 'function' && this.oStateMenu['mainCats_item_' + k] != undefined && k != iClickedId) {
                    this.toggleDisplay('mainCats_item_' + k, this.oStateMenu['mainCats_item_' + k]);
                }
            }
            
        };
        
        /**
        *   Close all subcategories within given root.
        *   @param iHg hoofdgroep id
        *   @param iSg subgroep id
        **/
        this.closeSubs = function(iHg, iSg){
            for ( var k in this.oStateMenu ) {
                if ( typeof(this.oStateMenu[k]) != 'function' && this.oStateMenu[k] == " " && k != "subCats_item_"+iSg ) {
                    this.toggleDisplay(k, this.oStateMenu[k]);
                }
            }
        };
        
        
        
        /**
        *   Set instead of toggle for updating items.
        *   @param string DOM id
        *   @param 
        **/
        this.setDisplayOn = function(sId) {
            oItem = oGeoStart.util.getElementById(sId);
            if(oItem.className.indexOf('cat_item_closed') !== -1 ) {
                oItem.className = oItem.className.replace('cat_item_closed', 'cat_item_open');
                oItem.style.backgroundColor =  '#CECECE';
            }
        }
        
		/**
		*	Load menu state from {@link cMenu#oStateMenu}
		**/
		this.loadDisplayState = function(){
            
			for ( k in oMenu.oStateMenu ){
                if ( oMenu.oStateMenu[k] != 'function' && k.indexOf('_route') == -1 ) {
                    oMenu.setDisplayOn(k);
                }
			}
		};
        
        
        /**
        *   Count current "visible" items whose 
        *   checkboxes arn't checked.
        *   @param string Element which contains the counter.
        **/
        this.countOffItems = function(sElement){
            if ( oGeoStart.util.getElementById(sElement) ) {
                oGeoStart.util.getElementById(sElement).innerHTML = oGeoStart.getVisiblityCounters().iVisible;                
            }
        };
        
        /**
        *   @deprecated Was niet mooi.
        *   @private
        **/
        this.openMenuGroup = function(sId){
            if ( !this.oHeaders ) { this.initMenuGroup(); }        
            for ( var k in this.oHeaders ) {
                if(typeof(this.oHeaders[k]) !='function'){
                    if ( k == sId ) {
                        this.oHeaders[k]['menu'].style.display = "";
                        //this.oHeaders[k]['header'].getElementsByTagName('a')[0].innerHTML = "";
                        this.oHeaders[k].action();
                    } else {
                        this.oHeaders[k]['menu'].style.display = "none";
                        //this.oHeaders[k]['header'].getElementsByTagName('a')[0].innerHTML = "<img src='images/help_plus.gif'>";
                        this.oHeaders[k]['header'].style.borderTop = "1px solid #D9D9D9";
                        //this.oHeaders[k].action();
                    }
                }
            }
        };
        
        
        /**
        *   @deprecated Was niet mooi.
        *   @private
        **/
        this.initMenuGroup = function(){
            this.oHeaders = {};
            this.oHeaders = { 'rubrieken': {'menu':    oGeoStart.util.getElementById('locaties-content'),
                                            'header':  oGeoStart.util.getElementById('locaties-header'),
                                            'action':  function(){ oMenu.toggleAll(true); oGeoStart.oRoutes.hide(); }},
                              'routes':    {'menu':    oGeoStart.util.getElementById('GeoDirections'),
                                            'header':  oGeoStart.util.getElementById('routes-header'),
                                            'action':  function(){ oMenu.toggleAll(false); oGeoStart.oRoutes.show(); }}
                                            };
        };
        
	/************************************************
	*												*
	*	Menu checkbox functions						*
	*												*
	************************************************/
		/**
		*	Toggle a category. Send appropiate commands to cMapObjects
        *   @param iId id of cateogry
        *   @param bDisplay Display or hide
		**/
		this.toggleCategory = function(iId, bDisplay){
            
            this.setCbState('sg', iId, bDisplay);
			if ( bDisplay ) { oGeoStart.showCategory(iId);
			} else {		  oGeoStart.hideCategory(iId);	}
		};
		
        /**
        *   Handle click of open HG. If currently closed, make sure the markers become visible.
        *   @param iId hoofdgroep id
        *   @private
        **/
        this.handleOpenHg = function(iId){
            if(oSettings.enable_display_on_open === true) {
                var sResult = oGeoStart.util.getElementById('mainCats_item_'+iId).className.indexOf('closed');             
                if ( sResult != -1 ) {
                    this.toggleParent(iId, true);
                }            
            }
        };
        
        this.handleOpenSg = function(iHg, iSg) {
            var sResult = oGeoStart.util.getElementById('subCats_item_'+iSg).className.indexOf('closed');             
            if(sResult != -1){
                if(oSettings.enable_display_on_open === true) {
                    oGeoStart.util.getElementById('GeoMenu_sg_cb_'+iSg).checked = true;
                    oMenu.closeSubs(iHg, iSg); 
                    oMenu.toggleCategory(iSg, true);                
                }
                
                oMenu.toggleDisplay('subCats_item_' + iSg, true);            
                
            } else {
                oMenu.toggleDisplay('subCats_item_' + iSg, false);
            }
        };
        
		/**
		*	Toggle parent category.
        *   @param iId Hoofdgroep id
        *   @param bDisplay Show or hide
		*   @private
        **/
		this.toggleParent = function(iId, bDisplay){
            
			var aInfo = [];
			this.setCbState('hg', iId, bDisplay);
			
			for ( var k in this.oTree[iId] ) {        
                if(typeof(this.oTree[iId][k]) != 'function'){
                    this.setCbState('sg', k, bDisplay);
				    aInfo.push(k);                    
                }
			}
            this.setChildCheckboxes('mainCats_item_' + iId, bDisplay); 
			if ( bDisplay ){
                oGeoStart.showCategoryGroup(aInfo);
			} else {
				oGeoStart.hideCategoryGroup(aInfo);
			}
		};
		
		/**
		*	Set all child checkboxes of hoofdmenu iId
        *   @param iId Hoofdgroep id
        *   @param bDisplay Show or hide
        *   @privata
		*   @private
        **/
		this.setChildCheckboxes = function(iId, bState){
            
            var aChildren = oGeoStart.util.getElementById(iId).getElementsByTagName('input');
			var i = aChildren.length;
			while ( i-- ){
				aChildren[i].checked = bState;
                oMenu.oStateCB[aChildren[i].id] = bState;
			}    
		};
		
        
        this.fillCbState = function(){
            var aChildren = oGeoStart.util.getElementById('locaties-content').getElementsByTagName('input');
            var i = aChildren.length;
            while ( i-- ){
                oMenu.oStateCB[aChildren[i].id] = aChildren[i].checked;
            }    
        }
        
		/**
		*	Save checkbox state
        *   @private
		**/
		this.setCbState = function(sG, iId, bChecked){
            var bPrevious  = oMenu.oStateCB['GeoMenu_' + sG + '_cb_' + iId];
            
			oMenu.oStateCB['GeoMenu_' + sG + '_cb_' + iId] = bChecked;			
            
			if ( sG == 'sg' ) { 
                oMenu.oStateCategory[iId] = bChecked; 
                                
                if ( bPrevious != bChecked ) {
                    oGeoStart.loadObjects();
                }
            }
		};
		
		/**
		*   Load checkboxes state into menu.
		**/
		this.loadCbState = function(){
			var aChildren = this.oMenuElement.getElementsByTagName('input');
			var i = aChildren.length;
			while ( i-- ){            
				if ( oMenu.oStateCB[aChildren[i].id] == false ) {
					aChildren[i].checked = false;
				} else {
					aChildren[i].checked = true;	
				}
			}
		};
        
        /**
        *   Toggle all items.
        *   @param sClick What was clicked. Used to check if you click a checkbox, to fix a bug.
        **/
        this.toggleAll = function(sClick){
            var sClick = sClick || '';        
        
            var eCb = oGeoStart.util.getElementById('toggleAll');
            
            /*Close ExtInfoWindow if the object exists*/
            if(oGeoStart.oMap.getExtInfoWindow()){
                oGeoStart.oMap.getExtInfoWindow().remove();
            }
            
            if ( eCb.type == 'checkbox' ) {                
                if ( sClick != 'input' ) {
                    eCb.checked = !eCb.checked;
                }
                bState = eCb.checked;
            } else {            
                bState = sClick;
                if ( sClick ) {
                    oGeoStart.util.getElementById('toggleOff').className = 'off toggle';
                    oGeoStart.util.getElementById('toggleOn').className = 'on toggle';
                } else {
                    oGeoStart.util.getElementById('toggleOff').className = 'on toggle';
                    oGeoStart.util.getElementById('toggleOn').className = 'off toggle';
                }
            }
                
            this.oStateCB['toggleAll'] = bState;
            
            
            this.setChildCheckboxes(this.oMenuElement.id, bState);
            
            for ( var k in this.oTree ) {
                if(typeof(this.oTree[k])!='function'){
                    for ( var i in this.oTree[k] ) {
                        if(typeof(this.oTree[k][i])!='function'){
                            this.oStateCategory[i] = bState;
                        }
                    }
                }
            }
            
            oGeoStart.setAll( bState );
            oGeoStart.loadObjects();
        };
        
    /*************************************************
    *                                                *
    *    List items functions                        *
    *                                                *
    *************************************************/
        /**
        *   Get list of all items in the cateogriy
        *   @param iCategory Category to get the list from
        *   @param iPage Page of the list, defaults to 1.
        **/
        this.getItemList = function(iCategory, iPage){
            var iPage = iPage || 1;
            
            if(oGeoStart.oCrossSiteProxy){
                oGeoStart.oCrossSiteProxy.load('oMenu.showItemList', sBaseUrl + "GeoStart/ajax/getCategoryItems.php?category="+iCategory+"&iPage="+iPage);
                oGeoStart.oCrossSiteProxy.call(oMenu.showItemList);
            } else {
                GDownloadUrl(sBaseUrl + "GeoStart/ajax/getCategoryItems.php?category="+iCategory+"&iPage="+iPage, oMenu.showItemList);
            }            
            
        };
        
        
        /**
        *   Get list of all sport accommedaties
        *   @param iCategory Sport to get the list from
        *   @param iPage Page of the list, defaults to 1.
        **/
        this.getSportList = function(iCategory, iPage){
            var iPage = iPage || 1;
            
            if(oGeoStart.oCrossSiteProxy){
                oGeoStart.oCrossSiteProxy.load('oMenu.showSportItemList', sBaseUrl + "GeoStart/ajax/getSportItems.php?sport="+iCategory+"&iPage="+iPage);
                oGeoStart.oCrossSiteProxy.call(oMenu.showItemList);
            } else {
                GDownloadUrl(sBaseUrl + "GeoStart/ajax/getSportItems.php?sport="+iCategory+"&iPage="+iPage, oMenu.showItemList);
            }            
        };
        
        
        /**
        *   Show category item list
        *   @param aData array with data from json request {@link cMenu#getSportList}
        **/
        this.showItemList = function(aData){
            oGeoStart.oMenuEffects.openInfoPane();     
            aJSON = eval("("+aData+")");
            
            /*
            if ( iPage == 1 && typeof(aJSON.sport_titel) == 'undefined' ) {
                pageHit(sBaseUrl + 'portaal/' + aInfo[0].hg_key + '/' + aInfo[0].sg_key );
            }
            */
            
            oGeoStart.util.getElementById('listWrap').innerHTML = aJSON.html;
            //oGeoStart.util.getElementById('tabTitleText').innerHTML = aJSON.sTitel;
            
            //swap('tab', true);
            //oGeoStart.util.getElementById('iMarkerId').value = '';
            //oGeoStart.util.getElementById('iCatId').value = aInfo[i-1].sg_id;
            setInfoPaneContent('list');
            
            //return; 
        };
        
    /**
    *   Load the hoofdgroep (open and toggle display)
    **/
    this.setPortal = function(){
        pageHit();

        this.toggleAll(); 
        if ( this.iRubriek > 0 ) {
            this.toggleDisplay("mainCats_item_" + this.iPortal );
            this.toggleDisplay("subCats_item_" + this.iRubriek );
            
            oGeoStart.util.getElementById('GeoMenu_sg_cb_'+ this.iRubriek).checked=true;            
            this.toggleCategory(this.iRubriek, true);
            
        } else {
            this.toggleParent(this.iPortal, true);
            this.toggleDisplay("mainCats_item_" + this.iPortal );
        }
        this.iPortal = 0;
        this.iRubriek = 0;        
    };
    
    
    /**
    *   Create a PIPE seperated string to send to getData.php to only load the markers that should be shown.
    **/
    this.getCheckBoxDataString = function(){
        if ( !this.oCheckBoxes ) {
            this.oCheckBoxes = this.oMenuItemsElement.getElementsByTagName('input');
        }        
        
        var i= this.oCheckBoxes.length;
        
        var aOnBoxes = [];
        
        while ( i-- ) {
            if ( this.oCheckBoxes[i].checked ) {
                if ( this.oCheckBoxes[i].id.indexOf('GeoMenu_sg_cb_') != -1 ) {
                    aOnBoxes.push(this.oCheckBoxes[i].id.substring(14));
                }
            }
        }
        return aOnBoxes.join('|');        
    };
    
    /**
    *   Create an array with all the opened subcats
    **/
    this.getVisibleSubCats = function(){
        if ( !this.oCheckBoxes ) {
            this.oCheckBoxes = this.oMenuItemsElement.getElementsByTagName('input');
        }        
        
        var i= this.oCheckBoxes.length;
        
        var aOnBoxes = [];
        
        while ( i-- ) {
            if ( this.oCheckBoxes[i].checked ) {
                if ( this.oCheckBoxes[i].id.indexOf('GeoMenu_sg_cb_') != -1 ) {
                    aOnBoxes.push(this.oCheckBoxes[i].id.substring(14));
                }
            }
        }
        return aOnBoxes;
    };    
};/**
* Menu effects.
* Events: slideend
*/
function cMenuEffects(sMenuContainerId) {
    this.speed              = 2; 
    this.speedHorizontal    = 2;
    
    this.iTabTimer          = 2;
    this.timerHorizontal    = 2;
    
    this.oMenuContainer     = oGeoStart.util.getElementById(sMenuContainerId);
    this.oMenuHeaders       = this.oMenuContainer.getElementsByTagName("dt");
    this.oMenuContents      = this.oMenuContainer.getElementsByTagName("dd");
    
    this.oMenuHandle        = oGeoStart.util.getElementById("menuHandle");
    this.oMapDiv            = oGeoStart.util.getElementById("geoMapContainer");
        
    this.iMenuHeight        = this.oMenuContainer.clientHeight;
    this.iTabs              = this.oMenuHeaders.length;
    
    this.bForceNoClose      = false;
    
    this.oInfoPane          = oGeoStart.util.getElementById("infoPane");
    this.oInfoPaneContent   = oGeoStart.util.getElementById("infoPaneContent");
    this.oInfoPaneHandle    = oGeoStart.util.getElementById("infoPane_img");

    
    
    for(i=0; i<this.iTabs; i++) {
        var sHeaderId   = this.oMenuHeaders[i].id;
        this.oMenuHeaders[i].onclick    = new Function("oGeoStart.oMenuEffects.slideTab("+ i + ")");       

        if(!HasClassName(this.oMenuHeaders[i], "active")){
            this.oMenuContents[i].style.display  = 'none';       
            this.oMenuContents[i].style.height   = 0 + 'px'; 
            this.oMenuContents[i].style.overflow = 'hidden';
        } else {
            this.oMenuContents[i].style.display  = 'block'; 
            this.oMenuContents[i].style.height   = this.iMenuHeight - (this.iTabs*32) + 5 + 'px';
        }

    }
        
    this.slideTab = function(iTab) {
        
        this.hideInfoPane();
        
        if(!HasClassName(this.oMenuHeaders[iTab], 'active')) {
            for(i=0; i<this.iTabs; i++){
                oTab        = this.oMenuHeaders[i];
                oContent    = this.oMenuContents[i];

                clearInterval(oContent.timer);
                if(iTab==i){
                    AddClassName(oTab, "active");
                    this.iMaxContentHeight = this.iMenuHeight - (this.iTabs*32) + 4;
                    
                    oContent.style.display  =   'block';
                    
                    this.startSlideEffect(i, 1);
                } else {
                    if(HasClassName(oTab, "active")) {
                        this.startSlideEffect(i, -1);                    
                        RemoveClassName(oTab, "active");
                    }
                }
            }

        }
        
    },
    
    this.openTab = function(sTab) {
        for(i=0; i<this.iTabs; i++) {
            var sHeaderId = this.oMenuHeaders[i].id;
            var sTabIdSplit = sHeaderId.split("-");
            var sTabId = sTabIdSplit[0];
            if(sTab == sTabId){
                this.slideTab(i);
            }
        }
    },
    
    this.startSlideEffect = function(iTab,iDirection){
        this.oMenuContents[iTab].direction  = iDirection; 
        
        var oInnerDiv = this.oMenuContents[iTab].getElementsByTagName("div")[0];
        if(HasClassName(oInnerDiv, "inner")) {
            if(iDirection == 1) {
                oInnerDiv.style.display = 'none';
            } else {
                oInnerDiv.style.display = 'none';
            }
        }
                
        this.oMenuContents[iTab].timer      = setInterval("oGeoStart.oMenuEffects.slideEffect('"+ iTab +"')",10)
    },
    
    this.getContainerHeight = function() {
        if(!bFullScreen) {
            return this.oMenuContainer.clientHeight;
        } else {
            var aSize = checkSize();
            var myHeight = aSize[1];
            return parseInt(myHeight-40-14-10);
        }
    },
    
    this.slideEffect = function(iTab) {

        speed = 2

        dist = (this.oMenuContents[iTab].direction==1)?Math.round((this.iMaxContentHeight-this.oMenuContents[iTab].offsetHeight)/speed):Math.round(this.oMenuContents[iTab].offsetHeight/speed);
        
        if(dist<=1){dist=1}
        
        this.oMenuContents[iTab].style.height = this.oMenuContents[iTab].offsetHeight + ( dist*this.oMenuContents[iTab].direction ) + 1 + 'px'; 

        if(this.oMenuContents[iTab].offsetHeight<=2&&this.oMenuContents[iTab].direction!=1){
            this.oMenuContents[iTab].style.display='none';
            clearInterval(this.oMenuContents[iTab].timer);    
            this.oMenuContents[iTab].timer = null;
            this.checkSlideDone();
        } else if(this.oMenuContents[iTab].offsetHeight>(this.iMaxContentHeight-1)&&this.oMenuContents[iTab].direction==1){
            this.oMenuContents[iTab].getElementsByTagName("div")[0].style.display ='block';
            clearInterval(this.oMenuContents[iTab].timer);
            //GEEFT IE JS ERROR delete(this.oMenuContents[iTab].timer);
            this.oMenuContents[iTab].timer = null;
            
            this.checkSlideDone();
        }
  
    },
    
    this.checkSlideDone = function(){
        var i = this.oMenuContents.length;
        var bDone = true;
        while(i--){
            if(this.oMenuContents[i].timer != null) {
                bDone = false;
            }            
        }
        if(bDone === true){
            GEvent.trigger(this, 'slideend');
        }
    }
    
    this.checkResize = function() {
        this.iMenuHeight = this.getContainerHeight();

        for(i=0; i<this.iTabs;i++) {
            if(HasClassName(this.oMenuHeaders[i], "active")){
                this.oMenuContents[i].style.height = parseInt(this.iMenuHeight - (this.iTabs*32) + 4) + 'px';
            }
        }            

    }
    
    this.toggleMenu = function() {
        var iDirection;
                
        var size          = checkSize();      
        var iScreenWidth  = size[0];
        
        oGeoStart.util.getElementById("menuHandle_img").style.display = "none";
        if(bInfoPaneVisible && !bInfoPaneOpen) {
            oGeoStart.util.getElementById("infoPane").style.display = "none";
        }
        
        if(bMenuOpen) {
            iDirection = -1;
            oGeoStart.util.getElementById("menuHandle_img").src= sBaseUrl + 'GeoStart/images/menuHandle_open.gif';
                      
        } else {
            oGeoStart.util.getElementById("menuHandle_img").src= sBaseUrl + 'GeoStart/images/menuHandle_close.gif';
            iDirection = 1;
            this.oMenuContainer.style.display='block';
            this.oMenuContainer.style.width=0+'px';
            this.oMapDiv.style.width = iScreenWidth - 20 - 285 + 'px';
        }
        
        this.iMapWidth                  = this.oMapDiv.offsetWidth;

        this.checkResize();
        this.oMenuContainer.direction   = iDirection;
        this.oMenuContainer.timer       = setInterval("oGeoStart.oMenuEffects.horizontalMenuEffect()", 20);
        
        bMenuOpen = !bMenuOpen;        

    }

    this.horizontalMenuEffect = function() {
        speed=2;
        var iWidth = this.oMenuContainer.offsetWidth;

        dist = (this.oMenuContainer.direction==1)?Math.round((276-iWidth)/speed):Math.round(iWidth/speed);       


        var iNewWidth = iWidth + ( dist*this.oMenuContainer.direction );        
        
        if(iWidth<10&&this.oMenuContainer.direction!=1){
            this.oMenuContainer.style.display='none';
            clearInterval(this.oMenuContainer.timer);
            oGeoStart.util.getElementById("menuHandle_img").style.display = "block";
            if(bInfoPaneVisible && !bInfoPaneOpen) {
                oGeoStart.util.getElementById("infoPane").style.display = "block";
            }
            resizer();
        }else if(iWidth>275&&this.oMenuContainer.direction==1){
            this.oMenuHandle.style.left = iWidth + 10 + 'px';      
            clearInterval(this.oMenuContainer.timer);
            oGeoStart.util.getElementById("menuHandle_img").style.display = "block";
            if(bInfoPaneVisible && !bInfoPaneOpen) {
                oGeoStart.util.getElementById("infoPane").style.display = "block";
            }
            resizer();
        } else {
            this.oMenuContainer.style.width = iNewWidth + 'px';             
        }
    }

    this.toggleInfoPane = function(){
        var iDirection;
                
        if(bInfoPaneOpen) {
            iDirection = -1;
            this.oInfoPaneHandle.src= sBaseUrl + 'GeoStart/images/infoPaneHandle_open.gif';
            oGeoStart.util.getElementById('infoPaneContent').style.display = 'none'; 
            oGeoStart.util.getElementById('closeInfoPaneOverlay').style.display = 'none'; 
            //oGeoStart.util.getElementById('permLinkDiv').style.display = 'none';
                      
        } else {
            //this.oInfoPane.style.display='block';
            //document.getElementById('infoPaneContent').style.display = 'block';
            this.oInfoPane.style.width='0px';
            oGeoStart.util.getElementById('closeInfoPaneOverlay').style.display = 'block';            
            this.oInfoPaneHandle.src= sBaseUrl + 'GeoStart/images/infoPaneHandle_close.gif';
            
            iDirection = 1;
        }
        
        ///this.iMapWidth                  = this.oMapDiv.offsetWidth;

        this.checkResize();
        this.oInfoPane.direction   = iDirection;
        this.oInfoPane.timer       = setInterval("oGeoStart.oMenuEffects.horizontalInfoPaneEffect()", 55);
        
        bInfoPaneOpen = !bInfoPaneOpen;
    }
    
    this.closeInfoPane = function() {
        oGeoStart.util.getElementById('closeInfoPaneOverlay').style.display = 'none'; 
        this.oInfoPane.style.display            = 'none';
        
        this.oInfoPaneContent.style.display      = 'none';
        this.oInfoPane.style.width              = '0px';
        
        bInfoPaneOpen = false;
        bInfoPaneVisible = false;
        
        GEvent.trigger(this, 'infoPaneClose');
                
        resizer();
        
    }
    
    this.hideInfoPane = function() {
        if(bInfoPaneOpen && this.bForceNoClose === false){
            this.oInfoPaneHandle.src= sBaseUrl + 'GeoStart/images/infoPaneHandle_open.gif';
            
            this.oInfoPaneContent.style.display = 'none'; 
            oGeoStart.util.getElementById('closeInfoPaneOverlay').style.display = 'none';
            this.checkResize();
            this.oInfoPane.direction   = -1;
            this.oInfoPane.timer       = setInterval("oGeoStart.oMenuEffects.horizontalInfoPaneEffect()", 55);
            bInfoPaneOpen = false;
        }
        
    }    

    this.openInfoPane = function() {
        oGeoStart.util.getElementById('closeInfoPaneOverlay').style.display = 'block'; 
        this.oInfoPane.style.display            = 'block';
        this.oInfoPaneHandle.src= sBaseUrl + 'GeoStart/images/infoPaneHandle_close.gif';
        
        this.oInfoPaneContent.style.display      = 'block';
        this.oInfoPane.style.width              = '580px';
        this.oInfoPaneHandle.style.left         = '580px';
        
        bInfoPaneOpen = true;
        bInfoPaneVisible = true;
        
        GEvent.trigger(this, 'infoPaneOpen');
        
        resizer();
    }
        
    
    this.horizontalInfoPaneEffect = function() {
        speed=2;
        var iWidth = this.oInfoPane.offsetWidth;
        
        
        dist = (this.oInfoPane.direction==1)?Math.round((580-iWidth)/speed):Math.round(iWidth/speed);       

        var iNewWidth = iWidth + ( dist*this.oInfoPane.direction );

       
        if(iNewWidth<11&&this.oInfoPane.direction!=1){
            this.oInfoPane.style.width='10px';
            this.oInfoPaneHandle.style.left = 10 + 'px'; 
            
            clearInterval(this.oInfoPane.timer);
            resizer();  
        }else if(iNewWidth>580&&this.oInfoPane.direction==1){
            oGeoStart.util.getElementById('infoPaneContent').style.display = 'block'; 
            this.oInfoPane.style.width='580px';
            clearInterval(this.oInfoPane.timer);
            resizer();  
        } else {
            this.oInfoPaneHandle.style.left = iNewWidth + 'px'; 
            this.oInfoPane.style.width = iNewWidth + 'px';             
        }            
    }
        
}/**
*   @class cMessageBox v. 1.0
*   Class showing messageboxes (like zoomlevel message). 
*
*   Floris Lovink - Swis BV
**/

function cMessageBox() {
    
    this.init = function(oMap){
        
        this._oMap = oMap;                                                      // GMap2 reference
        this._oControl = new MessageBoxControl(oMap);                       // Control object reference
        this._oMap.addControl(this._oControl);                                  // Load control into map
        this._oMessageContainer  = oGeoStart.util.getElementById('zoomMessage');
        this._oMessageText = oGeoStart.util.getElementById('zoomMessage_text'); 
        this._bDontShow = this.readCookie();
        modifyButtons();
        
    };
    
    
    
  
    
    
    this.show = function(iTotal){
        this.iTotal = iTotal;
        //this.iMaxVisible = iMaxVisible;
        this._oMessageContainer.style.display = "block";
        this._oMessageText.innerHTML = "Er worden " + iTotal + " locaties niet getoond.";            
    };
    
    this.hide = function(){
        this._oMessageContainer.style.display = 'none';
    };
    
    this.checkCb = function() {
        var bState = oGeoStart.util.getElementById("hideMsg").checked;
        this._bDontShow = bState;
        this.saveCookie();
    }
    
    this.saveCookie = function() {
        if(this._bDontShow == true) {
            var iDays = 365;
            var sValue = this._bDontShow;
        } else {
            var iDays = -1;
            var sValue = "";
        }
        
        var oDate = new Date();
        oDate.setTime(oDate.getTime()+(iDays*24*60*60*1000));        
        
        var sExpires = " ;expires="+oDate.toGMTString();
        document.cookie = "bDontShow="+sValue+sExpires+"; path=/";
    }
    
    this.readCookie = function() {
        var aCookies = document.cookie.split(';');
        for(i in aCookies) {            
            if(typeof(aCookies[i]) == "string" && aCookies[i].indexOf("bDontShow") > -1){
                if(aCookies[i].indexOf("true") > -1) {
                    return true;
                }
            }
        }
        return false;
    }
    
    

    
    
    var MessageBoxControl = function(oMap) { this.oMap = oMap; };
        MessageBoxControl.prototype = new GControl(true, false);
        MessageBoxControl.prototype.initialize = function () {
                var oMessageContainer = document.createElement("div");
                
                oMessageContainer.innerHTML                = "<div class='msg_box_header'><img src='GeoStart/images/icons/info.gif' /> LET OP! <img style='position: absolute; right: 5px; top: 5px; cursor:pointer;' src='" + sBaseUrl + "GeoStart/images/ballon/ballon_close.gif' alt='sluiten' onclick='oGeoStart.oMessageBox.hide();' ></div>";
                oMessageContainer.innerHTML               += "<div class='msg_box_content' style='text-align:left;'><div id='zoomMessage_text'></div><div id='msg_tip'>Verminder het aantal geselecteerd rubrieken onder Locaties of <a class='zoomAnchor' href='#' onclick='oGeoStart.oMap.zoomIn(); oGeoStart.oMessageBox.hide();return false;'>zoom in</a>.</div><div style='margin:10px 0px; font-size:10px; float:left;'><input type='checkbox' onclick='oGeoStart.oMessageBox.checkCb();' id='hideMsg' /><label for='hideMsg'>Toon dit niet meer.</label></div><div style='float:right; margin:10px 0px;'><input type='submit' style='width:35px;'value='Ok' onclick='oGeoStart.oMessageBox.hide();' /></div></div>";
                oMessageContainer.id                       = "zoomMessage";
                oMessageContainer.className                = "msg_box";
                oMessageContainer.style.display            = "none";
                //oMessageContainer.style.height             = "95px";
                oMessageContainer.style.top                = "50%";
                oMessageContainer.style.marginTop          = "-48px";
                oMessageContainer.style.left               = "50%"; 
                
                this.oMap.getContainer().appendChild(oMessageContainer);            
                //document.body.appendChild(oContainer);
                return oMessageContainer;
            };
}/**
*   @class cMapMaker v. 1.0
*   Class handling the frontend MapMaker. 
*
*   Hendrik Nijmeijer - Swis BV
**/
       


function cNewMapMaker() {
    
    this.sKey = "";
    
    /**
    * Standaard breedte.
    */
    this.iWidth = 500;

    /**
    * Standaard hoogte
    */
    this.iHeight = 400;
    
    this.oLoadObjectsListener = null;
    
    this.oInfoPaneCloseListener = null;
    this.oInfoPaneOpenListener = null;
    this.aFormListeners = null;
    
    this.bLayerView = false;
    
    this.init = function() {
        
    }
    
    /**
    *   HTML ophalen en in de meer informatie pagina zetten.
    */
    this.show = function() {        
        GDownloadUrl(sBaseUrl + 'GeoStart/ajax/getMapMakerPane.php?' + this.getMapDataString(), oGeoStart.oNewMapMaker.showPane);        
    }
    
    /**
    *   Mapmaker updaten in de database.
    */
    this.update = function() {
        
        oGeoStart.util.getElementById('mapmakerLoading').style.visibility = "";
        
        if(this.sKey != "") {
            GDownloadUrl(sBaseUrl + 'GeoStart/ajax/updateMapmaker.php?key=' + this.sKey + "&" + this.getMapDataString(), oGeoStart.oNewMapMaker.updateEmbed);
        }
    }
    
    /**
    *   Embed code updaten.
    */
    this.updateEmbed = function(sJson) { 
        if(typeof(document.getElementById("mapmakerPreview").contentWindow) == 'undefined'){
            setTimeout('oGeoStart.oNewMapMaker.updateEmbed("' + sJson + '")', 200);
            return;
        }
        var aInfo = eval('('+sJson+')');
        
        GEvent.trigger(oGeoStart.oNewMapMaker, 'mapmakerUpdated');
        
        oGeoStart.util.getElementById('mapmakerEmbedCode').innerHTML = oGeoStart.oNewMapMaker.getEmbedCode(aInfo.key, oGeoStart.oNewMapMaker.iWidth, oGeoStart.oNewMapMaker.iHeight);        
        
        if(typeof(document.getElementById("mapmakerPreview").contentWindow.oGeoStart) !== 'undefined'){
            document.getElementById("mapmakerPreview").contentWindow.oGeoStart.oMap.disableScrollWheelZoom();
            
            var oListener;
            oListener = GEvent.addListener(document.getElementById("mapmakerPreview").contentWindow.oGeoStart, 'loadObjectsDone', function() { 
                GEvent.removeListener(oListener);
                oListener = null;
                oGeoStart.util.getElementById('mapmakerLoading').style.visibility = "hidden";                
            });
            document.getElementById("mapmakerPreview").contentWindow.oGeoStart.loadObjects();            
        }
        
    }
    
    /**
    *   Embed code genereren.
    */
    this.getEmbedCode = function(sKey, iWidth, iHeight){
        var sIframeHtml  = '';
        sIframeHtml      = '&lt;iframe width="'+iWidth+'" height="'+iHeight+'" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="' + sBaseUrl + 'embed/' + sKey + '"&gt;&lt;/iframe&gt;';
        return sIframeHtml;
    }
     
    /**
    *   HTML inladen en listeners maken.
    */
    this.showPane = function(sJson) {
        var aInfo = eval('('+sJson+')');
        
        oGeoStart.oNewMapMaker.sKey = aInfo.key;
        
        /**
        * Bij openen van infoPange, dus niet unhiden.
        */
        
        oGeoStart.oMenuEffects.bForceNoClose = true;
        
        if(oGeoStart.oCbsData.getStatistiek() !== false ){
            oGeoStart.oNewMapMaker.bLayerView = true;
            if(oGeoStart.oNewMapMaker.oButtonListener == null){
                oGeoStart.oNewMapMaker.oButtonListener = GEvent.addDomListener(oGeoStart.util.getElementById('kaartlaag_verbergen_btn'), 'click', function(){                            
                    oGeoStart.oNewMapMaker.bLayerView = false;
                    oGeoStart.oNewMapMaker.show();
                    GEvent.removeListener(oGeoStart.oNewMapMaker.oButtonListener);
                    oGeoStart.oNewMapMaker.oButtonListener = null;                        
                });
            }
        }
        
        if(oGeoStart.oNewMapMaker.oInfoPaneOpenListener == null){
            oGeoStart.oNewMapMaker.oInfoPaneOpenListener = GEvent.addListener(oGeoStart.oMenuEffects, 'infoPaneOpen', function(){
                if(oGeoStart.oNewMapMaker.oLoadObjectsListener == null){
                    oGeoStart.oNewMapMaker.oLoadObjectsListener = GEvent.addListener(oGeoStart, 'loadObjects', function() { 
                        oGeoStart.oNewMapMaker.update(); 
                    });
                }            
            });
        }
        
        if(typeof(oGeoStart.oCbsData) != 'undefined'){
            if(oGeoStart.oNewMapMaker.oCbsListener == null){
                oGeoStart.oNewMapMaker.oCbsListener = GEvent.addListener(oGeoStart.oCbsData, 'cbsLayerChanged', function(){
                    
                    if(oGeoStart.oNewMapMaker.bLayerView === true){                                            
                        var sStat = oGeoStart.oCbsData.getStatistiek();
                        iFrameWindow = document.getElementById("mapmakerPreview").contentWindow;
                               
                        document.getElementById("mapmakerPreview").contentWindow.iFrameRun('oGeoStart.oCbsData.setStatistiek("' + sStat + '");');
                    
                    } else {
                        
                        if(oGeoStart.oNewMapMaker.oButtonListener == null){
                            oGeoStart.oNewMapMaker.oButtonListener = GEvent.addDomListener(oGeoStart.util.getElementById('kaartlaag_verbergen_btn'), 'click', function(){                            
                                oGeoStart.oNewMapMaker.bLayerView = false;
                                oGeoStart.oNewMapMaker.show();
                                GEvent.removeListener(oGeoStart.oNewMapMaker.oButtonListener);
                                oGeoStart.oNewMapMaker.oButtonListener = null;                        
                            });
                        }
                    
                        
                        oGeoStart.oNewMapMaker.bLayerView = true;
                        oGeoStart.oNewMapMaker.show();                        
                        
                    }
                    // GEvent.callback(iFrameWindow, iFrameWindow.oGeoStart.oCbsData.setStatistiek(sStat));
                    // document.getElementById("mapmakerPreview").contentWindow.oGeoStart.oCbsData.setStatistiek(sStat);
                    
                });
            }
            
        }
        
        /**
        * Bij sluiten van infoPange, DUS NEIT HIDEN
        */
        if(oGeoStart.oNewMapMaker.oInfoPaneCloseListener == null){
            oGeoStart.oNewMapMaker.oInfoPaneCloseListener = GEvent.addListener(oGeoStart.oMenuEffects, 'infoPaneClose', function(){
                
                oGeoStart.oMenuEffects.bForceNoClose = false;
                
                if(oGeoStart.oNewMapMaker.oLoadObjectsListener != null){
                    GEvent.removeListener(oGeoStart.oNewMapMaker.oLoadObjectsListener);
                    oGeoStart.oNewMapMaker.oLoadObjectsListener = null;
                }
                if(oGeoStart.oNewMapMaker.aFormListeners != null){
                    var i = oGeoStart.oNewMapMaker.aFormListeners.length;
                    while(i--){
                        GEvent.removeListener(oGeoStart.oNewMapMaker.aFormListeners[i]);
                    }
                    oGeoStart.oNewMapMaker.aFormListeners = null;                
                }
                if(oGeoStart.oNewMapMaker.oCbsListener != null){
                    GEvent.removeListener(oGeoStart.oNewMapMaker.oCbsListener);
                    oGeoStart.oNewMapMaker.oCbsListener = null;
                }
            });
        }
        
        
        oGeoStart.oMenuEffects.openInfoPane();
        
        oGeoStart.util.getElementById('moreInfoWrap').innerHTML = aInfo.html;
        
        oGeoStart.oNewMapMaker.initForm();        
        
        setInfoPaneContent("info");
    }
    
    /**
    *   Mapmaker update string opbouwen.
    */
    this.getMapDataString = function() { 
        
        var sArgs = '';
        
        var iZoom           = oGeoStart.oMap.getZoom();
        var sCenter         = oGeoStart.oMap.getCenter().toUrlValue();
        var sVisibleCats    = oMenu.getCheckBoxDataString();
        
        var sNorthEast = oGeoStart.oMap.getBounds().getNorthEast().toUrlValue();
        var sSouthWest = oGeoStart.oMap.getBounds().getSouthWest().toUrlValue();
        
        switch(oGeoStart.oMap.getCurrentMapType().getUrlArg()){
            case 'm':
                var sMapType = 1;
                break;
            case 'k':
                var sMapType = 2;
                break;
            case 'h':
                var sMapType = 3;
                break;
            case 'p':
                var sMapType = 4;
                break;
        }
        
        
        sArgs +=  'zoom=' + iZoom + '&center=' + sCenter;
        
        sArgs += '&sMapType=' + sMapType;
        
        sArgs += '&subcats=' + sVisibleCats;
        
        sArgs += '&ne=' + sNorthEast;
        
        sArgs += '&sw=' + sSouthWest;
        
        sArgs += '&iHeight=' + this.iHeight;
        sArgs += '&iWidth=' + this.iWidth;
        
        if(this.sKey != "") {
            sArgs += '&title=' + oGeoStart.util.getElementById('map_titel_input').value;
        }
        
        if(oSettings.show_cbs_data && oGeoStart.oCbsData.getStatistiek() != false) {
            sArgs += '&stat=' + oGeoStart.oCbsData.getStatistiek();
        }    
        
        return sArgs;
    }        
    
    
    this.getZoomForMapBounds = function() {
        var aBounds = new GLatLngBounds(oGeoStart.oMap.getBounds().getNorthEast(), oGeoStart.oMap.getBounds().getSouthWest());
        
        return oGeoStart.oMap.getBoundsZoomLevel(aBounds);
    }
    
    /**
    *   Resize mapmaker, values updaten van de "aangepast" inputs
    */
    this.resizeMapmaker = function(iWidth, iHeight){
        if(typeof(document.getElementById("mapmakerPreview").contentWindow) == 'undefined' || typeof(document.getElementById("mapmakerPreview").contentWindow.oGeoStart) == 'undefined' ){
            setTimeout('oGeoStart.oNewMapMaker.resizeMapmaker(' + iWidth + ',' + iHeight + ');', 100);
            return;
        }
        
        this.iWidth = iWidth;
        this.iHeight = iHeight;
        
        oGeoStart.util.getElementById('map_hoogte').value = iHeight;
        oGeoStart.util.getElementById('map_breedte').value = iWidth;
        
        document.getElementById("mapmakerPreview").height = iHeight;
        document.getElementById("mapmakerPreview").width  = iWidth;
        
        var oCenter = document.getElementById("mapmakerPreview").contentWindow.oGeoStart.oMap.getCenter();
        
        
        document.getElementById("mapmakerPreview").contentWindow.oGeoStart.util.getElementById('geoMap').style.width = (iWidth-2) + 'px';
        
        mStatistiek = document.getElementById("mapmakerPreview").contentWindow.oSettings.sStatistiek;
        
        if(mStatistiek != false){
            document.getElementById("mapmakerPreview").contentWindow.oGeoStart.util.getElementById('geoMap').style.height = (iHeight - 52 - 20) + 'px';
            document.getElementById("mapmakerPreview").contentWindow.oGeoStart.util.getElementById('geoMapFooter').style.width = (iWidth-7) + 'px';                
            //document.getElementById("mapmakerPreview").contentWindow.oGeoStart.util.getElementById('geoMapFooter').innerHTML = 'Bron: ' + document.getElementById("mapmakerPreview").contentWindow.location.host;
        } else {
            document.getElementById("mapmakerPreview").contentWindow.oGeoStart.util.getElementById('geoMap').style.height = (iHeight - 52 - 20) + 'px';
            document.getElementById("mapmakerPreview").contentWindow.oGeoStart.util.getElementById('geoMapFooter').style.width = (iWidth-7 + 20) + 'px';document.getElementById("mapmakerPreview").contentWindow.oGeoStart.util.getElementById('legenda_text').style.width = (iWidth - 120) + 'px';                               
        }
        
        document.getElementById("mapmakerPreview").contentWindow.oGeoStart.util.getElementById('geoMapHeader').style.width = (iWidth-7) + 'px';
        document.getElementById("mapmakerPreview").contentWindow.oGeoStart.util.getElementById('geoMapContainer').style.width = (iWidth-2) + 'px';
        
        document.getElementById("mapmakerPreview").contentWindow.oGeoStart.oMap.checkResize();
        // document.getElementById("mapmakerPreview").contentWindow.resizer();
        
        document.getElementById("mapmakerPreview").contentWindow.oGeoStart.oMap.panTo(oCenter);
        
        this.update();
        
    }
    
    /**
    *   Formulier listeners initialiseren.
    */
    this.initForm = function(){
        var self = this;
        
        self._setEnabledInput(false);
        
        self.aFormListeners = [];
        
        self.aFormListeners[self.aFormListeners.length] = GEvent.addDomListener(oGeoStart.util.getElementById('map_grootte_klein'), 'click', function(){
            self.resizeMapmaker(350, 300);
            self._setEnabledInput(false);
        });
        
        self.aFormListeners[self.aFormListeners.length] = GEvent.addDomListener(oGeoStart.util.getElementById('map_grootte_middel'), 'click', function(){
            self.resizeMapmaker(500, 400);
            self._setEnabledInput(false);
        });
        
        self.aFormListeners[self.aFormListeners.length] = GEvent.addDomListener(oGeoStart.util.getElementById('map_grootte_groot'), 'click', function(){
            self.resizeMapmaker(640, 480);
            self._setEnabledInput(false);
        });
        
        self.aFormListeners[self.aFormListeners.length] = GEvent.addDomListener(oGeoStart.util.getElementById('map_grootte_aangepast'), 'click', function(){
        //oGeoStart.util.getElementById('map_grootte_aangepast').onclick = function(){
            var iHeight = oGeoStart.util.getElementById('map_hoogte').value;
            var iWidth = oGeoStart.util.getElementById('map_breedte').value;
            self.resizeMapmaker(iWidth, iHeight);
            self._setEnabledInput(true);
            
            self.aFormListeners[self.aFormListeners.length] = GEvent.addDomListener(oGeoStart.util.getElementById('map_hoogte'), 'change', function(){
                self.setCustomGrootte();
            });
            
            self.aFormListeners[self.aFormListeners.length] = GEvent.addDomListener(oGeoStart.util.getElementById('map_breedte'), 'change', function(){
                self.setCustomGrootte();
            });
        });
        
        
        self.aFormListeners[self.aFormListeners.length] = GEvent.addDomListener(oGeoStart.util.getElementById('map_titel_input'), 'change', function(){
            self.update();
        });
        
        self.aFormListeners[self.aFormListeners.length] = GEvent.addDomListener(oGeoStart.util.getElementById('map_titel_input'), 'keyup', function(){
            var sTitle = oGeoStart.util.getElementById('map_titel_input').value;
            document.getElementById("mapmakerPreview").contentWindow.oGeoStart.util.getElementById('map_titel').innerHTML = sTitle;
        });
    }        
    
    /**
    *   Custom grootte uitlezen en het voorbeeld aanpassen.
    */
    this.setCustomGrootte = function(){
        if(oGeoStart.util.getElementById('map_grootte_aangepast').checked === true){
            var iHeight = oGeoStart.util.getElementById('map_hoogte').value;
            var iWidth = oGeoStart.util.getElementById('map_breedte').value;
            this.resizeMapmaker(iWidth, iHeight);            
            
        }
    }
    
    /**
    *   De aangepaste grootte inputs aan en uit zetten
    */
    this._setEnabledInput = function(bEnabled){
        if(bEnabled === true){
            sEnabled = '';
        } else {
            sEnabled = 'disabled'
        }
        oGeoStart.util.getElementById('map_hoogte').disabled = sEnabled;
        oGeoStart.util.getElementById('map_breedte').disabled = sEnabled;
            
    }
    
    this._copyMap = function(){
        if(typeof(this.oCopyControl) == 'undefined' || this.oCopyControl == null){
            this.oCopyControl = new Copy_Map_Control(oGeoStart.oMap);
            this.oCopyControl.initialize();            
        } else {
            this.oCopyControl.toggle();
        }
        
        
    }
    
}


var Copy_Map_Control = function(oMap) {this.oMap = oMap;};
        Copy_Map_Control.prototype.initialize = function () {
                var oContainer = document.createElement("div");


                /*
                if(typeof(window.parent) != 'undefined' && window.parent.oGeoStart != 'undefefined' && window.parent.oGeoStart.oNewMapMaker.sKey != '' ){
                    sKey   = window.parent.oGeoStart.oNewMapMaker.sKey;
                    iWidth = window.parent.oGeoStart.oNewMapMaker.iWidth;
                    iHeight= window.parent.oGeoStart.oNewMapMaker.iHeight;
                } else {
                    sKey   = oSettings.sMapMaker;
                    iWidth = oSettings.breedte;
                    iHeight= oSettings.hoogte;
                }
                */
               
                sIframeCode = this.getEmbedCode();
                
                oContainer.innerHTML           = "<img onclick='oGeoStart.oNewMapMaker._copyMap();' alt='sluiten' src='GeoStart/images/ballon/ballon_close.gif' class='mapMaker_close'><p>Kopieer de code om deze kaart in uw website te gebruiken.</p><textarea id='mapmaker_embed_code' rows='2' cols='24' onclick='this.focus(); this.select();'>" + sIframeCode + "</textarea>";
                oContainer.id                  = "copy_map_control";
                oContainer.style.width         = "200px";
                oContainer.style.overflow      = "hidden";
                oContainer.style.verticalAlign = "middle";
                oContainer.style.fontSize      = "11px";
                oContainer.style.height        = "120px";
                oContainer.style.padding       = "5px";
                oContainer.style.textAlign     = "left";
                oContainer.style.position      = "absolute";
                oContainer.style.left          = '10px';
                oContainer.style.top           = '31px';
                oContainer.style.display       = 'block';
                oContainer.className           = 'sprite-no-repeat-left';
                //oContainer.style.backgroundPosition  = 'right -495px';
                oContainer.style.border        = "1px solid #e4e4e4"; 
                oContainer.style.backgroundColor='white';
                    
                //oContainer.style.backgroundImage = "url('"+ sBaseUrl + "GeoStart/images/controls/mapMenuBackground.gif')";
                
                this.oContainer = oContainer;
                
                oGeoStart.util.getElementById('content').appendChild(oContainer);             
                                
            }
            
            
        Copy_Map_Control.prototype.toggle = function(){
            if(this.oContainer.style.display == "block"){
                this.oContainer.style.display = "none";
            } else {                
                oGeoStart.util.getElementById('mapmaker_embed_code').innerHTML = this.getEmbedCode();
                
                this.oContainer.style.display = "block";
            }
        }

        Copy_Map_Control.prototype.getEmbedCode = function(){
                var sKey = false;
                var iWidth = false;
                var iHeight = false;
                try {
                    sKey   = window.parent.oGeoStart.oNewMapMaker.sKey;
                    iWidth = window.parent.oGeoStart.oNewMapMaker.iWidth;
                    iHeight= window.parent.oGeoStart.oNewMapMaker.iHeight;
                } catch (e) {

                }

                if(sKey === false){
                    sKey   = oSettings.sMapMaker;
                    iWidth = oSettings.breedte;
                    iHeight= oSettings.hoogte;
                }

                return oGeoStart.oNewMapMaker.getEmbedCode(sKey, iWidth, iHeight);

        }
            
      /**
*    Preloader class.
*        .init(oMap)
*        .updateLoader(iMax, iCurrent)
*        .remove()
*   @class cPreloader Voorgang contol op de kaart, hoeveel is geladen e.d.
**/
function cPreloader(){
    /**
    *    Init the preloader. Create a Control on the map.
    *    Loader:     geo_preloader_container
    *    Info:        geo_preloader
    *   @param oMap GMap2 object
    *   @param iWidth How width should it be
    **/    
    this.init = function(oMap, iWidth){
        this._iWidth = iWidth || 176;
        this._oMap = oMap;                                                      // GMap2 reference
        this._oControl = new LoaderControl(oMap, iWidth);                       // Control object reference
        this._oMap.addControl(this._oControl);                                  // Load control into map
        this._oDiv = oGeoStart.util.getElementById('preloader');                      // Preloader DIV
        this._oText = oGeoStart.util.getElementById('geo_preloader_text');            // Preloader text DIV
        this._oContainer = oGeoStart.util.getElementById('geo_preloader_container');  // Preloader container
        this._sLoadstring = oSettings._sLoadString;                             // String for when loading ( before counter )
        this._iOperations = 0;
        this._iCurrent = 0;
        this.oInterval = false;
        this.blockTimeout = false;
    };
    

    /**
    *    Start preloader
    *   @param int iOperations Counter for the amount of operations that will be executed.
    **/
    this.start = function(iOperations) {
        this._iOperations = iOperations || 0;
        
        if(this._iOperations == 0 ) { return; }
        
        this._iCurrent = 0;
        
        this.blockTimeout = setTimeout('oGeoStart.oPreloader.showElement();', 200);
        
        this._oText.innerHTML = this._sLoadstring;
        
        this.oInterval = setInterval('oGeoStart.oPreloader.updateLoader(1);', 10);
        
    };

    this.showElement = function(){
        this._oContainer.style.display = "block";
    }

    /**
    *    Set preloader info.
    *   @param int iStep Add number of operations to preloader.
    **/
    this.updateLoader = function( iStep ){
        
        if(this.oInterval !== false){
            clearInterval(this.oInterval);
        }
        
        this._iCurrent += iStep;
        if ( this._iCurrent > 0 ){
            var percentage = Math.ceil((this._iCurrent / this._iOperations) * 100);
            if ( percentage > 100 ) { percentage = 100; }
            this._oDiv.style.width = percentage + '%'; 
            this._oText.innerHTML = "Locaties ophalen..." + this._iCurrent + ' van ' + this._iOperations;
        } 
    };
    
    /**
    *    Remove preloader. Well, hide actually.
    **/
    this.remove = function() {
        this._oContainer.style.display  = 'none';
        //this._oText.innerHTML           = "Locaties ophalen...";
        this._oDiv.style.width          = 0 + 'px';
        
        if(this.oInterval !== false) {
            clearInterval(this.oInterval);
            this.oInterval = false;
        }
        if(this.blockTimeout !== false) {
            clearInterval(this.blockTimeout);
            this.blockTimeout = false;
        }
        
        
        

    };


    /**
    *    Custom preloader control.
    *    Possibly extendable with other styles later on?
    *   @class
    **/    
    var LoaderControl = function(oMap, iWidth) { this.oMap = oMap; this.iWidth = iWidth; };
        LoaderControl.prototype = new GControl(true, false);
        LoaderControl.prototype.initialize = function () {
                var oContainer = document.createElement("div");
                oContainer.innerHTML               += "<div class='msg_box_content'><div style='text-align:left;width:320px;' id='geo_preloader_text'></div><div id='preloader_wrapper' style='border:1px solid #C6C6C6; padding:0px; margin:0px; width:316px; height:11px; line-height:11px; margin-top:5px; text-align:left;'><div id='preloader' class='preload_bar'></div></div></div>";
                //oContainer.innerHTML               += "<div class='msg_box_content'><div style='text-align:left;width:225px;' id='geo_preloader_text'></div><div id='preloader_wrapper' style='border:1px solid #C6C6C6; padding:0px; margin:0px; width:221px; height:11px; line-height:11px; margin-top:5px; text-align:left;'><div id='preloader' class='preload_bar'></div></div></div>";
                oContainer.id                       = "geo_preloader_container";
                oContainer.className                = "msg_box";
                  
                oContainer.style.display            = "none";
                oContainer.style.height             = "70px";
                oContainer.style.top                = "50%";
                oContainer.style.marginTop          = "-35px";  
                this.oMap.getContainer().appendChild(oContainer);            
                //document.body.appendChild(oContainer);
                return oContainer;
            }; /* 
        LoaderControl.prototype.getDefaultPosition = function () {
                console.log(getMapSize());
                return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0,0));
            };   */ 
};/**
*   GeoStart routes functionaliteit
*   @param Id of route element.
*   @class Route klasse. Routes zijn lijnen met tussenpunten. 
**/
function cRoutes(sRouteElement){

    /**
    *   Initlialize, loads data into object.
    **/
    this.init = function(){
        this.getData();
    };

    // Get route information DOm element.
    this.oEle = oGeoStart.util.getElementById(sRouteElement);
    this.aHtml = [];    
    
    /**
    *   Ajax request for routes data
    **/
    this.getData = function(){
        if(oGeoStart.oCrossSiteProxy){
            oGeoStart.oCrossSiteProxy.load('oRoutes.loadData', sBaseUrl + "GeoStart/ajax/getRouteData.php");
            oGeoStart.oCrossSiteProxy.call(oGeoStart.oRoutes.loadData);
        } else {
            GDownloadUrl(sBaseUrl + "GeoStart/ajax/getRouteData.php", oGeoStart.oRoutes.loadData);
        }
    };
        
    /**
    *   Parse JSON and call load functions.
    *   @param sJson JSON string from GeoStart/ajax/getRouteData.php
    *   @private
    **/
    this.loadData = function(sJson) {    
        var oData = eval('('+sJson+')');        
        oGeoStart.oRoutes.oRouteData = oData;
        oGeoStart.oRoutes.initialize();       
        oGeoStart.oRoutes.show(); 
    };
    
    /**
    *   Toggle all routes
    *   @param bState Show/hide
    **/    
    this.toggleAll = function(bState){
        if ( bState ) {
            oGeoStart.oRoutes.show();
        } else {
            oGeoStart.oRoutes.hide();
        }
    };
    
    /**
    *   Create Routes from this.oRouteData
    **/
    this.initialize = function(){
        for ( var k in this.oRouteData ) {
            if(typeof(this.oRouteData[k])!='function'){
                this.oRouteData[k].oPoly = oGeoStart.createPolyline(this.oRouteData[k]);
            
                //oGeoStart.oMap.addOverlay(this.oRouteData[k].oPoly);
                
                this.oRouteData[k]._PoiSort = Array();
                for ( var p in this.oRouteData[k]._PoiInfo ) {
                    if(typeof(this.oRouteData[k]._PoiInfo)!='function'){
                        this.oRouteData[k]._PoiInfo[p].sg_id = "poi"+this.oRouteData[k].polykleur;
                        this.createPoint(this.oRouteData[k]._PoiInfo[p], k);
                        this.oRouteData[k]._PoiSort[this.oRouteData[k]._PoiInfo[p].sorteer] = this.oRouteData[k]._PoiInfo[p].id;
                    }
                }
                this.createStartEnd(k);            
            }
        }            
    };
    
    /**
    *   Create start and end point of route
    *   @param sRouteId Id of route
    *   @private
    **/
    this.createStartEnd = function(sRouteId){
        this.oRouteData[sRouteId].oPoints['end'] = new GMarker(this.oRouteData[sRouteId].oPoly.getVertex(0), oIconmanager.get('route_end'));
        this.oRouteData[sRouteId].oPoints['start'] = new GMarker(this.oRouteData[sRouteId].oPoly.getVertex(this.oRouteData[sRouteId].oPoly.getVertexCount()-1), oIconmanager.get('route_start'));
        
        
        oGeoStart.oMap.addOverlay(this.oRouteData[sRouteId].oPoints['start']);
        this.oRouteData[sRouteId].oPoints['start'].hide();
        
        oGeoStart.oMap.addOverlay(this.oRouteData[sRouteId].oPoints['end']);
        this.oRouteData[sRouteId].oPoints['end'].hide();
    };
    
    /**
    *   Load/show routes
    **/
    this.show = function(){
        for ( var k in this.oRouteData ) {
            if(typeof(this.oRouteData[k]) != 'function'){            
                if ( !this.oRouteData[k].shows || this.oRouteData[k].shows == false ) {
                    this.oRouteData[k].shows = true;
                    oGeoStart.oMap.addOverlay(this.oRouteData[k].oPoly);
                                
                    for ( var p in this.oRouteData[k].oPoints ) { 
                        if(typeof(this.oRouteData[k].oPoints) !='function'){            
                            oGeoStart.oMap.addOverlay(this.oRouteData[k].oPoints[p]);
                            if ( p == 'start' || p == 'end' ) {
                                this.oRouteData[k].oPoints[p].hide();
                            }
                        }
                    }
                }
            }
        }        
    };
    
    /**
    *   Remove/hide routes
    **/
    this.hide = function(){
        for ( var k in this.oRouteData ) {
            if(typeof(this.oRouteData[k]) != 'function'){            
                
                if ( this.oRouteData[k].shows || this.oRouteData[k].shows == true ) {
                    this.oRouteData[k].shows = false;
                    oGeoStart.oMap.removeOverlay(this.oRouteData[k].oPoly);
                                
                    for ( var p in this.oRouteData[k].oPoints ) { 
                        if(typeof(this.oRouteData[k].oPoints) !='function'){            
                            oGeoStart.oMap.removeOverlay(this.oRouteData[k].oPoints[p]);
                        }
                    }
                }
            }
        }        
    };
    
    /**
    *   Check menu for updates on routes.
    *   @private
    **/
    this.update = function(){
        if ( oGeoStart.util.getElementById('GeoMenu_hg_cb_route').checked ) {
            this.show();
        } else {
            this.hide();
        }
        for ( var k in this.oRouteData ) {
            if(typeof(this.oRouteData[k]) != 'function'){            
                if ( this.oRouteData[k].shows || this.oRouteData[k].shows == true ) {
                
                    if ( oGeoStart.util.getElementById('GeoMenu_routes_' + k).className.indexOf("_open") != -1  ) {
                        this.highlight(k);
                    } else {
                        this.unhighlight(k);
                    }
                    
                }
            }
        }
    };
    
    /**
    *   Close routes in menu.
    **/    
    this.closeAll = function(sRoute) {
        var aInfo = oGeoStart.util.getElementById('GeoMenu_hg_route').getElementsByTagName('li');
        var i = aInfo.length;
        while ( i-- ) {
            if ( aInfo[i].id.indexOf("GeoMenu_routes_") != -1 && aInfo[i].id != "GeoMenu_routes_"+sRoute ) {
                aInfo[i].className = 'GeoMenu_closed';
            }
        }
    };
    
    /**
    *   Direct link for POI ( meer informatie for POI, scrolls to the item ).
    **/
    this.gotoPoiAnchor = function(iPoi){
        oGeoStart.util.getElementById('tab').scrollTop = 0;
        //window.location.hash = '#poi_' + iPoi;
    };
    
    /**
    *   Highlight the route
    **/
    this.highlight = function(k){
        this.oRouteData[k].oPoly.color = "#FF0000";
        oGeoStart.oMap.addOverlay(this.oRouteData[k].oPoly);
                                        
        for ( var p in this.oRouteData[k].oPoints ) {
            if(typeof(this.oRouteData[k]) != 'function'){            
                if ( p == 'start' || p == 'end' ){
                    this.oRouteData[k].oPoints[p].show();
                } else {
                    this.oRouteData[k].oPoints[p].setImage(oIconmanager.get('route', 'FF0000').image);
                }
            }
        }
    };
    
    /**
    *   Remove highlight for route
    *   @param sId Id of route
    **/
    this.unhighlight = function(sId){
        this.oRouteData[sId].oPoly.color = "#" + this.oRouteData[sId].polykleur;
        oGeoStart.oMap.addOverlay(this.oRouteData[sId].oPoly);
        for ( var k in this.oRouteData[sId].oPoints ) {
            if(typeof(this.oRouteData[k]) != 'function'){            
                if ( k == 'start' || k == 'end' ){
                    this.oRouteData[sId].oPoints[k].hide();
                } else {
                    this.oRouteData[sId].oPoints[k].setImage(oIconmanager.get('route', this.oRouteData[sId].polykleur).image);
                }
            }
        }
    };
    
    /**
    *   Create a single point
    *   @param aInfo array with data
    *   @param sRouteId route id
    *   @private
    **/
    this.createPoint = function(aInfo, sRouteId){
        if ( !this.oRouteData[sRouteId].oPoints ) {
            this.oRouteData[sRouteId].oPoints = {};
        }
        
        var oIcon = oIconmanager.get('route', this.oRouteData[sRouteId].polykleur);
        var point = new GMarker( new GLatLng( parseFloat(aInfo.lat), parseFloat(aInfo.lng) ), oIcon);    // Create object
        var id = aInfo.id;
        
        point.title     = aInfo.titel;          // Define title
        point.tooltip   = aInfo[oSettings._sTooltipField];
        point.type      = "point";            // Set geometry type. Not used yet in 1.0
        point._GeoInfo  = aInfo;                // All information given by cGeoData(PHP!)

        this.pointListeners(point);

        this.oRouteData[sRouteId].oPoints[id] = point;               // Add object to factory
                
        /** Add the overlay to the map **/
        // oGeoStart.oMap.addOverlay(this.oRouteData[sRouteId].oPoints[id]);
        
    };

    
    /**
    *   Show more information in route element.
    *   @param sRoute route id
    **/    
    this.showTabInfo = function(sRoute){
        
        this.oEle.innerHTML = this.getHtml(sRoute);
        
        setInfoPaneContent('route');
        
        oGeoStart.util.getElementById('tabTitleText').innerHTML = 'Route: ' + this.oRouteData[sRoute].titel;
        
        swap('tab', true);
    };
    
    /**
    *   Generate Meerinfo HTML
    *   @param sRoute route id
    *   @private
    **/
    this.getHtml = function(sRoute){
        if ( !this.oRouteTemplate ) {
            this.oRouteTemplate = new cTemplate();
            this.oRouteTemplate.sTemplateDir = sBaseUrl + 'GeoStart/templates/';
        }
    
        this.oRouteTemplate.loadTemplate('routes/route_meerinfo.js.tpl');
        
        this.oRouteTemplate.assign('sTitle', this.oRouteData[sRoute].titel);
        
        var sRoutePoints = '';
        for ( var i = 0; i < this.oRouteData[sRoute].aGeometry.length; i++ ) {
            if ( i < 49 ) {
                sRoutePoints += '|' + this.oRouteData[sRoute].aGeometry[i].lat + ',' + this.oRouteData[sRoute].aGeometry[i].lng;
            }
        }
        
        this.oRouteTemplate.assign('sGoogleMapsKey', oSettings.sGoogleMapsKey);
        this.oRouteTemplate.assign('sRoutePoints', sRoutePoints);
        if ( this.oRouteData[sRoute].omschrijving.length > 0 ) {
            this.oRouteTemplate.assign('sOmschrijving', this.oRouteData[sRoute].omschrijving);
        }
        
        this.oRouteTemplate.assign('sStatsHtml', this.getStatsHtml(sRoute));
        
        
        var aPoiHtml = [];
        for ( var k in this.oRouteData[sRoute].oPoints ) {
            if(typeof(this.oRouteData[sRoute].oPoints) != 'function'){            
                if ( typeof(this.oRouteData[sRoute].oPoints[k]._GeoInfo) != 'undefined') {
                    aPoiHtml.push(this.getPointHtml(this.oRouteData[sRoute].oPoints[k]));
                }
            }
        }
        
        this.oRouteTemplate.assign('sPoiHtml', aPoiHtml.join(''));
        
        return this.oRouteTemplate.fetch();
    };

    /**
    *   Generate single POI html.
    *   @param oPoint GPoint
    *   @private
    **/
    this.getPointHtml = function(oPoint){
        if ( !this.oPoiTemplate ) {
            this.oPoiTemplate = new cTemplate();
            this.oPoiTemplate.sTemplateDir = sBaseUrl + 'GeoStart/templates/';
        }                
        this.oPoiTemplate.loadTemplate('routes/route_poi.js.tpl');
        
        if ( oPoint._GeoInfo.afbeelding != '' ) {
            this.oPoiTemplate.assign('sAfbeelding', sBaseUrl + oPoint._GeoInfo.afbeelding);
        } else {
            this.oPoiTemplate.assign('sAfbeelding', 'http://maps.google.com/staticmap?size=242x180&markers=tinyred|' + oPoint._GeoInfo.lat + ',' + oPoint._GeoInfo.lng +'&key=' + oSettings.sGoogleMapsKey);
        }
        
        this.oPoiTemplate.assign('iRoutePoiId', oPoint._GeoInfo.route_poi_id);
        this.oPoiTemplate.assign('iRouteId', oPoint._GeoInfo.route_id);
        this.oPoiTemplate.assign('sTitle', oPoint.title);
        this.oPoiTemplate.assign('sOmschrijving', oPoint._GeoInfo.omschrijving);

        return this.oPoiTemplate.fetch();
    };
    
    /**
    *   Generate Statistics HTML
    *   @param sRoute Route id
    *   @private
    **/
    this.getStatsHtml =function(sRoute){
        if ( !this.oStatsTemplate ) {
            this.oStatsTemplate = new cTemplate();
            this.oStatsTemplate.sTemplateDir = sBaseUrl + 'GeoStart/templates/';
        }                
        this.oStatsTemplate.loadTemplate('routes/route_stats.js.tpl');
        
        var iMeters = Math.round(this.oRouteData[sRoute].oPoly.getLength());
        var iPoiCount = 0;
        for ( var x in this.oRouteData[sRoute].oPoints ) { 
            iPoiCount++;
        }
        
        this.oStatsTemplate.assign('iMeters', iMeters);
        this.oStatsTemplate.assign('iPoiCount', iPoiCount);
        
        return this.oStatsTemplate.fetch();
    };
    
    
    /**
    *   Listeners for POI marker
    *   @param point GPoint
    *   @private
    **/
    this.pointListeners = function(oRef){
        GEvent.addListener(oRef, "mouseover", function() {
            if ( oRef.type == "point" ) {                
                oGeoStart.oRoutes.highlight('route_' + oRef._GeoInfo.route_id);
                
                if ( oGeoStart._bEnableHover ) {
                    oGeoStart._hoverListener.remove();
                
                    if ( oGeoStart._oTooltip.markerOnScreen(oRef.getPoint()) ) {                // Check if marker is onscreen
                        oGeoStart._oTooltip.checkAlign(oRef.g_type);
                        oGeoStart._oTooltip.setText(oRef.title);
                        oGeoStart._oTooltip.addCat('poi');
                        
                        oGeoStart._oTooltip.show(oRef.getPoint());
                    }
                }
            }
            
        });
        
        GEvent.addListener(oRef, 'mouseout', function(){ oGeoStart.oRoutes.update(); });
        
        GEvent.addListener(oRef, 'click', function(){            
            oRef.openInfoWindowHtml(oGeoStart.oRoutes.getInfoWindowHtml(oRef._GeoInfo['route_id'], oRef._GeoInfo['route_poi_id']));
        });
    };
    
    /**
    *   Trigger event on poi of route
    *   @param sRoute Route id
    *   @param sPoi Poi id
    *   @param sEvent Event to trigger here
    **/
    this.trigger = function(sRoute, sPoi, sEvent){
        if ( this.oRouteData[sRoute].shows && this.oRouteData[sRoute].shows == true ) {
            GEvent.trigger(oGeoStart.oRoutes.oRouteData[sRoute].oPoints[sPoi], sEvent);
        }
    };
    
    
    /**
    *   Generate Infowindow HTML
    *   @param iRouteId route id
    *   @param iPoiId POI id
    *   @private
    **/
    this.getInfoWindowHtml = function(iRouteId, iPoiId){
        if ( !oGeoStart.oTemplate ) {
            oGeoStart.oTemplate = new cTemplate();
            oGeoStart.oTemplate.sTemplateDir = sBaseUrl + 'GeoStart/templates/';
        }                
        
    
        oGeoStart.oTemplate.loadTemplate('routes/route_infowindow.js.tpl');
        oGeoStart.oTemplate.assign('sTitel', this.oRouteData['route_' + iRouteId].oPoints['routep'+iPoiId]._GeoInfo.titel);
        oGeoStart.oTemplate.assign('iPoiId', iPoiId);
        oGeoStart.oTemplate.assign('iRouteId', iRouteId);
        oGeoStart.oTemplate.assign('iSorteer', this.oRouteData['route_' + iRouteId].oPoints['routep'+iPoiId]._GeoInfo.sorteer);
        oGeoStart.oTemplate.assign('iRouteId', iRouteId);
        
        return oGeoStart.oTemplate.fetch();        
    };
    
    
    /**
    *   Bereken volgende poi en trigger een click erop
    *   @param iRoute Route id
    *   @param iSorteer Current poi sorteer value
    *   @private
    **/
    this.nextPoi = function(iRoute, iSorteer){
        if ( iSorteer != this.oRouteData['route_' + iRoute]._PoiSort.length - 1 ) {
            this.trigger('route_' + iRoute, this.oRouteData['route_' + iRoute]._PoiSort[iSorteer + 1], 'click');
        } else {
            this.trigger('route_' + iRoute, this.oRouteData['route_' + iRoute]._PoiSort[1], 'click');
        }
    };
    
    /**
    *   Bereken vorige poi en trigger een click erop
    *   @param iRoute Route id
    *   @param iSorteer Current poi sorteer value
    *   @private
    **/
    this.prevPoi = function(iRoute, iSorteer){
        if ( iSorteer != this.oRouteData['route_' + iRoute]._PoiSort.length - 1 ) {
            this.trigger('route_' + iRoute, this.oRouteData['route_' + iRoute]._PoiSort[iSorteer - 1], 'click');
        } else {
            this.trigger('route_' + iRoute, this.oRouteData['route_' + iRoute]._PoiSort[this.oRouteData['route_' + iRoute]._PoiSort-1], 'click');
        }
    };
};/**
*   @desc   State machine class for geostart. First draft version. 
*           Saves state of current GeoStart.
*            
*            Version history:
*               0.1:    Primary skeleton
*               1.0:    Productie versie                
*
*   @author Bjorn Brala - Swis BV
*   @class cStateMachine Sla je huidige locatie/zoom/menu up in een cookie en laad deze eventueel later weer
**/
function cStateMachine() {
    this.aCookie = Array();
    
    /**
    *   @desc Initiliaze
    **/
    this.init = function(){
        this.loadCurrentState();
        if ( this.oState ) {
            this.changeToDelete();
            this.loadMapState();        
            this.loadMenuState();
        }
    };
    
    
    /**
    *   @desc Save current state
    **/
    this.saveCurrentState = function(){
        this.changeToDelete();
        this.saveCookie();
    };
    
    
    this.deleteCurrentState = function(){
        this.changeToSave();
        this.deleteCookieVars();
    };
    
    /**
    *   Change icon to delete state
    *   @private
    **/
    this.changeToDelete = function(){
        if ( !oGeoStart.oStateMachine.oImage ) {
            oGeoStart.oStateMachine.oImage = oGeoStart.util.getElementById('save_settings_image');
        }
        if ( !this.oLink ) {
            oGeoStart.oStateMachine.oLink =  oGeoStart.util.getElementById('save_settings_link');
        }
        if( !this.oText){
            oGeoStart.oStateMachine.oLinkText = oGeoStart.util.getElementById('save_settings_text');
        }
        oGeoStart.oStateMachine.oImage.src = "GeoStart/images/icons/menu/load_settings.gif";
        oGeoStart.oStateMachine.oLinkText.innerHTML = "Instellingen worden opgeslagen...";
                
        setTimeout('oGeoStart.oStateMachine.oImage.src = "GeoStart/images/icons/menu/delete_save_settings.gif";oGeoStart.oStateMachine.oLinkText.innerHTML = "Verwijder uw instellingen";oGeoStart.oStateMachine.oLink.onclick=function(){oGeoStart.oStateMachine.deleteCurrentState();return false;}', 1000);
    };
    
    /**
    *   @private
    **/
    this.changeToSave = function(){
        if ( !oGeoStart.oStateMachine.oImage ) {
            oGeoStart.oStateMachine.oImage = oGeoStart.util.getElementById('save_settings_image');
        }
        if ( !oGeoStart.oStateMachine.oLink ) {
            oGeoStart.oStateMachine.oLink =  oGeoStart.util.getElementById('save_settings_link');
        }
        if( !this.oText){
            oGeoStart.oStateMachine.oLinkText = oGeoStart.util.getElementById('save_settings_text');
        }
        oGeoStart.oStateMachine.oImage.src = "GeoStart/images/icons/menu/load_settings.gif";
        oGeoStart.oStateMachine.oLinkText.innerHTML = "Instellingen worden verwijderd....";
        
        setTimeout('oGeoStart.oStateMachine.oImage.src = "GeoStart/images/icons/menu/save_settings.gif";oGeoStart.oStateMachine.oLinkText.innerHTML = "Bewaar deze instellingen";oGeoStart.oStateMachine.oLink.onclick=function(){oGeoStart.oStateMachine.saveCurrentState();return false;}', 1000);        
    };
    
    /**
    *   @desc Load current state
    **/
    this.loadCurrentState = function(){
        // Load cookie information into state variable.
        this.oState = this.readCookie();               
    };
    

    /**
    *   @desc Get and save menu state
    *   @private
    **/
    this.getMenuState = function(){    
        
        // Menu CheckBox State (oStateCB)
        var oStateCB = "";
        for ( var key in oMenu.oStateCB ) {            
            if(typeof(oMenu.oStateCB[key]) != 'function'){
                oStateCB += key + ":" + oMenu.oStateCB[key] + "|";
            }
        }    
        
        // Menu cat state ( oStateCategory
        var oStateCategory = "";
        for ( var key in oMenu.oStateCategory ) {
            if(typeof(oMenu.oStateCategory[key]) != 'function'){
                oStateCategory += key + ":" + oMenu.oStateCategory[key] + "|";  
            }
            
        }    
        
        
        // Menu category classname (oStateMenu)
        var oStateMenu = "";
        for ( var key in oMenu.oStateMenu ) {
            if(typeof(oMenu.oStateMenu[key]) != 'function'){
                oStateMenu += key + ":" + oMenu.oStateMenu[key] + "|";
            }
        }
        
        var aCookie = Array();        
        aCookie.push("GeoStart_oStateCB="       + oStateCB + ";"        + this.expires);
        aCookie.push("GeoStart_oStateMenu="     + oStateMenu + ";"      + this.expires);
        aCookie.push("GeoStart_oStateCategory=" + oStateCategory + ";"  + this.expires);
        
        return aCookie;
    };
    
    /**
    *   @desc Get and save current map view
    *   @private
    **/
    this.getMapState = function(){
        var aCookie = Array();
        
        aCookie.push("GeoStart_lng=" + oGeoStart.oMap.getCenter().lng() + ";" + this.expires);
        aCookie.push("GeoStart_lat=" + oGeoStart.oMap.getCenter().lat() + ";" + this.expires);
        aCookie.push("GeoStart_maptype=" + oGeoStart.oMap.getCurrentMapType().getUrlArg() + ";" + this.expires);
        aCookie.push("GeoStart_zoom=" + oGeoStart.oMap.getZoom() + ";" + this.expires);
        
        return aCookie;
    
        // Get Center
        // Get Zoom
        // Get maptype
    };
    
    /**
    *   @desc Load Map State
    *   @private
    **/
    this.loadMapState = function(){
        
        setTimeout('oGeoStart.oMap.setZoom(parseInt(' + this.oState.GeoStart_zoom + '))', 1);
        
        setTimeout('oGeoStart.oMap.setCenter(new GLatLng(parseFloat(' + this.oState.GeoStart_lat + '), parseFloat(' + this.oState.GeoStart_lng + ')))', 100);
        
        switch(this.oState.GeoStart_maptype) {
            case 'm':
                var oMapType = "G_NORMAL_MAP";
                break;
            case 'k':
                var oMapType = "G_SATELLITE_MAP";
                break;
            case 'h':
                var oMapType = "G_HYBRID_MAP";
                break;
            case 'p':
                var oMapType = "G_PHYSICAL_MAP";
                break;
        }

        setTimeout('oGeoStart.oMap.setMapType(' + oMapType + ')', 100);
        
        
    };
    
    
    /**
    *   @desc   Load menu state from the cookie
    *           Helaas heel custom, kreeg JSON niet in 2 min aan de praat.
    *   @private
    **/
    this.loadMenuState = function(){
        if ( this.oState.GeoStart_oStateCB && this.oState.GeoStart_oStateCB.length > 0 ) {
            var aResult = this.oState.GeoStart_oStateCB.split("|");
            var i = aResult.length;
            while ( i-- ) {
                if ( aResult[i].length > 0 ) {
                    var aItem = aResult[i].split(":");
                    oMenu.oStateCB[aItem[0]] = aItem[1];
                }
            }
        }        

        
        if ( this.oState.GeoStart_oStateCategory && this.oState.GeoStart_oStateCategory.length > 0 ) {
            var aResult = this.oState.GeoStart_oStateCategory.split("|");
            var i = aResult.length;
            while ( i-- ) {
                if ( aResult[i].length > 0 ) {
                    var aItem = aResult[i].split(":");
                    oMenu.oStateCategory[aItem[0]] = aItem[1];
                }
            }
        }        
        
        
        if ( this.oState.GeoStart_oStateMenu && this.oState.GeoStart_oStateMenu.length > 0 ) {
            var aResult = this.oState.GeoStart_oStateMenu.split("|");
            var i = aResult.length;
            while ( i-- ) {
                if ( aResult[i].length > 0 ) {
                    var aItem = aResult[i].split(":");
                    oMenu.oStateMenu[aItem[0]] = aItem[1];
                }
            }
        }        

    };
    
    /**
    *   @desc Write information to a cookie
    *   @param days Days to save the cookie
    **/
    this.saveCookie = function(days){
        this.aCookie = Array();
    
        var days = days || 365;
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        this.expires = " expires="+date.toGMTString();
    
        this.createCookie();
        
        var i = this.aCookie.length;
        
        while ( i-- ) {
            document.cookie = this.aCookie[i];
        }
    };
  
    /**
    *   @desc Create cookie string from saved variabled.
    **/  
    this.createCookie =function(){
        var aMapState = this.getMapState();
        var i = aMapState.length;
        while ( i-- ) {
            this.aCookie.push(aMapState[i]);
        }        

        var aMenuState = this.getMenuState();
        var i = aMenuState.length;
        while ( i-- ) {
            this.aCookie.push(aMenuState[i]);
        }        
        return;
    }
    ;
    /**
    *   @desc Read information from cookie
    *   @private
    **/
    this.readCookie = function(){
        var ca = document.cookie.split(';');
        var oReturn = false;
        
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if ( c.indexOf("GeoStart_") != -1 ) {
                    if ( !oReturn ) {
                        oReturn = {};
                    }
                    oReturn[c.substring(0, c.indexOf("="))] = c.substring(c.indexOf("=")+1, c.length);
                }
        }
        return oReturn;
    };
    
    
    /**
    *   @desc Delete current cookie
    *   @private
    **/
    this.deleteCookieVars = function(){
        this.saveCookie(-1);
    };
    
    
};/**
*   @desc   State machine class for geostart. First draft version. 
*           Saves state of current GeoStart.
*            
*            Version history:
*               0.1:    Primary skeleton
*               1.0:    First implementation        1-5-2008
*
*   @author Bjorn Brala - Swis BV
*   @class cStateMachineMapOnly Sla je huidige locatie op in een cookie en laadt deze eventueel weer. Te gebruiken om bijvoorbeeld een kaart op dezelfde plek te houden als je naar een andere pagina doorklikt.
**/
function cStateMachineMapOnly() {
    this.aCookie = Array();
    this.bDisabled = false;
    
    /**
    *   @desc Initiliaze
    **/
    this.init = function(){
        if ( oGeoStart.oMap.isLoaded() ) {
            var days = days || 365;
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            this.expires = " expires="+date.toGMTString()+"; path=/";
        
            this.loadCurrentState();
            if ( this.oState && this.bDisabled == false ) {
                this.loadMapState();        
            }        
        } else {
            setTimeout('oState.init()', 100);
        }
    };
    
    
    /**
    *   @desc Update cookie information and write it ( mapmove etc )
    **/
    this.update = function(){
        this.createCookie();
        this.saveCookie();
    };
    
    /**
    *   @desc Save current state
    **/
    this.saveCurrentState = function(){
        this.saveCookie();
    };

    
    /**
    *   @desc Load current state
    **/
    this.loadCurrentState = function(){
        // Load cookie information into state variable.
        this.oState = this.readCookie();               
    };
    

    /**
    *   @desc Get and save current map view
    *   @private
    **/
    this.getMapState = function(){
        var aCookie = Array();
        
        aCookie.push("GeoStart_lng=" + oGeoStart.oMap.getCenter().lng() + ";" + this.expires);
        aCookie.push("GeoStart_lat=" + oGeoStart.oMap.getCenter().lat() + ";" + this.expires);
        aCookie.push("GeoStart_zoom=" + oGeoStart.oMap.getZoom() + ";" + this.expires);
        
        return aCookie;
    
        // Get Center
        // Get Zoom
        // Get maptype
    };
    
    /**
    *   @desc Load Map State
    *   @private
    **/
    this.loadMapState = function(){
        setTimeout('oGeoStart.oMap.setZoom(parseInt(' + this.oState.GeoStart_zoom + '))', 1);
        setTimeout('oGeoStart.oMap.setCenter(new GLatLng(parseFloat(' + this.oState.GeoStart_lat + '), parseFloat(' + this.oState.GeoStart_lng + ')))', 100);
    };
    
    /**
    *   @desc Write information to a cookie
    **/
    this.saveCookie = function(days){
        this.aCookie = Array();
    
        this.createCookie();
        
        var i = this.aCookie.length;
        
        while ( i-- ) {
            document.cookie = this.aCookie[i];
        }
    };
  
    /**
    *   @desc Create cookie string from saved variabled.
    **/  
    this.createCookie =function(){
        var aMapState = this.getMapState();
        var i = aMapState.length;
        while ( i-- ) {
            this.aCookie.push(aMapState[i]);
        }        

        return;
    };
    
    /**
    *   @desc Read information from cookie
    *   @private
    **/
    this.readCookie = function(){
        var ca = document.cookie.split(';');
        var oReturn = false;
        
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if ( c.indexOf("GeoStart_") != -1 ) {
                    if ( !oReturn ) {
                        oReturn = {};
                    }
                    oReturn[c.substring(0, c.indexOf("="))] = c.substring(c.indexOf("=")+1, c.length);
                }
        }
        return oReturn;
    };
    
    
    /**
    *   @desc Delete current cookie
    *   @private
    **/
    this.deleteCookieVars = function(){
        this.saveCookie(-1);
    };
    
    
};/**
*   cTemplate.class.js
*
*   Javascript smarty
* @class cTemplate Javascript smarty templates. if en section zijn ondersteund.
**/
function cTemplate(){

    this.oRequest = new cRequest();     
    this.sCurrentTemplate = null;
    this.sTemplateDir = '';
    this.sTemplate = [];

    /**
    *   @Desc Haal template op en cache deze
    *   @param tempalte name
    */
    this.loadTemplate = function(sName){
        // cache
        if (!this.sTemplate[sName]){
            if(typeof(oTemplateCache) != 'undefined' && typeof(oTemplateCache[sName]) != 'undefined'){
                this.sTemplate[sName] = oTemplateCache[sName];
            } else {
                this.oRequest.sUrl    = this.sTemplateDir + sName; 
                this.sTemplate[sName] = this.oRequest.getContent().responseText; 
            }
        }
        this.sCurrentTemplate = this.sTemplate[sName];

        if ( typeof(sBaseUrl) != 'undefined' ) {
            this.assign('sBaseUrl', sBaseUrl);        
        }
    };

    /**
    *   @Desc assign een variabele in de template
    *   @param sFind Variable name
    *   @param mReplace Value
    */
    this.assign = function(sFind, mReplace){
        if ( typeof(mReplace) != 'object' ) {
            mReplace = mReplace+"";
            if ( mReplace.length > 0 ) {
                this.doReplace(sFind, mReplace);
            }
        } else {
            this.doReplace(sFind, mReplace);
        }
        
    };    
    
    /**
    *   Do the replace action
    *   @param sFind Variable name
    *   @param mReplace Value
    **/
    this.doReplace = function(sFind, mReplace){

        var self = this;  
        var oRegex = new RegExp('\\{if \\$' + sFind + '\\}(.|[\r\n])*?\\{\\/if\\}');
        this.sCurrentTemplate = this.sCurrentTemplate.replace(oRegex, function($0, $1){ return self.parseIf($0, $1, sFind, mReplace)});
        var result = oRegex.exec(this.sCurrentTemplate);
        if ( result != null ) {
            this.doReplace(sFind, mReplace);
        }
        
        switch(typeof(mReplace)){
            case 'string':                                              
                var oRegex = new RegExp('\\{\\$' + sFind + '\\}', 'gi');                
                this.sCurrentTemplate = this.sCurrentTemplate.replace(oRegex, mReplace);
                break;
            case 'object':
                var oRegex = new RegExp('\\{section name=(.*) loop=\\$' + sFind + '\\}(.|[\r\n])*?\\{\\/section\\}');
                this.sCurrentTemplate = this.sCurrentTemplate.replace(oRegex, function($0, $1){ return self.parseSection($0, $1, sFind, mReplace)});
            break;    
        }
        
        var result = oRegex.exec(this.sCurrentTemplate);
        if ( result != null ) {
            this.doReplace(sFind, mReplace);
        }
    };
        
    /**
    * Parse a section and replace what is needed
    *   @param sSection Sectio nanme
    *   @param sCycler name
    *   @param sFind Variable name
    *   @param mReplace Value
    **/
    this.parseSection = function(sSection, sCycler, sFind, mReplace){

        // section tags eruit strippen
        var oRegex = new RegExp('\\{section name=(.*) loop=\\$(.*)\\}', 'g');  
        sSection = sSection.replace(oRegex, ''); 
        var oRegex = new RegExp('\\{\\/section\\}', 'g');  
        sSection = sSection.replace(oRegex, ''); 

        // loopen en vervangen
        var iMax    =  mReplace.length;
        var self    = this;
        var sReturn = '';

        for(var i=0; i < iMax; i++){
            var sHtml = '';
            var oRegex = new RegExp('\\{\\$' + sFind + '\\[' + sCycler + '\\]\\.([a-z0-9_]+)\\}', 'gi');   
            sHtml += sSection.replace(oRegex, function($0, $1){ return self.parseSectionVar($0, $1, i, sFind, mReplace)});
            sReturn += sHtml;
        }

        return sReturn;
    };

    /**
    *   @desc Parse and eval section variable.
    *   @param sSection Sectio nanme
    *   @param sVarName Variable name
    *   @param i Iteration
    *   @param sFind Variable name
    *   @param mReplace Value
    **/
    this.parseSectionVar = function(sSection, sVarName, i, sFind, mReplace){
        return eval( 'mReplace[' + i + '].' + sVarName);
    };

    /**
    *   @desc If vars eruit strippen en kale string terug geven
    **/
    this.parseIf = function(sIf, sCycler, sFind, mReplace){
        if(mReplace){
            // IF tags eruit strippen
            var oRegex = new RegExp('\\{if \\$' + sFind + '\\}', 'g');  
            sIf = sIf.replace(oRegex, ''); 
            
            var oRegex = new RegExp('\\{\\/if\\}', 'g');  
            sIf = sIf.replace(oRegex, ''); 
        } else {
            sIf = '';
        }

        return sIf;
        
    };


    /**
    *   Clean up wrapper
    **/
    this.cleanUp = function(){
        this.cleanSections();
        this.cleanIfs();
        this.cleanVars();
    };
        

    /**
    *   Ongebruikte IF statements eruit halen.
    **/
    this.cleanIfs = function(){
    
        // Zonder word boundry, dus {if $VAR}, alvast voor IF statements.
        var oRegex = new RegExp('\\{if \\$(.)*\\}(.|[\r\n](^\\{\\/if\\}))*\\{\\/if\\}', 'g');
        this.sCurrentTemplate = this.sCurrentTemplate.replace(oRegex, '');        

        // Kijken of er nog meer IF statements over zijn.
        var result = oRegex.exec(this.sCurrentTemplate);
        if ( result != null ) {
            this.cleanIfs();
        }

        //Met geneste sectie. Wellicht overbodig... Nog ff testen.
        var oRegex = new RegExp('\\{if \\$(.)*\\}(.|[\r\n])*?(\\{\\/section\\}|\\{\\/if\\})\\{\\/if\\}', 'g');
        this.sCurrentTemplate = this.sCurrentTemplate.replace(oRegex, '');        
        
        // Kijken of er nog meer if statements over zijn.
        var result = oRegex.exec(this.sCurrentTemplate);
        if ( result != null ) {
            this.cleanIfs();
        }
        
    };
    
    
    
    /**
    *   Ongebruikte vars weghalen.
    **/
    this.cleanVars = function(){
        var oRegex = new RegExp('\\{\\$[a-z0-9]*\\}', 'gi');    
        
        this.sCurrentTemplate = this.sCurrentTemplate.replace(oRegex, '');        
        
        // Kijken of er nog meer variabelen over zijn.
        var result = oRegex.exec(this.sCurrentTemplate);
        if ( result != null ) {
            this.cleanVars();
        }
    };
    
    
    
    /**
    *   Clean ongebruikte sections
    **/
    this.cleanSections = function(){
    
        // Clean unused sections
        var oRegex = new RegExp('\\{section name=(.*) loop=\\$(.)*\\}(.|[\r\n])*?\\{\\/section\\}');
        
        this.sCurrentTemplate = this.sCurrentTemplate.replace(oRegex, '');
        
        var result = oRegex.exec(this.sCurrentTemplate);
        if ( result != null ) {
            this.cleanSections();
        }
        
        
        
    };

    /** 
    *  @Desc Return de template
    *
    */
    this.fetch = function(){
        this.cleanUp();
        return this.sCurrentTemplate;
    };
};function cTilePolyHandler() { 
    
    this.oPolyIds       = {};
    this.iPreviousId    = -1;
    
    this.handleMouseMove = function(lat, lng, bTimedTrigger){
        if (typeof(bTimedTrigger) == 'undefined') {
            if(typeof(oGeoStart.oTilePolyHandler.oTimer) == 'undefined'){
                oGeoStart.oTilePolyHandler.oTimer = setTimeout('oGeoStart.oTilePolyHandler.handleMouseMove('+lat+', '+lng+', true);', 25);
            }
            return;
        } else {
            clearTimeout(oGeoStart.oTilePolyHandler.oTimer);            
            delete(oGeoStart.oTilePolyHandler.oTimer);
        }

        var latlng = new GLatLng(lat,lng);
        
        
        var bOverPolygon = false;
        for(id in this.oPolyIds) {
            if( typeof(oGeoStart.oPoints[id]) != "undefined"
                && !oGeoStart.oPoints[id].isHidden()
                && oGeoStart.oPoints[id].inBounds(latlng.lat(), latlng.lng())
                && oGeoStart.oPoints[id].containsPoint(latlng.lat(), latlng.lng())){
                    bOverPolygon = true;
                    
                    if(id != this.iPreviousId) {
                        if(this.iPreviousId != -1) {
                            oGeoStart.oPoints[this.iPreviousId].hidePolygon();
                        }
                        this.iPreviousId = id;
                        oGeoStart.oPoints[id].renderPolygon();
                        oGeoStart.oMap.getDragObject().setDraggableCursor("pointer");
                        return true;
                    }

            } 
        }
        
        if(!bOverPolygon && this.iPreviousId != -1) {
            oGeoStart.oPoints[this.iPreviousId].hidePolygon();
            this.iPreviousId = -1;
        }
        
        oGeoStart.oMap.getDragObject().setDraggableCursor(GDraggableObject.getDraggableCursor());
            
    }
    
    this.hideAllPolygons = function() {
        for(id in this.oPolyIds) {
            if( typeof(oGeoStart.oPoints[id]) != "undefined"
                && !oGeoStart.oPoints[id].isHidden()) {
                
                oGeoStart.oPoints[id].hidePolygon();
                
            }            
        }
    }
    
}/**
*   @class cTooltip v. 2.0
    Class showing / hiding a tooltip at certain 
    point on the map. Tooltip can contain any 
    information.
*
*   Björn Brala - Swis BV
**/
function cTooltip(oMap, sDiv, iTargetWidth, iTargetHeight, iOffsetX, iOffsetY) {
    this._oMap = oMap;                              // GMap2 object
    this._eDiv = oGeoStart.util.getElementById(sDiv);                           // Tooltip element
    this._iTargetWidth = iTargetWidth || 0;         // Width in pixels of target element
    this._iTargetHeight = iTargetHeight || 0;       // Heigth in pixels of target element
    this._iOffsetX = iOffsetX || 0;                 // Offset X in pixels - Tweaking x position
    this._iOffsetY = iOffsetY || 0;                 // Offset Y in pixels - Tweaking y position
    this._bCenter = false;
    this.oMarker;
    this.bHtmlLoaded = false;
    this.aMarkerStack = [];
    var self = this;
    
    //GEvent.addDomListener(self._eDiv, 'mouseover', function(){self.hide();});
    
    /** 
    *   Determine if tooltip should center itself or align to the right/left
    *   @private
    **/
    this.checkAlign = function(sType){
        this._current = sType;
        switch ( sType ) {
            case "POINT":                
                this._bCenter = false;
                break;
            case "LINESTRING":
                this._bCenter = true;
                break;
            case "POLYGON":
                this._bCenter = true;
                break;
            case "MULTIPOLYGON":
                this._bCenter = true;
                break;
        }
    };
    
    this.setMarker = function(oMarker){
        if(this.bHtmlLoaded === false){
            this.createHtml();
        }

        this.oMarker = oMarker;
        //this.aMarkerStack.push(oMarker);
    }
    
    this.getMarker = function(){ 
        return this.oMarker;
    }
        
    
    /**
    *   Crossbrowser find position voor DOM object
    *   @param obj DOM object
    *   @private
    **/
    this.findPos = function(obj) {
        var curleft = curtop = 0;
        if (obj.offsetParent) {
            curleft = obj.offsetLeft;
            curtop = obj.offsetTop;
            while (obj = obj.offsetParent) {
                curleft += obj.offsetLeft;
                curtop += obj.offsetTop;
            }
        }
        return [curleft,curtop];
    };
    
    /**
    *   Function used by getPosition. Results in a and b difference (in coordignates)
    *   @private
    **/
    this.subGPoints = function (a,b) {
        return new GPoint(a.x - b.x, a.y - b.y);
    };
    
   
    /**
    *   Get position for the tooltip. Checks of right side is out of bounds. If so, display left.
    *   @return object with x and y ( object.x, object.y )
    *   @param point GPOint
    **/
    this.getPixelPosition = function(point){ 
                
        //var mapOffsetTop        = this._oMap.getContainer().offsetTop;
        //var mapOffsetLeft       = this._oMap.getContainer().offsetLeft;

        //var oMapPos             = this.findPos(this._oMap.getContainer());
        
        // Bug: Bij een map met een offset aan de linker kant IE telt te 
        // offset op bij het totaal hetgeen resulteerd in een positie die te ver naar rechts is.
        
        var mapOffsetTop        = this._oMap.getContainer().offsetTop;
        var mapOffsetLeft       = this._oMap.getContainer().offsetLeft;
        
        var TlcLatLng           = this._oMap.fromContainerPixelToLatLng(new GPoint(0,0),true);
        var TlcDivPixel         = this._oMap.fromLatLngToDivPixel(TlcLatLng);
        var pointDivPixel       = this._oMap.fromLatLngToDivPixel(point);
        var pointContainerPixel = this.subGPoints(pointDivPixel, TlcDivPixel);     

        // Get bounds information for the map
        var bounds          = this._oMap.getBounds();
        var boundsSpan      = bounds.toSpan();
        var longSpan        = boundsSpan.lng();
        var latSpan        = boundsSpan.lat();
        var mapWidth        = this._oMap.getSize().width;
        var mapHeight        = this._oMap.getSize().height;
        
        // Convert pixel width to degrees ( map width )
        
        //this._eDiv.style.width = "372px";
        //oGeoStart.util.getElementById('middle').style.width = "372px";
        //console.log(this._eText);
        if ( !this._eContent ) {
            this._eContent = oGeoStart.util.getElementById('tooltip_content');        
        }
        if ( !this._eText ) {
            this._eText = oGeoStart.util.getElementById('tooltip_title');        
        }
        if ( this._eContent.offsetWidth > this._eText.offsetWidth ) {
            
            oGeoStart.util.getElementById('GeoTooltip').style.width = oGeoStart.util.getElementById('container').offsetWidth + "px";
            
        } else {
            
            oGeoStart.util.getElementById('GeoTooltip').style.width = oGeoStart.util.getElementById('container').offsetWidth + "px";
        } 
        
        var tooltipWidthInDeg = ( this._eDiv.offsetWidth ) / mapWidth * longSpan;
        var tooltipHeightInDeg = ( this._eDiv.offsetHeight ) / mapHeight * latSpan;

        // Offset tooltip to align to center of point. Used for polygones etc.
        if ( this._bCenter ) { 
            iCenterOffsetY = 0;
            iCenterOffsetX = ( this._eDiv.offsetWidth / 2 ) + (this._iTargetWidth/2);            
        } else { 
            iCenterOffsetX = 0; 
            iCenterOffsetY = 0; 
        }
        
        if ( !this._left ) {
            this._left = oGeoStart.util.getElementById("GeoTooltip_left");
        }
        if ( !this._right ) {
            this._right = oGeoStart.util.getElementById("GeoTooltip_right");
        }
        if ( !this._container ){
            this._container = oGeoStart.util.getElementById("container");
        }
        if( !this._eCatImg ){
            this._eCatImg = oGeoStart.util.getElementById('tooltip_image');
        }            
        
                 
        // Check for X position. 
        if ( ( point.lng() + tooltipWidthInDeg ) > bounds.getNorthEast().lng() ) {      
        
            pointContainerPixel.x = pointContainerPixel.x - this._eDiv.offsetWidth + this._iTargetWidth + mapOffsetLeft;
           // this._left.style.backgroundImage = "url(GeoStart/images/tooltip/tooltip_right_flip.png)";
           // this._right.style.backgroundImage = "url(GeoStart/images/tooltip/tooltip_left_flip.png)";
            this._container.style.padding = "10px 40px 10px 30px";
            this._eCatImg.style.left = (this._eDiv.offsetWidth-31) + "px";
            
        } else {                                                                        
            pointContainerPixel.x = pointContainerPixel.x + (Math.round(this._iTargetWidth/2)) + this._iOffsetX + mapOffsetLeft - iCenterOffsetX;
          //  this._left.style.backgroundImage = "url(GeoStart/images/tooltip/tooltip_left.png)";
          //  this._right.style.backgroundImage = "url(GeoStart/images/tooltip/tooltip_right.png)";
            this._container.style.padding = "10px 30px 10px 40px";
            this._eCatImg.style.left = 9 + "px";
        }
        
        
        
        
        // Check for Y position
        if ( ( point.lat() - tooltipHeightInDeg ) < bounds.getSouthWest().lat() ) {
            pointContainerPixel.y = pointContainerPixel.y - this._eDiv.offsetHeight + ( this._iTargetHeight / 2 ) + this._iOffsetY + mapOffsetTop;
   
            this._eCatImg.style.top = "25px";
   
            //this._leftBottomImage.src = "GeoStart/images/tooltip/bottom_left_flip.png"
            //this._rightBottomImage.src = "GeoStart/images/tooltip/bottom_right_flip.png"
   
        } else {
            pointContainerPixel.y = pointContainerPixel.y - (this._iTargetWidth/2) + this._iOffsetY + mapOffsetTop;

            this._eCatImg.style.top = "-13px";
            
            //this._leftBottomImage.src = "GeoStart/images/tooltip/bottom_left.png"
            //this._rightBottomImage.src = "GeoStart/images/tooltip/bottom_right.png"
        }
        
        //GLog.write(pointContainerPixel.x + 'x' + pointContainerPixel.y + ' - pointpixelcontainer');
        
        return pointContainerPixel;
    };
    
    
    /**
    *   check if tooltip is onscreen
    *   @param point GPoint
    *   @return boolean True/false
    **/
    this.markerOnScreen = function (point) {
        var bounds = this._oMap.getBounds();
        // check for onscreen.
        if ( bounds.contains(point) ) {
            return true;
        } else {
            return false;    
        }
    };

    /**
     *  Create HTML for the tooltip if needed.
     **/
     this.createHtml = function(){
        var oTemplate = new cTemplate();
        oTemplate.sTemplateDir = sBaseUrl + 'GeoStart/templates/';
        oTemplate.loadTemplate('tooltip_async.tpl');
        this._eDiv.innerHTML = oTemplate.fetch();
        this.bHtmlLoaded = true;
     }


    /** 
    *   Show tooltip on object
    *   @param point GPoint
    **/
    this.show = function(point){
        if(this.bHtmlLoaded === false){
            this.createHtml();
        }
        this._bIsHidden = false;
        var oCoordinates = this.getPixelPosition(point);
        this._eDiv.style.top = oCoordinates.y + 'px';
        this._eDiv.style.left = oCoordinates.x + 'px';
    };
    
    /**
    *   Helper, show tooltip at pixel position
    *   @private
    **/
    this.showPixels = function(oPixels){
        var point = this._oMap.fromContainerPixelToLatLng(oPixels);
        this.show(point);
    };
    
    
    /**
    *   Hides the tooltip div.
    **/
    this.hide = function () {   
        this._bIsHidden = true;
        this._current = false;
        this._eDiv.style.left = '-5000px';
        this._eDiv.style.top = '0px';
        
        //r i = this.aMarkerStack.length;
        /*/console.log(this.aMarkerStack);
        while(true){
            var oCurrent = this.aMarkerStack.pop();
            if(typeof(oCurrent) != 'undefined') {
                oGeoStart.checkVisibility(oCurrent);
            } else {
                return;
            }           
        }
        */
    };
    
    /**
    *   Hides the tooltip div.
    *   @private
    **/
    this.hideTooltip  = function () {  
        this._eDiv.style.left = '-5000px';
        this._eDiv.style.top = '0px';    
    };
    
    /**
    *   Pas tooltip titel aan
    *   @param sText titel
    **/
    this.setText = function(sText) {
        if(this.bHtmlLoaded === false){
            this.createHtml();
        }

        if ( !this._eText ) {
            this._eText = oGeoStart.util.getElementById('tooltip_title');        
        }
        this._eText.innerHTML = sText;
    };
    
    /**
    *   Category met mId invoegen. 
    *   @param {number|object} Nummer = cat id, object = 'array' met subgroepen.
    **/
    /**
    *   Category met mId invoegen. 
    *   @param {number|object} Nummer = cat id, object = 'array' met subgroepen.
    **/
    this.addContent = function(mId) {
        
        if ( !this._eContent ) {
            this._eContent = oGeoStart.util.getElementById('tooltip_content');        
        }
        if( !this._eCatImg ){
            this._eCatImg = oGeoStart.util.getElementById('tooltip_image');
        }
        if ( typeof(mId) == 'number' ||  typeof(mId) == "string") {
            this._eCatImg.innerHTML = "<img src=" + oIconmanager.get(parseInt(mId,10)).image + ">";
            this._eContent.innerHTML    = "<span style='color:#"+oIconmanager.get(parseInt(mId,10)).color+">"+oIconmanager.get(parseInt(mId,10)).sg_titel+"</span>";
        } else if ( typeof(mId) == 'object' ) {
            var sContent = '';
            var bFirst = true;
            
            var key = mId.length;
            while(key--){
                if ( bFirst ) {
                    bFirst = false;
                    this._eCatImg.innerHTML = "<img src=" + oIconmanager.get(this.oMarker._GeoInfo.sg_id).image + ">"; 
                   sContent += "<span style='color:#" + oIconmanager.get(mId[parseInt(key,10)]).color + "'>" + oIconmanager.get(mId[parseInt(key,10)]).sg_titel + "</span><br />";                    
                } else {
                    sContent += "<span style='color:#"+oIconmanager.get(mId[parseInt(key,10)]).color+"'>"+oIconmanager.get(mId[parseInt(key,10)]).sg_titel+"</span><br />";
                }
            }   
            this._eContent.innerHTML = sContent;
        }        
    };  
}/**
*   @desc cZones - Handler for zones. Hide / show on zoom and such.
*   @desc todo Optimize drag, hide zones when dragging
*   @class cZones Zone functionliteit, zone is een polygoon met een label. De zone kan veranderen in een lijn bij een bepaald zoomniveau en verdwijnen bij een bepaald zoomniveau.
**/
function cZones(oMap){
    this.oMap = oMap;
    this.aZones = [];
    this.sCurrentlyLoaded = "none";
    this.aLoadedOverlays = [];
    
    /**
    *   @desc initialize zone data
    **/
    this.init = function(){
        this.loadSettings();
        
        this.loadData();
        
        this.loadMapListeners();
        
        return this;
    };
    
    
    
    /**
    *   Example optimisation for dragging
    
    GEvent.addListener(oMapObjects.oMap, 'dragstart', function(){oVergunningen.setVisibility(false);});
    GEvent.addListener(oMapObjects.oMap, 'dragend', function(){ oVergunningen.setVisibility(true);});
    
    **/
    
    
    /**
    *   @desc Load settings for zones.
    **/
    this.loadSettings = function(){
        
        this._sDataUrl      = this._sDataUrl        || "GeoStart/ajax/getZoneData.php";
        
        this._iZoomVisible  = this._iZoomVisible    || 12;
        this._iZoomFilled   = this._iZoomFilled     || 16;
        this._iZoomHidden   = this._iZoomHidden     || 19;
        this._sColor        = this._sColor          || "#4C1664";
        this._iOpacity      = this._iOpacity        || "0.5";
        this._iBorderWidth  = this._iBorderWidth    || 3;
        this.bFirstLoad     = this.bFirstLoad       || true;
        this.bVisible       = this.bVisible         || true;
        this.sZoneTable     = this.sZoneTable       || 'gebieden';
        
        if ( this.bStartInvisble === true ) {
            this.bVisible = false;
        }        
    };
    
    /**
    *   Enable balloon for data field
    *   @param sField field with data for in the balloon
    **/
    this.enableBalloon = function(sField){
        var i = this.aZones.length;
        if ( i > 0 ) {
            while ( i-- ) {
                this.aZones[i].text.enableBalloon(sField);
            }
        } else {
            this.sEnableBalloon = sField;
        }
    };
    
    /**
    *   Do an ajax call with callback
    **/
    this.loadData = function(){
        if ( !sUser ) {
            var sUser = null; 
        }   

        if(oGeoStart.oCrossSiteProxy){
            oGeoStart.oCrossSiteProxy.load('loadZoneData', this._sDataUrl + "?sUser=" + sUser);
            oGeoStart.oCrossSiteProxy.call(this.loadZoneData);
        } else {
            GDownloadUrl( this._sDataUrl + "?sUser=" + sUser, GEvent.callback(this, this.loadZoneData));
        }        
    };
    
    
    this.createTileLayer = function() {
        var tilelayer = new GTileLayer(new GCopyrightCollection(), 0, 17);
        var self = this;
                
        tilelayer.getTileUrl = function(tile, zoom) {
            var sUrl = "http://mt" + (tile.y + tile.x) % 10 + ".tile01.swis.nl/zone/" + oSettings.sDbKey + "/" + self.sZoneTable + "/" + parseInt(oSettings._iSubsiteGroepId, 10) + "/"+tile.x+"/"+tile.y+"/"+zoom+".gif";
            return sUrl;
        };
        
        tilelayer.getOpacity = function() {
            return 0.5;
        }
        
        return new GTileLayerOverlay(tilelayer);
    }
    
    
    
    /**
    *   load the data gotten from the data url.
    *   @private
    *   @param oJson Jason string
    **/
    this.loadZoneData = function(oJson){
        var aData = eval('(' + oJson + ')');
        
        
        var i = aData.length;
        
        while ( i-- ) {
            
            if(oSettings._bTileServer){
                this.oTileOverlay = this.createTileLayer();                
                var oPolyoverlay = false;
                this.bTileOverlayLoaded = false;
            } else {
                var oPolyoverlay = this.createPolygon(aData[i]);
            }   
            
            // Poly data
            this.aZones[i] = {  "polyline": this.createPolyline(aData[i]),
                                "polygon":  oPolyoverlay,
                                "text":     this.createZoneLabel(aData[i]),
                                "id":       aData[i].id
                                };                                
            this.aZones[i].bounds = this.aZones[i].polyline.getBounds();
            this.aZones[i].text['_bounds'] = this.aZones[i].polyline.getBounds();
            
            
            if ( aData[i].kleur.length == 6 ) {
                this.aZones[i].kleur = "#" + aData[i].kleur;
            } else {
                this.aZones[i].kleur = this._sColor;
            }
            
        }
        
        // First load logic
        if ( this.bFirstLoad && this.bStartInvisble !== true ) {
            this.bStartInvisble = false;
            this.bFirstLoad = false;
            
            if ( this.sEnableBalloon ) {
                this.enableBalloon(this.sEnableBalloon);
            }           
            this.updateZones();
            
        } else if ( this.bFirstLoad ) {
            if ( this.sEnableBalloon ) {
                this.enableBalloon(this.sEnableBalloon);
            }
        }
    };
    
    
    /**
    *   Map listener to handle map chenges
    *   @private
    **/   
    this.loadMapListeners = function(){
        var oThis = this;
        GEvent.addListener(oThis.oMap, 'moveend', GEvent.callback(this, this.updateZones));
    };
    /**
    *   Toggle visibility
    *   @return boolean
    **/
    this.toggle = function(){
        if ( this.bFirstLoad ) {
            this.bFirstLoad = false;
            this.updateZones();
        }
    
        this.bVisible = !this.bVisible;
        this.visibility(this.bVisible); 
        return this.bVisible;       
    }
    
    /**
    *   Optimezed hide/show function
    **/
    this.setVisibility = function(bState) {
        if ( this.bFirstLoad ) {
            this.bFirstLoad = false;
            this.updateZones();
        }
        if ( this.bVisible !== bState ) {
            this.bVisible = bState;
            this.visibility(this.bVisible);
        }
    };

    /**
    *   Generate click on zone
    *   @param iId Zone id
    **/
    this.clickZone = function(iId){
        var i = this.aZones.length;
        while ( i-- ) {
            if ( parseInt(this.aZones[i].id, 10) == parseInt(iId, 10) ) {
                this.aZones[i].text.clickHandler();
                return;
            }
        }
    };
    
    
    /**
    *   Show / Hide all
    *   @param bState true/false
    **/
    this.visibility = function(bState){
        var i = this.aLoadedOverlays.length;
        if ( i > 0 ) {
            while ( i-- ) {
                if ( bState ) {
                    this.aLoadedOverlays[i].show();
                } else {
                    this.aLoadedOverlays[i].hide();
                }
            }
        }
    };
    
    /**
    *   Adding/removing zones and changing opacity.
    *   @private
    **/
    this.updateZones = function(){
        if(this.bFirstLoad === false){
            var state = this.checkForStateChange();
            if ( state ) {
                this.removeAll();            
                this.updateDisplay(state);
                this.sCurrentlyLoaded = state;
            }
        }
    };
    
    
    /**
    *   remove old overlays
    *   @private
    **/
    this.removeAll = function(){
        var i = this.aLoadedOverlays.length;
        if ( i > 0 ) {
            while(i--){
                this.oMap.removeOverlay(this.aLoadedOverlays[i]);
                if(oSettings._bTileServer){
                    this.bTileOverlayLoaded = false;
                }
            }
            this.aLoadedOverlays = Array();
        }
    };
    
    /**
    *   Update the display of zones. Depending on state it will be displayed.
    *   @private
    *   @param sState polygon/none/polyline
    **/
    this.updateDisplay = function(sState){
        switch ( sState ) {
            case "none":
                break;
            case "polygon":
                var i = this.aZones.length;
                while ( i-- ) {
                    if(this.aZones[i].polygon === false ){
                        if(this.bTileOverlayLoaded !== true){
                            this.oMap.addOverlay(this.oTileOverlay);
                            this.bTileOverlayLoaded = true;
                            this.aLoadedOverlays.push(this.oTileOverlay);
                        }
                    } else {
                        this.oMap.addOverlay(this.aZones[i].polygon);
                        this.aLoadedOverlays.push(this.aZones[i].polygon);
                    }
                    this.oMap.addOverlay(this.aZones[i].text);
                    this.aLoadedOverlays.push(this.aZones[i].text);                    
                }
                break;
            case "polyline":
                var i = this.aZones.length;
                while ( i-- ) {
                    this.oMap.addOverlay(this.aZones[i].polyline);
                    this.aLoadedOverlays.push(this.aZones[i].polyline);                    
                }
                break;        
        }
        this.visibility(this.bVisible);
    };
    
    /**
    *   Check what should be loaded at this time.
    *   @private
    **/
    this.checkForStateChange = function(){
        var iZoom   = this.oMap.getZoom();        
        var sNewState;

        if ( iZoom < this._iZoomVisible ) {
            sNewState = "none";
        } else if ( iZoom >= this._iZoomVisible && iZoom <= this._iZoomFilled ) {
            sNewState = "polygon";
        } else if ( iZoom >= this._iZoomFilled && iZoom <= this._iZoomHidden ) {
            sNewState = "polyline";
        } else if ( iZoom < this._iZoomHidden ) {
            sNewState = "none";
        }
        if ( sNewState == this.sCurrentlyLoaded ) {
            return false;
        } else {
            return sNewState;
        }
    };
    
    /**
    *   Create a polyline
    *   @param aInfo Default information from ajax/getZoneData.php
    *   @private
    **/   
    this.createPolyline = function(aInfo){
        var aPoints = this.createPoints(aInfo);
        if ( aInfo.kleur && aInfo.kleur.length == 6 ) {
            var sKleur  = "#"+aInfo.kleur;
        } else { 
            var sKleur = this._sColor;
        }
        var oPoly = new GPolyline(aPoints, sKleur, this._iBorderWidth, 1);

        
        oPoly._GeoInfo = aInfo;
        return oPoly;
    };
    
    /**
    *   Create a polyline
    *   @param aInfo Default information from ajax/getZoneData.php
    *   @private
    **/   
    this.createPolygon = function(aInfo){        
        var aPoints = this.createPoints(aInfo);
        
        if ( aInfo.kleur && aInfo.kleur.length == 6 ) {
            var sKleur  = "#"+aInfo.kleur;
        }else{ 
            var sKleur = this._sColor;
        }

        var oPoly = new GPolygon(aPoints, sKleur, this._iBorderWidth, parseFloat(0.8), sKleur, parseFloat(this._iOpacity));
        
        oPoly._GeoInfo = aInfo;
        return oPoly;
    };
    
    /**
    *   Create the center label for the polygone.
    *   @param aInfo Default information from ajax/getZoneData.php
    *   @private
    **/
    this.createZoneLabel = function(aInfo){
        var sTitel  = aInfo.titel;
        var point   = new GLatLng(parseFloat(aInfo.lat), parseFloat(aInfo.lng));
        var oLabel  = new ZoneLabel(point, sTitel);
        oLabel._Data = aInfo;
        return oLabel;
    };
    
    
    /**
    *   Convert array of lat's and lng's to real GPoints()
    *   @param aInfo Default information from ajax/getZoneData.php
    *   @private
    **/
    this.createPoints = function(aInfo){
        var aPoints = aInfo['aGeometry']['aGeometry'];
        var iLength = aPoints.length;
        var aGPoints = new Array();
        for(var i=0; i<iLength; i++){
            point = new GLatLng( parseFloat(aPoints[i].lat), parseFloat(aPoints[i].lng) );
            aGPoints.push(point);
        }
        return aGPoints;
    };
};

/**
*   Zone label. sText 5 times superimposed with a small offset to sumilate a white glow
*   @param point GPoin
*   @param sText Label text
*   @contructor
**/
function ZoneLabel(point, sText) {
    this._sText = sText;
    this._point = point;
};
ZoneLabel.prototype = new GOverlay();



/**
*   Create the label HTML
**/
ZoneLabel.prototype.initialize = function(map) {

    var oElement = document.createElement('div');
    
    oElement.style.position     = "absolute";
    oElement.style.textAlign    = "center";
    oElement.style.width        = "50px";
    oElement.style.height       = "20px";
    oElement.style.cursor       = "pointer";
    
    var aText = Array();
    
    aText.push("<span style='position:absolute;top:1px;left:1px;z-index:1000000000;color:black;'>"+this._sText+"</span>");
    aText.push("<span style='position:absolute;top:0px;left:0px;color:white;'>"+this._sText+"</span>");
    aText.push("<span style='position:absolute;top:2px;left:2px;color:white;'>"+this._sText+"</span>");
    aText.push("<span style='position:absolute;top:2px;left:0px;color:white;'>"+this._sText+"</span>");
    aText.push("<span style='position:absolute;top:0px;left:2px;color:white;'>"+this._sText+"</span>");
    var sText = aText.join('');
    
    oElement.innerHTML = sText;
    
    // Our rectangle is flat against the map, so we add our selves to the
    // MAP_PANE pane, which is at the same z-index as the map itself (i.e.,
    // below the marker shadows)
    map.getPane(G_MAP_MARKER_SHADOW_PANE).appendChild(oElement);
    
    this.map_ = map;
    this.div_ = oElement;
    var self = this;
    GEvent.addDomListener(oElement, 'click', function(){
        self.clickHandler();
    });
    
};


/**
*   You can enable the ballon for zone labels.
*   @param sField which field of aData to use
**/
ZoneLabel.prototype.enableBalloon = function(sField){
    this.balloonEnabled = true;
    this.balloonField = sField;
};

/**
*   Generate balloon HTML, should actually be a template.
*   @todo MOVE TO TEMPLATE
**/
ZoneLabel.prototype.getBalloonHtml = function(){    
    var oElement = document.createElement("div");
    oElement.className = "infoWindow";
    var aHtml = new Array();
    
    aHtml.push("<strong>"+this._Data['titel']+"</strong>");
    aHtml.push("<p>"+this._Data[this.balloonField]+"</p>");
    oElement.innerHTML = aHtml.join('');
        
    var oLink = document.createElement("a");
    oLink.className = "zoomAnchor";
    oLink.innerHTML = "<img alt='+' src='GeoStart/images/controls/grey/small_plus.gif'/> Zoom in naar de zone";
    var href = document.createAttribute('href');
    href.nodeValue = "#";
    oLink.setAttributeNode(href);
    
    var oLinkDiv = document.createElement("div");
    oLinkDiv.className = "ballonButton";
    oLinkDiv.appendChild(oLink);
    oLinkDiv.style.paddingTop = "20px";
    
    var self = this;
    GEvent.addDomListener(oLink, 'click', function(){
        self.zoomToZone();
        self.map_.closeInfoWindow();
    });
    oElement.appendChild(oLinkDiv);
    return oElement;
};
/**
*   What to do when zone label is clicked.
**/
ZoneLabel.prototype.clickHandler = function(){
    if ( this.balloonEnabled ) {
        this.map_.openInfoWindowHtml(this._point, this.getBalloonHtml());
    } else {
        this.zoomToZone();
    }
};


/**
*   Zoom to the zone
**/
ZoneLabel.prototype.zoomToZone = function(){
    this.map_.setCenter(this._point, this.map_.getBoundsZoomLevel(this._bounds));
};
/**
*   Hide the main DIV on the map pane
**/
ZoneLabel.prototype.hide = function() {
  this.div_.style.display = "none";
};

/**
*   Show the main DIV on the map pane
**/
ZoneLabel.prototype.show = function() {
  this.div_.style.display = "block";
};

/**
* Remove the main DIV from the map pane
**/
ZoneLabel.prototype.remove = function() {
  this.div_.parentNode.removeChild(this.div_);
};

/**
*   Copy our data to a new Rectangle
**/
ZoneLabel.prototype.copy = function() {
  return new ZoneLabel(this._point, this._sText);
};

// Redraw the rectangle based on the current projection and zoom level
ZoneLabel.prototype.redraw = function(force) {
  // We only need to redraw if the coordinate system has changed
  if (!force) return;
  
  // Calculate the DIV coordinates of two opposite corners of our bounds to
  // get the size and position of our rectangle
  var coords = this.map_.fromLatLngToDivPixel(this._point);
  
  this.div_.style.left = ( coords.x - 25 ) + "px";
  this.div_.style.top = ( coords.y - 10 ) + "px";
  
};
if (!window.XMLHttpRequest) 
{ 
    window.XMLHttpRequest = function() 
    { 
        var types = [ 
            'Microsoft.XMLHTTP', 
            'MSXML2.XMLHTTP.5.0', 
            'MSXML2.XMLHTTP.4.0', 
            'MSXML2.XMLHTTP.3.0', 
            'MSXML2.XMLHTTP' 
        ]; 

        for (var i = 0; i < types.length; i++) 
        { 
            try 
            { 
                return new ActiveXObject(types[i]); 
            } 
            catch(e) {} 
        } 

        return undefined; 
    } 
}


function cRequest(){
	
	this.sArgs	= '';
	this.sUrl	= '';
	this.sType	= 'GET';
	var xmlhttp	= new XMLHttpRequest(); 
	
	
	this.addArgument = function (name, value){
		
		this.sArgs += escape(name) + '=' + escape(value) + '&';
	};
	this.clearArguments = function(){
		this.sArgs = '';
	};
	this.getContent = function(){
				
		if (this.sType.toUpperCase() == 'POST'){
			xmlhttp.open('POST', this.sUrl, false);
			xmlhttp.setRequestHeader('Content-type',	'application/x-www-form-urlencoded');	
			xmlhttp.setRequestHeader('Content-length',	this.sArgs.length);	
			xmlhttp.setRequestHeader('Connection',		'close');	
			xmlhttp.send(this.sArgs);
		} else {					
			var seperator = '?';
			if (this.sUrl.indexOf('?') > 0){
				seperator = '&';
			}
			xmlhttp.open('GET', this.sUrl + seperator + this.sArgs, false);
			xmlhttp.send(null);			
		}
		this.clearArguments();
		return xmlhttp;
	};
	
	
	this.sendForm = function(oForm){

		this.sUrl 	= oForm.action;
		this.sType	= oForm.method;

		var aInputs  = oForm.getElementsByTagName('input');	
		var i = aInputs.length;
		while (i--){
			if (aInputs[i].type == 'checkbox' || aInputs[i].type == 'radio'){
				if (aInputs[i].checked){
					this.addArgument(aInputs[i].name, aInputs[i].value);
				}
			} else {
				this.addArgument(aInputs[i].name, aInputs[i].value);
			}
		}
		var aSelects = oForm.getElementsByTagName('select');
		for (var i = 0; i < aSelects.length; i++){
			for (var j=0; j < aSelects[i].options.length; j++){
				if (aSelects[i].options[j].selected){
					this.addArgument(aSelects[i].name, aSelects[i].options[j].value);
				}
			}
		}
		var aTextareas  = oForm.getElementsByTagName('textarea');	
		var i = aTextareas.length;
		while (i--){
			this.addArgument(aTextareas[i].name, aTextareas[i].value);
		}		
		return this.getContent();		
	};
}
/*

DragResize v1.0
(c) 2005-2006 Angus Turnbull, TwinHelix Designs http://www.twinhelix.com

Licensed under the CC-GNU LGPL, version 2.1 or later:
http://creativecommons.org/licenses/LGPL/2.1/
This is distributed WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

*/


if(typeof addEvent!='function'){var addEvent=function(o,t,f,l){var d='addEventListener',n='on'+t,rO=o,rT=t,rF=f,rL=l;if(o[d]&&!l)return o[d](t,f,false);if(!o._evts)o._evts={};if(!o._evts[t]){o._evts[t]=o[n]?{b:o[n]}:{};o[n]=new Function('e','var r=true,o=this,a=o._evts["'+t+'"],i;for(i in a){o._f=a[i];r=o._f(e||window.event)!=false&&r;o._f=null}return r');if(t!='unload')addEvent(window,'unload',function(){removeEvent(rO,rT,rF,rL)})}if(!f._i)f._i=addEvent._i++;o._evts[t][f._i]=f};addEvent._i=1;var removeEvent=function(o,t,f,l){var d='removeEventListener';if(o[d]&&!l)return o[d](t,f,false);if(o._evts&&o._evts[t]&&f._i)delete o._evts[t][f._i]}}function cancelEvent(e,c){e.returnValue=false;if(e.preventDefault)e.preventDefault();if(c){e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation()}};function DragResize(myName,config){var props={myName:myName,enabled:true,handles:['tl','tm','tr','ml','mr','bl','bm','br'],isElement:null,isHandle:null,element:null,handle:null,minWidth:10,minHeight:10,minLeft:0,maxLeft:9999,minTop:0,maxTop:9999,zIndex:1,mouseX:0,mouseY:0,lastMouseX:0,lastMouseY:0,mOffX:0,mOffY:0,elmX:0,elmY:0,elmW:0,elmH:0,allowBlur:true,ondragfocus:null,ondragstart:null,ondragmove:null,ondragend:null,ondragblur:null};for(var p in props)this[p]=(typeof config[p]=='undefined')?props[p]:config[p]};DragResize.prototype.apply=function(node){var obj=this;addEvent(node,'mousedown',function(e){obj.mouseDown(e)});addEvent(node,'mousemove',function(e){obj.mouseMove(e)});addEvent(node,'mouseup',function(e){obj.mouseUp(e)})};DragResize.prototype.select=function(newElement){with(this){if(!oGeoStart.util.getElementById||!enabled)return;if(newElement&&(newElement!=element)&&enabled){element=newElement;element.style.zIndex=++zIndex;if(this.resizeHandleSet)this.resizeHandleSet(element,true);elmX=parseInt(element.style.left);elmY=parseInt(element.style.top);elmW=element.offsetWidth;elmH=element.offsetHeight;if(ondragfocus)this.ondragfocus()}}};DragResize.prototype.deselect=function(delHandles){with(this){if(!oGeoStart.util.getElementById||!enabled)return;if(delHandles){if(ondragblur)this.ondragblur();if(this.resizeHandleSet)this.resizeHandleSet(element,false);element=null}handle=null;mOffX=0;mOffY=0}};DragResize.prototype.mouseDown=function(e){with(this){if(!oGeoStart.util.getElementById||!enabled)return true;var elm=e.target||e.srcElement,newElement=null,newHandle=null,hRE=new RegExp(myName+'-([trmbl]{2})','');while(elm){if(elm.className){if(!newHandle&&(hRE.test(elm.className)||isHandle(elm)))newHandle=elm;if(isElement(elm)){newElement=elm;break}}elm=elm.parentNode}if(element&&(element!=newElement)&&allowBlur)deselect(true);if(newElement&&(!element||(newElement==element))){if(newHandle)cancelEvent(e);select(newElement,newHandle);handle=newHandle;if(handle&&ondragstart)this.ondragstart(hRE.test(handle.className))}}};DragResize.prototype.mouseMove=function(e){with(this){if(!oGeoStart.util.getElementById||!enabled)return true;mouseX=e.pageX||e.clientX+document.documentElement.scrollLeft;mouseY=e.pageY||e.clientY+document.documentElement.scrollTop;var diffX=mouseX-lastMouseX+mOffX;var diffY=mouseY-lastMouseY+mOffY;mOffX=mOffY=0;lastMouseX=mouseX;lastMouseY=mouseY;if(!handle)return true;var isResize=false;if(this.resizeHandleDrag&&this.resizeHandleDrag(diffX,diffY)){isResize=true}else{var dX=diffX,dY=diffY;if(elmX+dX<minLeft)mOffX=(dX-(diffX=minLeft-elmX));else if(elmX+elmW+dX>maxLeft)mOffX=(dX-(diffX=maxLeft-elmX-elmW));if(elmY+dY<minTop)mOffY=(dY-(diffY=minTop-elmY));else if(elmY+elmH+dY>maxTop)mOffY=(dY-(diffY=maxTop-elmY-elmH));elmX+=diffX;elmY+=diffY}with(element.style){left=elmX+'px';width=elmW+'px';top=elmY+'px';height=elmH+'px'}if(window.opera&&document.documentElement){var oDF=oGeoStart.util.getElementById('op-drag-fix');if(!oDF){var oDF=document.createElement('input');oDF.id='op-drag-fix';oDF.style.display='none';document.body.appendChild(oDF)}oDF.focus()}if(ondragmove)this.ondragmove(isResize);cancelEvent(e)}};DragResize.prototype.mouseUp=function(e){with(this){if(!oGeoStart.util.getElementById||!enabled)return;var hRE=new RegExp(myName+'-([trmbl]{2})','');if(handle&&ondragend)this.ondragend(hRE.test(handle.className));deselect(false)}};DragResize.prototype.resizeHandleSet=function(elm,show){with(this){if(!elm._handle_tr){for(var h=0;h<handles.length;h++){var hDiv=document.createElement('div');hDiv.className=myName+' '+myName+'-'+handles[h];elm['_handle_'+handles[h]]=elm.appendChild(hDiv)}}for(var h=0;h<handles.length;h++){elm['_handle_'+handles[h]].style.visibility=show?'inherit':'hidden'}}};DragResize.prototype.resizeHandleDrag=function(diffX,diffY){with(this){var hClass=handle&&handle.className&&handle.className.match(new RegExp(myName+'-([tmblr]{2})'))?RegExp.$1:'';var dY=diffY,dX=diffX,processed=false;if(hClass.indexOf('t')>=0){rs=1;if(elmH-dY<minHeight)mOffY=(dY-(diffY=elmH-minHeight));else if(elmY+dY<minTop)mOffY=(dY-(diffY=minTop-elmY));elmY+=diffY;elmH-=diffY;processed=true}if(hClass.indexOf('b')>=0){rs=1;if(elmH+dY<minHeight)mOffY=(dY-(diffY=minHeight-elmH));else if(elmY+elmH+dY>maxTop)mOffY=(dY-(diffY=maxTop-elmY-elmH));elmH+=diffY;processed=true}if(hClass.indexOf('l')>=0){rs=1;if(elmW-dX<minWidth)mOffX=(dX-(diffX=elmW-minWidth));else if(elmX+dX<minLeft)mOffX=(dX-(diffX=minLeft-elmX));elmX+=diffX;elmW-=diffX;processed=true}if(hClass.indexOf('r')>=0){rs=1;if(elmW+dX<minWidth)mOffX=(dX-(diffX=minWidth-elmW));else if(elmX+elmW+dX>maxLeft)mOffX=(dX-(diffX=maxLeft-elmX-elmW));elmW+=diffX;processed=true}return processed}};function vergunningenkaart(){
    this.width = 475;
    this.height = 400;
    
    this.display = function(sPlaatsnaam){
    
        var p = escape(document.location.href);
        var rfr = escape(document.referrer);
        if (rfr == "undefined"){ 
            rfr = "";
        }
        var sHTML    = '<iframe style="float:none;margin:2px;" frameborder="0" ';
        sHTML       += 'src="http://www.vergunningenkaart.nl/MapMaker/' + sPlaatsnaam +'&location=' + p + '&rfr=' + rfr + '" ';
        sHTML       += 'width="' + this.width + 'px" height="' + this.height + 'px"></iframe>';
        document.writeln(sHTML);
        
    }
}
vergunningenkaart = new vergunningenkaart();/*
* ExtInfoWindow Class, v1.0 
*  Copyright (c) 2007, Joe Monahan (http://www.seejoecode.com)
* 
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
*       http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This class lets you add an info window to the map which mimics GInfoWindow
* and allows for users to skin it via CSS.  Additionally it has options to
* pull in HTML content from an ajax request, triggered when a user clicks on
* the associated marker.
*/


/**
 * Creates a new ExtInfoWindow that will initialize by reading styles from css
 *
 * @constructor
 * @param {GMarker} marker The marker associated with the info window
 * @param {String} windowId The DOM Id we will use to reference the info window
 * @param {String} html The HTML contents
 * @param {Object} opt_opts A contianer for optional arguments:
 *    {String} ajaxUrl The Url to hit on the server to request some contents 
 *    {Number} paddingX The padding size in pixels that the info window will leave on 
 *                    the left and right sides of the map when panning is involved.
 *    {Number} paddingY The padding size in pixels that the info window will leave on 
 *                    the top and bottom sides of the map when panning is involved.
 *    {Number} beakOffset The repositioning offset for when aligning the beak element. 
 *                    This is used to make sure the beak lines up correcting if the 
 *                    info window styling containers a border.
 */
function ExtInfoWindow(marker, windowId, html, opt_opts) {
  this.html_ = html;
  this.marker_ = marker;
  this.infoWindowId_ = windowId;

  this.options_ = opt_opts == null ? {} : opt_opts;
  this.ajaxUrl_ = this.options_.ajaxUrl == null ? null : this.options_.ajaxUrl;
  this.callback_ = this.options_.ajaxCallback == null ? null : this.options_.ajaxCallback;
  
  this.maxContent_ = this.options_.maxContent == null ? null : this.options_.maxContent;
  this.maximizeEnabled_ = this.maxContent_ == null ? false : true;
  this.isMaximized_ = false;

  this.borderSize_ = this.options_.beakOffset == null ? 0 : this.options_.beakOffset;
  this.paddingX_ = this.options_.paddingX == null ? 0 + this.borderSize_ : this.options_.paddingX + this.borderSize_;
  this.paddingY_ = this.options_.paddingY == null ? 0 + this.borderSize_ : this.options_.paddingY + this.borderSize_;

  this.map_ = null;

  this.container_ = document.createElement('div');
  this.container_.style.position = 'relative';
  this.container_.style.display = 'none';

  this.contentDiv_ = document.createElement('div');
  this.contentDiv_.id = this.infoWindowId_ + '_contents';
  this.contentDiv_.innerHTML = this.html_;
  this.contentDiv_.style.display = 'block';
  this.contentDiv_.style.visibility = 'hidden';

  this.wrapperDiv_ = document.createElement('div');
};

//use the GOverlay class
ExtInfoWindow.prototype = new GOverlay();

/**
 * Called by GMap2's addOverlay method.  Creates the wrapping div for our info window and adds
 * it to the relevant map pane.  Also binds mousedown event to a private function so that they
 * are not passed to the underlying map.  Finally, performs ajax request if set up to use ajax
 * in the constructor.
 * @param {GMap2} map The map that has had this extInfoWindow is added to it.
 */
ExtInfoWindow.prototype.initialize = function(map) {
  this.map_ = map;

  if( this.maximizeEnabled_ ){
    this.maxWidth_ = this.map_.getSize().width * 0.9;
    this.maxHeight_ = this.map_.getSize().height * 0.9;
  }

  this.defaultStyles = {
    containerWidth: this.map_.getSize().width / 2,
    borderSize: 1
  };

  this.wrapperParts = {
    tl:{t:0, l:0, w:0, h:0, domElement: null},
    t:{t:0, l:0, w:0, h:0, domElement: null},
    tr:{t:0, l:0, w:0, h:0, domElement: null},
    l:{t:0, l:0, w:0, h:0, domElement: null},
    r:{t:0, l:0, w:0, h:0, domElement: null},
    bl:{t:0, l:0, w:0, h:0, domElement: null},
    b:{t:0, l:0, w:0, h:0, domElement: null},
    br:{t:0, l:0, w:0, h:0, domElement: null},
    beak:{t:0, l:0, w:0, h:0, domElement: null},
    close:{t:0, l:0, w:0, h:0, domElement: null}
  };
  if( this.maximizeEnabled_ ){
    this.wrapperParts.max = {t:0, l:0, w:0, h:0, domElement: null}
    this.wrapperParts.min = {t:0, l:0, w:0, h:0, domElement: null}
  }

  for (var i in this.wrapperParts ) {
    var tempElement = document.createElement('div');
    tempElement.id = this.infoWindowId_ + '_' + i;
    tempElement.style.visibility = 'hidden';
    document.body.appendChild(tempElement);
    tempElement = oGeoStart.util.getElementById(this.infoWindowId_ + '_' + i);
    var tempWrapperPart = this.wrapperParts[i];    
    tempWrapperPart.w = parseInt(this.getStyle_(tempElement, 'width'), 10);
    tempWrapperPart.h = parseInt(this.getStyle_(tempElement, 'height'), 10);
    
    //Added a try/catch. Remove child cause an error when using mapBlowups with route directions...
    try{
        document.body.removeChild(tempElement);
    }
    catch(e){}
  }
  for (var i in this.wrapperParts) {
    if (i == 'close' ) {
      //first append the content so the close button is layered above it
      this.wrapperDiv_.appendChild(this.contentDiv_);
    }
    var wrapperPartsDiv = null;
    if (this.wrapperParts[i].domElement == null) {
      wrapperPartsDiv = document.createElement('div');
      this.wrapperDiv_.appendChild(wrapperPartsDiv);
    } else {
      wrapperPartsDiv = this.wrapperParts[i].domElement;
    }
    wrapperPartsDiv.id = this.infoWindowId_ + '_' + i;
    wrapperPartsDiv.style.position = 'absolute';
    wrapperPartsDiv.style.width = this.wrapperParts[i].w + 'px';
    wrapperPartsDiv.style.height = this.wrapperParts[i].h + 'px';
    wrapperPartsDiv.style.top = this.wrapperParts[i].t + 'px';
    wrapperPartsDiv.style.left = this.wrapperParts[i].l + 'px';
    this.wrapperParts[i].domElement = wrapperPartsDiv;
  }
  
  this.map_.getPane(G_MAP_FLOAT_PANE).appendChild(this.container_);
  this.container_.id = this.infoWindowId_;
  var containerWidth  = this.getStyle_(oGeoStart.util.getElementById(this.infoWindowId_), 'width');
  this.container_.style.width = (containerWidth == null ? this.defaultStyles.containerWidth : containerWidth);

  this.map_.getContainer().appendChild(this.contentDiv_);
  this.contentWidth = this.getDimensions_(this.container_).width;
  this.contentDiv_.style.width = this.contentWidth + 'px';
  this.contentDiv_.style.position = 'absolute';

  this.container_.appendChild(this.wrapperDiv_);
  
  if( this.maximizeEnabled_ ){
    this.minWidth_ = this.getDimensions_(this.container_).width;
    //console.log(this.minWidth_);
  }
  
  if (this.maximizeEnabled_) {
    thisMap = this.map_;
    thisMaxWidth = this.maxWidth_;
    thisMaxHeight = this.maxHeight_;
    thisContainer = this.container_;
    thisMaxContent = this.maxContent_;
    if(this.marker_) {
      GEvent.trigger(this.marker_, 'extinfowindowbeforeclose'); 
    }

    thisMinWidth = this.container_.style.width;
    thisMinHeight = this.container_.style.height;
    //add event handler for maximize and minimize icons
    GEvent.addDomListener(this.wrapperParts.max.domElement, 'click', 
      function() {
        var infoWindow = thisMap.getExtInfoWindow();
        infoWindow.container_.style.width = thisMaxWidth + 'px';
        infoWindow.ajaxRequest_(thisMaxContent);

    if(this.marker_) {
      GEvent.trigger(this.marker_, 'extinfowindowclose');
    }
        infoWindow.isMaximized_ = true;
        infoWindow.redraw(true);
      
        //swap min/max icons
        infoWindow.toggleMaxMin_();
      }
    );
    GEvent.addDomListener(this.wrapperParts.min.domElement, 'click', 
      function() {
        var infoWindow = thisMap.getExtInfoWindow();
        infoWindow.container_.style.width = thisMinWidth;
        infoWindow.container_.style.height = thisMinHeight;
        if (infoWindow.ajaxUrl_ != null ) {
           infoWindow.ajaxRequest_(this.ajaxUrl_);
        }else{
          infoWindow.contentDiv_.innerHTML = infoWindow.html_;
        }
        
        infoWindow.isMaximized_ = false;
        infoWindow.redraw(true);
        infoWindow.resize();

        //swap min/max icons
        infoWindow.toggleMaxMin_();
      }
    );
    
    this.toggleMaxMin_();
    
  }

  var stealEvents = ['mousedown', 'dblclick', 'DOMMouseScroll'];
  for( i=0; i < stealEvents.length; i++ ){
    GEvent.bindDom(this.container_, stealEvents[i], this, this.onClick_);
  }

  GEvent.trigger(this.map_, 'extinfowindowopen');
  if (this.ajaxUrl_ != null ) {
    this.ajaxRequest_(this.ajaxUrl_);
  }
};

/**
 * Private function to steal mouse click events to prevent it from returning to the map.
 * Without this links in the ExtInfoWindow would not work, and you could click to zoom or drag 
 * the map behind it.
 * @private
 * @param {MouseEvent} e The mouse event caught by this function
 */
ExtInfoWindow.prototype.onClick_ = function(e) {
  if(navigator.userAgent.toLowerCase().indexOf('msie') != -1 && document.all) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  } else {
    //e.preventDefault();
    e.stopPropagation();
  }
};

/**
 * Remove the extInfoWindow container from the map pane. 
 */
ExtInfoWindow.prototype.remove = function() {
  if (this.map_.getExtInfoWindow() != null) {
    GEvent.trigger(this.map_, 'extinfowindowbeforeclose');
    
    GEvent.clearInstanceListeners(this.container_);
    if (this.container_.outerHTML) {
      this.container_.outerHTML = ''; //prevent pseudo-leak in IE
    }
    if (this.container_.parentNode) {
      this.container_.parentNode.removeChild(this.container_);
    }
    this.container_ = null;
    GEvent.trigger(this.map_, 'extinfowindowclose');
    this.map_.setExtInfoWindow_(null);
  }
};

/**
 * Return a copy of this overlay, for the parent Map to duplicate itself in full. This
 * is part of the Overlay interface and is used, for example, to copy everything in the 
 * main view into the mini-map.
 * @return {GOverlay}
 */
ExtInfoWindow.prototype.copy = function() {
  return new ExtInfoWindow(this.marker_, this.infoWindowId_, this.html_, this.options_);
};

/**
 * Draw extInfoWindow and wrapping decorators onto the map.  Resize and reposition
 * the map as necessary. 
 * @param {Boolean} force Will be true when pixel coordinates need to be recomputed.
 */
ExtInfoWindow.prototype.redraw = function(force) {
  if (!force || this.container_ == null) return;
  
  //set the content section's height, needed so  browser font resizing does not affect the window's dimensions
  var contentHeight = this.contentDiv_.offsetHeight;
  this.contentDiv_.style.height = contentHeight + 'px';
  
  this.contentWidth = this.getDimensions_(this.container_).width;
  this.contentDiv_.style.width = this.container_.style.width;

  //reposition contents depending on wrapper parts.
  //this is necessary for content that is pulled in via ajax
  this.contentDiv_.style.left = this.wrapperParts.l.w + 'px';
  this.contentDiv_.style.top = this.wrapperParts.tl.h + 'px';
  this.contentDiv_.style.visibility = 'visible';

  //Finish configuring wrapper parts that were not set in initialization
  this.wrapperParts.tl.t = 0;
  this.wrapperParts.tl.l = 0;
  this.wrapperParts.t.l = this.wrapperParts.tl.w;
  this.wrapperParts.t.w = (this.wrapperParts.l.w + this.contentWidth + this.wrapperParts.r.w) - this.wrapperParts.tl.w - this.wrapperParts.tr.w;
  this.wrapperParts.t.h = this.wrapperParts.tl.h;
  this.wrapperParts.tr.l = this.wrapperParts.t.w + this.wrapperParts.tl.w;
  this.wrapperParts.l.t = this.wrapperParts.tl.h;
  this.wrapperParts.l.h = contentHeight;
  this.wrapperParts.r.l = this.contentWidth + this.wrapperParts.l.w;
  this.wrapperParts.r.t = this.wrapperParts.tr.h;
  this.wrapperParts.r.h = contentHeight;
  this.wrapperParts.bl.t = contentHeight + this.wrapperParts.tl.h;
  this.wrapperParts.b.l = this.wrapperParts.bl.w;
  this.wrapperParts.b.t = contentHeight + this.wrapperParts.tl.h;
  this.wrapperParts.b.w = (this.wrapperParts.l.w + this.contentWidth + this.wrapperParts.r.w) - this.wrapperParts.bl.w - this.wrapperParts.br.w;
  this.wrapperParts.b.h = this.wrapperParts.bl.h;
  this.wrapperParts.br.l = this.wrapperParts.b.w + this.wrapperParts.bl.w;
  this.wrapperParts.br.t = contentHeight + this.wrapperParts.tr.h;
  this.wrapperParts.beak.l = this.borderSize_ + (this.contentWidth / 2) - (this.wrapperParts.beak.w / 2);
  this.wrapperParts.beak.t = this.wrapperParts.bl.t + this.wrapperParts.bl.h - this.borderSize_;
  this.wrapperParts.close.l = this.wrapperParts.tr.l +this.wrapperParts.tr.w - this.wrapperParts.close.w - this.borderSize_;
  this.wrapperParts.close.t = this.borderSize_;
  if( this.maximizeEnabled_ ){
    this.wrapperParts.max.l = this.wrapperParts.close.l - this.wrapperParts.max.w - 5;
    this.wrapperParts.max.t = this.wrapperParts.close.t;
    this.wrapperParts.min.l = this.wrapperParts.max.l;
    this.wrapperParts.min.t = this.wrapperParts.max.t;
  }

  //create the decoration wrapper DOM objects
  //append the styled info window to the container
  for (var i in this.wrapperParts) {
    if (i == 'close' ) {
      //first append the content so the close button is layered above it
      this.wrapperDiv_.insertBefore(this.contentDiv_, this.wrapperParts[i].domElement);
    }
    var wrapperPartsDiv = null;
    if (this.wrapperParts[i].domElement == null) {
      wrapperPartsDiv = document.createElement('div');
      this.wrapperDiv_.appendChild(wrapperPartsDiv);
    } else {
      wrapperPartsDiv = this.wrapperParts[i].domElement;
    }
    wrapperPartsDiv.id = this.infoWindowId_ + '_' + i;
    wrapperPartsDiv.style.position='absolute';
    wrapperPartsDiv.style.width = this.wrapperParts[i].w + 'px';
    wrapperPartsDiv.style.height = this.wrapperParts[i].h + 'px';
    wrapperPartsDiv.style.top = this.wrapperParts[i].t + 'px';
    wrapperPartsDiv.style.left = this.wrapperParts[i].l + 'px';
    this.wrapperParts[i].domElement = wrapperPartsDiv;
  }

  //add event handler for the close icon
  var currentMarker = this.marker_;
  var thisMap = this.map_;
  GEvent.addDomListener(this.wrapperParts.close.domElement, 'click', 
    function() {
      thisMap.closeExtInfoWindow();
    }
  );
  
  
  
  //position the container on the map, over the marker
  var pixelLocation = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
  this.container_.style.position = 'absolute';
  var markerIcon = this.marker_.getIcon();
  this.container_.style.left = (pixelLocation.x 
    - (this.contentWidth / 2) 
    - markerIcon.iconAnchor.x 
    + markerIcon.infoWindowAnchor.x
  ) + 'px';

  this.container_.style.top = (pixelLocation.y
    - this.wrapperParts.bl.h
    - contentHeight
    - this.wrapperParts.tl.h
    - this.wrapperParts.beak.h
    - markerIcon.iconAnchor.y
    + markerIcon.infoWindowAnchor.y
    + this.borderSize_
  ) + 'px';

  this.container_.style.display = 'block';

  if(this.map_.getExtInfoWindow() != null) {
    this.repositionMap_();
  }
};

ExtInfoWindow.prototype.toggleMaxMin_ = function(){
  if( this.wrapperParts.max.domElement != null && this.wrapperParts.min.domElement != null ){
    if (this.isMaximized_) {
      this.wrapperParts.max.domElement.style.display = 'none';
      this.wrapperParts.min.domElement.style.display = 'block';
    }else{
      this.wrapperParts.max.domElement.style.display = 'block';
      this.wrapperParts.min.domElement.style.display = 'none';
    }
  }
}

/**
 * Determine the dimensions of the contents to recalculate and reposition the 
 * wrapping decorator elements accordingly.
 */
ExtInfoWindow.prototype.resize = function(){ 
  //Create temporary DOM node for new contents to get new height
  //This is done because if you manipulate this.contentDiv_ directly it causes visual errors in IE6
  var tempElement = this.contentDiv_.cloneNode(true);
  tempElement.id = this.infoWindowId_ + '_tempContents';
  tempElement.style.visibility = 'hidden';    
  tempElement.style.height = 'auto';
  document.body.appendChild(tempElement);
  tempElement = oGeoStart.util.getElementById(this.infoWindowId_ + '_tempContents');
  var contentHeight = tempElement.offsetHeight;
  document.body.removeChild(tempElement);

  //Set the new height to eliminate visual defects that can be caused by font resizing in browser
  this.contentDiv_.style.height = contentHeight + 'px';

  var contentWidth = this.container_.offsetWidth;
  var pixelLocation = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());

  var oldWindowHeight = this.wrapperParts.t.domElement.offsetHeight + this.wrapperParts.l.domElement.offsetHeight + this.wrapperParts.b.domElement.offsetHeight;    
  var oldWindowPosTop = this.wrapperParts.t.domElement.offsetTop;

  //resize info window to look correct for new height
  this.wrapperParts.l.domElement.style.height = contentHeight + 'px';
  this.wrapperParts.r.domElement.style.height = contentHeight + 'px';
  var newPosTop = this.wrapperParts.b.domElement.offsetTop - contentHeight;
  this.wrapperParts.l.domElement.style.top = newPosTop + 'px';
  this.wrapperParts.r.domElement.style.top = newPosTop + 'px';
  this.contentDiv_.style.top = newPosTop + 'px';
  windowTHeight = parseInt(this.wrapperParts.t.domElement.style.height, 10);
  newPosTop -= windowTHeight;
  this.wrapperParts.close.domElement.style.top = newPosTop + this.borderSize_ + 'px';
  this.wrapperParts.tl.domElement.style.top = newPosTop + 'px';
  this.wrapperParts.t.domElement.style.top = newPosTop + 'px';
  this.wrapperParts.tr.domElement.style.top = newPosTop + 'px';

  this.repositionMap_();
};

/**
 * Check to see if the displayed extInfoWindow is positioned off the viewable 
 * map region and by how much.  Use that information to pan the map so that 
 * the extInfoWindow is completely displayed.
 * @private
 */
ExtInfoWindow.prototype.repositionMap_ = function(){
  //pan if necessary so it shows on the screen
  var mapNE = this.map_.fromLatLngToDivPixel(
    this.map_.getBounds().getNorthEast()
  );
  var mapSW = this.map_.fromLatLngToDivPixel(
    this.map_.getBounds().getSouthWest()
  );
  var markerPosition = this.map_.fromLatLngToDivPixel(
    this.marker_.getPoint()
  );

  var panX = 0;
  var panY = 0;
  var paddingX = this.paddingX_;
  var paddingY = this.paddingY_;
  var infoWindowAnchor = this.marker_.getIcon().infoWindowAnchor;
  var iconAnchor = this.marker_.getIcon().iconAnchor;

  //test top of screen    
  var windowT = this.wrapperParts.t.domElement;
  var windowL = this.wrapperParts.l.domElement;
  var windowB = this.wrapperParts.b.domElement;
  var windowR = this.wrapperParts.r.domElement;
  var windowBeak = this.wrapperParts.beak.domElement;

  var offsetTop = markerPosition.y - ( -infoWindowAnchor.y + iconAnchor.y +  this.getDimensions_(windowBeak).height + this.getDimensions_(windowB).height + this.getDimensions_(windowL).height + this.getDimensions_(windowT).height + this.paddingY_);
  if (offsetTop < mapNE.y) {
    panY = mapNE.y - offsetTop;
  } else {
    //test bottom of screen
    var offsetBottom = markerPosition.y + this.paddingY_;
    if (offsetBottom >= mapSW.y) {
      panY = -(offsetBottom - mapSW.y);
    }
  }

  //test right of screen
  var offsetRight = Math.round(markerPosition.x + this.getDimensions_(this.container_).width/2 + this.getDimensions_(windowR).width + this.paddingX_ + infoWindowAnchor.x - iconAnchor.x);
  if (offsetRight > mapNE.x) {
    panX = -( offsetRight - mapNE.x);
  } else {
    //test left of screen
    var offsetLeft = - (Math.round( (this.getDimensions_(this.container_).width/2 - this.marker_.getIcon().iconSize.width/2) + this.getDimensions_(windowL).width + this.borderSize_ + this.paddingX_) - markerPosition.x - infoWindowAnchor.x + iconAnchor.x);
    if( offsetLeft < mapSW.x) {
      panX = mapSW.x - offsetLeft;
    }
  }

  if (panX != 0 || panY != 0 && this.map_.getExtInfoWindow() != null ) {
    this.map_.panBy(new GSize(panX,panY));
  }
};

/**
 * Private function that handles performing an ajax request to the server.  The response
 * information is assumed to be HTML and is placed inside this extInfoWindow's contents region.
 * Last, check to see if the height has changed, and resize the extInfoWindow accordingly.
 * @private
 * @param {String} url The Url of where to make the ajax request on the server
 */
ExtInfoWindow.prototype.ajaxRequest_ = function(url){
  var thisMap = this.map_;
  var thisCallback = this.callback_;
  GDownloadUrl(url, function(response, status){
    if (thisMap.getExtInfoWindow() !== null) {
      var infoWindow = oGeoStart.util.getElementById(thisMap.getExtInfoWindow().infoWindowId_ + '_contents');
      if (response == null || status == -1 ) {
        infoWindow.innerHTML = '<span class="error">ERROR: The Ajax request failed to get HTML content from "' + url + '"</span>';
      } else {
        infoWindow.innerHTML = response;
      }
      if (thisCallback != null ) {
        thisCallback();
      }
      thisMap.getExtInfoWindow().resize();
    }
    GEvent.trigger(thisMap, 'extinfowindowupdate');
  });
};

/**
 * Private function derived from Prototype.js to get a given element's
 * height and width
 * @private
 * @param {Object} element The DOM element that will have height and 
 *                    width will be calculated for it.
 * @return {Object} Object with keys: width, height
 */
ExtInfoWindow.prototype.getDimensions_ = function(element) {
  var display = this.getStyle_(element, 'display');
  if (display != 'none' && display != null) { // Safari bug
    return {width: element.offsetWidth, height: element.offsetHeight};
  }

  // All *Width and *Height properties give 0 on elements with display none,
  // so enable the element temporarily
  var els = element.style;
  var originalVisibility = els.visibility;
  var originalPosition = els.position;
  var originalDisplay = els.display;
  els.visibility = 'hidden';
  els.position = 'absolute';
  els.display = 'block';
  var originalWidth = element.clientWidth;
  var originalHeight = element.clientHeight;
  els.display = originalDisplay;
  els.position = originalPosition;
  els.visibility = originalVisibility;
  return {width: originalWidth, height: originalHeight};
};

/**
 * Private function derived from Prototype.js to get a given element's
 * value that is associated with the passed style
 * @private
 * @param {Object} element The DOM element that will be checked.
 * @param {String} style The style name that will be have it's value returned.
 * @return {Object}
 */
ExtInfoWindow.prototype.getStyle_ = function(element, style) {
  var found = false;
  style = this.camelize_(style);
  if (element.id == this.infoWindowId_ && style == 'width' && element.style.display == 'none') {
      element.style.visibility = 'hidden';
      element.style.display = '';
  }
  var value = element.style[style];
  if (!value) {
    if (document.defaultView && document.defaultView.getComputedStyle) {
      var css = document.defaultView.getComputedStyle(element, null);
      value = css ? css[style] : null;
    } else if (element.currentStyle) {
      value = element.currentStyle[style];
    }
  }
  if((value == 'auto') && (style == 'width' || style == 'height') && (this.getStyle_(element, 'display') != 'none')) {
    if( style == 'width' ) {
      value = element.offsetWidth;
    }else {
      value = element.offsetHeight;
    }
  }
  if (element.id == this.infoWindowId_ && style == 'width' && element.style.display != 'none') {
      element.style.display = 'none';
      element.style.visibility = 'visible';    
  }
  return (value == 'auto') ? null : value;
};

/**
 * Private function pulled from Prototype.js that will change a hyphened
 * style name into camel case.
 * @private
 * @param {String} element The string that will be parsed and made into camel case
 * @return {String}
 */
ExtInfoWindow.prototype.camelize_ = function(element) {
  var parts = element.split('-'), len = parts.length;
  if (len == 1) return parts[0];
  var camelized = element.charAt(0) == '-'
    ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
    : parts[0];

  for (var i = 1; i < len; i++) {
    camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
  }
  return camelized;
};

GMap.prototype.ExtInfoWindowInstance_ = null;
GMap.prototype.ClickListener_ = null;
GMap.prototype.InfoWindowListener_ = null;

/**
 * Creates a new instance of ExtInfoWindow for the GMarker.  Register the newly created 
 * instance with the map, ensuring only one window is open at a time. If this is the first
 * ExtInfoWindow ever opened, add event listeners to the map to close the ExtInfoWindow on 
 * zoom and click, to mimic the default GInfoWindow behavior.
 *
 * @param {GMap} map The GMap2 object where the ExtInfoWindow will open
 * @param {String} cssId The id we will use to reference the info window
 * @param {String} html The HTML contents
 * @param {Object} opt_opts A contianer for optional arguments:
 *    {String} ajaxUrl The Url to hit on the server to request some contents 
 *    {Number} paddingX The padding size in pixels that the info window will leave on 
 *                    the left and right sides of the map when panning is involved.
 *    {Number} paddingX The padding size in pixels that the info window will leave on 
 *                    the top and bottom sides of the map when panning is involved.
 *    {Number} beakOffset The repositioning offset for when aligning the beak element. 
 *                    This is used to make sure the beak lines up correcting if the 
 *                    info window styling containers a border.
 */
GMarker.prototype.openExtInfoWindow = function(map, cssId, html, opt_opts) {
  if (map == null) {
    throw 'Error in GMarker.openExtInfoWindow: map cannot be null';
    return false;
  }
  if (cssId == null || cssId == '') {
    throw 'Error in GMarker.openExtInfoWindow: must specify a cssId';
    return false;
  }
  
  map.closeInfoWindow();
  if (map.getExtInfoWindow() != null) {
    map.closeExtInfoWindow();
  }
  if (map.getExtInfoWindow() == null) {
    map.setExtInfoWindow_( new ExtInfoWindow(
      this,
      cssId,
      html,
      opt_opts
    ) );
    if (map.ClickListener_ == null) {
      //listen for map click, close ExtInfoWindow if open
      map.ClickListener_ = GEvent.addListener(map, 'click',
      function(event) {
          if( !event && map.getExtInfoWindow() != null ){
            map.closeExtInfoWindow();
          }
        }
      );
    }
    if (map.InfoWindowListener_ == null) {
      //listen for default info window open, close ExtInfoWindow if open
      map.InfoWindowListener_ = GEvent.addListener(map, 'infowindowopen', 
      function(event) {
          if (map.getExtInfoWindow() != null) {
            map.closeExtInfoWindow();
          }
        }
      );
    }
    map.addOverlay(map.getExtInfoWindow());
  }
};

/**
 * Remove the ExtInfoWindow instance
 * @param {GMap2} map The map where the GMarker and ExtInfoWindow exist
 */
GMarker.prototype.closeExtInfoWindow = function(map) {
  if( map.getExtInfoWindow() != null ){
    map.closeExtInfoWindow();
  }
};

/**
 * Get the ExtInfoWindow instance from the map
 */
GMap2.prototype.getExtInfoWindow = function(){
  return this.ExtInfoWindowInstance_;
};
/**
 * Set the ExtInfoWindow instance for the map
 * @private
 */
GMap2.prototype.setExtInfoWindow_ = function( extInfoWindow ){
  this.ExtInfoWindowInstance_ = extInfoWindow;
}
/**
 * Remove the ExtInfoWindow from the map
 */
GMap2.prototype.closeExtInfoWindow = function(){
  if( this.getExtInfoWindow() != null ){
    this.ExtInfoWindowInstance_.remove();
  }
};


function iFrameRun(sCommand){
    eval(sCommand);
}


/**********************************************************************
Deze functie kijkt of de enter knop is ingedrukt in het trefwoord veld.
**********************************************************************/

function handleKeyPress(e, sEle){
    
    if ( typeof(e.keyCode) != 'undefined' ) {
        var key=e.keyCode;
    } else {
        e.which;
    }
    if (key==13){
        //activate('tabSearch');
        oGeoStart.html.showSearch();
        oGeoStart.html.showSearch(oGeoStart.util.getElementById(sEle).value);
    }
};


/**
*   @desc Make pages function. Dynamicly generated pages and callbackfunction
*   @note Currently hard coded limit to 20 pages
*
*   @param int iCurrent Current page number
*   @param int iTotal Total count of pages
*   @param string sCallPageFucntion string function to initiate change of page. Add __PAGENR__ to place the vairable page number
*   @param string sTop Element name of pagecounter container
*   @param string sBottom Element name of pagecounter container 2
**/
function makePages(iCurrent, iTotal, sCallPageFunction, sTop, sBottom){
    var sPages = '';
    var sClass = '';
    if ( iTotal > 20 )  { iTotal = 20; }
    
    if ( iTotal > 1 ) {
    
        iPrevious = iCurrent - 1;
        if ( iPrevious == 0 ) { iPrevious = 1; }
        sPages += '<a href="#" onclick="' + sCallPageFunction.replace("__PAGENR__", ( iCurrent - 1)) + '"><</a>';
        
        for ( var i=1; i<=iTotal; i++ ) {
            if ( i == iCurrent ) { sClass = 'class="current"' } else { sClass = ''; }
            sPages += '<a href="#" ' + sClass + ' onclick="' + sCallPageFunction.replace("__PAGENR__", ( i )) + ';return false;">' + i + '</a>';
        }
        
        iNext = iCurrent + 1;
        if ( iNext > iTotal ) { iNext = iTotal; }
        sPages += '<a href="#" onclick="' + sCallPageFunction.replace("__PAGENR__", iNext ) + ';return false;">></a>';
    }
        
    oGeoStart.util.getElementById(sTop).innerHTML = sPages;
    oGeoStart.util.getElementById(sBottom).innerHTML = sPages;
};




/**********************************************************************
Stop teh click event from passing throught the dom object
**********************************************************************/
function stopClick(e){
    if (!e){
        var e = window.event;
    }
    e.cancelBubble = true;
    if (e.stopPropagation){
        e.stopPropagation();
    }
};



/**********************************************************************
You can use the checkForTag method to check whether specific tags exist.
**********************************************************************/
function checkForTag(tag){
    if(tag != undefined){
        return true;
    } else {
        return false;
    }
};

/**
*   Return oGeoStart.util.getElementById() without the typing.
**/
/*
function $(id){
    return oGeoStart.util.getElementById(id);
};
*/


/**********************************************************************
Statistieken teller. De stats zijn in webbeheer uit te lezen.
Je kan een pagina adres opgeven (handig voor ajax requests).
Als je geen pagina opgeeft wordt document.location.href gebruikt. 
**********************************************************************/
function pageHit(pagina){
    
    if(pagina != null){
        p = escape(pagina);
    } else {
        p = escape(document.location.href);
    }
        
    rfr = escape(document.referrer);
    if (rfr == "undefined"){ rfr = "";}
    sx = screen.width;
    sy = screen.height;
    sc = (navigator.appName.indexOf("Microsoft") > -1) ? screen.colorDepth : screen.pixelDepth;
    src = 'stats.php?p=' + p + '&rfr=' + rfr + '&sx=' + sx + '&sy=' + sy + '&sc=' + sc;
    //src = '<img style="position:absolute;left:-10px;top:-10px;" src="' + src + '" width="1" height="1" border="0" alt="" />';
    src = '<img src="' + src + '" width="1" height="1" border="0" alt="" />';
    
    //oGeoStart.util.getElementById('counter').innerHTML = src;
};

function cleanInput(sValue, oInput){ 
    if ( oInput.value == sValue ) {
        oInput.value='';
    }
};

        
        

/**********************************************************************
Twee functies om van een thumb plaatje een large versie in een popup te tonen
**********************************************************************/
imagename = '';
var popup = null;

function enlarge(fullimg){
    if(popup && !popup.closed){
        popup.close();
    }
    
    popup = window.open("about:blank","","width=155,height=116,status=no,toolbar=no,scrollbars=no,menubar=no,location=no,resizable=no");
    imagename = fullimg;
    
    setTimeout('updatePopup()',500)
};

function updatePopup(){
    doc = popup.document;
    doc.open('text/html');
    doc.write('<html><head><title>Uitvergroting</title><meta http-equiv="imagetoolbar" content="no" /><base href="' + sBaseUrl + '" /><link type="text/css" rel="stylesheet" href="css/popup.css" /></head><body>');
    doc.write('<a href="javascript:;" onClick="window.close()"><img name="FullImage" src="' + imagename + '" onLoad="window.resizeTo(FullImage.offsetWidth+25, FullImage.offsetHeight+80);"></a>');
    doc.write('</body></html>');
    doc.close();
};
/*
var sImageName      = '';
var oImageHolder    = '';

function enlarge(sFullImg){
    oImageHolder                     = oGeoStart.util.getElementById('location_large_img');
    oImageHolder.style.display       = "none";
    oGeoStart.util.getElementById('imgLoader').style.display     = 'block';
    sImageName                       = sFullImg; 
    
    if(oImageHolder.hasChildNodes()){
        var oLargeImage = oGeoStart.util.getElementById('largeImg');
    }
    else{
        var oLargeImage = document.createElement('img');
    }
    
    oLargeImage.id                  = 'largeImg';  
    oImageHolder.appendChild(oLargeImage);
    setTimeout('updateLargeImg()',500)
};

function updateLargeImg(){
    oGeoStart.util.getElementById('imgLoader').style.display            = 'none';
    oGeoStart.util.getElementById('largeImg').src                       = sImageName;
    oGeoStart.util.getElementById('location_large_img').style.display   = 'block';
};
*/

/**********************************************************************
Drie functie om cookies te gebruiken binnen javascript
**********************************************************************/
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
};

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
};

function eraseCookie(name) {
    createCookie(name,"",-1);
};

function cookieHandler(){
    if ( oGeoStart.util.getElementById('setcookie').checked ) {        
        createCookie('hideHelp', true, 31);        
    } else {        
        eraseCookie('hideHelp');        
    }
};


// ----------------------------------------------------------------------------
// HasClassName
//
// Description : returns boolean indicating whether the object has the class name
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//

function HasClassName(objElement, strClass)
   {

   // if there is a class
   if ( objElement.className )
      {

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // get uppercase class for comparison purposes
      var strClassUpper = strClass.toUpperCase();

      // find all instances and remove them
      for ( var i = 0; i < arrList.length; i++ )
         {

         // if class found
         if ( arrList[i].toUpperCase() == strClassUpper )
            {

            // we found it
            return true;

            }

         }

      }

   // if we got here then the class name is not there
   return false;

   }
// 
// HasClassName
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// AddClassName
//
// Description : adds a class to the class attribute of a DOM element
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//

function AddClassName(objElement, strClass, blnMayAlreadyExist)
   {

   // if there is a class
   if ( objElement.className )
      {

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // if the new class name may already exist in list
      if ( blnMayAlreadyExist )
         {

         // get uppercase class for comparison purposes
         var strClassUpper = strClass.toUpperCase();

         // find all instances and remove them
         for ( var i = 0; i < arrList.length; i++ )
            {

            // if class found
            if ( arrList[i].toUpperCase() == strClassUpper )
               {

               // remove array item
               arrList.splice(i, 1);

               // decrement loop counter as we have adjusted the array's contents
               i--;

               }

            }

         }

      // add the new class to end of list
      arrList[arrList.length] = strClass;

      // add the new class to beginning of list
      //arrList.splice(0, 0, strClass);
      
      // assign modified class name attribute
      objElement.className = arrList.join(' ');

      }
   // if there was no class
   else
      {

      // assign modified class name attribute      
      objElement.className = strClass;
   
      }

   }
// 
// AddClassName
// ----------------------------------------------------------------------------


// ----------------------------------------------------------------------------
// RemoveClassName
//
// Description : removes a class from the class attribute of a DOM element
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to remove
//

function RemoveClassName(objElement, strClass)
   {

   // if there is a class
   if ( objElement.className )
      {

      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // get uppercase class for comparison purposes
      var strClassUpper = strClass.toUpperCase();

      // find all instances and remove them
      for ( var i = 0; i < arrList.length; i++ )
         {

         // if class found
         if ( arrList[i].toUpperCase() == strClassUpper )
            {

            // remove array item
            arrList.splice(i, 1);

            // decrement loop counter as we have adjusted the array's contents
            i--;

            }

         }

      // assign modified class name attribute
      objElement.className = arrList.join(' ');

      }
   // if there was no class
   // there is nothing to remove

   }
        //<![CDATA[
        
        var oMenu;    
        var oDir;
        var oMapMaker;  
        var oGeoStart;
        
        function delayGotoHidden(iId){                       
            if ( oGeoStart.isBusy() == true || oMenu.bFirstLoad == true ) {
                setTimeout('delayGotoHidden(' + iId + ')', 100);   
            } else {
                oGeoStart.gotoHiddenId(iId);
            }
        }
        
        function initSearchBox(){
            oGeoStart.util.getElementById('mainsearch').onsubmit = function(){
                oGeoStart.html.showSearch();
                return false;                
            }
            
            oGeoStart.util.getElementById('searchInput')._defaultValue = oGeoStart.util.getElementById('searchInput').value;
            
            oGeoStart.util.getElementById('searchInput').onclick = function(){
                if(oGeoStart.util.getElementById('searchInput').value == oGeoStart.util.getElementById('searchInput')._defaultValue) {
                    oGeoStart.util.getElementById('searchInput').value='';
                }
            }
            oGeoStart.util.getElementById('searchInput').onblur = function(){
                if(oGeoStart.util.getElementById('searchInput').value == '') {
                    oGeoStart.util.getElementById('searchInput').value = oGeoStart.util.getElementById('searchInput')._defaultValue;
                }
            }
            oGeoStart.util.getElementById('go').onclick = function(){
                oGeoStart.html.showSearch();
           }
          
            
        }
        
        function onLoad() {
            
            document.body.className = 'js';
            
         /*if ( !oSettings.sMapMaker ) {
            oHelp = new cHelpScreen();
            if ( readCookie('hideHelp') != 'true' ) {
                oHelp.show();
            }
          }
          ;
          if ( !oSettings.sMapMaker && !iMarkerId && !iPortaalId && !iRubriekId) {     
            oIntroScreen = new cIntroScreen();
            oIntroScreen.init();
            oIntroScreen.show();
          }
           */ 
           
           
           
          if (GBrowserIsCompatible()) {
            oGeoStart = new cGeoStart();                    // Create new map                        
            
            
            
            oMenu = new cMenu();                                  // Load menu class
            oMenu.init( 'locaties-content', 'location_menu', 'locationCounter');   // Point to menu div.
            
            modifyButtons();
            
           
            
            g = oGeoStart;
            m = oMenu;
            
            oGeoStart.init('geoMap', oSettings.map_default_center_lat, oSettings.map_default_center_lng, oSettings.map_default_zoom);  // Initialize map js
            
            
            if ( !oSettings.sMapMaker ) {
                //var oSetControl = new control_settings(new Object(), oGeoStart.oMap, 30, 33);oGeoStart.oMap.addControl(oSetControl);
                // Load state machine
                oGeoStart.oStateMachine = new cStateMachine();
                oGeoStart.oStateMachine.init();
            }
            oGeoStart.oSearch = new cGeoSearch;
            oGeoStart.oSearch.init(oGeoStart.oMap, oGeoStart.util.getElementById('GeoCode_search'));
            initSearchBox();
            
            if(oSettings.use_clusters === true){
                oGeoStart.oClusterer = new Clusterer();
            }
            
            
            // Als er een ander profiel
            if ( oSettings.sKey == 'standaard' ) {                
                /*
                oGeoStart.oZones = new cZones(oGeoStart.oMap);
                oGeoStart.oZones._iZoomFilled = 14;          
                oGeoStart.oZones._iZoomVisible= 9;
                oGeoStart.oZones.init();
                            
                oGeoStart.oRoutes = new cRoutes('routeForm');
                oGeoStart.oRoutes.init();
                */
                
                /*oVergunningen = new cZones(oGeoStart.oMap);
                
                oVergunningen._sDataUrl = "GeoStart/ajax/getZoneData.php";
                oVergunningen.sZoneTable = 'gebieden';
                oVergunningen._iZoomFilled = 14;
                oVergunningen.init();
                
                
                oTarieven = new cZones(oGeoStart.oMap)
                oTarieven._sDataUrl = "GeoStart/ajax/getTariefData.php";
                oTarieven.bStartInvisble = true;
                oTarieven.sZoneTable = 'tarieven';
                oTarieven.enableBalloon('omschrijving');
                oTarieven._iZoomFilled = 14;
                oTarieven.init();                       
                
                var oTarievenControl = new Control_Tarieven(oGeoStart.oMap, 'Tarieven');
                oGeoStart.oMap.addControl(oTarievenControl);
                var oVergunningenControl = new Control_Vergunningen(oGeoStart.oMap, 'Vergunningen');
                oGeoStart.oMap.addControl(oVergunningenControl);*/
                
                
            }
            
            if ( oSettings._sMapControls ) {
                
                oGeoStart.loadControls(oSettings._sMapControls);
            }
            
            // Temp save control
            
          }
          oGeoStart.oMap.checkResize();
          
          if ( iPortaalId > 0 ) {                
                oMenu.iPortal = iPortaalId;                
          }
          
          if ( iRubriekId > 0 ) {
                oMenu.iRubriek = iRubriekId;
          }
          

          if ( iMarkerId > 0 ) {
            // setTimeout('delayGotoHidden(' + iMarkerId + ')', 5000);   
            delayGotoHidden(iMarkerId);              
          }         
          
          //oDir = new GDirections(oGeoStart.oMap, oGeoStart.util.getElementById('routeInner'));

          
          if ( bRoute ) {
                oGeoStart.oMenuEffects.slideTab(1);
          } 
          
          if ( sSearch != 0 ) {
                swap('tab', true);
                oGeoStart.html.showSearch(sSearch);
                activate('tabSearch');
                var eSearch = oGeoStart.util.getElementById('keyword')
                eSearch.value = sSearch;
                eSearch.className = '';
          }

          //oGeoStart.AjaxHistory = new cAjaxHistory();
          if(!oSettings.sMapMaker){
            //resizer();          
          }
          document.attachEvent('onresize', resizer);
          
          /** CBS statistieken **/
          if(oSettings.show_cbs_data == 1) {
            oGeoStart.oCbsData = new cCbsData();
            oGeoStart.oCbsData.init();

            if(oSettings.sMapMaker && oSettings.statistiek != '' ) {
                oGeoStart.oCbsData.setStatistiek(oSettings.statistiek);
                oGeoStart.util.getElementById('geoMapFooter').style.display = "block";
            }
          }
          
          if(oSettings.sMapMaker){
              oGeoStart.util.getElementById('geoMapContainer').style.width = oSettings.breedte - 2 + 'px';
              oGeoStart.util.getElementById('geoMapHeader').style.width = (oSettings.breedte - 2 - 5) + 'px'; 
              oGeoStart.util.getElementById('geoMapFooter').style.width = (oSettings.breedte - 2 - 5) + 'px'; 
              
              oGeoStart.util.getElementById('geoMap').style.width = oSettings.breedte - 2 + 'px';
              
              oGeoStart.util.getElementById('geoMapHeader').style.display = 'block';
              //oGeoStart.util.getElementById('geoMapHeader').innerHTML = oSettings.sTitle;              
              oGeoStart.util.getElementById('map_titel').innerHTML = oSettings.sTitle;              
              oGeoStart.util.getElementById('geoMapFooter').style.lineHeight = 24 + 'px';
              oGeoStart.util.getElementById('geoMapFooter').style.textAlign = 'left';
              oGeoStart.util.getElementById('geoMapFooter').style.paddingLeft = 5 + 'px';
              
              if(oSettings.statistiek == ''){
                  oGeoStart.util.getElementById('geoMap').style.height = (oSettings.hoogte - 2 - 23 - 23 - 2 - 2) + 'px';
                  oGeoStart.util.getElementById('geoMapFooter').innerHTML = '<' + 'a href="' + sBaseUrl + '">Bron: ' + window.location.host + '</'+'a>';          
              } else {
                  oGeoStart.util.getElementById('geoMap').style.height = (oSettings.hoogte - 2 - 23 - 23 - 2 - 2 - 20) + 'px';
                  oGeoStart.util.getElementById('geoMapFooter').style.height = '44px';
                  
                  oGeoStart.util.getElementById('legenda_text').style.width = (oSettings.breedte - 120) +  'px';                  
              }
          }
          
          
          oGeoStart.oMap.getContainer().appendChild(oGeoStart.util.getElementById('mapMaker_frame'));
          
                                                     
        }                
        
        document.attachEvent('onload', onLoad);
       
        //]]>

function mapMakerWizardResizer() {
      if(!oSettings.sMapMaker){
    
          var iHeaderHeight = 0;

          
          var size = checkSize();      
          myWidth  = size[0];
          myHeight = size[1];
          

          
          // geen fullscreen
          if(!bFullScreen) {
            
              
            if(oSettings._bMenu !== false){ 
                //oGeoStart.util.getElementById('header').style.display       = 'block';
            }
            //oGeoStart.util.getElementById('geoStart').style.marginTop       = (iHeaderHeight)+'px';
            //oGeoStart.util.getElementById('geoStart').style.height          = (myHeight-iHeaderHeight-10)+'px';
            
            myHeight = 1000;
            myWidth  = 700;
            
            oGeoStart.util.getElementById('geoMapContainer').style.height   = (myHeight-iHeaderHeight-40-15)+'px';
            
            oGeoStart.util.getElementById('geoStart').style.position = '';
            oGeoStart.util.getElementById('geoStart').style.height          = (myHeight)+'px';

            oGeoStart.util.getElementById('infoPane').style.height          = (myHeight-iHeaderHeight-40-15)+'px';                    
            oGeoStart.util.getElementById('geoMap').style.height            = (myHeight-iHeaderHeight-40-15-24)+'px';            
            oGeoStart.util.getElementById('menuContainer').style.height     = (myHeight-iHeaderHeight-40-14)+'px'; 

            
            /** menuhandle zetten **/
            oGeoStart.util.getElementById('menuHandle').style.height        = (myHeight-iHeaderHeight-40-15)+'px';
            oGeoStart.util.getElementById('menuHandle').style.display       = "none";          
            
            oGeoStart.util.getElementById('closeInfoPaneOverlay').style.top = iHeaderHeight-12-24 + 'px';
            oGeoStart.util.getElementById('leftPaneContainer').style.marginRight = '5px'; 
            
          } else {
            // wel fullscreen
            oGeoStart.util.getElementById('header').style.display           = 'none';
            
            oGeoStart.util.getElementById('geoStart').style.position = 'absolute';
            oGeoStart.util.getElementById('geoStart').style.top = '0px';
            oGeoStart.util.getElementById('geoStart').style.left = '0px';
            
            var oPos = findPos(oGeoStart.util.getElementById('geoStart'));
            
            oGeoStart.util.getElementById('geoStart').style.top = (-oPos[1]) + 'px';
            oGeoStart.util.getElementById('geoStart').style.left = (10-oPos[0]) + 'px';
            
            oGeoStart.util.getElementById('geoStart').style.height          = (myHeight - 60)+'px';
            oGeoStart.util.getElementById('geoStart').style.marginTop       = '10px';
            
            oGeoStart.util.getElementById('infoPane').style.height          = (myHeight-40-15-10)+'px';
            oGeoStart.util.getElementById('geoMap').style.height            = (myHeight-40-15-10-24)+'px';

            oGeoStart.util.getElementById('menuContainer').style.height     = (myHeight-40-14-10)+'px';
            
            oGeoStart.util.getElementById('menuHandle').style.height        = (myHeight-40-15-10)+'px';
            oGeoStart.util.getElementById('menuHandle').style.display       = "block";
            
            oGeoStart.util.getElementById('leftPaneContainer').style.marginRight = '0px';
            
            if(oSettings.hoogte){
                oGeoStart.util.getElementById('geoMapContainer').style.height   = oSettings.hoogte + 'px';
            }
            else{
                oGeoStart.util.getElementById('geoMapContainer').style.height   = (myHeight-40-15-10)+'px';
            }
            
            oGeoStart.util.getElementById('closeInfoPaneOverlay').style.top = 44 + 'px';
            
          }

                
          if(bMenuOpen) {
            if(!bFullScreen) {
                oGeoStart.util.getElementById('geoMapContainer').style.width    = (myWidth-307)+'px';
            } else {
                // menu open & fullscreen

                oGeoStart.util.getElementById('geoMapContainer').style.width    = (myWidth-309)+'px';
            }
            
            oGeoStart.util.getElementById('mapMenuContainer').style.width   = (myWidth-305)+'px';
            oGeoStart.util.getElementById('menuContainer').style.display    = 'block';
            oGeoStart.util.getElementById('menuContainer').style.width      = 278+'px';
            oGeoStart.util.getElementById('menuHandle').style.left          = 290+'px';
            oGeoStart.util.getElementById('infoPane').style.left            = 296 + 'px';
            
          } else {
                if(oSettings.breedte){  
                    oGeoStart.util.getElementById('geoMapContainer').style.width = oSettings.breedte - 2 + 'px';    
                } 
                else{ 
            if(!bFullScreen) {
                oGeoStart.util.getElementById('geoMapContainer').style.width    = (myWidth-40)+'px';
            } else {
                oGeoStart.util.getElementById('geoMapContainer').style.width    = (myWidth-28)+'px';
            }  }        
            oGeoStart.util.getElementById('menuContainer').style.display    = 'none';
            oGeoStart.util.getElementById('mapMenuContainer').style.width   = (myWidth-305)+'px';
          
            oGeoStart.util.getElementById('menuHandle').style.left          = 11+'px';        
            oGeoStart.util.getElementById('infoPane').style.left            = 17 + 'px';
          }
          
          oGeoStart.util.getElementById('mapMenu').style.width            = (myWidth-310-17)+'px';                
          oGeoStart.util.getElementById('geoStart').style.width           = (myWidth-20)+'px';
          
          /** menuhandle-img in het midden zetten **/

          oGeoStart.util.getElementById('menuHandle_img').style.top      = (oGeoStart.util.getElementById('geoMapContainer').clientHeight/2)-77 + 'px';
          oGeoStart.util.getElementById('infoPane_img').style.top        = (oGeoStart.util.getElementById('geoMapContainer').clientHeight/2)-24 + 'px'; 
          
          oGeoStart.util.getElementById('closeInfoPaneOverlay').style.left     = oGeoStart.util.getElementById('geoMapContainer').offsetLeft + 1 + 'px';
          oGeoStart.util.getElementById('closeInfoPaneOverlay').style.height   = oGeoStart.util.getElementById('geoMapContainer').clientHeight + 'px';
          oGeoStart.util.getElementById('closeInfoPaneOverlay').style.width    = oGeoStart.util.getElementById('geoMapContainer').clientWidth + 'px';
          
          // roep accordionobject aan om items goed te zetten:
          try {
              if(oSettings._bMenu !== true || typeof(oSettings._bMenu) != "undefined") {
                oGeoStart.oMenuEffects.checkResize();
              }
          } catch(e){ }

          /** Try/catch because this function is called before the creation of the map object **/
          try {
            oGeoStart.oMap.checkResize();
          } catch(e) { }
          /*
          try {
            oIntroScreen.checkResize();
          } catch(e) { }
           */         
          //oGeoStart.oMapMaker.checkResize();
          
      }
      
      if ( oGeoStart.util.getElementById('Loading_mapMaker') != null ) {
        oGeoStart.util.getElementById('Loading_mapMaker').style.display = 'none';
      }
      
};if ( (typeof(bIntegrated) == 'undefined' || bIntegrated == false) && typeof(document.attachEvent) != 'function' ) {
    
    document.events = [];
    document.attachEvent = function(type, reference) {
        var evt = this.events;
        if(!evt[type]){ evt[type] = []; }
        evt[type][evt[type].length] = reference;

        document[type] = function(e) { 
            document.executeEvents(type, e);        
        };
    };

    document.executeEvents = function(type, e) {
        for(var i in this.events[type]) {
            this.events[type][i](e);
        }    
    };
    window.onunload = function() { document.executeEvents('onunload'); };
    window.onload = function() { document.executeEvents('onload'); };
    window.onresize = function() { document.executeEvents('onresize'); };

}

var bFullScreen     = false;
var bMenuOpen       = true;
var bInfoPaneOpen   = false;
var bInfoPaneVisible= false;

function toggleFullScreen() {
    if(bFullScreen) {
        oGeoStart.util.getElementById("fullscreen_btn_off").style.display = 'block';
        oGeoStart.util.getElementById("fullscreen_btn_on").style.display  = 'none';
        oGeoStart.util.getElementById("menuHandle_img").src               = sBaseUrl + "GeoStart/images/menuHandle_open.gif";
        document.body.style.overflow = '';
        
        
        
        oGeoStart.util.getElementById('content').style.backgroundImage = '';
        oGeoStart.util.getElementById('topbar').style.backgroundImage = '';
        
        bFullScreen = false;
        bMenuOpen = true;
        
        
    } else {
        oGeoStart.util.getElementById("fullscreen_btn_off").style.display = 'none';
        oGeoStart.util.getElementById("fullscreen_btn_on").style.display  = 'block';
        oGeoStart.util.getElementById('content').style.backgroundImage = 'url(static/denhaagpresentation/images/bg_body_2.gif)';
        oGeoStart.util.getElementById('topbar').style.backgroundImage = 'url(static/denhaagpresentation/images/bg_body_2.gif)';
        bFullScreen = true;
        bMenuOpen = false;
        document.body.style.overflow = 'hidden';
        scroll(0,0);
    }
    
    resizer();
}


function windowOpen(sLink, iWidth, iHeight) {
    window.open(sLink, '_blank', 'location=0,statusbar=0,menubar=0,width='+iWidth+',height='+iHeight);
}


/**
*   Function for fluid design. 
**/
function resizer() {
      if(!oSettings.sMapMaker){
          var oCenter = oGeoStart.oMap.getCenter();
    
          var iHeaderHeight = parseInt(oSettings._HeaderHeight);
          
          var size = checkSize();      
          myWidth  = size[0];
          myHeight = size[1];
          
          // geen fullscreen
          if(!bFullScreen) {
            if(oSettings._bMenu !== false){ 
                oGeoStart.util.getElementById('header').style.display       = 'block';
                oGeoStart.util.getElementById('header').style.height = iHeaderHeight + 'px';
            }
            
            
            oGeoStart.util.getElementById('geoStart').style.marginTop       = (iHeaderHeight)+'px';
            oGeoStart.util.getElementById('geoStart').style.height          = (myHeight-iHeaderHeight-10)+'px';
            
            oGeoStart.util.getElementById('geoMapContainer').style.height   = (myHeight-iHeaderHeight-40-15)+'px';
            
            

            oGeoStart.util.getElementById('infoPane').style.height          = (myHeight-iHeaderHeight-40-15)+'px'; 
            
            oGeoStart.util.getElementById('geoMap').style.height            = (myHeight-iHeaderHeight-40-15)+'px';            
            oGeoStart.util.getElementById('menuContainer').style.height     = (myHeight-iHeaderHeight-40-14)+'px'; 

            
            /** menuhandle zetten **/
            oGeoStart.util.getElementById('menuHandle').style.height        = (myHeight-iHeaderHeight-40-15)+'px';
            oGeoStart.util.getElementById('menuHandle').style.display       = "none";          
            
            oGeoStart.util.getElementById('closeInfoPaneOverlay').style.top = 44 + 'px';
            oGeoStart.util.getElementById('leftPaneContainer').style.marginRight = '5px'; 
          } else {
            // wel fullscreen
            oGeoStart.util.getElementById('header').style.display           = 'none';
            
            oGeoStart.util.getElementById('geoStart').style.height          = (myHeight - 60)+'px';
            oGeoStart.util.getElementById('geoStart').style.marginTop       = '10px';
            
            oGeoStart.util.getElementById('infoPane').style.height          = (myHeight-40-15-10)+'px';
            oGeoStart.util.getElementById('geoMap').style.height            = (myHeight-40-15-10-24)+'px';

            oGeoStart.util.getElementById('menuContainer').style.height     = (myHeight-40-14-10)+'px';
            
            oGeoStart.util.getElementById('menuHandle').style.height        = (myHeight-40-15-10)+'px';
            oGeoStart.util.getElementById('menuHandle').style.display       = "block";
            
            oGeoStart.util.getElementById('leftPaneContainer').style.marginRight = '0px';
            
            if(oSettings.hoogte){
                oGeoStart.util.getElementById('geoMapContainer').style.height   = oSettings.hoogte + 'px';
            }
            else{
                oGeoStart.util.getElementById('geoMapContainer').style.height   = (myHeight-40-15-10)+'px';
            }
            
            oGeoStart.util.getElementById('closeInfoPaneOverlay').style.top = 44 + 'px';
            
          }

                
          if(bMenuOpen) {
            if(!bFullScreen) {
                oGeoStart.util.getElementById('geoMapContainer').style.width    = (myWidth-307)+'px';
            } else {
                // menu open & fullscreen

                oGeoStart.util.getElementById('geoMapContainer').style.width    = (myWidth-309)+'px';
            }
            
            oGeoStart.util.getElementById('mapMenuContainer').style.width   = (myWidth-305)+'px';
            oGeoStart.util.getElementById('menuContainer').style.display    = 'block';
            oGeoStart.util.getElementById('menuContainer').style.width      = 278+'px';
            oGeoStart.util.getElementById('menuHandle').style.left          = 290+'px';
            oGeoStart.util.getElementById('infoPane').style.left            = 296 + 'px';
            
          } else {
            if(oSettings.breedte){  
                oGeoStart.util.getElementById('geoMapContainer').style.width = oSettings.breedte - 2 + 'px';    
            } 
            else{ 
                if(!bFullScreen) {
                    oGeoStart.util.getElementById('geoMapContainer').style.width    = (myWidth-40)+'px';
                } else {
                    oGeoStart.util.getElementById('geoMapContainer').style.width    = (myWidth-28)+'px';
                }  
            }        
            oGeoStart.util.getElementById('menuContainer').style.display    = 'none';
            oGeoStart.util.getElementById('mapMenuContainer').style.width   = (myWidth-305)+'px';
          
            oGeoStart.util.getElementById('menuHandle').style.left          = 11 + 'px';        
            oGeoStart.util.getElementById('infoPane').style.left            = 17 + 'px';
          }
          
          oGeoStart.util.getElementById('mapMenu').style.width            = (myWidth-310-17)+'px';                
          oGeoStart.util.getElementById('geoStart').style.width           = (myWidth-20)+'px';
          
          /** menuhandle-img in het midden zetten **/

          oGeoStart.util.getElementById('menuHandle_img').style.top      = (oGeoStart.util.getElementById('geoMapContainer').clientHeight/2)-77 + 'px';
          oGeoStart.util.getElementById('infoPane_img').style.top        = (oGeoStart.util.getElementById('geoMapContainer').clientHeight/2)-24 + 'px'; 
          
          oGeoStart.util.getElementById('closeInfoPaneOverlay').style.left     = oGeoStart.util.getElementById('geoMapContainer').offsetLeft + 1 + 'px';
          oGeoStart.util.getElementById('closeInfoPaneOverlay').style.height   = oGeoStart.util.getElementById('geoMapContainer').clientHeight + 'px';
          oGeoStart.util.getElementById('closeInfoPaneOverlay').style.width    = oGeoStart.util.getElementById('geoMapContainer').clientWidth + 'px';
          
          // roep accordionobject aan om items goed te zetten:
          try {
              if(oSettings._bMenu !== true || typeof(oSettings._bMenu) != "undefined") {
                oGeoStart.oMenuEffects.checkResize();
              }
          } catch(e){ }

          /** Try/catch because this function is called before the creation of the map object **/
          try {
            oGeoStart.oMap.checkResize();
          } catch(e) { }
          /*
          try {
            oIntroScreen.checkResize();
          } catch(e) { }
           */         
          //oGeoStart.oMapMaker.checkResize();
          
          oGeoStart.oMap.panTo(oCenter);
          
      }
      
      if ( oGeoStart.util.getElementById('Loading_mapMaker') != null ) {
        oGeoStart.util.getElementById('Loading_mapMaker').style.display = 'none';
      }
      
};

/** Call the function on resize **/
//onresize = resizer;

var counter = 0;
function positionHelp(myHeight){
    var eHelp = oGeoStart.util.getElementById('help_draggable');
    

    counter++;
    iHeaderHeight = parseInt(oSettings._HeaderHeight);
    iHeight = checkSize()[1];
    if ( eHelp ) {
        var aPosition = findPos(oGeoStart.util.getElementById('help_draggable'));

        //var iTop = ( 0 - iHeaderHeight + ( ( iHeight - 579 - aPosition[1] ) / 2 ) );

        var currentTop = parseInt(eHelp.style.top.replace('px', ''));
        
        if ( iHeight > 600 ) {
            eHelp.style.top = ( ( ( iHeight - 579 ) / 2 ) - findPos(oGeoStart.util.getElementById("help_container"))[1] ) + "px";            
        } else {
            eHelp.style.top = ( 0 - findPos(oGeoStart.util.getElementById("help_container"))[1] ) + "px";
        }
    } else {
        setTimeout('positionHelp(' + myHeight + ')', 100);
    }
};

/**
*   In the main info tab, there are 3 divs. Use this to activate the correct div.
**/
function setInfoPaneContent(sBlock){
    var aBlocks = new Object();
    aBlocks['search'] = oGeoStart.util.getElementById('searchResultWrap');
    aBlocks['info'] = oGeoStart.util.getElementById('moreInfoWrap');
    aBlocks['list'] = oGeoStart.util.getElementById('listWrap');
    aBlocks['help'] = oGeoStart.util.getElementById('helpWrap');
    
    for ( var sId in aBlocks ) {
        
        aBlocks[sId].style.display = 'none';
    }
    
    aBlocks[sBlock].style.display = 'block';
    
    setTimeout('oGeoStart.util.getElementById("infoPaneContent").scrollTop = 0', 0);
    
};
 
/**
*   In the main info tab, there are 3 divs. Use this to activate the correct div.
**/
function setMoreInfoTab(sBlock, e){
    var aBlocks = new Object();
    aBlocks['location_description'] = oGeoStart.util.getElementById('location_description');
    aBlocks['location_images'] = oGeoStart.util.getElementById('location_images');
    aBlocks['location_address'] = oGeoStart.util.getElementById('location_address');
    aBlocks['location_cats'] = oGeoStart.util.getElementById('location_cats');
    aBlocks['location_link'] = oGeoStart.util.getElementById('location_link');
    
    var oTabs = oGeoStart.util.getElementById('infoPane_tabs');
   
    for(var i = 0; i < oTabs.childNodes.length; i++){
        if(oTabs.childNodes[i].className == "infoPane_tab"){
            oTabs.childNodes[i].firstChild.className = "";   
        }
        //oTabs.childNodes[i].firstChild.className = "";
    }
    
   // document.getElementsByClassName()
    
    e.className = "active";
    
    
    for ( var sId in aBlocks ) {
        aBlocks[sId].style.display = 'none';
    }    
    aBlocks[sBlock].style.display = 'block';
    
}; 
 
 
 
/**
*   Toggle help display on the map. 
*   eHC: Help Control element.
**/
function toggleHelp(){
    var eH = oGeoStart.util.getElementById('help');
    var eHC = oGeoStart.util.getElementById('Control_grey_help');
    if ( eH.style.display != 'block' ){
        eH.style.display = 'block';  
        eHC.style.fontWeight = 'bold';      
        pageHit('Google_Maps_Help');
    } else {
        eH.style.display = 'none';
        eHC.style.fontWeight = 'normal';
    }    
};

    /**
    *   Crossbrowser find position voor DOM object
    **/
    function findPos(obj) {
        var curleft = curtop = 0;
        if (obj.offsetParent) {
            curleft = obj.offsetLeft;
            curtop = obj.offsetTop;
            while (obj = obj.offsetParent) {
                curleft += obj.offsetLeft;
                curtop += obj.offsetTop;
            }
        }
        return [curleft,curtop];
    };




function checkSize() {
      var myWidth = 0, myHeight = 0;
      if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
        
      } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
      } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
      }      
      var retVal = [myWidth, myHeight];
      
      return retVal;
}


/** 
*   The tab title is dynamic and can contain 'Detail pagina' and 'Locatie overzicht' 
*   This function reads input#sCurTab.value to check what was loaded last.
**/
function tabTitleClick(){
    var sCurTab = oGeoStart.util.getElementById('sCurTab').value;
    
    setTabContent(sCurTab);
    activate('tabTitle');
    swap('tab', true);
};

function stopClick(e){
    if (!e){
        var e = window.event;
    }
    e.cancelBubble = true;
    if (e.stopPropagation){
        e.stopPropagation();
    }
};

function toggleDirForm(){
    if(oGeoStart.util.getElementById('infoWindow_route').style.display != "block"){
        oGeoStart.util.getElementById('infoWindow_route').style.display     = "block";
        oGeoStart.util.getElementById('infoWindow_location').style.display  = "none";
    }
    else{
        oGeoStart.util.getElementById('infoWindow_route').style.display     = "none";
        oGeoStart.util.getElementById('infoWindow_location').style.display  = "block";        
    }
    modifyButtons();
    
}

function changeRouteLabel(sSource){
    if(sSource == 'from'){        
        
        oGeoStart.util.getElementById('routeLabel').innerHTML = "Bestemming:";
    }
    else{
        oGeoStart.util.getElementById('routeLabel').innerHTML = "Vertrekpunt:";
    }
    
}

function togglePermLink(sLink){
   // if(!oSettings.sMapMaker){
        var permLinkDiv         = oGeoStart.util.getElementById('permLinkDiv'); 
        //var balloonHeight   = balloon.offsetHeight; 
        if(permLinkDiv.style.display != "block"){
             oGeoStart.util.getElementById('closeInfoPaneOverlay').style.display = 'block'; 
            permLinkDiv.style.display = "block";
            oGeoStart.util.getElementById('permLinkInput').value = ""+sLink;
            oGeoStart.util.getElementById('permLinkInput').select();
            var oRect = findPos(oGeoStart.util.getElementById("geoMap"));
            
            //permLinkDiv.style.left = (oRect[0] +  (oGeoStart.util.getElementById('geoMap').clientWidth / 2)) + "px";
            permLinkDiv.style.left = "520px";
            oGeoStart.util.getElementById('permLinkInput').select();
           // balloon.offsetHeight = balloonHeight + 20;
        }
        else{
            permLinkDiv.style.display = "none";
             oGeoStart.util.getElementById('closeInfoPaneOverlay').style.display = 'none'; 
            //balloon.offsetHeight = balloonHeight - 20;
        }
    //}
}
  
function modifyButtons(){
    var buttons = oGeoStart.util.getElementById('geoStart').getElementsByTagName('input');
    //alert(buttons[0].type); 
     
    for(var i = 0; i < buttons.length; i++){
        if((buttons[i].type == "submit" || buttons[i].type == "button" ) && buttons[i].className != "nostyle" && buttons[i].className != "hidden"){
           if(typeof(buttons[i]) != null){
               try{
                   var button       = buttons[i];  
                   var parent       = button.parentNode;
                   
                   if(parent.className != 'buttonWrap'){
                       parent.removeChild(button);
                       
                       var buttonWrap           = document.createElement('div');
                       buttonWrap.className     = 'buttonWrap';
                       button.className         = 'button';
                       buttonWrap.appendChild(button);
                       
                       parent.appendChild(buttonWrap);
                   }
               }
               catch(e){}
           }
           
            
              
        }
        //buttons[i].style.color = "lime"; 
         
        
        
    }
    
}   
/**
 * Check to see if the displayed extInfoWindow is positioned off the viewable 
 * map region and by how much.  Use that information to pan the map so that 
 * the extInfoWindow is completely displayed.
 * @private
 */
 
 
ExtInfoWindow.prototype.repositionMap_ = function(){
  //pan if necessary so it shows on the screen
  var mapNE = this.map_.fromLatLngToDivPixel(
    this.map_.getBounds().getNorthEast()
  );
  var mapSW = this.map_.fromLatLngToDivPixel(
    this.map_.getBounds().getSouthWest()
  );
  var markerPosition = this.map_.fromLatLngToDivPixel(
    this.marker_.getPoint()
  );

  var panX = 0;
  var panY = 0;
  var paddingX = this.paddingX_;
  var paddingY = this.paddingY_;
  var infoWindowAnchor = this.marker_.getIcon().infoWindowAnchor;
  var iconAnchor = this.marker_.getIcon().iconAnchor;

  //test top of screen    
  var windowT = this.wrapperParts.t.domElement;
  var windowL = this.wrapperParts.l.domElement;
  var windowB = this.wrapperParts.b.domElement;
  var windowR = this.wrapperParts.r.domElement;
  var windowBeak = this.wrapperParts.beak.domElement;

  var offsetTop = markerPosition.y - ( -infoWindowAnchor.y + iconAnchor.y +  this.getDimensions_(windowBeak).height + this.getDimensions_(windowB).height + this.getDimensions_(windowL).height + this.getDimensions_(windowT).height + this.paddingY_);
  if (offsetTop < mapNE.y) {
    panY = mapNE.y - offsetTop;
  } else {
    //test bottom of screen
    var offsetBottom = markerPosition.y + this.paddingY_;
    if (offsetBottom >= mapSW.y) {
      panY = -(offsetBottom - mapSW.y);
    }
  }

  //test right of screen
  var offsetRight = Math.round(markerPosition.x + this.getDimensions_(this.container_).width/2 + this.getDimensions_(windowR).width + this.paddingX_ + infoWindowAnchor.x - iconAnchor.x);
  if (offsetRight > mapNE.x) {
    panX = -( offsetRight - mapNE.x);
  } else {
    //test left of screen
    var offsetLeft = - (Math.round( (this.getDimensions_(this.container_).width/2 - this.marker_.getIcon().iconSize.width/2) + this.getDimensions_(windowL).width + this.borderSize_ + this.paddingX_) - markerPosition.x - infoWindowAnchor.x + iconAnchor.x);
    if( offsetLeft < mapSW.x) {
      panX = mapSW.x - offsetLeft;
    }
  }

  if (panX != 0 || panY != 0 && this.map_.getExtInfoWindow() != null ) {
      if( (panY < -200 || panY > 200) && (panX < -200 || panX > 200)  ) {
        this.map_.setCenter(this.marker_.getPoint());
      }else {
        this.map_.panBy(new GSize(panX,panY));
      }
  }  
};    /**
    *   Custom map controls.
    *   Left control ( Created for: "Help" )
    *   @param oMap Map object
    *   @param sText Text on the button
    **/    
    var Cbs_Control = function(oMap, sText) { this.oMap = oMap; this.sText = sText; };
        Cbs_Control.prototype = new GControl(true, false);
        Cbs_Control.prototype.initialize = function () {
                var oContainer = document.createElement("div");
                oContainer.innerHTML         = "<span style='display:block;height:23px;line-height:22px;vertical-align:middle;'><img style='vertical-align:middle;' src='GeoStart/images/CBS_logo_rechtsboven.gif'> " + this.sText + "</span>";
                oContainer.id                 = "cbs_control";
                oContainer.style.width       = "60px";
                oContainer.style.overflow      = "hidden";
                oContainer.style.verticalAlign = "middle";
                oContainer.style.fontSize    = "11px";
                oContainer.style.height        = "23px";
                oContainer.style.textAlign     = "center";
                oContainer.style.cursor        = "pointer";
                oContainer.style.border        = "1px solid #c6c6c6";     
                oContainer.style.backgroundImage = "url('"+ sBaseUrl + "GeoStart/images/controls/mapMenuBackground.gif')";
                
                /** Onclick function **/
      
                
                var self = this;
                GEvent.addListener(oGeoStart.oMenuEffects, 'slideend', function(){
                    var i = oGeoStart.oMenuEffects.oMenuContents.length;
                    while(i--){
                        if(oGeoStart.oMenuEffects.oMenuContents[i].id == 'statistiek-content' && oGeoStart.oMenuEffects.oMenuContents[i].style.display == 'block'){
                            oContainer.style.fontWeight = 'bold';
                            return;
                        }                        
                    }
                    oContainer.style.fontWeight = 'normal';
                });
                
                GEvent.addDomListener(oContainer, 'click', function(){ 
                    var i = oGeoStart.oMenuEffects.oMenuHeaders.length;
                    while(i--){
                        if(oGeoStart.oMenuEffects.oMenuHeaders[i].id == 'statistiek-header'){
                            oGeoStart.oMenuEffects.oMenuHeaders[i].onclick();
                            return;
                        }
                    }
                }); 
                
                
                this.oMap.getContainer().appendChild(oContainer);             
                                
                return oContainer;
            }
            Cbs_Control.prototype.getDefaultPosition = function () {
                return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(266,10));
            };
            
      var cCbsLegend = function(oMap) { this.oMap = oMap; };
    cCbsLegend.prototype = new GControl(true, false);
    cCbsLegend.prototype.initialize = function () {
            this.sTitel = "";
            this.sPercentage = "";
            var oLegendContainer = document.createElement("div");
            oLegendContainer.id = 'legendContainer';
            
            oLegendContainer.className = "legend";
            oLegendContainer.style.cssText= "display:none;padding:5px;margin:0px;width:240px;";

            this.oMap.getContainer().appendChild(oLegendContainer);
                        
            return oLegendContainer;
        }
    cCbsLegend.prototype.setMinMax = function(min, max){
            document.getElementById("legendContainer").innerHTML    = "<h3 id='legendTitle'>" + this.sTitel + "</h3><span style='font-weight:bold; width:120px; float:left;'>"+min + this.sPercentage + "</span><span style='font-weight:bold; text-align:right; width:120px; float:left;'>"+max + this.sPercentage + "</span><img alt='Schaalverdeling' title='Schaalverdeling' src='GeoStart/images/legenda_schaal_big.gif'><br /><span class='bronDef'><a href='#' onclick='oGeoStart.oCbsData.getStatistiekBron(); return false'>Bron: CBS 2008</a></span>";            
        
    };
    
    cCbsLegend.prototype.setPercentages = function(bPercentages){
        if(bPercentages) {
            this.sPercentage = "%";
        } else {
            this.sPercentage = "";
        }
    }
    
    
    cCbsLegend.prototype.show = function() {
        document.getElementById("legendContainer").style.display = "block";
    }

    cCbsLegend.prototype.hide = function() {
        document.getElementById("legendContainer").style.display = "none";
    }    
    
    cCbsLegend.prototype.setTitel = function(sTitel) {
        this.sTitel = sTitel;
    }
    
    cCbsLegend.prototype.getDefaultPosition = function () {
            return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(5,20));
        };/**
 * @name ExtLargeMapControl
 * @version 1.1
 * @author Masashi, Bjorn Brala
 * @fileoverview Creates a control with buttons to pan in four directions,
 * and zoom in and zoom out, and a zoom slider. The UI is based on the 
 * LargeMapControl from Google Maps (circa December 2008), but it does not
 * have any integration with Street View.
 */


/*global GKeyboardHandler, GDraggableObject*/

/**
 * @name ExtLargeMapControlOptions
 * @class This class represents optional arguments to the control.
 * @property {String} [zoomInBtnTitle="zoom in"] Specifies tooltip for 
 * zoom in button.
 * @property {String} [zoomOutBtnTitle="zoom out"] Specifies tooltip for 
 * zoom out button button.
 * @property {String} [moveNorthBtnTitle="north"] Specifies tooltip for 
 * pan north button.
 * @property {String} [moveSouthBtnTitle="south"] Specifies tooltip for 
 * pan south button.
 * @property {String} [moveEastBtnTitle="east"] Specifies tooltip for 
 * pan east button.
 * @property {String} [moveWestBtnTitle="west"] Specifies tooltip for 
 * pan west button.
 * @property {String} [returnBtnTitle="home position"] Specifies tooltip for 
 * center button that returns user to original location.
 * @property {String} [type] If set to "small", the control will consist of
 * only the zoom in/zoom out buttons.
 */

/**
 * @desc Creates an ExtLargeMapControl, with optional configuration settings.
 * @param {ExtLargeMapControlOptions} opts
 * @constructor
 */    
function ExtLargeMapControl(opts) {
  this.sliderStep = 9;
  this.imgSrc = "http://maps.google.com/mapfiles/mapcontrols3d.png";
  this.imgSmallSrc = "http://maps.google.com/mapfiles/szc3d.png";
  
  this.divTbl = {};
  this.divTbl.container = { "left" : 0, "top" : 0, "width" : 59};
  this.divTbl.topArrowBtn = { "left" : 20, "top" : 0, "width" : 18, "height" : 18};
  this.divTbl.leftArrowBtn = { "left" : 0, "top" : 20};
  this.divTbl.rightArrowBtn = { "left" : 40, "top" : 20};
  this.divTbl.bottomArrowBtn = { "left" : 20, "top" : 40};
  this.divTbl.centerBtn = { "left" : 20, "top" : 20};
  this.divTbl.zoomSlideBarContainer = { "left" : 19, "top" : 86, "width" : 22};
  this.divTbl.zoomSliderContainer = { "left" : 0, "top" : 0, "width" : 22, "height" : 14};
  this.divTbl.zoomSliderContainerImg = { "left" : 0, "top" : -384, "width" : 22, "height" : 14};
  this.divTbl.zoomOutBtnContainer = { "left" : 0, "top" : 0, "width" : 59, "height" : 23};
  this.divTbl.zoomOutBtnContainerImg = { "left" : 0, "top" : -360, "width" : 59, "height" : 23};

  opts = opts || {};
  this.zoomInBtnTitle = opts.zoomInBtnTitle || "zoom in";
  this.zoomOutBtnTitle = opts.zoomOutBtnTitle || "zoom out";
  this.moveNorthBtnTitle = opts.moveNorthBtnTitle || "north";
  this.moveSouthBtnTitle = opts.moveSouthBtnTitle || "south";
  this.moveEastBtnTitle = opts.moveEastBtnTitle || "east";
  this.moveWestBtnTitle = opts.moveWestBtnTitle || "west";
  this.homeBtnTitle = opts.homeBtnTitle || "home position";
  this.opts = opts;
  
  this.divSmallTbl = {};
  this.divSmallTbl.container = { "left" : 0, "top" : 0, "width" : 19, "height" : 42};
  this.divSmallTbl.zoomInBtn = { "left" : 0, "top" : 0, "width" : 19, "height" : 21};
  this.divSmallTbl.zoomOutBtnImg = { "left" : 0, "top" : -21, "width" : 19, "height" : 21};
  this.divSmallTbl.zoomOutBtn = { "left" : 0, "top" : 21, "width" : 19, "height" : 21};

}


/**
 * @private
 */
ExtLargeMapControl.prototype = new GControl();


/**
 * @desc Initialize the map control
 * @private
 */
ExtLargeMapControl.prototype.initialize = function (map) {

  this._map = map;

  GEvent.addListener(map, 'maptypechanged', GEvent.callback(this, this._updateZoomSliderRange));

  var _handleList = {};
  
  this._keyboardhandler = new GKeyboardHandler(map);
  var agt = navigator.userAgent.toLowerCase();
  
  this._is_ie    = ((agt.indexOf("msie") !== -1) && (agt.indexOf("opera") === -1));
  this._is_gecko = (agt.indexOf('gecko') !== -1);
  this._is_opera = (agt.indexOf("opera") !== -1);

  //common image
  var commonImg = new Image();
  commonImg.src = this.imgSrc;

  var container;
  var zoomOutBtn;
  var zoomInBtn; 
  if (this.opts.type === "small") {
    // create container
    container = document.createElement("div");
    container.style.left = this.divSmallTbl.container.left + "px";
    container.style.top = this.divSmallTbl.container.top + "px";
    container.style.width = this.divSmallTbl.container.width + "px";
    container.style.height = this.divSmallTbl.container.height + "px";
    container.style.position = "absolute";
    container.style.overflow = "hidden";
    this._container = container;
    
    //zoom up button
    zoomInBtn = this.makeImgDiv_(this.imgSmallSrc, this.divSmallTbl.zoomInBtn);
    zoomInBtn.style.cursor = "pointer";
    zoomInBtn.title = this.zoomInBtnTitle;
    container.appendChild(zoomInBtn); 

    //zoom down button
    zoomOutBtn = this.makeImgDiv_(this.imgSmallSrc, this.divSmallTbl.zoomOutBtnImg);
    zoomOutBtn.style.cursor = "pointer";
    zoomOutBtn.style.overflow = "hidden";
    zoomOutBtn.style.position = "absolute";
    zoomOutBtn.style.left = this.divSmallTbl.zoomOutBtn.left + "px";
    zoomOutBtn.style.top = this.divSmallTbl.zoomOutBtn.top + "px";
    zoomOutBtn.style.width = this.divSmallTbl.zoomOutBtn.width + "px";
    zoomOutBtn.style.height = this.divSmallTbl.zoomOutBtn.height + "px";
    zoomOutBtn.title = this.zoomOutBtnTitle;
    container.appendChild(zoomOutBtn); 

    // events
    GEvent.bindDom(zoomOutBtn, "click", this, this._eventZoomOut);
    GEvent.bindDom(zoomInBtn, "click", this, this._eventZoomIn);
  } else {
    // calculation of controller size
    var currentMapType = map.getCurrentMapType();
    var minZoom = parseInt(currentMapType.getMinimumResolution(), 10);
    var maxZoom = parseInt(map.getCurrentMapType().getMaximumResolution(), 10);
    this._maxZoom = maxZoom;
    this._step = this.sliderStep;
    var ctrlHeight = (86 + 5) + (maxZoom - minZoom + 1) * this.sliderStep + 5;

    // create container
    container = this.makeImgDiv_(this.imgSrc, this.divTbl.container);
    container.style.height = (ctrlHeight + this.sliderStep + 2) + "px";
    _handleList.container = container;
    this._container = container;

    //top arrow button
    var topBtn = this.makeImgDiv_(this.imgSrc, this.divTbl.topArrowBtn);
    topBtn.style.cursor = "pointer";
    topBtn.style.left = "20px";
    topBtn.style.top = "0px";
    topBtn.title = this.moveNorthBtnTitle;
    container.appendChild(topBtn); 

    //left arrow button
    var leftBtn = topBtn.cloneNode(true);
    leftBtn.style.left = this.divTbl.leftArrowBtn.left + "px";
    leftBtn.style.top = this.divTbl.leftArrowBtn.top + "px";
    leftBtn.title = this.moveWestBtnTitle;
    container.appendChild(leftBtn); 

    //right arrow button
    var rightBtn = topBtn.cloneNode(true);
    rightBtn.style.left = this.divTbl.rightArrowBtn.left + "px";
    rightBtn.style.top = this.divTbl.rightArrowBtn.top + "px";
    rightBtn.title = this.moveEastBtnTitle;
    container.appendChild(rightBtn); 

    //bottom arrow button
    var bottomBtn = topBtn.cloneNode(true);
    bottomBtn.style.left = this.divTbl.bottomArrowBtn.left + "px";
    bottomBtn.style.top = this.divTbl.bottomArrowBtn.top + "px";
    bottomBtn.title = this.moveSouthBtnTitle;
    container.appendChild(bottomBtn); 

    //center button
    var homeBtn = topBtn.cloneNode(true);
    homeBtn.style.left = this.divTbl.centerBtn.left + "px";
    homeBtn.style.top = this.divTbl.centerBtn.top + "px";
    homeBtn.title = this.homeBtnTitle;
    container.appendChild(homeBtn); 

    _handleList.topBtn = topBtn;
    _handleList.leftBtn = leftBtn;
    _handleList.rightBtn = rightBtn;
    _handleList.bottomBtn = bottomBtn;
    _handleList.homeBtn = homeBtn;


    // zoom slider container
    var zoomSlideBarContainer = document.createElement("div");
    zoomSlideBarContainer.style.position  = "absolute";
    zoomSlideBarContainer.style.left = this.divTbl.zoomSlideBarContainer.left + "px";
    zoomSlideBarContainer.style.top = this.divTbl.zoomSlideBarContainer.top + "px";
    zoomSlideBarContainer.style.width = this.divTbl.zoomSlideBarContainer.width + "px";
    zoomSlideBarContainer.style.height = ((maxZoom - minZoom + 1) * this.sliderStep) + "px";
    zoomSlideBarContainer.style.overflow = "hidden";
    zoomSlideBarContainer.style.cursor = "pointer";
    container.appendChild(zoomSlideBarContainer); 
    _handleList.slideBar = zoomSlideBarContainer;

    // zoom slider Button
    var zoomLevel = map.getZoom();
    var zoomSliderContainer = this.makeImgDiv_(this.imgSrc, this.divTbl.zoomSliderContainerImg);
    
    zoomSliderContainer.style.top = ((maxZoom - zoomLevel) * this.sliderStep + 1) + "px";
    zoomSliderContainer.style.left = this.divTbl.zoomSliderContainer.left + "px";
    zoomSliderContainer.style.width = this.divTbl.zoomSliderContainer.width + "px";
    zoomSliderContainer.style.height = this.divTbl.zoomSliderContainer.height + "px";

    zoomSlideBarContainer.cursor = "url(http://maps.google.com/mapfiles/openhand.cur), default";
    zoomSlideBarContainer.appendChild(zoomSliderContainer); 
    _handleList.slideBarContainer = zoomSliderContainer;



    //zoomOut Btn container
    var zoomOutBtnContainer = this.makeImgDiv_(this.imgSrc, this.divTbl.zoomOutBtnContainerImg);
    zoomOutBtnContainer.style.top = (86 + (maxZoom - minZoom + 1) * this.sliderStep) + "px";
    zoomOutBtnContainer.style.left = this.divTbl.zoomOutBtnContainer.left + "px";
    zoomOutBtnContainer.style.width = this.divTbl.zoomOutBtnContainer.width + "px";
    zoomOutBtnContainer.style.height = this.divTbl.zoomOutBtnContainer.height + "px";

    zoomOutBtnContainer.cursor = "url(http://maps.google.com/mapfiles/openhand.cur), default";
    container.appendChild(zoomOutBtnContainer); 
    _handleList.zoomOutBtnContainer = zoomOutBtnContainer;


    //zoomOut button
    zoomOutBtn = document.createElement("div");
    zoomOutBtn.style.position = "absolute";
    zoomOutBtn.style.left = "20px";
    zoomOutBtn.style.top = (91 + (maxZoom - minZoom + 1) * this.sliderStep) + "px";
    zoomOutBtn.style.width = "18px";
    zoomOutBtn.style.height = "23px";
    zoomOutBtn.style.cursor = "pointer";
    zoomOutBtn.style.overflow = "hidden";
    zoomOutBtn.title = this.zoomOutBtnTitle;
    container.appendChild(zoomOutBtn); 
    _handleList.zoomOutBtn = zoomOutBtn;

    //zoomIn button
    zoomInBtn = document.createElement("div");
    zoomInBtn.style.position = "absolute";
    zoomInBtn.style.left = "20px";
    zoomInBtn.style.top = "65px";
    zoomInBtn.style.width = "18px";
    zoomInBtn.style.height = "23px";
    zoomInBtn.style.cursor = "pointer";
    zoomInBtn.style.overflow = "hidden";
    zoomInBtn.title = this.zoomInBtnTitle;
    container.appendChild(zoomInBtn); 
    _handleList.zoomInBtn = zoomInBtn;

    // events
    GEvent.bindDom(_handleList.topBtn, "click", this, this._eventTop);
    GEvent.bindDom(_handleList.leftBtn, "click", this, this._eventLeft);
    GEvent.bindDom(_handleList.rightBtn, "click", this, this._eventRight);
    GEvent.bindDom(_handleList.bottomBtn, "click", this, this._eventBottom);
    GEvent.bindDom(_handleList.homeBtn, "click", this, this._eventHome);
    GEvent.bindDom(_handleList.zoomOutBtn, "click", this, this._eventZoomOut);
    GEvent.bindDom(_handleList.zoomInBtn, "click", this, this._eventZoomIn);
    GEvent.bindDom(_handleList.slideBar, "click", this, this._eventSlideBar);
    GEvent.bind(map, "zoomend", this, this._eventZoomEnd);

    var drgOpt = {
      container : _handleList.slideBar
    };
    var drgCtrl = new GDraggableObject(_handleList.slideBarContainer, drgOpt);
    GEvent.bindDom(drgCtrl, "dragend", this, this._eventSlideDragEnd);
    this._slider =  drgCtrl;

    //set current slider position
    this._eventZoomEnd(map.getZoom(), map.getZoom());
  }

  // Save DOM element reference in the object.
  this._handleList = _handleList;

  map.getContainer().appendChild(container);
  
  return container;
};

/**
 * Update Zoomslider to ajust to Max and Min resolution on the current maptype
 * @private
**/
ExtLargeMapControl.prototype._updateZoomSliderRange = function (setMaxZoom) {
  
  
  var minZoom = parseInt(this._map.getCurrentMapType().getMinimumResolution(), 10);
  var maxZoom = parseInt(this._map.getCurrentMapType().getMaximumResolution(), 10);
  if (this.isNull(setMaxZoom) === false) {
    maxZoom = setMaxZoom;
  } else {
    this._maxZoom = maxZoom;
  }
  var ctrlHeight = (86 + 5) + (maxZoom - minZoom + 1) * this.sliderStep + 5;
  
  if (this.isNull(this._handleList) === true) {
    return;
  }

  // Update DOM elements to ajust to current Resolution range.
  this._handleList.container.style.height = (ctrlHeight + this.sliderStep + 2) + "px";
  this._handleList.slideBar.style.height = ((maxZoom - minZoom + 1) * this.sliderStep) + "px";
  this._handleList.zoomOutBtnContainer.style.top = (86 + (maxZoom - minZoom + 1) * this.sliderStep) + "px";
  this._handleList.zoomOutBtn.style.top = (91 + (maxZoom - minZoom + 1) * this.sliderStep) + "px";
  this._handleList.slideBarContainer.style.top = ((maxZoom - this._map.getZoom()) * this.sliderStep + 1) + "px";

};


/**
 * @private
 */
ExtLargeMapControl.prototype._eventTop = function () {
  this._map.panDirection(0, 1);
};


/**
 * @private
 */
ExtLargeMapControl.prototype._eventLeft = function () {
  this._map.panDirection(1, 0);
};

/**
 * @private
 */
ExtLargeMapControl.prototype._eventRight = function () {
  this._map.panDirection(-1, 0);
};

/**
 * @private
 */
ExtLargeMapControl.prototype._eventBottom = function () {
  this._map.panDirection(0, -1);
};

/**
 * @private
 */
ExtLargeMapControl.prototype._eventZoomOut = function () {
  this._map.zoomOut();
};

/**
 * @private
 */
ExtLargeMapControl.prototype._eventZoomIn = function () {
  this._map.zoomIn();
};


/**
 * @private
 */
ExtLargeMapControl.prototype._eventSlideBar = function (e) {
  var map = this._map;
  //calculate zoomlevel
  var mouseY = e.clientY;
  var slideStep = this._step;
  var maxZoom = this._maxZoom;
  var container = this._container;

  //set new zoomLevel
  var ctrlPos = this._getDomPosition(container);
  mouseY -= (ctrlPos.y + 91);
  var zoomLevel = Math.floor(maxZoom - (mouseY / slideStep));
  zoomLevel = zoomLevel < 0 ? 0 : zoomLevel;
  map.setZoom(zoomLevel);  
};

/**
  * @private
 */
ExtLargeMapControl.prototype._getDomPosition = function (that) {
  var targetEle = that;
  var pos = { x : 0, y : 0 };
  
  while (targetEle) {
    pos.x += targetEle.offsetLeft; 
    pos.y += targetEle.offsetTop; 
    targetEle = targetEle.offsetParent;

    if (targetEle && this._is_ie) {
      pos.x += (parseInt(ExtLargeMapControl.getElementStyle(targetEle, 
          "borderLeftWidth", "border-left-width"), 10) || 0);
      pos.y += (parseInt(ExtLargeMapControl.getElementStyle(targetEle, 
          "borderTopWidth", "border-top-width"), 10) || 0);
    }
  }

  if (this._is_gecko) {
    var bd = document.getElementsByTagName("BODY")[0];
    pos.x += 2 * (parseInt(ExtLargeMapControl.getElementStyle(bd, 
        "borderLeftWidth", "border-left-width"), 10) || 0);
    pos.y += 2 * (parseInt(ExtLargeMapControl.getElementStyle(bd, 
        "borderTopWidth", "border-top-width"), 10) || 0);
  }
  return pos;
};


/**
 * @private
 */
ExtLargeMapControl.getElementStyle = function (targetElm, IEStyleProp, CSSStyleProp) {
  var elem = targetElm;
  if (elem.currentStyle) {
    return elem.currentStyle[IEStyleProp];
  } else if (window.getComputedStyle) {
    var compStyle = window.getComputedStyle(elem, "");
    return compStyle.getPropertyValue(CSSStyleProp);
  }
};


/**
 * @private
 */
ExtLargeMapControl.prototype._eventSlideDragEnd = function (e) {
  //calculate zoomlevel
  var maxZoom = this._maxZoom;
  var mouseY = this._slider.top;
  var step = this._step;

  //set new zoomLevel
  var zoomLevel = Math.floor(maxZoom - (mouseY / step));
  zoomLevel = zoomLevel < 0 ? 0 : zoomLevel;
  this._map.setZoom(zoomLevel);
};


/**
 * @private
 */
ExtLargeMapControl.prototype._eventHome = function () {
  this._map.returnToSavedPosition();
};


/**
 * @private
 */
ExtLargeMapControl.prototype._eventZoomEnd = function (oldZoom, newZoom) {
  var maxZoom = this._maxZoom;
  if (newZoom < maxZoom) {
    this._updateZoomSliderRange();
  } else {
    this._updateZoomSliderRange(newZoom);
    maxZoom = newZoom;
  }
  var step = this._step;
  this._slider.moveTo(new GPoint(0, (maxZoom - newZoom) * step));
};

/**
 * @private
 * @ignore
 */
ExtLargeMapControl.prototype.copy = function () {
  return new ExtLargeMapControl(this.latlng_, this.opts);
};


/**
 * @private
 * @ignore
 */
ExtLargeMapControl.prototype.getDefaultPosition = function () {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 10));
};


/**
 * @private
 * @ignore
 */
ExtLargeMapControl.prototype.selectable = function () {
  return false;
};

/**
 * @private
 * @ignore
 */
ExtLargeMapControl.prototype.printable = function () {
  return true;
};

/**
 * @private
 * @desc      detect null,null string and undefined
 * @param     value
 * @return    true  :  value is nothing
 *            false :  value is not nothing
 */
ExtLargeMapControl.prototype.isNull = function (value) {
  if (!value && value !== 0 ||
     value === undefined ||
     value === "" ||
     value === null ||
     typeof value === "undefined") {
    return true;
  }
  return false;
};

/**
 * @private
 * @desc      create div element with PNG image
 */
ExtLargeMapControl.prototype.makeImgDiv_ = function (imgSrc, params) {
  var imgDiv = document.createElement("div");
  imgDiv.style.position = "absolute";
  imgDiv.style.overflow = "hidden";
  
  if (params.width) {
    imgDiv.style.width = params.width + "px";
  }
  if (params.height) {
    imgDiv.style.height = params.height + "px";
  }
  
  
  var img = null;
  if (!this._is_ie) {
    img = new Image();
    img.src = imgSrc;
  } else {
    img = document.createElement("div");
    if (params.width) {
      img.style.width = params.width + "px";
    }
    if (params.height) {
      img.style.height = params.height + "px";
    }
  }
  img.style.position = "relative";
  img.style.left = params.left + "px";
  img.style.top =  params.top + "px";
  img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "')";
  imgDiv.appendChild(img);
  return imgDiv;
};

    /**
    *   Custom map controls.
    *   Middle control ( best fit: Kaart )
    *   @param oMap Map object
    *   @param sText Text on the button
    **/    
    var Control_grey_center = function(oMap, sText) { this.oMap = oMap; this.sText = sText; };
        Control_grey_center.prototype = new GControl(true, false);
        Control_grey_center.prototype.initialize = function () {
                var oContainer = document.createElement("div");
                oContainer.className           = "sprite-repeat-x"
                oContainer.style.backgroundPosition = "0 0";
                oContainer.innerHTML           = "<span style='display:block;height:23px;line-height:23px;'>" + this.sText + "</span>";
                oContainer.id                  = "control_grey_satellite";
                oContainer.style.width         = "70px";
                oContainer.style.verticalAlign = "middle";
                oContainer.style.fontSize      = "11px";
                oContainer.style.height        = "23px";
                oContainer.style.textAlign     = "center";
                oContainer.style.cursor        = "pointer";
                oContainer.style.fontWeight    = "normal";
                oContainer.style.border        = "1px solid #c6c6c6";
                oContainer.style.borderLeft    = "none";
                oContainer.style.overflow      = "hidden";
                //oContainer.style.backgroundImage = "url('"+ sBaseUrl + "GeoStart/images/controls/mapMenuBackground.gif')";

                /** Make bold when clicked **/
                GEvent.addDomListener(oContainer, 'click', function(){ 
                    oGeoStart.oMap.enableContinuousZoom();
                    oGeoStart.oMap.setMapType(G_SATELLITE_MAP);
                    oContainer.style.fontWeight = 'bold'; 
                    
                    oGeoStart.util.getElementById('control_grey_normal').style.fontWeight = 'normal'; 
                    oGeoStart.util.getElementById('control_grey_beide').style.fontWeight = 'normal'; 
                    oGeoStart.util.getElementById('control_grey_terrein').style.fontWeight = 'normal';                     
                });

                if(oSettings.map_default_type == "G_SATELLITE_MAP") {
                    oContainer.style.fontWeight = 'bold';
                }
                               
                this.oMap.getContainer().appendChild(oContainer);
                
                return oContainer;
            }
            Control_grey_center.prototype.getDefaultPosition = function () {
                return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(135,10));
            };


            
    /**
    *   Custom map controls.
    *   Right control ( best fit Satelliet )
    *   @param oMap Map object
    *   @param sText Text on the button
    **/    
    var Control_grey_right = function(oMap, sText) { this.oMap = oMap; this.sText = sText; };
        Control_grey_right.prototype = new GControl(true, false);
        Control_grey_right.prototype.initialize = function () {
                var oContainer = document.createElement("div");
                oContainer.innerHTML         = "<span style='display:block;height:23px;line-height:23px;'>" + this.sText + "</span>";
                oContainer.id                 = "control_grey_beide";
                oContainer.style.width       = "60px";
                oContainer.style.verticalAlign = "middle";
                oContainer.style.fontSize    = "11px";
                oContainer.style.height        = "23px";
                oContainer.style.textAlign     = "center";
                oContainer.style.overflow      = "hidden";
                oContainer.style.cursor        = "pointer";
                oContainer.style.border        = "1px solid #c6c6c6";
             
                oContainer.className           = "sprite-repeat-x"
                oContainer.style.backgroundPosition = "0 0";
                //oContainer.style.backgroundImage = "url('"+ sBaseUrl + "GeoStart/images/controls/mapMenuBackground.gif')";

                /** Make bold when clicked **/
                GEvent.addDomListener(oContainer, 'click', function(){ 
                    oGeoStart.oMap.enableContinuousZoom();
                    oGeoStart.oMap.setMapType(G_HYBRID_MAP);
                    oContainer.style.fontWeight = 'bold';
                    oGeoStart.util.getElementById('control_grey_normal').style.fontWeight = 'normal'; 
                    oGeoStart.util.getElementById('control_grey_satellite').style.fontWeight = 'normal'; 
                    oGeoStart.util.getElementById('control_grey_terrein').style.fontWeight = 'normal';                     
                });            
                
                if(oSettings.map_default_type == "G_HYBRID_MAP") {
                    oContainer.style.fontWeight = 'bold';
                }

                this.oMap.getContainer().appendChild(oContainer);
                                
                return oContainer;
            }
            Control_grey_right.prototype.getDefaultPosition = function () {
                return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(75,10));
            };    
            
    var Control_grey_right2 = function(oMap, sText) { this.oMap = oMap; this.sText = sText; };
        Control_grey_right2.prototype = new GControl(true, false);
        Control_grey_right2.prototype.initialize = function () {
                var oContainer = document.createElement("div");
                oContainer.innerHTML         = "<span style='display:block;height:23px;line-height:23px;'>" + this.sText + "</span>";
                oContainer.id                 = "control_grey_terrein";
                oContainer.style.width       = "65px";
                oContainer.style.verticalAlign = "middle";
                oContainer.style.fontSize    = "11px";
                oContainer.style.fontWeight    = "normal";
                oContainer.style.height        = "23px";
                oContainer.style.textAlign     = "center";
                oContainer.style.overflow      = "hidden";
                oContainer.style.cursor        = "pointer";
                oContainer.style.border        = "1px solid #c6c6c6";
             
                oContainer.className           = "sprite-repeat-x"
                oContainer.style.backgroundPosition = "0 0";
                //oContainer.style.backgroundImage = "url('"+ sBaseUrl + "GeoStart/images/controls/mapMenuBackground.gif')";

                /** Make bold when clicked **/
                GEvent.addDomListener(oContainer, 'click', function(){ 
                    oGeoStart.oMap.enableContinuousZoom();
                    oGeoStart.oMap.setMapType(G_PHYSICAL_MAP);
                    oContainer.style.fontWeight = 'bold';
                    
                    oGeoStart.util.getElementById('control_grey_normal').style.fontWeight = 'normal'; 
                    oGeoStart.util.getElementById('control_grey_satellite').style.fontWeight = 'normal'; 
                    oGeoStart.util.getElementById('control_grey_beide').style.fontWeight = 'normal'; 
                });            
                
                if(oSettings.map_default_type == "G_PHYSICAL_MAP") {
                    oContainer.style.fontWeight = 'bold';
                }
            
                this.oMap.getContainer().appendChild(oContainer);
                                
                return oContainer;
            }
            Control_grey_right2.prototype.getDefaultPosition = function () {
                return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
            };               

            
    /**
    *   Custom map controls.
    *   Left control ( Created for: "Help" )
    *   @param oMap Map object
    *   @param sText Text on the button
    **/    
    var Control_grey_left = function(oMap, sText) { this.oMap = oMap; this.sText = sText; };
        Control_grey_left.prototype = new GControl(true, false);
        Control_grey_left.prototype.initialize = function () {
                var oContainer = document.createElement("div");
                oContainer.innerHTML         = "<span style='display:block;height:23px;line-height:23px;'>" + this.sText + "</span>";
                oContainer.id                 = "control_grey_normal";
                oContainer.style.width       = "60px";
                oContainer.style.overflow      = "hidden";
                oContainer.style.verticalAlign = "middle";
                oContainer.style.fontSize    = "11px";
                oContainer.style.height        = "23px";
                oContainer.style.textAlign     = "center";
                oContainer.style.cursor        = "pointer";
                oContainer.style.border        = "1px solid #c6c6c6";     
                oContainer.className           = "sprite-repeat-x"
                oContainer.style.backgroundPosition = "0 0";
                //oContainer.style.backgroundImage = "url('"+ sBaseUrl + "GeoStart/images/controls/mapMenuBackground.gif')";
                
                /** Onclick function **/
      
                
                GEvent.addDomListener(oContainer, 'click', function(){ 
                    oGeoStart.oMap.enableContinuousZoom();
                    oGeoStart.oMap.setMapType(G_NORMAL_MAP);
                    oContainer.style.fontWeight = 'bold';
                    
                    oGeoStart.util.getElementById('control_grey_beide').style.fontWeight = 'normal'; 
                    oGeoStart.util.getElementById('control_grey_satellite').style.fontWeight = 'normal'; 
                    oGeoStart.util.getElementById('control_grey_terrein').style.fontWeight = 'normal';                     
                });            
                if(oSettings.map_default_type == "G_NORMAL_MAP") {
                    oContainer.style.fontWeight = 'bold';
                }
                
                this.oMap.getContainer().appendChild(oContainer);             
                                
                return oContainer;
            }
            Control_grey_left.prototype.getDefaultPosition = function () {
                return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(206,10));
            };
            
          /**
    *   Custom map controls.
    *   @param oMap Map object
    *   @param sText Text on the button
    **/    
    var Mini_control_grey_left = function(oMap) { this.oMap = oMap; };
        Mini_control_grey_left.prototype = new GControl(true, false);
        Mini_control_grey_left.prototype.initialize = function () {
                var oContainer = document.createElement("div");
                oContainer.innerHTML           = "<span style='padding-top:1px;display:block;height:16px;'>map</span>";
                oContainer.id                  = "Mini_control_grey_left";
                oContainer.style.width         = "29px";
                oContainer.style.verticalAlign = "middle";
                oContainer.style.fontSize      = "9px";
                oContainer.style.height        = "17px";
                oContainer.style.textAlign     = "center";
                oContainer.style.cursor        = "pointer";
                oContainer.style.fontWeight    = "bold";
                oContainer.style.backgroundImage = "url('"+ sBaseUrl + "GeoStart/images/controls/minigrey/mini_map_sat.gif')";

                /** Make bold when clicked **/
                GEvent.addDomListener(oContainer, 'click', function(){ 
                    oGeoStart.oMap.setMapType(G_NORMAL_MAP);
                    oContainer.style.fontWeight = 'bold'; 
                    oGeoStart.util.getElementById('Mini_control_grey_right').style.fontWeight = 'normal';
                });

                
                
                this.oMap.getContainer().appendChild(oContainer);
                
                return oContainer;
            }
            Mini_control_grey_left.prototype.getDefaultPosition = function () {
                return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(51,10));
            };

    /**
    *   Custom map controls.
    *   Right control ( best fit Satelliet )
    *   @param oMap Map object
    *   @param sText Text on the button
    **/    
    var Mini_control_grey_right = function(oMap) { this.oMap = oMap; };
        Mini_control_grey_right.prototype = new GControl(true, false);
        Mini_control_grey_right.prototype.initialize = function () {
                var oContainer = document.createElement("div");
                oContainer.innerHTML         = "<span style='padding-top:1px;display:block;height:16px;'>sat</span>";
                oContainer.id                 = "Mini_control_grey_right";
                oContainer.style.width       = "29px";
                oContainer.style.verticalAlign = "middle";
                oContainer.style.fontSize    = "9px";
                oContainer.style.height        = "17px";
                oContainer.style.textAlign     = "center";
                oContainer.style.cursor        = "pointer";
                oContainer.style.backgroundImage = "url('"+ sBaseUrl + "GeoStart/images/controls/minigrey/mini_map_sat.gif')";

                /** Make bold when clicked **/
                GEvent.addDomListener(oContainer, 'click', function(){ 
                    oGeoStart.oMap.setMapType(G_SATELLITE_MAP); 
                    oContainer.style.fontWeight = 'bold';
                    oGeoStart.util.getElementById('Mini_control_grey_left').style.fontWeight = 'normal'; 
                });            
            
                this.oMap.getContainer().appendChild(oContainer);
                                
                return oContainer;
            }
            Mini_control_grey_right.prototype.getDefaultPosition = function () {
                return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(20,10));
            };

            
    /**
    *   Custom map controls.
    *   Zoom and Pan controls
    **/    
    var Mini_control_grey_zoom = function(oMap) { this.oMap = oMap;};
        Mini_control_grey_zoom.prototype = new GControl(true, false);
        Mini_control_grey_zoom.prototype.initialize = function () {
                var oContainer = document.createElement("div");
                oContainer.id                   = "Control_grey_pan";
                oContainer.style.width          = '16px';
                oContainer.style.height         = '36px';
                oContainer.style.backgroundImage= "url('"+ sBaseUrl + "GeoStart/images/controls/minigrey/mini_zoom_control.gif')";
                
                var oZoomin = document.createElement("div");
                var oZoomout = document.createElement("div");

                oZoomin.style.cssText = 'display:block;width:15px;height:15px;cursor:pointer;margin: 0 ;';
                oZoomout.style.cssText = 'display:block;width:15px;height:15px;cursor:pointer;margin: 3px 0 0 0px;';

                GEvent.addDomListener(oZoomin, 'click', function(){ oGeoStart.oMap.zoomIn();});            
                GEvent.addDomListener(oZoomout, 'click', function(){ oGeoStart.oMap.zoomOut();});            
                
                oContainer.appendChild(oZoomin);
                oContainer.appendChild(oZoomout);
                
                this.oMap.getContainer().appendChild(oContainer);
                                
                return oContainer;
            }
            Mini_control_grey_zoom.prototype.getDefaultPosition = function () {
                return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,10));
            };

            
            
            
    /**
    *   Custom copyright for GeoStart
    **/    
    var powered_by_geostart = function(oMap) { this.oMap = oMap; };
        powered_by_geostart.prototype = new GControl(true, false);
        powered_by_geostart.prototype.initialize = function () {
                var oContainer = document.createElement("div");
                oContainer.innerHTML    = "<a target='_blank' href='http://www.geostart.nl' style='display:block;height:29px;width:90px;'><img class='png' style='border:0;' src='"+sBaseUrl+"GeoStart/images/controls/powered_by_geostart.png'></a>";
                
                oContainer.id           = "powered_by_geostart";
                oContainer.style.cssText= "width:89px;text-decoration:none;border:none;height:29px;cursor:pointer;padding-bottom:2px;_padding-bottom:0px;";

                this.oMap.getContainer().appendChild(oContainer);
                
                return oContainer;
            }
        powered_by_geostart.prototype.getDefaultPosition = function () {
                return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(67,1));
            };
    /**
    *   Custom overlay for GreenMaps
    *   @param object oMap
    *   @param int x
    *   @param int y
    **/    
    var control_settings = function(oSettings, oMap, x, y) { this.oMap = oMap; this.oSettings = oSettings; this.x = x; this.y=y };
        control_settings.prototype = new GControl(true, false);
        control_settings.prototype.initialize = function () {
                var oContainer = document.createElement("div");
                oContainer.innerHTML    = "<img id='save_settings_image' src='"+sBaseUrl+"GeoStart/images/controls/icon_save_as.gif' style='margin-right:3px;display:block;float:left;'><a id='save_settings_link' target='_blank' onclick='oGeoStart.oStateMachine.saveCurrentState();return false;' href='#' style='background:#F1F1E9;display:block;padding:4px 0 5px 30px;color:#2eb000;'>Stel&nbsp;in&nbsp;als&nbsp;startpagina</a>";
                
                oContainer.id           = "save_settings";
                oContainer.style.cssText= "text-align:center;border:1px solid #6B6863;width:248px;text-decoration:none;height:22px;cursor:pointer;background-color:#F1F1E9;";

                this.oMap.getContainer().appendChild(oContainer);
                
                return oContainer;
            }        
        control_settings.prototype.getDefaultPosition = function () {
                return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(this.x,this.y));
            };

    var Control_Tarieven = function(oMap, sText) { this.oMap = oMap; this.sText = sText; };
        Control_Tarieven.prototype = new GControl(true, false);
        Control_Tarieven.prototype.initialize = function () {
                var oContainer = document.createElement("div");
                oContainer.innerHTML           = "<span style='display:block;height:23px;line-height:23px;'>" + this.sText + "</span>";
                oContainer.id                  = "control_tarieven";
                oContainer.style.width         = "70px";
                oContainer.style.verticalAlign = "middle";
                oContainer.style.fontSize      = "11px";
                oContainer.style.height        = "23px";
                oContainer.style.textAlign     = "center";
                oContainer.style.cursor        = "pointer";
                oContainer.style.fontWeight    = "normal";
                oContainer.style.border        = "1px solid #c6c6c6";
                oContainer.style.borderLeft    = "none";
                oContainer.style.overflow      = "hidden";
                oContainer.className           = "sprite-repeat-x"
                oContainer.style.backgroundPosition = "0 0";
                //oContainer.style.backgroundImage = "url('"+ sBaseUrl + "GeoStart/images/controls/mapMenuBackground.gif')";

                var self = this;
                
                /** Make bold when clicked **/
                GEvent.addDomListener(oContainer, 'click', function(){ 
                    var bVisible = oTarieven.toggle()
                    self._setBold(bVisible);                    
                    oVergunningen.setVisibility(false);
                });

                this.oMap.getContainer().appendChild(oContainer);
                
                this.oContainer = oContainer;
                
                return oContainer;
            }
            Control_Tarieven.prototype._setBold = function(bBold){
                if(bBold){
                    oGeoStart.util.getElementById('control_tarieven').style.fontWeight = 'bold'; 
                    oGeoStart.util.getElementById('control_vergunningen').style.fontWeight = 'normal';
                } else {
                    oGeoStart.util.getElementById('control_tarieven').style.fontWeight = 'normal';
                    oGeoStart.util.getElementById('control_vergunningen').style.fontWeight = 'normal';
                }
            }
            
            Control_Tarieven.prototype.getDefaultPosition = function () {
                return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(270,10));
            };

            
       var Control_Vergunningen = function(oMap, sText) { this.oMap = oMap; this.sText = sText; };
        Control_Vergunningen.prototype = new GControl(true, false);
        Control_Vergunningen.prototype.initialize = function () {
                var oContainer = document.createElement("div");
                oContainer.innerHTML           = "<span style='display:block;height:23px;line-height:23px;'>" + this.sText + "</span>";
                oContainer.id                  = "control_vergunningen";
                oContainer.style.width         = "95px";
                oContainer.style.verticalAlign = "middle";
                oContainer.style.fontSize      = "11px";
                oContainer.style.height        = "23px";
                oContainer.style.textAlign     = "center";
                oContainer.style.cursor        = "pointer";
                oContainer.style.fontWeight    = "bold";
                oContainer.style.border        = "1px solid #c6c6c6";
                oContainer.style.overflow      = "hidden";
                oContainer.className           = "sprite-repeat-x"
                oContainer.style.backgroundPosition = "0 0";
                //oContainer.style.backgroundImage = "url('"+ sBaseUrl + "GeoStart/images/controls/mapMenuBackground.gif')";

                var self = this;
                
                /** Make bold when clicked **/
                GEvent.addDomListener(oContainer, 'click', function(){ 
                    var bVisible = oVergunningen.toggle();
                    self._setBold(bVisible);                    
                    oTarieven.setVisibility(false);
                });

                this.oMap.getContainer().appendChild(oContainer);
                
                this.oContainer = oContainer;
                
                return oContainer;
            }
            
            Control_Vergunningen.prototype._setBold = function(bBold){
                if(bBold){
                    oGeoStart.util.getElementById('control_vergunningen').style.fontWeight = 'bold'; 
                    oGeoStart.util.getElementById('control_tarieven').style.fontWeight = 'normal';
                } else {
                    oGeoStart.util.getElementById('control_vergunningen').style.fontWeight = 'normal';
                    oGeoStart.util.getElementById('control_tarieven').style.fontWeight = 'normal';
                }
            }
            
            Control_Vergunningen.prototype.getDefaultPosition = function () {
                return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(340,10));
            };
    /**
    *   Custom zoom control showing the message to zoom in
    **/  
function cZoomArrow(){    
    
    this.init = function(oMap) {
        this._oMap          = oMap;
        this._oControl      = new zoom_arrow(this._oMap);
        this._oMap.addControl(this._oControl);        
        this._bVisible      = false;
        this._oContainer    = oGeoStart.util.getElementById('zoom_arrow');
        
    }
    
    
    this.show = function(){
        this._oContainer.style.display = "block";
        this._bVisible = true;
    }
    
    this.hide = function(){
        this._oContainer.style.display = "none";
        this._bVisible = false;
    }
    
    this.checkHidden = function(iHidden, iVisible) {
        if(this._oMap.getZoom() < this._oMap.getCurrentMapType().getMaximumResolution()) {
            var iTotalHidden = parseInt(iHidden - iVisible, 10);
            if(iTotalHidden > 0 && this._bVisible == false){
                this.show();
            } else if ( iTotalHidden < 1 && this._bVisible == true){
                this.hide();
            }
        } else {
            this.hide();
        }
    }
    
    
      
    var zoom_arrow = function(oMap) { this.oMap = oMap; };
        zoom_arrow.prototype = new GControl(true, false);
        zoom_arrow.prototype.initialize = function () {
                var oContainer = document.createElement("div");
                oContainer.innerHTML    = "<img style='border:0; cursor:pointer;' onclick='oGeoStart.oMap.zoomIn();' src='"+sBaseUrl+"GeoStart/images/zoomArrow.gif'>";
                oContainer.style.display = "none";
                oContainer.id           = "zoom_arrow";
                //oContainer.style.cssText= "width:89px;text-decoration:none;border:none;height:29px;cursor:pointer;padding-bottom:2px;_padding-bottom:0px;";

                this.oMap.getContainer().appendChild(oContainer);
                
                return oContainer;
            }
        zoom_arrow.prototype.getDefaultPosition = function () {
                return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(50,70));
        };
}