var icr;
var icr_features = [];
var icr_activated_list = [];
var show_icr_all = true, show_icr_none = false;
var show_cpr = true;
var mouse_position;

var icr_attributes = {
    "1": {strokeColor: '#3BC600'}, "1-A": {strokeColor: '#3BC600'}, "1-B": {strokeColor: '#3BC600'},
    "2": {strokeColor: '#7287F9'},  "2-A": {strokeColor: '#7287F9'}, "2-B": {strokeColor: '#7287F9'},
    "3": {strokeColor: '#CE0000'},  "3-A": {strokeColor: '#CE0000'}, "3-B": {strokeColor: '#CE0000'},
    "4": {strokeColor: '#B400CC'},
    "5": {strokeColor: '#195400'}, "5-A": {strokeColor: '#195400'}, "5-B": {strokeColor: '#195400'},
    "6": {strokeColor: '#195400'},  "6-A": {strokeColor: '#195400'}, "6-B": {strokeColor: '#195400'},
    "7": {strokeColor: '#CE0000'},
    "8": {strokeColor: '#3BC600'},
    "9": {strokeColor: '#B400CC'}, "9-A": {strokeColor: '#B400CC'}, "9-B": {strokeColor: '#B400CC'},
    "10": {strokeColor: '#CE0000'}, "10-A": {strokeColor: '#CE0000'}, "10-B": {strokeColor: '#CE0000'},
    "11": {strokeColor: '#7287F9'}, "11-A": {strokeColor: '#7287F9'}, "11-B": {strokeColor: '#7287F9'},
    "12": {strokeColor: '#195400'}, "12-A": {strokeColor: '#195400'}, "12-B": {strokeColor: '#195400'},
    "A": {strokeColor: '#E05900'}, "B": {strokeColor: '#E05900'}, "C": {strokeColor: '#E05900'},
    "CK": {strokeColor: '#0084E2'},
    "SZ": {strokeColor: '#0084E2'}, "SZ-A": {strokeColor: '#0084E2'}, "SZ-B": {strokeColor: '#0084E2'},
    "MM": {strokeColor: '#001699'}, "MM-A": {strokeColor: '#001699'}, "MM-B": {strokeColor: '#001699'},
    "PP": {strokeColor: '#CE0000'}
}
var icr_length = [];
var multiple_icr_list = ["1", "2", "3", "5", "6", "9", "10", "11", "12", "SZ", "MM"];

