// mapfunctions.js
addEvent(window, "load", load);
addEvent(window, "unload", GUnload);

var EventId = null;
var MainTabName = 'Info';
var SubTabName = 'Omleiding';
var inMap = null;
var aDays = [];
var aMonths = [];

var aOverlays = new Array();
var aDiversionsData = new Array();
var aGPeriods = new Array();
var aGEvent;
var isFirstTab = false;

var ogDate = new Date();

var gMap;
var gShowMap;
var gHeavinesses = [];

var milieuzone_polygon=new GPolygon.fromEncoded ({ polylines: [ {
        color: "#FF0000",
        weight: 4,
        points: "}_}|Hyoi^fIhNjDjFhA}Dg@yC|PrDdKfObLnHr@v@??tAwHlAhBmCxH]`Dv@lA~LhIlA~@sKlYyB~MiHpJs@pE?fDb@lCwMtKjRxWsCrG`HlNsGtGeFpGaEkFsFdNkI`QmAmIyBgJuBgMqCyL{D{OoIhAwBRqM}YmAyCuEeTsFpC}ByJpK}JEoV}CcEIcB|@sFmAsIiHaBWuCr@w@S{BFqATuAbCyAt@lA~JpCfEIrBoA~AaEf@mCrABdBvBl@cGhAyDvAmErC_J",
        levels: "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
        zoomFactor: 32,
        numLevels: 4
    }], fill: true, color: "#0000ff", opacity: 0.3, outline: true});

var wwa2_eindhoven_milieuzone_polygon=new GPolygon.fromEncoded ({ polylines: [ {
        color: "#FF0000",
        weight: 4,
        points: "ot{xHqui`@kCnJuEtLoHzNwKxGkLtEqU~I{FOiEpCaNxC{I`@yB_CkCiNaLqd@iIkb@eByNe@oQiAwPe@_GT}HNyJOeI~@k{@b@gUd@sH~BiJdEoJzG_FjKyGnCeEtI{G`NgFtKaD`G}A~HjAoDvj@eGhKiAvBnNv[zArAn@aDXeE`GgFhB}Lj@cHdEci@xGhCjDj@jDjAtF|DhEfJvIhRdHnQtBxJ?xR{@dTeDxz@{Idm@uFzVoBfJ",
        levels: "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
        zoomFactor: 32,
        numLevels: 4
    }], fill: true, color: "#0000ff", opacity: 0.3, outline: true});    
    
var wwa2_den_bosch_milieuzone_polygon=new GPolygon.fromEncoded ({ polylines: [ {
        color: "#FF0000",
        weight: 4,
        points: "}lmzHiki_@}EcQ}AyFzBeI^b@fAyA^kDeAmCWiH}BuLEyHSiEa@oKYyJoAqDwEiGgEyDc@`AsB}@m@|@yEeB_As@wBpC_@YaEzFjFhOcI~UyFdQeDfJgBqAkEhEI|Bj@rGa@|BfAdCaCx@cCdB_CzFsB|G`MrE|KxC~MjDfThGnN`GxEdBx@gCOkDnAgFnAwI",
        levels: "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
        zoomFactor: 32,
        numLevels: 4
    }], fill: true, color: "#0000ff", opacity: 0.3, outline: true});

var filteredEvents = [];

var colors = new Array("#ff0066", "#ff0000", "#6600ff", "#66ff00", "#0066ff", "#00ff66");

var aEventFields = ["id", "project_name", "project_number", "project_contents", "project_start", "project_end", "website",  
"location",  "heaviness", "traffic_diversion", "road_type", "description", "time_period", "longitude", "latitude", "direction","source",  "type", "type_report", "time_period_humanise", "communication", "shapetype", "event_period"];

function inDistrict(){

    this.polygon_id = null;
    this.polygon_name = null;
    this.parent_id = null;
    this.polydata = null;
    this.parentDistrict = null;
    
}


var Districts = new Array();

aDays[0] = 'zondag';
aDays[1] = 'maandag';
aDays[2] = 'dinsdag';
aDays[3] = 'woensdag';
aDays[4] = 'donderdag';
aDays[5] = 'vrijdag';
aDays[6] = 'zaterdag';

aMonths[0] = 'januari';
aMonths[1] = 'februari';
aMonths[2] = 'maart';
aMonths[3] = 'april';
aMonths[4] = 'mei';
aMonths[5] = 'juni';
aMonths[6] = 'juli';
aMonths[7] = 'augustus';
aMonths[8] = 'september';
aMonths[9] = 'oktober';
aMonths[10] = 'november';
aMonths[11] = 'december';

//defaults to today
var todayStart = new Date(ogDate);
todayStart.setHours (0,0,0,0);
var todayEnd = new Date(ogDate);
todayEnd.setHours(23,59,59);


if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }

    return res;
  };
}


//generate times objects

var aTimeIntervals = new Array ();
for (i=0;i<7;i++) {
	aTimeIntervals [i] = { from:new Date (todayStart), to:new Date (todayEnd) };
}

//today
//0 is ok already

//this week
aTimeIntervals [1].to.setDate ( todayEnd.getDate()+7 );

//next week
aTimeIntervals [2].to.setDate ( todayEnd.getDate()+14 );
aTimeIntervals [2].from.setDate ( todayStart.getDate()+7 );

//this month
if ( todayEnd.getMonth () == 11 ) {

	aTimeIntervals [3].to.setMonth ( 0 );
	aTimeIntervals [3].to.setFullYear ( todayEnd.getFullYear () + 1 );
}

else {
	aTimeIntervals [3].to.setMonth ( todayEnd.getMonth () + 1 );
}

//next month
if ( todayStart.getMonth () == 11 ) {

	aTimeIntervals [4].from.setMonth ( 0 );
	aTimeIntervals [4].from.setFullYear ( todayStart.getFullYear () + 1 );
}

else {
	aTimeIntervals [4].from.setMonth ( todayStart.getMonth () + 1 );
}

if ( todayEnd.getMonth () == 11 ) {

	aTimeIntervals [4].to.setMonth ( 1 );
	aTimeIntervals [4].to.setFullYear ( todayEnd.getFullYear () + 1 );
}

else {
	aTimeIntervals [4].to.setMonth ( todayEnd.getMonth () + 2 );
}

aTimeIntervals [5].to.setFullYear ( todayEnd.getFullYear () +1 );
aTimeIntervals [6].from.setFullYear ( todayStart.getFullYear () +1 );
aTimeIntervals [6].to.setFullYear ( todayEnd.getFullYear () +2 );

function updateCamPicture()
{
     var src = $('.webcamimg').attr('src')
     if (src)
     {
         var ts = new Date().getTime(); 
         $('.webcamimg').attr('src', src + '&' + ts);
         setTimeout(updateCamPicture, 1000);
     }   
}