function mapVeloInit(config) {

    // ### Villo ###
    villo = makeLayer(
        "villo", {
            style_mark: {
                "default": {
                    externalGraphic: clusterStyle("img/villo_map.gif", "cluster/villo/off/${count}.gif", media_url + "bruxelles_mobilite_media/"),
                    graphicHeight: clusterStyle(23,35),
                    graphicWidth: clusterStyle(19,32),
                    graphicXOffset: clusterStyle(-9.5, -16),
                    graphicYOffset: clusterStyle(-23,-35),
                    cursor: clusterStyle("default", "pointer")
                },
                "select": {
                    externalGraphic: clusterStyle("img/villo_map.gif", "cluster/villo/on/${count}.gif", media_url + "bruxelles_mobilite_media/")
                }
            },
            strategies: [new LimitedClusterStrategy({ distance: 25 })]
        },
        {
            format: function (data) { 
                var statemessage = "{free_places}: <span class='maptip-dynamic'>{FREEBS}</span> / {free_bikes}: <span class='maptip-dynamic'>{FREEBK}</span>"+ "<br/>";
                if (!data.FREEBS && !data.FREEBK) statemessage = "";
                if (data.STATE != "open") statemessage = "<span class='maptip-dynamic'>{" + data.STATE + "_msg}</span>"+ "<br/>";
                  
                return "<span class='villo-station-no'>{station_no}{ID}</span><i>{STREET}<br/></i>" + statemessage ;
            },
            fr: { 'station_no': 'Station n° ' , 'free_places': 'Emplacements libres', 'free_bikes': 'Vélos disponibles', "closed_msg": "Station fermée", "maintenance_msg": "Station en cours d'entretien", "construction_msg": "Station bientôt disponible" },
            nl: { 'station_no': 'Station nr ', 'free_bikes': 'Beschikbare fietsen', 'free_places': 'Beschikbare fietspalen', "closed_msg": "Station gesloten", "maintenance_msg": "Station in onderhoud", "construction_msg": "Station gaat binnenkort open" }
        },
		{ 
            switchs: [true],
            titles: {fr: ["Stations villo"], nl: ["Villo-stations"]},
            icons: {all: [media_url + "bruxelles_mobilite_media/img/villo_map.gif"]},
            visible: false
        },
        { url: config.villo_url, interval: 120000, dataType: config.villo_url.match(/^https?:\/\//) ? "jsonp" : "json" }
    );

   // ### Velocistes ###
    velocistes = makeLayer(
        "cycling_shops", 
        { style_mark: {externalGraphic: media_url + "bruxelles_mobilite_media/img/velocistes_map.gif"}},
        { 
            format: "<b>{NAAM}</b><br/><i>{ADRESSE}</i><br/>{TEL}<br/>",
            nl: { "ADRES":"ADRESSE" }
        },
		{ 
            switchs: [true],
            titles: {fr: ["Vélocistes"], nl: ["Fietswinkels"]},
            icons: {all: [media_url + "bruxelles_mobilite_media/img/velocistes_map.gif"]},
            visible: false
        },
	    { url: media_url + "categories_files/cycling_shops.json" }	
    );
    
    // ### Services Velo ###
    services_velo = makeLayer(
        "cycling_services", 
        { style_mark: {externalGraphic: media_url + "bruxelles_mobilite_media/img/services_velo_map.gif"}},
        { 
            format: "<b>{NOM}</b><br/><i>{ADRESSE}<br/>{TEL}<br/>{INFO}</i><br/>",
            nl: { "NAAM": "NOM" , "ADRES":"ADRESSE", "INFO_NL": "INFO" }
        },
		{ 
            switchs: [true],
            titles: {fr: ["Services vélo"], nl: ["Fietsdiensten"]},
            icons: {all: [media_url + "bruxelles_mobilite_media/img/services_velo_map.gif"]},
            visible: false
        },
	    { url: media_url + "categories_files/cycling_services.json" }
    );

    // ### ICR ###
    var format = "image/png";
    if($.browser.msie && $.browser.version.substr(0,2) == "6.") format = "image/gif";
    icr = new OpenLayers.Layer.WMS("icr",
                "/urbis/geoserver/wms",
                {
                    "layers": 'mobility:cycling_itineraries',
                    "transparent": true,
                    "format": format
                },
                {
                    isBaseLayer: false
                }
    );
    map.addLayer(icr);
    for (icr_nbr in icr_attributes) {
        icr_activated_list.push(icr_nbr);
    }
    
    cpr = new OpenLayers.Layer.WMS("CPR",
                "/urbis/geoserver/wms",
                {
                    "layers": 'mobility:cycling_promenade',
                    "transparent": true,
                    "format": format
                },
                {
                    isBaseLayer: false
                }
    );
    map.addLayer(cpr);
    
    makeLayer(
		"icr-fake", 
		{}, 
		{},
		{ 
		    switchs: [false],
		    expand_div: "ICR_legend",
		    titles: {fr: ["ICR"], nl: ["ICR"]},
		    icons: {all: [media_url + "bruxelles_mobilite_media/img/velo_cat.gif"]},
			visible: false,
			setVisibility: function (visible, n) {
				icr.setVisibility(visible); 
			}
		},
		{}
	);
    
    sul = new OpenLayers.Layer.WMS("SUL",
                "/urbis/geoserver/wms",
                {
                    "layers": 'urbis:URB_M_ZIPOINT',
                    "styles":'urbis_SUL_style', 
                    "transparent": true,
                    "format": format
                },
                {
                    isBaseLayer: false
                }
    );
    map.addLayer(sul);
    
    jQuery.getJSON(media_url + "categories_files/icr.json", function(data){
            for (var i=0 ; i < data.features.length ; i+=1){
                    icr_length.push({"circuit":{"name":data.features[i].properties.ICR,"length":data.features[i].properties.SUM_LENGHT}});
            }
    })
    
}

function hideLegendTip() {
    jQuery("#mapContainerContent").append(jQuery("#mapTip")); 
    jQuery("#mapTip").css({'visibility' : 'hidden'});
    jQuery("#mapTip").html("");
}


function showLegendTip(top, left, icr_nbr){
    
    var multiple = 0; 
    var content = "";
    for (var i=0 ; i <  icr_length.length ; i+=1) {
        if (icr_length[i].circuit.name.indexOf(icr_nbr) == 0) { 
            if (icr_nbr == icr_length[i].circuit.name || icr_length[i].circuit.name.indexOf("-") == icr_nbr.toString().length) {
                content += "<b>" + icr_length[i].circuit.name + "</b>: " + Math.round(parseFloat(icr_length[i].circuit.length)/10)/100 + " km <br />";
                multiple += 1; 
            }
        }
    }
    
    if (icr_nbr == -1){ // if the legent is for the cycling promenade
    	//verifier langue
    	nbrekm="65.78 km"
    	textfr ="Promenade verte";
    	textnl ="Groene wandeling";
    	
    	if (lang=="nl") content +="<b> "+textnl+" </b>: "+nbrekm+"<br />";
    	else content +="<b> "+textfr+" </b>: "+nbrekm+" <br />";
    }

    jQuery("#mapTip").html(content);
    
    if (!$.browser.msie) $("#mapTip").corner("keep"); 
    jQuery(".ICR").append(jQuery("#mapTip"));
    
    if (multiple == 1) {
        top = top - 40;
    } else {
        top = top - 70;
    }

    if (icr_nbr == "10" || icr_nbr == "11" || icr_nbr == "12" ) left = left - 60;
    jQuery("#mapTip").css({
                        "top" : top,
                        "left" : left 
                    });
                    
    if (icr_nbr == -1) {left = left - 95;top = top + 30}
    jQuery("#mapTip").css({
                        "top" : top,
                        "left" : left 
                    });
    
    jQuery("#mapTip").css({'visibility' : 'visible'});
}

function showHideLegendVelo() {
    jQuery("#legendICR_All").click(function()
	{
        if (!show_icr_all) {
			jQuery("#legendICR_All").removeClass("disabled");
            jQuery("#legendICR_None").addClass("disabled");
            show_icr_none = false;
            show_icr_all = true;
            icr_activated_list = [];
            for (icr_nbr in icr_attributes) {
                icr_activated_list.push(icr_nbr);
                legend_icr = "#legendICR_" + icr_nbr;
                jQuery(legend_icr).css({"opacity": 0});
            }
            var filter = "ICR > ''";
            icr.mergeNewParams({'CQL_FILTER': filter});
            icr.setVisibility(true);
            show_cpr = true;
        	cpr.setVisibility(true);
        	jQuery("#legendCPR").css({"opacity": 0});
        }
    });

    jQuery("#legendICR_None").addClass("disabled");
    jQuery("#legendICR_None").click(function()
	{
        if (!show_icr_none) {
            jQuery("#legendICR_None").removeClass("disabled");
            jQuery("#legendICR_All").addClass("disabled");
            show_icr_all = false;
            show_icr_none = true;
            icr.setVisibility(false);
            icr_activated_list = [];
            for (icr_nbr in icr_attributes) {
                legend_icr = "#legendICR_" + icr_nbr;
                jQuery(legend_icr).css({"opacity": 0.80});
            }
            show_cpr = false;
            cpr.setVisibility(false);            
            jQuery("#legendCPR").css({"opacity": 0.80});
        }
    });

    var legend_icr = "";
    for (icr_nbr in icr_attributes) {
        legend_icr = "#legendICR_" + icr_nbr;
        jQuery(legend_icr).hover(
            function() {
                var top = parseInt(jQuery(this).css("top").substring(0,jQuery(this).css("top").indexOf("px")));
                var left = parseInt(jQuery(this).css("left").substring(0,jQuery(this).css("left").indexOf("px")));
                var icr_x = jQuery(this).attr("id").replace("legendICR_", "");
                var i = jQuery.inArray(icr_x, icr_activated_list);
                showLegendTip(top, left, icr_x);
                if ( i == -1) jQuery(this).css({"opacity": 0});
                else jQuery(this).css({"opacity": 0.80});
            },
            function() {
                hideLegendTip();
                var icr_x = jQuery(this).attr("id").replace("legendICR_", "");
                var i = jQuery.inArray(icr_x, icr_activated_list);
                if ( i == -1) jQuery(this).css({"opacity": 0.80});
                else jQuery(this).css({"opacity": 0});
            }
        );
        jQuery(legend_icr).click(function() {
            jQuery("#legendICR_None").addClass("disabled");
            jQuery("#legendICR_All").addClass("disabled");
            show_icr_all = false;
            show_icr_none = false;
            var icr_x = jQuery(this).attr("id").replace("legendICR_", "");
            var i = jQuery.inArray(icr_x, icr_activated_list);
            if ( i == -1) {
                icr_activated_list.push(icr_x);
                jQuery(this).css({"opacity": 0});
                if (jQuery.inArray(icr_x, multiple_icr_list) != -1) {
                    icr_activated_list.push(icr_x + "-A");
                    icr_activated_list.push(icr_x + "-B");
                }
            }
            else {
                icr_activated_list.splice(i, 1);
                jQuery(this).css({"opacity": 0.80});
                if (jQuery.inArray(icr_x, multiple_icr_list) != -1) {
                    icr_activated_list.splice(jQuery.inArray(icr_x + "-A", icr_activated_list), 1);
                    icr_activated_list.splice(jQuery.inArray(icr_x + "-B", icr_activated_list), 1);
                }
            }
            var filter = '';
            for (var i=0; i<icr_activated_list.length; i++) {
                filter += "ICR='" + icr_activated_list[i] + "' or ";
            }
            filter += "ICR='-1'";
            icr.mergeNewParams({'CQL_FILTER': filter});
            icr.setVisibility(true);
        });
    }
    
    jQuery("#legendCPR").hover( function()
	{
        var top = parseInt(jQuery(this).css("top").substring(0,jQuery(this).css("top").indexOf("px")));
        var left = parseInt(jQuery(this).css("left").substring(0,jQuery(this).css("left").indexOf("px")));
        showLegendTip(top, left, -1);
        if (!show_cpr) jQuery(this).css({"opacity": 0});
        else jQuery(this).css({"opacity": 0.80});
    },
    function() {
        hideLegendTip();
        var cpr_x = jQuery(this).attr("id");
        if (!show_cpr)jQuery(this).css({"opacity": 0.80});
        else jQuery(this).css({"opacity": 0});
    });    
    jQuery("#legendCPR").click(function()
	{
	    jQuery("#legendICR_None").addClass("disabled");
        jQuery("#legendICR_All").addClass("disabled");
        show_icr_all = false;
        show_icr_none = false;
        if (show_cpr) {
            show_cpr = false;
            cpr.setVisibility(false);            
            jQuery(this).css({"opacity": 0.80});
        }else{
        	show_cpr = true;
        	cpr.setVisibility(true);
        	jQuery(this).css({"opacity": 0});
        }
    });

	// trigger after toolbar is setup
    /*window.setTimeout(function () {
        var $ICR = $(".ICR");
        var $ICRParent = $ICR.parent();
        var $mapContainerContent = $("#mapContainerContent");

        var fullscreen_tool = map.getControlsByClass("FullScreen")[0];
        fullscreen_tool.events.register("fullscreen_on", fullscreen_tool, function () {
            $mapContainerContent.append($ICR);
            $ICR.css({ "margin-left": "120px", "margin-top": "0px" });
            $("#mapDiv").css({height: $("#mapDiv").height() - $ICR.height() });
        });

        fullscreen_tool.events.register("fullscreen_off", fullscreen_tool, function () {
            $ICRParent.append($ICR);
            $ICR.css({"margin-left": "", "margin-top": ""});
        });
    }, 100) ;*/
}