//for use with polyline data
function stripslashes(str){
    str = str.replace(/\\'/g, '\'');
    str = str.replace(/\\"/g, '"');
    str = str.replace(/\\\\/g, '\\');
    str = str.replace(/\\0/g, '\0');
    return str;
}

function DEBUG(str){

    document.getElementById("footer_banners").innerHTML += str;
}

function update_event_delay(){
    
    inMap.showInEventsByType();
    var period = getPeriodValue();
	SetTime(period);
    inMap.hide_loading("#maploadoverlay");
	$("#work input, #poi input").attr("disabled", "");
    
}

function update_events(){
    show_loading("#map", "#maploadoverlay");
    window.setTimeout(update_event_delay, 20);
}

//FIXME: this is almost a duplicate of newload function, merge those please
function setCertainDay(mDay)
{
   if (GBrowserIsCompatible()) {
        //show_loading("#map", "#maploadoverlay");
        
        inMap = new inMaps(document.getElementById("map"));
        
        inMap.init();
        
        var sLocation = window.location.href;
        
        var EventPattern = /event_id=([0-9]+)/;
        var PeriodPattern = /period=([1-6]{1})/;
        var FirstTabPattern = /firsttab=1/;
        
        var aEventMatch = EventPattern.exec(sLocation);
        var aPeriodMatch = PeriodPattern.exec(sLocation);
        var aFirstTabMatch = FirstTabPattern.exec(sLocation);
        
        if (aEventMatch) {
            EventId = aEventMatch[1];
        }
 
        if (aFirstTabMatch) {
            isFirstTab = true;
        }
         
        var iMonth = mDay.getMonth() + 1;
        iMonth = (iMonth < 10) ? '0' + iMonth.toString() : iMonth;
        
        var iDay = mDay.getDate();
        iDay = (iDay < 10) ? '0' + iDay.toString() : iDay;
        
        var dTimer = new Date();
        inMap.getJsonInEvents(sBaseUrl + '/certaineventsjson.php?day=' + mDay.getFullYear() + '-'  + iMonth + '-' + iDay + '&' + dTimer.getTime());
        
        /*
        var oHeaviness = new inSelection('heaviness');
        var oTimePeriod = new inSelection('time_period');
        
        inMap.addSelection(oHeaviness);
        inMap.addSelection(oTimePeriod);
        */
        

        if (aPeriodMatch) {

            var period = aPeriodMatch[1];

            document.getElementById('period').selectedIndex = aPeriodMatch[1];

        }

        else {

            var period = getPeriodValue();

        }
        
        ogDate = mDay;
		SetTime(period);

    } 
}

//start the ball rolling

function getPeriodValue()
{
    return $('[@name="time_selection"]:checked').val();
}

function newload()
{
    if (GBrowserIsCompatible()) {
        //show_loading("#map", "#maploadoverlay");
        $(".poi").click(function (){update_events();});    
        inMap = new inMaps(document.getElementById("map"));
        
        inMap.init();
        
        var sLocation = window.location.href;
        
        var EventPattern = /event_id=([0-9]+)/;
        var PeriodPattern = /period=([1-6]{1})/;
        var FirstTabPattern = /firsttab=1/;
        
        var aEventMatch = EventPattern.exec(sLocation);
        var aPeriodMatch = PeriodPattern.exec(sLocation);
        var aFirstTabMatch = FirstTabPattern.exec(sLocation);
        
        if (aEventMatch) {
            EventId = aEventMatch[1];
        }
 
        if (aFirstTabMatch) {
            isFirstTab = true;
        }
         
      /*
	    var dTimer = new Date();
        inMap.getJsonInEvents(sBaseUrl + '/dynamic_map/eventsjson.php?11' + dTimer.getMilliseconds());
      */
        SiteUrlPattern 	= /wegwijsa2.nl/;
        //SiteUrlPattern 	= /wwa2/;
    	aSiteUrlMatch  = SiteUrlPattern.exec( sLocation );
        
        SiteUrlMapPagePattern = /verkeersinformatie/;
        aSiteUrlMapPageMatch  = SiteUrlMapPagePattern.exec( sLocation );
        
        SiteUrlMapPageEnglishPattern = /traffic-information/;
        aSiteUrlMapPageEnglishMatch = SiteUrlMapPageEnglishPattern.exec ( sLocation );
        
        Wwa2HomePage = false;
        
        if (aSiteUrlMatch)
        {
            Wwa2HomePage = true;
        }
        
        if (aSiteUrlMapPageMatch || aSiteUrlMapPageEnglishMatch || aSiteUrlMatch)
        {
	    geocoder = new GClientGeocoder();
			
          	 //inMap.GMap.setCenter( new GLatLng( 51.883273, 5.262451 ), 9 );	 
           	//centerlocation = "'s Hertogenbosch";
           	centerlocation = "Sint-Oedenrode";
	    	geocoder.getLatLng(centerlocation,function(point) {
			inMap.GMap.setCenter(point,10);
            });
        }
     
     
     
	   inMap.getJsonInEvents(sBaseUrl + '/dynamic_map/eventsjson.php');
        /*
        var oHeaviness = new inSelection('heaviness');
        var oTimePeriod = new inSelection('time_period');
        
        inMap.addSelection(oHeaviness);
        inMap.addSelection(oTimePeriod);
        */
        

        if (aPeriodMatch) {

            var period = aPeriodMatch[1];
            $('#time_selection' + period).attr("checked", true);
        }

        else {

            var period = getPeriodValue();

        }
        SetTime(period);
		$("#work input, #poi input").attr("disabled", "");
        //inMap.getJsonInDistricts(sBaseUrl + '/districtsjson.php?' + dTimer.getMilliseconds());
        
        //jams_functions.js function call
        updateData();
        //trains function 
        initTrains();
    }
    
}


function load(){
    $("#work input, #poi input").attr("disabled", "1");
	window.setTimeout(newload, 20 );
}

function inMaps(mapElement){
    this.GMap = null;
    this.inMapElement = mapElement;
    this.inList = null;
    this.inEvents = [];
    this.inPoi = [];
    this.inSelection = {};
    this.inOpenWindow = null;
    this.markerBatch = null;
    this.markerManager = null;
    this.firstRun = true;
 }  
 
inMaps.prototype.init = function(SCROLL){
        
	if (this.inMapElement == null) {
            alert('The Map could not be initialized. Map element is not specified!');
            return;
        }
        
        this.GMap = new GMap2(this.inMapElement);
        
        //globalize the object
        gMap = this.GMap;
        
        this.GMap.addControl(new GLargeMapControl());
        this.GMap.addControl(new GScaleControl());
		this.GMap.addControl(new GMapTypeControl());


        this.GMap.setCenter( new GLatLng( 52.094695, 5.123062 ), 12 );
        this.GMap.getCurrentMapType().getMinimumResolution = function (){return 7;}
        this.markerManager = new MarkerManager(this.GMap);
        this.markerBatch = [];
        
        if (SCROLL == true) {
            if (this.inMapElement.addEventListener) {
                addEvent(this.inMapElement, "DOMMouseScroll", scrollEvent);
            }
            else {
                addEvent(this.inMapElement, "mousewheel", scrollEvent);
            }
        }
        
       this.GMap.getInfoWindow();
       this.GMap.getInfoWindow().show();
    }
    
inMaps.prototype.getJsonInDistricts = function(sJsonUrl){
    
        sendRequest(sJsonUrl, this.parseJsonInDistricts, null, null, this);
    }
    
inMaps.prototype.parseJsonInDistricts = function(req, oInMap){
    
        var jDistricts = eval('(' + req.responseText + ')');

	
	for ( i = 0; i < jDistricts.length; i ++ ) {
        
            jd = jDistricts[i];
            
            var oD = new inDistrict();
            oD.polygon_id = jd.polygon_id;
            oD.parent_id = jd.parent_id;
            oD.polygon_name = jd.polygon_name;
            oD.polydata = jd.polydata;
            oD.parentDistrict = jd.parentDistrict;
            Districts.push(oD);
        }
        
        SetDistrict(true);
    }
    
inMaps.prototype.getJsonInEvents = function(sJsonUrl){
        sendRequest(sJsonUrl, this.parseJsonInEvents, null, null, this);
    }
 
 
 
inMaps.prototype.parseInJsonPeriods = function(aPeriods, aretPeriods){
    
        iPeriodsLength = aPeriods.length;
        
        for (var i = 0; i < iPeriodsLength; i++) {
        
            aretPeriods[i] = new inPeriods();

            aretPeriods[i].id                            = aPeriods[i].id;
            aretPeriods[i].event_id                      = aPeriods[i].event_id;
            aretPeriods[i].start_datm                    = aPeriods[i].start_datm;
            aretPeriods[i].start_tijd                    = aPeriods[i].start_tijd;
            aretPeriods[i].end_datm                      = aPeriods[i].end_datm;
            aretPeriods[i].end_tijd                      = aPeriods[i].end_tijd;
            aretPeriods[i].type_hinder                   = aPeriods[i].type_hinder;
            aretPeriods[i].oorzaak_hinder                = aPeriods[i].oorzaak_hinder;
            aretPeriods[i].oude_omleiding                = aPeriods[i].oude_omleiding;
            aretPeriods[i].afgesloten                    = aPeriods[i].afgesloten;
            aretPeriods[i].oude_tijd_afsluiting          = aPeriods[i].oude_tijd_afsluiting;
            aretPeriods[i].oude_tijd_afsluiting_anders   = aPeriods[i].oude_tijd_afsluiting_anders;
            aretPeriods[i].num	                         = aPeriods[i].num;
        }
    }

inMaps.prototype.parseInJsonPoi = function(poi, retPoi){
    iPoiLength = poi.length;
    for (var i = 0; i < iPoiLength; i++) {
       retPoi[i] = new inPoi(); 
       retPoi[i].category_poi_id = poi[i].category_poi_id;
       retPoi[i].event_id = poi[i].event_id;
       retPoi[i].description = poi[i].description;
       retPoi[i].code = poi[i].code;
       retPoi[i].shape_id = poi[i].shape_id;
    }
}

 
inMaps.prototype.parseInJsonDetours = function(Detours, retDetours){
    
        fDetourLength = Detours.length;
        
        for (var i = 0; i < fDetourLength; i++) {
        
            retDetours[i] = new inDetour();

            retDetours[i].detour_id         = Detours[i].detour_id;
            retDetours[i].name              = Detours[i].name;
            retDetours[i].color             = Detours[i].color;
            retDetours[i].direction         = Detours[i].direction;
            retDetours[i].description       = Detours[i].description;
            if (Detours[i].encodedDetour)
            {
                if (Detours[i].encodedDetour.Points)
                {
                    retDetours[i].points            = Detours[i].encodedDetour.Points;
                }
                
                if (Detours[i].encodedDetour.Levels)
                {
                    retDetours[i].levels            = Detours[i].encodedDetour.Levels;
                }
                
            }
            retDetours[i].event_periods_num = Detours[i].event_periods_num;
            retDetours[i].num	            = Detours[i].num;

        }
    }
    
inMaps.prototype.parseJsonInEvents = function(req, oInMap){
        
	var aJson = eval('(' + req.responseText + ')');
        fLength = aJson.length;
        
        if (fLength > 0) {
			
	        var i = fLength - 1;
            while ( i >=  0 ) {
                var oEvent = new inEvent();
                
                j = aEventFields.length - 1;
                
        		while (j >= 0 ) {
                    oEvent[aEventFields[j]] = aJson[i][aEventFields[j]]
		            j--;
                }
                
                if (aJson[i]['Detours']) {
                
                    oEvent.detours = new Array ();
		            
                    oInMap.parseInJsonDetours(aJson[i]['Detours'], oEvent.detours);
                }
                
                if (aJson[i]['Periods']) {
                
                    oEvent.periods = new Array ();
                    oInMap.parseInJsonPeriods(aJson[i]['Periods'], oEvent.periods);
                }
                
                if (aJson[i]['poi'])
                {
                    oEvent.poi = new Array();
                    oInMap.parseInJsonPoi(aJson[i]['poi'], oEvent.poi);
                }
                
                if (aJson[i]['encodedPoints'])
                {
                    oEvent.encodedPoints = new inEncodedPoints();
                    oEvent.encodedPoints.Points = aJson[i]['encodedPoints']['Points'];
                    oEvent.encodedPoints.Levels = aJson[i]['encodedPoints']['Levels'];
                }

                oEvent.init();
                oEvent.infoTabs = InfoWindowTabs(oEvent);
                oEvent.inMap = this;
                
                oInMap.addInEvent(oEvent);
               	i--; 
            }
            
        }
        else {
        
            oEvent = new inEvent();
            oEvent.point = oInMap.GMap.getCenter();
            oEvent.icon = oEvent.getIcon(3);
            oEvent.marker = new GMarker(oEvent.point, oEvent.icon);
            oEvent.project_name = 'Werkzaamheden en evenementen momenteel niet bekend, informatie volgt.';
            if (oEvent.listelement)
            {
                oEvent.listelement.className = 'event-3';    
            }
            oEvent.inMap = this;
            
            oEvent.marker.openInfoWindowHtml(oEvent.project_name);
            oEvent.addMarker(oInMap.GMap);
            oEvent.setBehaviours();
            
            oInMap.addInEvent(oEvent);
            
        }
        
        oInMap.showInEventsByType(); 
        inMap.hide_loading("#maploadoverlay");
    }
    
    
    
inMaps.prototype.hide_loading = function(id){
        $(id).css("display", "none");
    }
    
    
inMaps.prototype.addInEvent = function(oEvent){
        this.inEvents.push(oEvent);
    }
    
inMaps.prototype.addSelection = function(oSelection){
        oSelection.inMap = this;
        this.inSelection[oSelection.type] = oSelection;
    }
    
inMaps.prototype.showInEventsByType = function(){
    
        function inSelection(heaviness, type){
            if (is_home() && (heaviness == 1 || heaviness == 2) ) {
                return true;
            }
            else 
                if (!is_home()) {
                
                    heaviness = (type == 10) ? heaviness : parseInt(heaviness) + 4;
                    
                    if (heaviness && parseInt(heaviness) > 0 && parseInt(heaviness) < 9) 
                        return gHeavinesses[heaviness - 1];
                    else 
                        return false;
                }
        }
       	 
        function inTime(event_period){
            if (event_period)
                {
                var i = event_period.length - 1;
                if ( is_home () )
                {
                    while (i >= 0) {
                        if (event_period[i] == 3)
                        {
                            return true;
                        }
                        i--;
                    }    
                }
                else
                {
                while (i >= 0) {
    	            if ($("#time_selection"+event_period[i]+":checked").length)
           {
               return true;
           }
                    i--;
                }    
                    
                }
            }
                
            return false;
        }

        
        function inPoiSelection ( poi_code, shape ) {
            if ( is_home () ) return false;
            
           return $("#poi" + poi_code + shape + ":checked").length;
            //document.getElementById("poi" + poi_code + shape).checked;
			return false;
		}
        
	
        this.markerBatch = [];
        var oShowEvent = null;
		
	this.markerManager.clearMarkers();
    
    for (var j=0;j<8;j++)
    {
        gHeavinesses[j] = $("#d" + (j+1) + ":checked").length;    
    }
    
	filteredEvents = this.inEvents.filter(function(element, index, array){
		element.onMap = false;
		 if (element.id == EventId){
		 	return true;
		 } 
		//return ( (!element.isPoi() && inSelection(element.heaviness, element.type) && inTime(element.project_start, element.project_end) ) || (element.isPoi() && inPoiSelection(element.poi[0].code, element.shapetype)) );
        return ( (!element.isPoi() && inSelection(element.heaviness, element.type) && inTime(element.event_period)  ) || (element.isPoi() && inPoiSelection(element.poi[0].code, element.shapetype)) );
      
	});

	
    

	j = filteredEvents.length-1;
	var oE = null;
		
        while (j >= 0) {
            oE = filteredEvents[j];
            
            if (!oE.onMap) {
                if (!oE.initialized) {
                
                    oE.addMarker(this);
                    oE.setBehaviours();
                    
                    oE.initialized = true;
                }

                this.markerBatch.push(oE.marker);
                oE.onMap = true;    
            }
            
            if (oE.id == EventId) {
                oShowEvent = oE;
                EventId = null;
            }
            j--;
        }

        this.markerManager.addMarkers(this.markerBatch, 1);
        this.markerManager.refresh();
        
        if (oShowEvent != null) {
        	oShowEvent.showInfoWindow();
        }
    }
    
    
//end of inMaps

function inPoi(){
    this.category_poi_id;
    this.event_id;
    this.description;
    this.code;
    this.shape_id;
}

function inDetour(){

    this.detour_id;
    this.name;
    this.color;
    this.direction;
    this.description;
    this.points;
    this.levels;
    this.event_periods_num;
    this.num;
    
    this.init = function(data){
    
    }
    
    this.setProperty = function(name, value){
    
        this[name] = value;
        
    }
    
}

function inEncodedPoints() {
    this.Points;
    this.Levels;
}

function inPeriods(){

    this.id;
    this.event_id;
    this.start_datm;
    this.start_tijd;
    this.end_datm;
    this.end_tijd;
    this.type_hinder;
    this.oorzaak_hinder;
    this.oude_omleiding;
    this.afgesloten;
    this.oude_tijd_afsluiting;
    this.oude_tijd_afsluiting_anders;
    this.num;
   
}


function testalert()
{
    //alert('We are here');
}

function inEvent(){
    this.id;
    this.point;
    this.icon;
    this.iconType;
    this.marker;
    this.inMap;
    this.onMap = false;
    this.inList = false;
    this.ListItemElement = null;
    this.ListItemElementLink = null;
    this.infoTabs = null;
    this.project_name = '';
    this.project_number = '';
    this.project_contents = '';
    this.project_start = '';
    this.project_end = '';
    this.website = '';
    this.location = '';
    this.heaviness = '';
    this.traffic_diversion = '';
    this.description = '';
    this.time_period = '';
    this.longitude = '';
    this.latitude = '';
    this.direction = '';
    this.source = '';
    this.type = '';
    this.type_report = '';
    this.time_period_humanise = '';
    this.communication ='';
    this.shapetype = '';
    
    this.oInfoWindowOptions = {
        maxWidth: 300,
        onOpenFn: testalert()
    };

    this.detours;
    this.periods;
    this.initialized = false;
    this.MainTabName = '';
    this.MainTabContent = '';
    this.MainSubName = '';
    this.MainSubContent = '';
    this.poi;
    this.encodedPoints;
    
}  

inEvent.prototype.showInfoWindow = function(){
        
        if(is_home())
        {
        	//programm link to the map page (reisinfo) on which the inforwindow will open - 
        	//same fuctionality as on haalmeeruitdeweg.nl homepage
        	//alert("home");
            if (Wwa2HomePage) 
            {
                window.location = "verkeersinformatie?firsttab=1&period=0&event_id=" + this.id;        
            }
            else
            {
                window.location = "reisinfo?firsttab=1&period=0&event_id=" + this.id;    
            }
        }
        else
        {
			if (this.infoTabs != null) 
			{
				this.inMap.inOpenWindow = this.id;
				this.marker.openInfoWindowTabsHtml(this.infoTabs, this.oInfoWindowOptions);
			}
			else 
			{
				this.marker.openInfoWindowHtml('Geen informatie beschikbaar' + e.name + e.message);
			}
			
		
			if (this.detours != null && this.detours != undefined && this.detours.length > 0) 
			{
				if (this.source == 'Falk' && this.detours[0].name == sTextDtour)
				{
				   
				   createTextDiversionMap(this); 
				}
				else
				{
					createDiversionMap(this );                
				}
			}
			else if (this.periods != null && this.periods != undefined && this.periods.length > 0)
			{
				createOldDiversionMap(this);
			}
        }
    }
    
inEvent.prototype.init = function(){

    this.point = new GLatLng(parseFloat(this.latitude), parseFloat(this.longitude));
    this.iconType = this.iconType(parseInt(this.heaviness), parseInt(this.type));
    if (this.isPoi()) 
    {
        this.icon = (this.poi) ? this.getPoiIcon(this.poi[0].code, this.poi[0].shape_id) : this.getIcon(this.iconType);
    }else{
        this.icon = this.getIcon(this.iconType);
    }
    this.marker = new GMarker(this.point, this.icon);
    }


inEvent.prototype.setBehaviours = function(){
        this.marker.parent = this;
        
        GEvent.addListener(this.marker, "click", function(){
            this.tooltip.hide();
            this.parent.showInfoWindow();
        });
        
        GEvent.addListener(this.marker, 'mouseover', function(){
            this.tooltip.show();
        });
        GEvent.addListener(this.marker, 'mouseout', function(){
            this.tooltip.hide();
        });
    }
    
inEvent.prototype.isPoi = function(){
    return (this.poi) ? true : false;
    }
    
inEvent.prototype.addMarker = function(oMap){
        
        //var tooltiptext = (this.isPoi()) ? this.project_name : this.project_contents;
        var tooltiptext = this.project_name;
        var tooltip = new Tooltip(this.marker, tooltiptext, this.project_start, this.project_end, this.heaviness, this.direction, this.time_period_humanise,4, this.isPoi());            
        this.marker.tooltip = tooltip;
        oMap.GMap.addOverlay(tooltip);
        
}
    
    
inEvent.prototype.iconType = function(heaviness, type){
        if (type == 10) {
            return heaviness;
        }
        else {
            return heaviness + 4;
        }
    }
    
inEvent.prototype.getIcon = function(type){
        
    /*    
	if ( BrowserDetect.browser == "Explorer" ) {
		
		iconExt = ".gif";
	}
	else {
		iconExt = ".png";
	}
	*/
   var iconExt = ".png";
   var iconPath = '/dynamic_map/images/';
	switch (type) {
            case 1:
                var imgIcon = 'icons-hinder-ernstig';
                var imgShadow = 'images/icons-alert-schaduw.png';
                break;
            case 2:
                var imgIcon = 'icons-hinder-groot';
                var imgShadow = 'images/icons-alert-schaduw.png';
                break;
            case 3:
            default:
                var imgIcon = 'icons-hinder-middel';
                var imgShadow = 'images/icons-alert-schaduw.png';
                break;
            case 4:
                var imgIcon = 'icons-hinder-licht';
                var imgShadow = 'images/icons-alert-schaduw.png';
                break;
            case 5:
                var imgIcon = 'icons-evenement-ernstig';
                var imgShadow = 'images/icons-alert-schaduw-eveneme.png';
                break;
            case 6:
                var imgIcon = 'icons-evenement-groot';
                var imgShadow = 'images/icons-alert-schaduw-eveneme.png';
                break;
            case 7:
                var imgIcon = 'icons-evenement-matig';
                var imgShadow = 'images/icons-alert-schaduw-eveneme.png';
                break;
            case 8:
                var imgIcon = 'icons-evenement-licht';
                var imgShadow = 'images/icons-alert-schaduw-eveneme.png';
                break;
        }
        
        var icon = new GIcon(G_DEFAULT_ICON);
        icon.image =iconPath +imgIcon + iconExt;
    /*    
	if ( BrowserDetect.browser == "Explorer" && BrowserDetect.version == "6.0" ) {
		icon.shadow = null;
        	icon.shadowSize = null;
	}

	else {
		icon.shadow = imgShadow;
        	icon.shadowSize = new GSize(49, 33);
	}
	*/
        icon.shadow = null;
        icon.shadowSize = null;
        icon.iconSize = new GSize(29, 33);
        icon.iconAnchor = new GPoint(14, 33);
        icon.infoWindowAnchor = new GPoint(30, 5);
        
        return icon;
    }
    
inEvent.prototype.getPoiIcon = function ( type, shape ) {
		
		//var iconPath = 'images/icons-poi/';
        var iconPath = '/sites/all/themes/zen/utrechtbereikbaar/images/icons-poi/';
		
		switch ( parseInt ( type ) ) {
			
			case 10: 	
				if ( parseInt(shape) == 2 ) var imgIcon = 'poi-11-fietsenstalling.gif';		
			 	if ( parseInt(shape) == 4 ) var imgIcon = 'poi-10-ov-lijnen.gif';
				if ( parseInt(shape) == 5 ) var imgIcon = 'poi-2-milieu.gif';		
			break;

			case 11:var imgIcon = 'poi-3-pr.gif';			break;
			case 12:var imgIcon = 'poi-4-pr-ub.gif';		break;
			case 13:var imgIcon = 'poi-5-greenwheels.gif';		break;
			case 14:var imgIcon = 'poi-6-carpool.gif';		break;
			case 16:var imgIcon = 'poi-7-telewerk.gif';		break;
			case 17:var imgIcon = 'poi-8-parkeergarage.gif';	break;
			case 22:var imgIcon = 'poi-9-bushalte.gif';		break;
			case 19:var imgIcon = 'poi-1-fiets.gif';	break;
			case 20:var imgIcon = 'poi-12-treinstation.gif';	break;
			case 21:var imgIcon = 'poi-13-webcam.gif';		break;
			case 23:var imgIcon = 'poi-15-distributie.gif';		break;
			case 24:var imgIcon = 'poi-16-vracht-opstelpunt.gif';	break;
			case 25:var imgIcon = 'poi-19-boot.gif';		break;
            case 28:var imgIcon = 'poi-14-ovnetwerk.gif';		break;
            
		}
		
		var icon 			= new GIcon();
		icon.image 			= iconPath+imgIcon;
		icon.iconSize 			= new GSize( 30, 31 );
		
		icon.iconAnchor 		= new GPoint( 14, 33 );
		icon.infoWindowAnchor 	= new GPoint( 30, 5 );
		
		return icon;

	}
//end of inEvent

function SetDistrict(upper_regions){

    if (document.getElementById('district')) {
    
        var dSelect = document.getElementById('district');
        dSelect.length = 0;

	//add first option
	var Option = document.createElement( 'OPTION' );
	Option.value = "-2";
	Option.appendChild(document.createTextNode( 'Gemeente' ));
       	dSelect.appendChild (Option);
	
        //parent regions
        var rSelect = document.getElementById('upper_region');
        
        for (var i = 0; i < Districts.length; i++) {
            var Option = document.createElement('OPTION');
            Option.value = Districts[i].polygon_id;
            Option.appendChild(document.createTextNode(Districts[i].polygon_name));
             
            if ((rSelect[rSelect.selectedIndex].value == -1 && Districts[i].parent_id > 0) ||
            (rSelect[rSelect.selectedIndex].value == Districts[i].parent_id)) {
                dSelect.appendChild(Option);
            }
            
            else 
                if (Districts[i].parent_id == 0 && upper_regions) {
                    rSelect.appendChild(Option);
                }
        }
        
        dSelect.onchange = rSelect.onchange = function(){
        
            
            //get the right district
            
            for (var i = 0; i < Districts.length; i++) {
                if (Districts[i].polygon_id == this.value) 
                    break;
            }
            
            //fixme: bounding box around polygon
            var lines = [{
                color: "#FF000",
                weight: 5,
                opacity: 0.3,
                points: stripslashes(Districts[i].polydata.Points),
                levels: Districts[i].polydata.Levels,
                zoomFactor: 32,
                numLevels: 4
            }];
            poly = new GPolygon.fromEncoded({
                polylines: lines,
                fill: true,
                color: "#030303",
                opacity: 0.3,
                outline: true
            });
            
            bounds = poly.getBounds();
            
            inMap.GMap.setZoom(inMap.GMap.getBoundsZoomLevel(bounds));
            inMap.GMap.setCenter(bounds.getCenter());
            
            //we only need the overlay for zooming to the right point on the map
            // IE houd de focus op de select en als je scrollt, scroll je door de 
            // lijst heen wat niet wenselijk is dus de focus wordt op een ander
            // veld gelegd
            //document.getElementById('d1').focus();
            
            /*
            if (this.name = "upper_region") {
                SetDistrict(false);
            }
            */
		
            update_events();
        }
    }
    else {
        alert('Geen ditrict element in de code');
    }
}

function SetTime(period){
    var oDate = new Date(ogDate);
    var oDateFrom = new Date(ogDate);
    var oDateTo = new Date(ogDate);
    
    period = period || 0;
    
    switch (parseInt(period)) {
    
        case 0:
        default:
            
            // this week
            oDateFrom = oDate;
            oDateTo.setDate(oDate.getDate() + 1);
            
            break;
        case 1:
            
            // this week
            oDateFrom = oDate;
            oDateTo.setDate(oDate.getDate() + 7);
            break;
        case 2:
            // next week
            oDateFrom.setDate(oDate.getDate() + 7);
            oDateTo.setDate(oDate.getDate() + 14);
            break;
        case 3:
            // this month
            oDateFrom = oDate;
            oDateTo.setMonth(oDate.getMonth() + 1);
            break;
        case 4:
            // next month
            oDateFrom.setMonth(oDate.getMonth() + 1);
            oDateTo.setMonth(oDate.getMonth() + 2);
            break;
        case 5:
            // this year
            oDateFrom = oDate;
            oDateTo.setYear(takeYear(oDate) + 1);
            break;
        case 6:
            // next year
            oDateFrom.setYear(takeYear(oDate) + 1);
            oDateTo.setYear(takeYear(oDate) + 2);
            break;
    }
    
   
    /*
    var HeaderElement = document.getElementById('map_header');
    var DateElement = HeaderElement.getElementsByTagName('em')[0];
    
    // normaal is het van "datum" tot "datum"
    // maar met deze bewerking krijg je van "datum" tot en met "datum"
    oDateTo.setDate(oDateTo.getDate() - 1);
    
    DateElement.innerHTML = dateFormat(oDateFrom, oDateTo);
    */
    
}

function dateFormat(fromDate, toDate){
    
    function humanize_date ( D ) {
	    return aDays[D.getDay()] + ' ' + D.getDate() + ' ' + aMonths[D.getMonth()] + ' ' + takeYear(D);
    }
    
    var fromString = humanize_date ( fromDate );
    var toString = humanize_date ( toDate );
    if ( fromString == toString ) {
	     return  fromString;//"Vandaag";
    }
    else { 
	    return "van "+fromString + " tot en met " + toString;
	}
}

function nextDate(date, days){
    var newDate = new Date();
    newDate.setDate(date.getDate() + days);
    return newDate;
}

function takeYear(theDate){
    var x = theDate.getYear();
    var y = x % 100;
    y += (y < 38) ? 2000 : 1900;
    return y;
}

function truncateStr(website, length)
{
    return (website.length > length) ? website.substring(0, length) + "..." : website;
}

function InfoWindowTabs(oEvent){

    var pattern = /^(www\.)?[a-zA-Z0-9\.]+\.[a-z]{2,5}(\/.*)?/i;
    var hpattern = /^http/;
    var multlinkpattern = /((https?|ftp):\/\/\S+[^\s.,>)\];'\"!?])/g;
    //var multlinkpattern = /((https?|ftp):\/\/[^\s,]+)/ig; 
    
    /*
    Lijn C Oss-Den Bosch: P+R Nuland, Den Bosch
Shuttlelijn: http://www.wegwijsa2.nl/files/uploads/oss.pdf

Lijn C Oss- Den Bosch: Heesch
Shuttlelijn: http://www.wegwijsa2.nl/files/uploads/oss.pdf
    */
    var website = '';
    var description = '';
    var trunclength = 40;
    var webcam_pattern = /http:\/\/images\.fileindex\.nl(.+)\.jpe?g/;
    
    
    if (webcam_pattern.test(oEvent.website)) {
        website = '<img src="' + oEvent.website + '" height="288" weight="352" />';
    }
    else 
    {
        if (oEvent.website.indexOf("camera.html") > 0)
        {
            website = '<iframe src="' + oEvent.website + '" frameborder="0" height="288" weight="397" ></iframe>';
        }
        else
        {
            if (oEvent.website.indexOf("</a>") > 0 )
            {
                website = '<div class="website">Meer informatie: ' + oEvent.website.replace("<a", "<a target='blank_' ");                
            }
            else
            {
        if (multlinkpattern.test(oEvent.website)) {
            oEvent.website = oEvent.website.replace(multlinkpattern,function(sMatch) {
                        return "<a href=\"" + sMatch + "\"  target=\"_blank\">" + truncateStr(sMatch, trunclength) + "</a>"; 
                   }); 
                    website = '<p class="website">Meer informatie: ' + oEvent.website + '</p>';
        }
        else {
            if (pattern.test(oEvent.website)) {
                        website = '<div class="website">Meer informatie: <a href="http://' + oEvent.website + '" target="_blank">' + truncateStr(oEvent.website, trunclength) + '</a>';
                
            }
            else
            {
                if (oEvent.website != '')
                {
                            website = '<div class="website">Meer informatie: ' + oEvent.website;                    
                    
                }
            }
            
            if (oEvent.website != '')
            {
                if (multlinkpattern.test(oEvent.communication))
                {
                   oEvent.communication = oEvent.communication.replace(multlinkpattern,function(sMatch) {
                        return "<a href=\"" + sMatch + "\"  target=\"_blank\">" + truncateStr(sMatch, trunclength) + "</a>"; 
                   });  
                   //oEvent.communication = '<a href="' + oEvent.communication + '" target="_blank">' + truncateStr(oEvent.communication, trunclength) + '</a>';
                }
                
                website += ( (oEvent.communication) ? '<div class="communication">' + oEvent.communication : '</div>' ) +  '</div>';                            
            }
        }
            }
                
            
        }
    }
        
    
    if (oEvent.traffic_diversion == '' ||
    oEvent.traffic_diversion == 'Niet van toepassing' ||
    oEvent.traffic_diversion == 'geen') {
        diversion = 'Geen informatie beschikbaar.';
    }
    else {
        diversion = oEvent.traffic_diversion;
    }
    
    if (oEvent.description == '' ||
    oEvent.description == 'Niet van toepassing' ||
    oEvent.description == 'geen' ||
    !oEvent.description) {
        description = '';
    }
    else {
        //Capitalize already done in sql query
        description = '<strong>Omschrijving verkeerssituatie:</strong><br />' + oEvent.description;

    }
    
    var oProjectStart = new Date();
    var oProjectEnd = new Date();
    
    oProjectStart.setTime(Date.parse(oEvent.project_start));
    oProjectEnd.setTime(Date.parse(oEvent.project_end));
    
    var periode = dateFormat(oProjectStart, oProjectEnd);
    
    //some exceptions
    if ( oEvent.source == 'Via' && oEvent.periods.length &&  oEvent.periods[0].oorzaak_hinder ) {
	oEvent.project_contents = oEvent.periods[0].oorzaak_hinder;
    }

    var dir = "";
    if ( oEvent.direction != "Niet van toepassing" &&  oEvent.direction != "not available") 
	    	dir = ' (ri. '  + oEvent.direction + ')';
	
    if (oEvent.isPoi())
    {
       
	   var  locat =  '';
	   if(oEvent.location != '' && oEvent.location != null )
	   	locat = '<p>' + oEvent.location + '</p>';
		
		if(description != '')
        {
		 description = oEvent.description;
        }
		 
        /*
        if (multlinkpattern.test(description)) {
            description = description.replace(multlinkpattern,function(sMatch) {
                        return "<a href=\"" + sMatch + "\"  target=\"_blank\">" + truncateStr(sMatch, trunclength) + "</a>"; 
                   }); 
        }
        */
        

	    var MainTabHTML = '<div >' + '<h4>' + oEvent.project_name + '</h4>'
						+ '<p>' + ((oEvent.project_contents)? oEvent.project_contents : '') + '</p>'	+ description +   locat + website + '</div>';
        //console.debug(description);
                        
    }
    else
    {
        var MainTabHTML = '<div class="mappopup"><h4>' + ((oEvent.project_number != '') ? oEvent.project_number + ',' : '') + ' ' + oEvent.project_name + dir + '</h4>' +
        ((oEvent.project_contents != '' && oEvent.project_contents != null) ? "<p>" + oEvent.project_contents.replace(/\\n/g, ' ') + "</p>" : '')
        + ((oEvent.location != '' && oEvent.location != null) ? '<p>' + oEvent.location + '</p>' : '')
        + ((oEvent.road_type != '' && oEvent.road_type != null) ? '<p>' + oEvent.road_type + '</p>' : '') +
          '<p class="periode">Periode: ' +
        periode + oEvent.time_period_humanise  + 
        '</p>' +
        //'<p>' + getLEventTypeLabel (oEvent.heaviness) + '</p>' +  
        website +
        '</div>';
        
        
    }
    
    
    //FIXME: only if info is available, incorporate in if above
    var desc = "&nbsp;";
        if (typeof(oEvent.detours[0]) != 'undefined' && oEvent.detours[0].description != ''){
			desc = oEvent.detours[0].description;
		}	
	if (oEvent.source == 'Falk' && typeof(oEvent.detours[0]) != 'undefined' && oEvent.detours[0].description != '' && oEvent.detours[0].name == sTextDtour)
	{
	   var SubTabHTML = '<div id="detourinfo">'+getTextDetourHtml(oEvent.detours[0].description)+'</div>';
	}
	else
	{			
	    var SubTabHTML = '<div id="minimapwrapper">' +
	    '<div id="legend">&nbsp;</div>' +
	    '<div id="miniMap">&nbsp;</div>' +
	    '<div class="clear"></div>' +
	    '</div>' +
	    '<div id="detourinfo">'+desc+'</div>';
    }

    
    this.MainTabName = MainTabName;
    this.MainTabContent = MainTabHTML;
    this.MainSubName = SubTabName;
    this.MainSubContent = SubTabHTML;

    if (oEvent.detours.length > 0 || oEvent.periods.length) {
			return [new GInfoWindowTab(MainTabName, MainTabHTML), new GInfoWindowTab(SubTabName, SubTabHTML)];
    }
    else {
    
        return [new GInfoWindowTab(MainTabName, MainTabHTML)];
    }
}

function removeStuff(id)
{
  	if ( el = document.getElementById ( id ) ) {
		el.innerHTML = "";
		el.removeAttribute ( "id" );
		el = undefined;
	}

}

function createOldDiversionMap(oEvent)
{
    
    	removeStuff('minimapwrapper');
	cont = document.getElementById ( 'detourinfo' );


	
	//old events only have one period
    if (oEvent.periods[0].oude_omleiding)
    {
        cont.innerHTML = oEvent.periods[0].oude_omleiding + "<br /><br />";        
        if (oEvent.periods[0].type_hinder)
        {
            cont.innerHTML += getTextDetourHtml(oEvent.periods[0].type_hinder);
        }
    }
    else
    {
        if (oEvent.periods[0].type_hinder)
        {
            cont.innerHTML = getTextDetourHtml(oEvent.periods[0].type_hinder);
        }
    }
}

function getTextDetourHtml(text)
{
    return "<b>Omschrijving verkeerssituatie:</b><br/><br />" + text;
}

function createTextDiversionMap(oEvent)
{
    removeStuff('minimapwrapper');
    
	cont = document.getElementById ( 'detourinfo' );
    if (typeof(oEvent.detours[0].description) != 'undefined' && cont != null)
    {
        cont.innerHTML = getTextDetourHtml(oEvent.detours[0].description);    
    }
	if(document.getElementById('legend'))
	{
		if(document.getElementById('legend').innerHTML = '&nbsp;')
			document.getElementById('legend').style.display = 'none';
	}
		
}

function createDiversionMap(oEvent){


    oDetour = oEvent.detours;
    oPeriods = oEvent.periods;

    cont = document.getElementById("miniMap");
    if (!cont)
    {
        oEvent.marker.closeInfoWindow();
    }
    
    if (cont) {
        cont.innerHTML = "";
        cont.style.height = "160px";
        cont.style.width = "365px";
        
        minimap = new GMap2(cont);
        
        //set center FIRST !!!!
        minimap.setCenter(oEvent.point, 9);
        minimap.addControl(new GSmallZoomControl());
        
        var legend = "<ul id='periods'>";
        var detourinfodiv = '#detourinfo';
        var bounds = undefined;
        
        aGEvent = oEvent.point;
        minimap.addOverlay (new GMarker(oEvent.point, oEvent.icon));
        
	if (oEvent.source == 'Via')
        {
            iPeriodLength = oPeriods.length;
            aGPeriods = new Array();
            aOverlays = new Array();
            aDiversionsData = new Array();
            
            for (var j = 0; j < iPeriodLength; j++) {
               legend += "<li><a onclick=\"showDiversions('#detours" + j + "', this,  '" + detourinfodiv + "', "+ j +");\" href=\"javascript:void(0)\" class=\"plus_bg\">Fase " + j + "</a>";

               aGPeriods[j] = oPeriods[j];
               iDetourLength = oDetour.length;
               iDeourNum = 0;           
               legend += "<ul id=\"detours" + j + "\" class=\"detours\" style=\"display: none\">";

               for (var i = 0; i < iDetourLength; i++) {
                   
                    if (oDetour[i].event_periods_num == oPeriods[j].num) {
                        iDeourNum++;
                        var overlay = new GPolyline.fromEncoded({
                                            color: colors[(i % colors.length)],
                                            weight: 5,
                                            points: stripslashes(oDetour[i].points),
                                            levels: oDetour[i].levels,
                                            zoomFactor: 32,
                                            numLevels: 4
                                        });
                        aOverlays[i] = overlay;
                        
			aDiversionsData[i] = oDetour[i];
                        legend += "<li><a href=\"javascript:void(0)\"  onclick=\"chngDiversion(" + i + ", '" + detourinfodiv + "', this, " + j +");\">Oml. " + iDeourNum + "</a></li>";
                    }       
    
               }
               legend += "</ul>";           
               legend += "</li>";
            }            
        }
        else if (oEvent.source == 'Falk')
        {
            var iNumber = 1;
            for (var i = 0; i < oDetour.length; i++) {
                if (oDetour[i].points) {
                    var overlay = new GPolyline.fromEncoded({
                        color: colors[(i % colors.length)],
                        weight: 5,
                        points: stripslashes(oDetour[i].points),
                        levels: oDetour[i].levels,
                        zoomFactor: 32,
                        numLevels: 4
                    });
                    
                    aOverlays[i] = overlay;
                    //a bit dirty
                    if (bounds == undefined) 
                        bounds = overlay.getBounds();
                    if (i == 0) {
                        minimap.addOverlay(overlay);
                        $(detourinfodiv).html("<div>" + oDetour[i].name + "</div>");
                        if (oDetour[i].description)
                        {
                            $("<div><strong>Omleiding:</strong>" + oDetour[i].description + "</div>").appendTo(detourinfodiv);
                        }
                    }
                    
                    aDiversionsData[i] = oDetour[i];
                    
                    legend += "<li style=\"color:" + colors[(i % colors.length)] + "\">";
                    legend += "<a " + ((i == 0) ? "class=\"sel\"" : "") + " href=\"#\" onclick=\"chngFalkDiversion(" + i + ", '" + detourinfodiv + "', this )\"> Oml. " + iNumber + "</a>";
                    legend += "</li>";
                    iNumber++;
                }
            }    
        }

        
        if (bounds)
        {
            minimap.setZoom(minimap.getBoundsZoomLevel(bounds));
            minimap.setCenter(bounds.getCenter());
        }
        
        legend += "</ul>";
        
        document.getElementById("legend").innerHTML = legend;
        
        var CopyrightDiv = cont.firstChild.nextSibling;
        var CopyrightImg = cont.firstChild.nextSibling.nextSibling;
        CopyrightDiv.style.display = "none";
        CopyrightImg.style.display = "none";
        
    
    }
}


function getPeriodTerm(period)
{
    return dateFormat( new Date(Date.parse(period.start_datm)),new Date(Date.parse(period.end_datm)));
}

function hideDetours()
{
    l = aOverlays.length;
    for (var j = 0; j < l; j++) {
        if (aOverlays[j])
            aOverlays[j].hide();
    }
}

function drawPeriodTerm(id, num, period)
{
    $(id).html("<strong>Fase " + num +":</strong> " + getPeriodTerm(period) );  
}


function showDiversions(id1, id2, id3, num)
{
  hideDetours();
  minimap.setCenter(aGEvent, 9);
  $(id1).toggle('fast');
  $(id2).toggleClass("minus_bg");
  $(".sel_period").removeClass("sel_period");
  $(".sel").removeClass("sel");
  $(id2).addClass("sel_period");
  
  if (aGPeriods[num])
  {
      drawPeriodTerm(id3, num, aGPeriods[num]);    
  }
  
}


function chngDiversion(i, id, id2, num){
    minimap.setZoom(minimap.getBoundsZoomLevel(aOverlays[i].getBounds()));
    minimap.setCenter(aOverlays[i].getBounds().getCenter());
    hideDetours();
    minimap.addOverlay(aOverlays[i]);
    aOverlays[i].show();
    
    drawPeriodTerm(id, num, aGPeriods[num]);
    $("<div>" + aDiversionsData[i].name + "</div>").appendTo(id);
    $("<div><strong>Omleiding:</strong> " + aDiversionsData[i].description + "</div>").appendTo(id);
    $(".sel").removeClass("sel");
    $(".sel_period").removeClass("sel_period");
    $(id2).addClass("sel");
    gMap.updateInfoWindow(gMap.getInfoWindow().getTabs());
    
    
}

function chngFalkDiversion(i, id, id2)
{
    minimap.setZoom(minimap.getBoundsZoomLevel(aOverlays[i].getBounds()));
    minimap.setCenter(aOverlays[i].getBounds().getCenter());
    hideDetours();
    minimap.addOverlay(aOverlays[i]);
    aOverlays[i].show();
    
    $(id).html("<div>" + aDiversionsData[i].name + "</div>");
    $("<div><strong>Omleiding:</strong> " + aDiversionsData[i].description + "</div>").appendTo(id);
    $(".sel").removeClass("sel");
    $(".sel_period").removeClass("sel_period");
    $(id2).addClass("sel");
    
    
    gMap.updateInfoWindow(gMap.getInfoWindow().getTabs());
}



function scrollEvent(event){
    var delta = 0;
    if (!event) {
        event = window.event;
    }
    
    if (event.wheelDelta) {
        delta = event.wheelDelta / 120;
        if (window.opera) {
            delta = -delta;
        }
    }
    else 
        if (event.detail) {
            delta = -event.detail / 3;
        }
    
    if (delta) {
        if (delta < 0) {
            map.zoomOut();
        }
        else {
            map.zoomIn();
        }
    }
    
    if (event.preventDefault) {
        event.preventDefault();
    }
    
    event.returnValue = false;
}


function getLEventTypeLabel(type){
    
    switch (type) {
        case "1":
            return 'Hinder: mogelijk meer dan 30 min. extra reistijd';
            break;
            
        case "2":
            return 'Hinder: mogelijk 10-30 min. extra reistijd';
            break;
            
        case "3":
            return 'Hinder: mogelijk 2-10 min. extra reistijd';
            break;
            
        case "4":
            return 'Hinder: mogelijk minder dan 2 min. extra reistijd';
            break;
            
        default:
            return '';
            break;
    }
}


function getEventTypeLabel(type){
    
    switch (type) {
        case "1":
            return '> 30 min. extra reistijd';
            break;
            
        case "2":
            return '> 10 min. extra reistijd';
            break;
            
        case "3":
            return '2-10 min. extra reistijd';
            break;
            
        case "4":
            return '< 2 min. extra reistijd';
            break;
            
        default:
            return '';
            break;
    }
}

function Tooltip(marker, text, start, end, type, direction, time_period_humanise, padding, isPoi){
    
    this.marker_ = marker;
    this.direction_ = direction;
    this.text_ = text;
    this.start_ = start;
    this.end_ = end;
    this.type_ = type;
    this.padding_ = padding;
    this.isPoi = isPoi;
    //don't display if work is permanent
    this.time_period_ = time_period_humanise;
}

Tooltip.prototype = new GOverlay();

Tooltip.prototype.initialize = function(map){
    var div = document.createElement("div");
    
    var s = new Date(this.start_);
    var e = new Date(this.end_);
    
    start = s.getDate() + "-" + (s.getMonth()+1) + "-" + takeYear(s);
    end = e.getDate() + "-" + (e.getMonth()+1) + "-" + takeYear(e);
	var period = "";
	(start == end) ? period = start : period = start + ' tot en met ' + end;
    if (this.isPoi)
    {
        div.innerHTML = ('<strong>' + this.text_ + '</strong>');        
    }
    else
    {
        //div.innerHTML = ('<strong>' + this.text_ + '</strong><br/>' + period + '<br/><span>' + getEventTypeLabel(this.type_) + this.time_period_ + '</span>' );        
        div.innerHTML = ('<strong>' + this.text_ + '</strong><br/>' + period);        
    }
    
    div.className = 'tooltip';
    div.style.position = 'absolute';
    div.style.visibility = 'hidden';
    map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
    this.map_ = map;
    this.div_ = div;
}

Tooltip.prototype.remove = function(){
    this.div_.parentNode.removeChild(this.div_);
}

Tooltip.prototype.copy = function(){
    return new Tooltip(this.marker_, this.text_, this.padding_);
}

Tooltip.prototype.redraw = function(force){
    if (!force) 
        return;
    var markerPos = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
    var iconAnchor = this.marker_.getIcon().iconAnchor;
    var xPos = Math.round(markerPos.x + 24);
    var yPos = markerPos.y - iconAnchor.y - this.padding_ + 7;
    this.div_.style.top = yPos + this.div_.style.height + 'px';
    this.div_.style.left = xPos + 'px';
}

Tooltip.prototype.show = function(){
    this.div_.style.visibility = 'visible';
}

Tooltip.prototype.hide = function(){
    this.div_.style.visibility = 'hidden';
}

function show_loading(id1, id2){
    var static_box = $(id1);
    var moving_box = $(id2);
	
	$("#work input, #poi input").attr("disabled", "1");
	
    var mb_width = static_box.width() / 2 - moving_box.width() / 2;
    var mb_height = static_box.height() / 2 - moving_box.height() / 2;

    moving_box.css("top", mb_height);
    moving_box.css("left", mb_width);
    moving_box.css("display", "block");
    moving_box.css("position", "absolute");	
    
}

function show_milieuzone(){
    if ($("input#milieuzone:checked").length > 0)
    {
            inMap.GMap.removeOverlay(milieuzone_polygon);
            inMap.GMap.addOverlay(milieuzone_polygon);
            GEvent.addListener(milieuzone_polygon, "click", function(){
                inMap.GMap.openInfoWindowHtml(new GLatLng('52.08920895995907', '5.115852355957031') , '<div class="mappopup"><h4>Milieuzone</h4><p>De milieuzone geldt voor vrachtauto\'s met een totaal toegestane massa van meer dan 3,5 ton. Voertuigen die voldoen aan de euronorm 4 of 5 (of beter) en Euro 2 en 3 vrachtauto\'s met een roetfilter hebben toegang tot de milieuzone. Voor meer informatie: <a href="http://www.utrecht.nl/milieuzone">www.utrecht.nl/milieuzone</a></p></div>');
            });   
    }
    else
    {
        inMap.GMap.removeOverlay(milieuzone_polygon);
    }
}

function show_mileuzone_wwa2()
{
    show_def_mileuzone(wwa2_eindhoven_milieuzone_polygon, '#milieuzone', '51.43833229292695', '5.475654602050781', '<div class="mappopup"><h4>Milieuzone</h4><p>De milieuzone geldt voor vrachtauto\'s met een totaal toegestane massa van meer dan 3,5 ton. Voertuigen die voldoen aan de euronorm 4 of 5 (of hoger) en Euro 2 en 3 vrachtauto\'s met een gecertificeerd roetfilter hebben toegang tot de milieuzone.<br> Voor meer informatie: <br><a href="http://www.eindhoven.nl/web/show/id=354749/contentid=36129#-_in_welk_gebied_ligt_de_eindhovense_milieuzone" target="_blank">http://www.eindhoven.nl/web/show/id=354749/contentid=...</a></p></div>');
    show_def_mileuzone(wwa2_den_bosch_milieuzone_polygon, '#milieuzone', '51.689476818198614', '5.303478240966797', '<div class="mappopup"><h4>Milieuzone</h4><p>De milieuzone geldt voor vrachtauto\'s met een totaal toegestane massa van meer dan 3,5 ton. Voertuigen die voldoen aan de euronorm 4 of 5 (of hoger) en Euro 2 en 3 vrachtauto\'s met een gecertificeerd roetfilter hebben toegang tot de milieuzone.<br> Voor meer informatie: <br><a href="http://www.denbosch.nl/content.cfm?contentid=2F22D9D2-8021-0F65-099CC3CA417C0561#Milieueisen" target="_blank">http://www.denbosch.nl/content.cfm?contentid=...</a></p></div>');
    //'<div class="mappopup"><h4>Milieuzone</h4><p>De milieuzone geldt voor vrachtauto\'s met een totaal toegestane massa van meer dan 3,5 ton. Voertuigen die voldoen aan de euronorm 4 of 5 (of beter) en Euro 2 en 3 vrachtauto\'s met een roetfilter hebben toegang tot de milieuzone. Voor meer informatie: <a href="http://www.utrecht.nl/milieuzone">www.utrecht.nl/milieuzone</a></p></div>'
}

function show_def_mileuzone(zone, id, lat, lng, text)
{
     if ($(id + ":checked").length > 0)
    {
            inMap.GMap.removeOverlay(zone);
            inMap.GMap.addOverlay(zone);
 
            GEvent.addListener(zone, "click", function(){
                inMap.GMap.openInfoWindowHtml(new GLatLng(lat, lng) , text);
            });   
     }
    else
    {
        inMap.GMap.removeOverlay(zone);
    }   
}
function hide_loading(id){
    $(id).css("display", "none");
	$("#work input, #poi input").attr("disabled", "");
}