﻿
//=================================================================================
// Map inicializacija
// TODO Urediti!
//=================================================================================





//=================================================================================
// Globalne variable in funkcije

var map = null;
var panel = null;
var routingPanel = null;
var routing = null;
var selectedVia = {};

Ext.EventManager.on(window, 'unload', function()
{
    if(map != null)
        map.dispose();
    if(panel != null)
        panel.dispose();
    if(routingPanel != null)
        routingPanel.dispose();          
});

function onResize()
{
    if(map != null)
        map.resize();
    if(panel != null)
        panel.resize();
    if(routingPanel != null)
        routingPanel.resize();
}

function openContextMenu(menu)
{
    var pageLocation = [];
    if(window.event.pageX)
    {
        pageLocation[0] = window.event.pageX;
        pageLocation[1] = window.event.pageY;
    }
    else
    {
        pageLocation[0] = window.event.clientX;
        pageLocation[1] = window.event.clientY;
    }
           
    menu.showAt(pageLocation);  
}

//=================================================================================
// Map inicializacija
// TODO: sedaj predvidevamo da obstajajo nekatere globalne variable (layout, ...)

function initRMap()
{
    RMap.MapApplication.resourcesUrl = applicationSettings.rmapResourcesUri;
    RMap.MapApplication.proxyUrl = applicationSettings.proxyUri;
    RMap.MapApplication.waitBtn = "Common/hourglass_anim.gif";
    //RMap.MapApplication.indImg = "Common/hourglass_anim.gif";
    //RMap.MapApplication.tileBuffer=2;
    var mapSettings = RMap.MapSettingsLoader.loadMap(applicationSettings.rmapMapSettingUri);
    if(mapSettings.failed==true)
    {
        mapSettings.defaultCenter={x:450000, y:100000};
        mapSettings.defaultCoordinateSystem=RMap.CoordinateSystem.getCoordinateSystem("EPSG:2170");
        mapSettings.tileMapCoordinateSystem=RMap.CoordinateSystem.getCoordinateSystem("EPSG:2170");
        mapSettings.zoomLevels=[256];
    }
    mapSettings.detailZoomLevel=mapSettings.getBestZoomLevel("2m");
    mapSettings.defaultZoomLevel= (document.body.offsetWidth>1375) ? mapSettings.getBestZoomLevel("250m") : mapSettings.getBestZoomLevel("500m");    
    var config = {mapSettings:mapSettings};
		var ctrlInd=RMap.MapControl.createIndicatorControl();
		var ctrlNav=RMap.MapControl.createNavigationControl();
    map = new RMap.Map()    
    map.initialize(document.getElementById('mapContainer'), config);
    map.scaleBarControl = RMap.MapControl.createScaleBarControl('EPSG:4326');
    //map.addControl(ctrlInd, { left:'6px', top:'6px' });
    map.addControl(ctrlNav, { top:'5px', left:'5px' });
    map.addControl(RMap.MapControl.createThemeSelectorControl(), { top:'5px', right:'5px' });
    map.addControl(map.scaleBarControl, { bottom:'15px', left:'5px' });
    //var ovrCtrl=RMap.MapControl.createMapOverviewControl();
    //map.addControl(ovrCtrl, { bottom: '-1px', right: '-1px' });
    map.addControl(RMap.MapControl.createMapOverviewControl({closed:true}), { bottom: '-1px', right: '-1px' });
    map.setOpacity(25);
    //ovrCtrl.close();
    initRmapLayer_tujina();
    
    panel = new RMap.PanelContainer(document.getElementById('layerListContainer'), {count:true});
    panel.attachEvent("panel", Delegate.create(this, onPanelEvent));
    //=================================================================================
    //Routing inicializacija
    routingPanel = new RMap.PanelContainer(document.getElementById('routingContainer'));
    RMap.RoutingSettings.geocodingUrl=applicationSettings.geocodeServiceUri;
    RMap.RoutingSettings.serviceUrl=applicationSettings.rmapRoutingServiceUri;
    RMap.RoutingSettings.transformer=applicationSettings.rmapRoutingTransformer;
    RMap.RoutingSettings.maxViaNumber=1;
    RMap.RoutingSettings.geocodingTolerance=applicationSettings.geocodeTolerance;
    RMap.RoutingSettings.messageACHC=lngDict["rtgMsgACHC"];

    if(lngDict["rtgCapt"]!=null)
			RMap.RoutingSettings.caption=lngDict["rtgCapt"];
    if(lngDict["rtgDesc"]!=null)
			RMap.RoutingSettings.message=lngDict["rtgDesc"];
		if(lngDict["ctxResFail"]!=null)
			RMap.RoutingSettings.geocoding_requestProblem=lngDict["ctxResFail"];
		if(lngDict["ctxResNoRoad"]!=null)
			RMap.RoutingSettings.geocoding_noRoad=lngDict["ctxResNoRoad"];
		if(lngDict["rtgFastest"]!=null)
			RMap.RoutingSettings.fastest=lngDict["rtgFastest"];
		if(lngDict["rtgShortest"]!=null)
			RMap.RoutingSettings.shortest=lngDict["rtgShortest"];
		if(lngDict["rtgReverse"]!=null)
			RMap.RoutingSettings.reverse=lngDict["rtgReverse"];
		if(lngDict["rtgClear"]!=null)
			RMap.RoutingSettings.clear=lngDict["rtgClear"];	
		if(lngDict["rtgCategory"]!=null)
			RMap.RoutingSettings.category=lngDict["rtgCategory"];	
		if(lngDict["rtgStart"]!=null)
			RMap.RoutingSettings.start=lngDict["rtgStart"];	
		if(lngDict["rtgVia"]!=null)
			RMap.RoutingSettings.via=lngDict["rtgVia"];	
		if(lngDict["rtgEnd"]!=null)
			RMap.RoutingSettings.end=lngDict["rtgEnd"];												
         
    //RMap.RoutingSettings.autoReload=false;
    routing = new RMap.Routing(map, routingPanel, {externalMode:true, forceBlowup:false});
    routing.attachEvent("routing", Delegate.create(this, onRoutingEvent));
		routing.routeItemDescriptor=Delegate.create(this, routeItemTemplate);
		window.routingInsert="<br/><br/><a href='javascript:onRoutingStationSelected(&quot;start&quot;,window.manualInfoLoc)'>začetek poti</a> &nbsp; <a href='javascript:onRoutingStationSelected(&quot;via&quot;,window.manualInfoLoc)'>vmesna postaja</a> &nbsp; <a href='javascript:onRoutingStationSelected(&quot;stop&quot;,window.manualInfoLoc)'>konec poti</a>";
		
    var routingMenuStart = new Ext.menu.Item
    ({ 
        text: lngDict["ctxRoutRemStart"],
        icon: '_res/images/routing/start_off.gif',
        handler:routingRemoveStart
    })
    var routingMenuVia = new Ext.menu.Item
    ({ 
        text: lngDict["ctxRoutRemVia"],
        icon: '_res/images/routing/via_off.gif',
        handler:routingRemoveVia
    })
    var routingMenuCilj = new Ext.menu.Item
    ({ 
        text: lngDict["ctxRoutRemStop"],
        icon: '_res/images/routing/cilj_off.gif',
        handler:routingRemoveCilj
    })
    var routingMenu = new Ext.menu.Menu();
    routingMenu.add
    (
        routingMenuStart,
        routingMenuVia,
        routingMenuCilj
    );
    
    //=================================================================================
    //map menu
    
    var mapMenuVia= new Ext.menu.Item
    ({
        text: lngDict["ctxRoutVia"],
        icon: '_res/images/routing/via.gif',
        handler: function(){onRoutingStationSelected('via')} // function(){innerLayout.getRegion('west').showPanel('routingContainer'); routingPanel.resize(); routing.removeAllVias(); if(routing.addVia(_mouseEventArgs.worldLocation.x, _mouseEventArgs.worldLocation.y)==true) routing.loadRoute();}
    });
    var mapMenuRouting = new Ext.menu.Item({
        text: lngDict["ctxRout"],
        icon: '_res/icons/a/car.png',
        menu: 
        {
            items: 
            [
                {
                    text: lngDict["ctxRoutStart"],
                    icon: '_res/images/routing/start.gif',
                    handler: function(){onRoutingStationSelected('start')} // function(){innerLayout.getRegion('west').showPanel('routingContainer'); routingPanel.resize(); if(routing.setStart(_mouseEventArgs.worldLocation.x, _mouseEventArgs.worldLocation.y)==true) routing.loadRoute();}
                },
                mapMenuVia,
                {
                    text: lngDict["ctxRoutStop"],
                    icon: '_res/images/routing/cilj.gif',
                    handler: function(){onRoutingStationSelected('stop')} // function(){innerLayout.getRegion('west').showPanel('routingContainer'); routingPanel.resize(); if(routing.setEnd(_mouseEventArgs.worldLocation.x, _mouseEventArgs.worldLocation.y)==true) routing.loadRoute();}
                }
            ]
        }
    });
    
    var mapMenuRGCRpe = {
        text: lngDict["ctxAddr"],
        icon: '_res/icons/a/application_home.png',
        handler: rgcRpe
    };
    
    var mapMenuRGCCeste = {
        text: lngDict["ctxRoad"],
        icon: '_res/icons/a/application_home.png',
        handler: rgcCeste
    };
    
    var mapMenuView = {
        text: lngDict["ctxView"],
        icon: '_res/icons/a/application_home.png',
        menu: 
        {
            items: 
            [
                {
                    text: lngDict["ctxViewCtr"],
                    icon: '_res/icons/a/zoom.png',
                    handler: function(){map.setCenter(_mouseEventArgs.worldLocation.x, _mouseEventArgs.worldLocation.y);}
                },
                {
                    text: lngDict["ctxViewDet"],
                    icon: '_res/icons/a/zoom_in.png',
                    handler: function(){map.zoomToLocation(map.getDetailZoomLevel(), _mouseEventArgs.worldLocation.x, _mouseEventArgs.worldLocation.y);}
                },
                {
                    text: lngDict["ctxViewGen"],
                    icon: '_res/icons/a/zoom_out.png',
                    handler: function(){map.zoomToLocation(map.getDefaultZoomLevel(), _mouseEventArgs.worldLocation.x, _mouseEventArgs.worldLocation.y);}
                }
            ]
        }
    };
       
    var mapMenu= new Ext.menu.Menu(); 
    
    mapMenu.add
    (
        mapMenuRGCRpe,
        mapMenuRGCCeste,
        '-',
        mapMenuView,
        '-',
        mapMenuRouting
    );
         
          
    var _mouseEventArgs = null; 
       
		function onRoutingStationSelected(tip, loc)
		{
			var isCnt=true;
			var ok=false;
			if(loc==null)
			{
				loc=_mouseEventArgs.worldLocation;
				isCnt=false;
			}
			if(tip=="start")
			{
				ok=routing.setStart(loc.x, loc.y);
			}
			else if(tip=="via")
			{
				routing.removeAllVias();
				ok=routing.addVia(loc.x, loc.y);
			}
			else if(tip=="stop")
			{
				ok=routing.setEnd(loc.x, loc.y);
			}
			if(ok)
			{
				innerLayout.getRegion('west').showPanel('routingContainer');
				routingPanel.resize();
				routing.loadRoute();
				if(isCnt)
				{
					clearTimeout(window.ciw);
					window.ciw=setTimeout(function(){map.closeInfoWindow.call(map)},0);
				}
			}
		}
    window.onRoutingStationSelected=onRoutingStationSelected;
        
    function onMouseEvent(sender, mouseEventArgs)
    {
        if(mouseEventArgs.action != RMap.MouseAction.ContextMenu)
        {    
            Ext.menu.MenuMgr.hideAll();
            return;
        }
        
        var pageLocation = [];
        if(window.event.pageX)
        {
            pageLocation[0] = window.event.pageX;
            pageLocation[1] = window.event.pageY;
        }
        else
        {
            pageLocation[0] = window.event.clientX;
            pageLocation[1] = window.event.clientY;
        }
            
        _mouseEventArgs = mouseEventArgs;
        if(routing!=null)
        {
            if(mouseEventArgs.userData!=null && mouseEventArgs.userData.layer==routing.getRoutingLayer())
            {
                var xsiType=mouseEventArgs.userData.drawing.getFeature().properties["xsi_type"];
                if(xsiType=="RouteDescriptionStart")
                {
                    routingMenuStart.show();
                    routingMenuVia.hide();
                    routingMenuCilj.hide();
                    routingMenu.showAt(pageLocation);
                }
                else if(xsiType=="RouteDescriptionVia")
                {
                    selectedVia.ind = -1;
                    var ftrs = routing.getRoutingLayer().getFeatureView().getStorage().getFeatures();
                    var ftr = mouseEventArgs.userData.drawing.getFeature();
                    for (var f=0; f<ftrs.length; f++)
                    {
                        if(ftrs[f].properties["xsi_type"]=="RouteDescriptionVia")
                            selectedVia.ind++;
                        if (ftr == ftrs[f])
                            break;
                    }
                    routingMenuStart.hide();
                    routingMenuVia.show();
                    routingMenuCilj.hide();
                    routingMenu.showAt(pageLocation);
                }
                else if(xsiType=="RouteDescriptionEnd")
                {
                    routingMenuStart.hide();
                    routingMenuVia.hide();
                    routingMenuCilj.show();
                    routingMenu.showAt(pageLocation);
                }
                return;
            }
            else
            {
							mapMenuVia.show();
//                if(RMap.RoutingSettings.maxViaNumber>routing.getVias().length)
//                    mapMenuVia.show();
//                else    
//                    mapMenuVia.hide();
            }
        }
        mapMenu.showAt(pageLocation);  
    }
    
    function routingRemoveStart()
    {
        routing.removeStart();
        routing.loadRoute();
    }
    function routingRemoveVia()
    {
        routing.removeVia(selectedVia.ind);
        routing.loadRoute();
    }
    function routingRemoveCilj()
    {
        routing.removeCilj();
        routing.loadRoute();
    }
    function onRoutingEvent(sender, args) // trenutno malo goljufam in kličem kar alerting od modula kažipot. Pravilno bi bilo, da bi šel celoten alerting preko page.js, pa naj kažipot kliče tja.
    {   	
      if(args.action==RMap.RoutingAction.GeocodingFailed)
          alertMessage(lngDict["ctxResFail"],"INFO");
      else if(args.action==RMap.RoutingAction.NoRoad)
          alertMessage(lngDict["ctxResNoRoad"],"INFO");
      else if(args.action==RMap.RoutingAction.Changed && map.layers["Realis.Rmap.Routing.Layer"]!=null)
			{
				var strg = map.layers["Realis.Rmap.Routing.Layer"].getFeatureView().getStorage();
				if (strg._features!=null && strg._features.length>0 && strg.getDescriptions()!=null && strg.getDescriptions().priceSumFlag == null && strg.getDescriptions().description!=null)
				{
					var sum=[0,0,0,0,0,0,0,0,0,0];
					var needs = false;
					for (var f = 0; f < strg._features.length; f++)
					{
						var ftr=strg._features[f];
						if(ftr!=null && ftr.properties["xsi_type"]=="RouteDescriptionTerminal" && ftr.properties["Prices"]!=null && ftr.properties.Name!="Hrušica")
						{
							var prc = ftr.properties.Prices;
							for (var f2 = 0; f2 < prc.length; f2++)
							{
								var p = parseFloat(prc[f2]);
								if (!isNaN(p)) 
								{
									sum[f2] += p;
									needs = true;
								}
							}
						}
					}
					if (needs == true)
						strg.getDescriptions().description += "<br/>" + routeItemTemplate({properties:{xsi_type:"RouteDescriptionTerminal", Prices:sum, Name:""}}, true, true);
					strg.getDescriptions().priceSumFlag = true;
				}
			}
    }  


    var serviceConnection = new Ext.data.Connection();          
    
    function rgcCallback(requestObj, sucsess, response)
    {
        if(!sucsess)
        {
            map.openInfoWindow('Error: ' + response.status + " " + response.statusText, requestObj.params.x, requestObj.params.y, map.getDefaultCoordinateSystem());
            return;
        }
        
        var json = response.responseText;
        var o = Ext.decode(json);
        
        if(o.items.length == 0)
        {
            var emptyMessage = 'Error: unknown service content ' + requestObj.params.content;
            
            switch(requestObj.params.content)
            {
                case 'ceste':
                    emptyMessage = lngDict["ctxResNoRoad"];
                    break;
                case 'rpe_ad':
                    emptyMessage = lngDict["ctxResNoAddr"];
                    break;
            }
            
            map.openInfoWindow(emptyMessage, requestObj.params.x, requestObj.params.y, map.getDefaultCoordinateSystem());
            return;
        }
        
        switch(requestObj.params.content)
        {      				
            case 'ceste':
                window.manualInfoLoc={x:o.items[0].bvx, y:o.items[0].bvy};
                map.openInfoWindow(o.items[0].descr + " " + o.items[0].ds_field + " " + Math.round(o.items[0].ds_at) + "m"+window.routingInsert, o.items[0].bvx, o.items[0].bvy);
                break;
            case 'rpe_ad':
                window.manualInfoLoc={x:o.items[0].bvx, y:o.items[0].bvy};
                map.openInfoWindow(o.items[0].descr+window.routingInsert, o.items[0].bvx, o.items[0].bvy);
                break;
        }        
    }

    function rgcCeste()
    {
        map.openInfoWindow(lngDict["loading"], _mouseEventArgs.worldLocation.x, _mouseEventArgs.worldLocation.y, map.getDefaultCoordinateSystem());
        mapMenu.hide();
        
        serviceConnection.request({
            url: applicationSettings.geocodeServiceUri, 
            params: {
                content: 'ceste', 
                dist: applicationSettings.geocodeTolerance,
                x: _mouseEventArgs.worldLocation.x, 
                y: _mouseEventArgs.worldLocation.y
            },
            callback: rgcCallback
        });
    }

   
    function rgcRpe()
    {
        map.openInfoWindow(lngDict["loading"], _mouseEventArgs.worldLocation.x, _mouseEventArgs.worldLocation.y, map.getDefaultCoordinateSystem());
        mapMenu.hide();
        
        serviceConnection.request({
            url: applicationSettings.geocodeServiceUri, 
            params: {
                content: 'rpe_ad',
                dist: applicationSettings.geocodeTolerance,
                x: _mouseEventArgs.worldLocation.x, 
                y: _mouseEventArgs.worldLocation.y
            },
            callback: rgcCallback
        });
    }
            
    map.attachEvent("mouse", Delegate.create(this, onMouseEvent));
    map.attachEvent("view", function(){Ext.menu.MenuMgr.hideAll();});
    
    var items=window.rmapSlojiMenu.items.items;     
    for(var f=0;f<items.length;f++)
    {
        if(items[f].checked==true)
            initRmapLayer(items[f].id,true);
    }
    
 }
   
function onPanelEvent(sender,args)
{
	if(args.action==RMap.PanelAction.Focus)
		args.panel.getLayer().setOrder(RMap.OrderPosition.Front);
}


function routeItemTemplate(ftr, isPanel, isSum)
{
		if(ftr.properties["xsi_type"]!="RouteDescriptionTerminal")
				return "";
		
		if(window.terminalTmpStr==null)
		{
			var str=[];
			var tmp;
			str.push("<br/><table border='0' cellspacing='0' cellspacing='0' style='width:95%; background:#ffffff; border:#000000 1px solid; color:#000000; font-size:10px; font-weight:bold'>");
			str.push("<tr>");
			str.push("<td colspan='6' style='color:#ffffff; padding:1px; background:#7993B9; border-bottom:#000000 1px solid'>"+lngDict["rtgR34"]+"</td>");
			str.push("</tr>");
			str.push("<tr>");
			str.push("<td style='padding:1px; border-bottom:#000000 1px solid; background:#D5D5D5;' colspan='2'> &nbsp; </td>");
			tmp = "<td style='padding:1px; border-bottom:#000000 1px solid; border-left:#000000 1px solid; text-align:center; background:#D5D5D5; white-space:nowrap;'>";
			str.push(tmp+"6h-22h</td>");
			str.push(tmp+"22h-6h</td>");
			str.push(tmp+"E3*</td>");
			str.push(tmp+"E4*</td>");
			str.push("</tr>");
			str.push("<tr>");
			str.push("<td style='padding:1px; text-align:center; border-bottom:#000000 1px solid;'>&nbsp;R3&nbsp;</td>");
			str.push("<td style='padding:0px; border-bottom:#000000 1px solid; text-align:center;'><img src='{@res}Routing/ikona-cestnina_C.gif'/></td>");
			tmp = "<td style='padding:1px; border-bottom:#000000 1px solid; border-left:#000000 1px solid; text-align:right;'>";
			str.push(tmp+"{@price2}</td>");
			str.push(tmp+"{@price4}</td>");
			str.push(tmp+"{@price6}</td>");
			str.push(tmp+"{@price7}</td>");
			str.push("</tr>");
			str.push("<tr>");
  		str.push("<td style='padding:1px; text-align:center;'>&nbsp;R4&nbsp;</td>");
			str.push("<td style='padding:0px; text-align:center;'><img src='{@res}Routing/ikona-cestnina_D.gif'/></td>");
			tmp = "<td style='padding:1px; border-left:#000000 1px solid; text-align:right;'>";
			str.push(tmp+"{@price3}</td>");
			str.push(tmp+"{@price5}</td>");
			str.push(tmp+"{@price8}</td>");
			str.push(tmp+"{@price9}</td>");
			str.push("</tr>");
			str.push("</table>");
			str.push(lngDict["rtgR3R4"]);
			window.terminalTmpStr=str.join('');
			window.terminalTmpStr=window.terminalTmpStr.replace(/{@res}/g,RMap.MapApplication.resourcesUrl);
			window.terminalTmpStr=window.terminalTmpStr.replace(/{@cat}/g,RMap.MapApplication.category);
			window.terminalTmpStr=window.terminalTmpStr.replace(/{@cat3}/g,RMap.MapApplication.category3);
			window.terminalTmpStr=window.terminalTmpStr.replace(/{@cat4}/g,RMap.MapApplication.category4);
    }
    if(window.hrusicaTmpStr==null)
		{
			var str=[];
			str.push(" - " + lngDict["hrusica"]);
			str.push("<br/><table border='0' cellspacing='0' cellspacing='0' style='width:95%; margin-top:3px; background:#ffffff; border:#000000 1px solid; color:#000000; font-size:10px; font-weight:bold'>");
			str.push("<tr>");
			str.push("<td colspan='2' style='color:#ffffff; padding:1px; background:#7993B9; border-bottom:#000000 1px solid'>"+lngDict["placiloEUR"]+"</td>");
			str.push("</tr>");
			str.push("<tr>");
			str.push("<td style='padding:1px; text-align:center; border-bottom:#000000 1px solid;'>&nbsp;1. "+lngDict["rtgCategory"]+"&nbsp;</td>");
			str.push("<td style='padding:1px; text-align:right; border-bottom:#000000 1px solid; border-left:#000000 1px solid;'>{@price0}</td>");
			str.push("</tr>");
			str.push("<tr>");
  		str.push("<td style='padding:1px; text-align:center; border-bottom:#000000 1px solid;'>&nbsp;2. "+lngDict["rtgCategory"]+"&nbsp;</td>");
			str.push("<td style='padding:1px; text-align:right; border-bottom:#000000 1px solid; border-left:#000000 1px solid; '>{@price1}</td>");
			str.push("</tr>");
			str.push("<tr>");
			str.push("<td style='padding:1px; text-align:center; border-bottom:#000000 1px solid;'>&nbsp;3. "+lngDict["rtgCategory"]+"&nbsp;</td>");
			str.push("<td style='padding:1px; text-align:right; border-bottom:#000000 1px solid; border-left:#000000 1px solid;'>{@price2}</td>");
			str.push("</tr>");
			str.push("<tr>");
			str.push("<td style='padding:1px; text-align:center;'>&nbsp;4. "+lngDict["rtgCategory"]+"&nbsp;</td>");
			str.push("<td style='padding:1px; text-align:right; border-left:#000000 1px solid;'>{@price3}</td>");
			str.push("</tr>");
			str.push("</table>");
			window.hrusicaTmpStr=str.join('');
			window.hrusicaTmpStr=window.hrusicaTmpStr.replace(/{@res}/g,RMap.MapApplication.resourcesUrl);
			window.hrusicaTmpStr=window.hrusicaTmpStr.replace(/{@cat}/g,RMap.MapApplication.category);
			window.hrusicaTmpStr=window.hrusicaTmpStr.replace(/{@cat3}/g,RMap.MapApplication.category3);
			window.hrusicaTmpStr=window.hrusicaTmpStr.replace(/{@cat4}/g,RMap.MapApplication.category4);
    }
    
    var s="";
		var prices=ftr.properties.Prices;
		if(prices!=null)
		{
			s= ftr.properties.Name=="Hrušica" ? window.hrusicaTmpStr : window.terminalTmpStr;
			for (var f = 0; f < prices.length; f++)
				s = s.replace("{@price" + f + "}", parseFloat(prices[f]).toFixed(2));
			if(ftr.properties.Name=="Razdrto" && prices[2]=="/" && prices[3]=="/")
				s="<br/><span style='font-weight:bold'>"+lngDict["razdrto"]+"</span>";				
		}
    if(isSum)
			s=s.replace(lngDict["rtgR34"], lngDict["rtgSum"]);
    return s;
}



var rmapLayers={};
function initRmapLayer(name, item)
{
    var init = (item==true || item.checked==false) ? true : false;
    if(map!=null)
    {
        if(name=="dogodki")
        {
            if(isNullOrUndefined(map.layers["dogodki"]) && init==true)
            {
                initRmapLayer_dogodki();
            }
            else
            {
                if(rmapLayers.dogodki!=null)
                {
                    panel.remove(rmapLayers.dogodki);
                    rmapLayers.dogodki=null;
                }
                map.removeLayer("dogodki");
            }
        }
        else if(name=="kamere")
        {
            if(isNullOrUndefined(map.layers["kamere"]) && init==true)
            {
                initRmapLayer_kamere();
            }
            else
            {
                if(rmapLayers.kamere!=null)
                {
                    panel.remove(rmapLayers.kamere);
                    rmapLayers.kamere=null;
                }
                map.removeLayer("kamere");
            }
        }
        else if(name=="vozila")
        {
            if(isNullOrUndefined(map.layers["vozila"]) && init==true)
            {
                initRmapLayer_vozila();
            }
            else
            {
                if(rmapLayers.vozila!=null)
                {
                    panel.remove(rmapLayers.vozila);
                    rmapLayers.vozila=null;
                }
                map.removeLayer("vozila");
            }
        }   
        else if(name=="spis")
        {
            if(isNullOrUndefined(map.layers["spis"]) && init==true)
            {
                initRmapLayer_spis();
            }
            else
            {
                if(rmapLayers.spis!=null)
                {
                    panel.remove(rmapLayers.spis);
                    rmapLayers.spis=null;
                }
                map.removeLayer("spis");
            }
        }
        else if(name=="burja")
        {
            if(isNullOrUndefined(map.layers["burja"]) && init==true)
            {
                initRmapLayer_burja();
            }
            else
            {
                if(rmapLayers.burja!=null)
                {
                    panel.remove(rmapLayers.burja);
                    rmapLayers.burja=null;
                }
                map.removeLayer("burja");
            }
        }  
        else if(name=="vreme")
        {
            if(isNullOrUndefined(map.layers["vreme"]) && init==true)
            {
                initRmapLayer_vreme();
            }
            else
            {
                if(rmapLayers.vreme!=null)
                {
                    panel.remove(rmapLayers.vreme);
                    rmapLayers.vreme=null;
                }
                map.removeLayer("vreme");
            }
        }        
        else if(name=="cvis")
        {
            if(isNullOrUndefined(map.layers["cvis"]) && init==true)
            {
                initRmapLayer_cvis();
            }
            else
            {
                if(rmapLayers.cvis!=null)
                {
                    panel.remove(rmapLayers.cvis);
                    rmapLayers.cvis=null;
                }
                map.removeLayer("cvis");
            }
        }
        else if(name=="stevci")
        {
            if(isNullOrUndefined(map.layers["stevci"]) && init==true)
            {
                initRmapLayer_stevci();
            }
            else
            {
                if(rmapLayers.stevci!=null)
                {
                    panel.remove(rmapLayers.stevci);
                    rmapLayers.stevci=null;
                }
                map.removeLayer("stevci");
            }
        } 
    }
    else
    {
        item.setChecked(true);
    }
}

//=================================================================================
//dogodki kazipot
function initRmapLayer_dogodki()
{  
    var schema = new RMap.FeatureSchema
    (
			[ new RMap.Property('updated', Date, RMap.PropertyInfo.Timestamp|RMap.PropertyInfo.Sortable, null, null, "Zadnja sprememba")],
			RMap.CoordinateSystem.getCoordinateSystem('EPSG:2170')
    );

    schema.setInfoWindowContentTemplate(Delegate.create(this, function(feature)
    {
    	return feature.getProperty(lngDict["lng"] == "EN" ? "opisEn" : "opis") + (feature.properties["updated"] ? " "+lngDict["listTime"]+": "+feature.properties["updated"].format(lngDict["dateFormat"]) : "");
    }));
    schema.setPanelItemContentTemplate(Delegate.create(this, function(feature)
    {
     	return feature.getProperty(lngDict["lng"] == "EN" ? "opisEn" : "opis") + (feature.properties["updated"] ? " "+lngDict["listTime"]+": "+feature.properties["updated"].format(lngDict["dateFormat"]) : "")
		}));
       
		var stDict={};
		stDict["Zastoj"]=1;
		stDict["Izredni dogodek"]=2;
		stDict["Delo na cesti"]=3;
		stDict["Prepoved za tovornjake"]=4;
		stDict["Zaprta cesta"]=5;
		stDict["Poledica"]=6;
		stDict["Veter"]=7;
		stDict["Sneg"]=8;
		stDict["Nesreča"]=9;

		var styler = new RMap.CustomStyler(Delegate.create(this, function(feature)
		{	
			var ps = new RMap.MarkerStyle();
			try
			{          
				var icon;
				var vzrok=stDict[feature.properties['vzrok']];	
				var prior = parseInt(feature.properties['prioriteta']);
				ps.iconSrc = "_res/images/dogodki/nzap"+vzrok;
				if(prior==1)
				{
						ps.iconSize={width:25,height:25};
						ps.anchor={left:13,top:13};
				}
				else if(prior<9)
				{
						ps.iconSrc+="m";
						ps.iconSize={width:20,height:20};
						ps.anchor={left:10,top:10};
				}      
				else if(prior>=9)
				{
						ps.iconSrc+="s";
						ps.iconSize={width:15,height:15};
						ps.anchor={left:8,top:8};
				}
				var tm = window.letBlink && feature.properties.vneseno && feature.properties.vneseno.getTime ? new Date().getTime() - feature.properties.vneseno.getTime() : null;
				ps.iconSrc += (window.letBlink && tm!=null && tm<600000) ? "_blink.gif" : ".gif";    
			}
			catch(ex)
			{}
			return ps;
		}));
		var darsDogodki2Loader = new RMap.FeatureReader(applicationSettings.dogodkiUri, 'get', new RMap.JsonDeserializer({ item: 'dogodki.dogodek', id: 'id', x: 'x', y: 'y' }), null, null, null, applicationSettings.proxyCache);
		var darsDogodki2Storage = new RMap.RemoteFeatureStorage(schema, darsDogodki2Loader, 60000, true, 60000);
    
    map.addLayer(new RMap.DrawingLayer('dogodki', darsDogodki2Storage.getDefaultView(), styler));
    rmapLayers.dogodki=new RMap.LayerPanel(map.layers["dogodki"], lngDict["events"], {reverse:true});
    panel.add(rmapLayers.dogodki);
    
    RMapFilterApply();
		RMapSortApply();
}
  
//=================================================================================         
//kamere
function initRmapLayer_kamere()
{
    var darsKamereLoader = new RMap.FeatureReader(applicationSettings.kamereUri, 'get', new RMap.GeoRssDeserializer());
    var schema = new RMap.FeatureSchema([], RMap.CoordinateSystem.getCoordinateSystem('EPSG:2170'));
    
    schema.setPanelItemContentTemplate(Delegate.create(this, function(feature)
    {
        return feature.getProperty("title");
    }));
    
    var darsKamereStorage = new RMap.RemoteFeatureStorage(schema, darsKamereLoader, 0, true);    
    var kamereStyler = new RMap.CustomStyler(Delegate.create(this, function(feature)
    {
        var ps = new RMap.MarkerStyle();
        ps.iconSrc="_res/images/Traffic/acam.gif";
				ps.iconSize={width:18,height:16};
				ps.anchor={left:9,top:8};
        return ps;
    }));  
    var darsKamereLayer = new RMap.DrawingLayer('kamere', darsKamereStorage.getDefaultView(), kamereStyler);
    map.addLayer(darsKamereLayer);  
    //darsKamereLayer.setOrder(RMap.OrderPosition.Back);
      
    rmapLayers.kamere=new RMap.LayerPanel(darsKamereLayer, lngDict["cameras"])
    panel.add(rmapLayers.kamere);
}

function initRmapLayer_cvis()
{   
    var darsCvisLoader = new RMap.FeatureReader(applicationSettings.cvisUri, 'get', new RMap.GeoRssDeserializer({id:"link"}), null, null, null, null);
    var schema = new RMap.FeatureSchema(
    [ new RMap.Property('pubDate', Date, RMap.PropertyInfo.Timestamp|RMap.PropertyInfo.Sortable, null, null, "Zadnja sprememba"),
      new RMap.Property('title', String, RMap.Default, null, null, "Title"),
      //new RMap.Property('cesta_cesta', String, RMap.PropertyInfo.Sortable, null, null, "Porocilo"),
      new RMap.Property('description', String, RMap.Default, null, null, "Description")
    ],RMap.CoordinateSystem.getCoordinateSystem('EPSG:4326'));
       
    schema.setPanelItemContentTemplate(Delegate.create(this, function(feature)
    {
        return feature.properties.title + "<br/>" + feature.properties.cesta_cesta.stanje.opis;
    }));
    
    schema.setInfoWindowContentTemplate(Delegate.create(this, function(feature)
    {
        var s="<b>"+feature.properties["title"]+"</b><br/>";
        s+= feature.properties["description"]+"<br/><br/>";
        s+= "<a target='CVIS_window' href='"+feature.properties["link"]+"' onclick='if(window.CvisTarget==null || window.CvisTarget.closed==true){window.CvisTarget=window.open(this.href);} else {window.CvisTarget.location=this.href;window.CvisTarget.focus()}'/>Vstop v CVIS</a><br/>";
        return s;
    }));
              
    var darsCvisStorage = new RMap.RemoteFeatureStorage(schema, darsCvisLoader, 60000 * 3, true); 
    
    var styler = new RMap.CustomStyler(Delegate.create(this, function(feature) 
    {
			var ps = new RMap.MarkerStyle();
			var icn="gray";
			var val=feature.properties.cesta_cesta.stanje.value;
			if(val==0)
				icn="green";
			else if(val==1 || val==2)
				icn="blue";
			else if(val==3 || val==4 || val==6)
				icn="red";
			else if(val==5)
				icn="orange";
			ps.iconSrc="_res/images/cvis/cvis_"+icn+".gif";
			ps.iconSize={width:15,height:35};
			ps.anchor={left:7,top:28};
			ps.infoWindowAnchor={left:7,top:7};
			return ps;
    }));
    
    var cvisLayer=new RMap.DrawingLayer('cvis', darsCvisStorage.getDefaultView(), styler);
    map.addLayer(cvisLayer); 
    //cvisLayer.setOrder(RMap.OrderPosition.Back);
    
    rmapLayers.cvis=new RMap.LayerPanel(map.layers["cvis"], lngDict["weastations"])
    panel.add(rmapLayers.cvis);
}

// Vreme
function initRmapLayer_vreme()
{
  var weaIContent=function(feature)
  {
    var cnt=feature.properties.domain_longTitle + "<br/>";
    if(feature.properties.nn_shortText>'')
			cnt += feature.properties.nn_shortText + ", ";
    cnt += feature.properties.t + " " + feature.properties.td_var_unit;
    if(feature.properties.wwsyn_shortText>'')
			cnt += "<br/>" + feature.properties.wwsyn_shortText;
    return cnt;
  }

	var weaStyler = new RMap.CustomStyler(Delegate.create(this, function(feature)
	{
		var ps = new RMap.MarkerStyle();
		if(feature.properties['nn_icon-wwsyn_icon']>'')
			ps.iconSrc=applicationSettings.weatherIconsUrl + feature.properties['nn_icon-wwsyn_icon'] + ".png";
		else
//			ps.iconSrc=applicationSettings.iconsRepository + "Weather/nipodatka.png";
			ps.iconSrc=applicationSettings.iconsRepository + "blank.gif";
		return ps;
	})); 

	var weaLoader = new RMap.FeatureReader(applicationSettings.weatherUri, 'get', new RMap.JsonDeserializer({item:'data.metData', x:'domain_lon', y:'domain_lat'}), null, null, "json", null);
	var weaSchema = new RMap.FeatureSchema([], RMap.CoordinateSystem.getCoordinateSystem('EPSG:4326'));
	weaSchema.setInfoWindowContentTemplate(Delegate.create(this, weaIContent));
	weaSchema.setPanelItemContentTemplate(Delegate.create(this, weaIContent));
	var weaStorage = new RMap.RemoteFeatureStorage(weaSchema, weaLoader, 60000*3, true);    
	var weaLayer = new RMap.DrawingLayer('vreme', weaStorage.getDefaultView(), weaStyler);
	map.addLayer(weaLayer);  
	rmapLayers.vreme=new RMap.LayerPanel(map.layers["vreme"], lngDict["weather"]);
	panel.add(rmapLayers.vreme);
}

// Burja
function initRmapLayer_burja()
{
  var infoContent=function(feature)
  {      
    var cnt=feature.properties["title"] + ": " + feature.properties["veter"] + " km/h";
    return cnt;
  }

	var styler = new RMap.CustomStyler(Delegate.create(this, function(feature)
	{
		var ps = new RMap.MarkerStyle();
		var v=feature.properties['veter'];
		if(v<5)
			ps.iconSrc=applicationSettings.iconsRepository + "burja/wind1.gif";
		else if(v<20)
			ps.iconSrc=applicationSettings.iconsRepository + "burja/wind2.gif";
		else if(v<50)
			ps.iconSrc=applicationSettings.iconsRepository + "burja/wind3.gif";
		else if(v<80)
			ps.iconSrc=applicationSettings.iconsRepository + "burja/wind4.gif";
		else
			ps.iconSrc=applicationSettings.iconsRepository + "burja/wind5.gif";
		ps.iconSize={width:25,height:30};
		ps.anchor={left:4,top:30};
		ps.infoWindowAnchor={left:3,top:5};
		return ps;
	})); 

	var loader = new RMap.FeatureReader(applicationSettings.burjaUrl, 'get', new RMap.JsonDeserializer({item:'feed.entry', x:'LONGITUDE', y:'LATITUDE'}), null, null, "json", null);
	var schema = new RMap.FeatureSchema([], RMap.CoordinateSystem.getCoordinateSystem('EPSG:4326'));
	schema.setInfoWindowContentTemplate(Delegate.create(this, infoContent));
	schema.setPanelItemContentTemplate(Delegate.create(this, infoContent));
	var storage = new RMap.RemoteFeatureStorage(schema, loader, 60000*3, true);    
	var layer = new RMap.DrawingLayer('burja', storage.getDefaultView(), styler);
	map.addLayer(layer);  
	rmapLayers.burja=new RMap.LayerPanel(map.layers["burja"], lngDict["burja"]);
	panel.add(rmapLayers.burja);
}

//=================================================================================
//SPIS
function initRmapLayer_spis()
{              
	var schema = new RMap.FeatureSchema(
	[ new RMap.Property('updated', Date, RMap.PropertyInfo.Timestamp|RMap.PropertyInfo.Sortable, null, null, "Zadnja sprememba"),
		new RMap.Property('spis_status', Number, RMap.PropertyInfo.Sortable, null, null, "Status"),
		new RMap.Property('spis_priority', Number, RMap.PropertyInfo.Sortable, null, null, "Prioriteta")
	],RMap.CoordinateSystem.getCoordinateSystem('EPSG:4326'));
	   
	schema.setPanelItemContentTemplate(Delegate.create(this, function(feature)
	{
		var s="<b>"+feature.properties["spis_tip"] + ": " + feature.properties["title"]+"</b><br/>";
		s+= feature.properties["summary"] ? feature.properties["summary"].replace(/!D!/g,"{Datum}").replace(/!U!/g,"{Ura}") + "<br/>" : "<br/>";
		s+= "status: " + (feature.properties["spis_status"]==1?"deluje":"ne deluje") + ", prioriteta: " + feature.properties["spis_priority"];
		s+= feature.properties["updated"] ? "<br/>spremenjeno: " + new Date(feature.properties["updated"]).format("dd.MM.yyyy HH:mm") : "";
		return s;
	}));

	schema.setInfoWindowContentTemplate(Delegate.create(this, function(feature)
	{
		var w = feature.properties["spis_tip"]=="PP" ? 192 : 400;
		var s="<b>"+feature.properties["title"]+"</b><br/>";
		s+= feature.properties["summary"] ? feature.properties["summary"].replace(/!D!/g,"{Datum}").replace(/!U!/g,"{Ura}")+"<br/>" : "";
		s+= "<div style='display:block; width:"+w+"px; height:67px;'><img src='" + feature.properties['link'] + "' style='width:"+w+"px; height:67px;'/></div>";
		s+= "status: " + (feature.properties["spis_status"]==1?"deluje":"ne deluje") + ", &nbsp; prioriteta: " + feature.properties["spis_priority"] + ", &nbsp; tip: " + feature.properties["spis_tip"];
		s+= feature.properties["updated"] ? "<br/>spremenjeno: " + new Date(feature.properties["updated"]).format("dd.MM.yyyy HH:mm") : "";
		return s;
	}));
	   
	var darsSpisLoader = new RMap.FeatureReader(applicationSettings.spisUri, 'get', new RMap.GeoRssDeserializer({id:"id"}), null, null, null, null);
	var darsSpisStorage = new RMap.RemoteFeatureStorage(schema, darsSpisLoader, 60000 * 3, true); 

	var styler = new RMap.CustomStyler(Delegate.create(this, function(feature) {
		var ps = new RMap.MarkerStyle();
		if(feature.properties.summary==null || feature.properties.summary.replace(new RegExp("!U!|!D!| |/", "g"),"")=="")
			ps.iconSrc="_res/images/spis/portal0.gif";
		else
			ps.iconSrc="_res/images/spis/portal1.gif";
		ps.iconSize={width:22,height:24};
		ps.anchor={left:17,top:23};
		ps.infoWindowAnchor={left:10,top:9};
		return ps;
	}));
	   
	var spisLayer=new RMap.DrawingLayer('spis', darsSpisStorage.getDefaultView(), styler);
	map.addLayer(spisLayer); 
	//spisLayer.setOrder(RMap.OrderPosition.Back);
	rmapLayers.spis=new RMap.LayerPanel(spisLayer, lngDict["portals"])
	panel.add(rmapLayers.spis);
}

//=================================================================================
//Števci
function initRmapLayer_stevci()
{
  var schema = new RMap.FeatureSchema([], RMap.CoordinateSystem.getCoordinateSystem('EPSG:2170'));
  
  schema.setInfoWindowContentTemplate(Delegate.create(this, function(feature)
	{
		var str=[];
		str.push("<b>" + feature.properties["stevci_cestaOpis"] + ", "+lngDict["loc"]+" " + feature.properties["stevci_lokacijaOpis"]+"</b><br/><br/>");
		var ss=[[],[],[],[],[],[],[]];
		var ftrs=darsStevciStorage.getFeatures();
		for(var f=0;f<ftrs.length;f++)
		{
			var prps=ftrs[f].properties;
			if(prps["stevci_lokacija"]==feature.properties["stevci_lokacija"])
			{
				var stat=parseInt(prps["stevci_stat"])+1;
				if(stat<2)
					stat=0;
				if(stat>6)
					stat=1;
				var s=[];
				s.push("<img src='_res/images/stevci/stevec_"+prps["stevci_stat"]+".gif' style='float:left; margin-right:10px'/>");
				s.push(lngDict["stvDir"]+" "+prps["stevci_smerOpis"]+ " " + (prps["stevci_pasOpis"]>'' ? prps["stevci_pasOpis"] : "") + ": " +prps["stevci_statOpis"]);
				s.push("<br/>"+lngDict["stvSpd"]+":&nbsp;"+prps["stevci_hit"]+"&nbsp;km/h,&nbsp; "+lngDict["stvNum"]+":&nbsp;"+prps["stevci_stev"]+"/h,&nbsp; "+lngDict["stvRaz"]+":&nbsp;"+prps["stevci_gap"]+"&nbsp;s<br style='clear:all'/><br/>");
				ss[stat][ss[stat].length]=s.join("");
			}
		}
		for(var f=ss.length-1;f>=0;f--)
		{
			for(var ff=0;ff<ss[f].length;ff++)
				str.push(ss[f][ff]);
		}
		str=str.join("");
		return str.substring(0,str.length-5);
	}));
  schema.setPanelItemContentTemplate(Delegate.create(this, function(feature)
  {
      return feature.properties["title"]+ ":<br/>" +feature.properties["stevci_statOpis"];
  }));

  var stevciStyler = new RMap.CustomStyler(Delegate.create(this, function(feature)
  {	
    var ps = new RMap.MarkerStyle();
    ps.iconSrc="_res/images/stevci/stevec_"+feature.properties["stevci_stat"]+".gif";
    ps.iconSize={width:21,height:21};
		ps.anchor={left:10,top:10};
    return ps;
  }));  

  var comparer = Delegate.create(this, function(feature1, feature2) 
  {
		var fp = feature1.properties["stevci_stat"];
		if(fp==6)
			fp=0.5;
		var sp = feature2.properties["stevci_stat"];
		if(sp==6)
			sp=0.5;

		if (!fp)
			return 1;
		else if (!sp)
			return -1;
		if (fp > sp)
			return 1;
		else if (fp < sp)
			return -1;
		else
			return 0;
  });

  var darsStevciLoader = new RMap.FeatureReader(applicationSettings.stevciUri, 'get', new RMap.JsonDeserializer({item:'feed.entry',id:'id',x:'stevci_geoX',y:'stevci_geoY'}), null, null, "json", null);
  var darsStevciStorage = new RMap.RemoteFeatureStorage(schema, darsStevciLoader, 60000 * 3, true);    
	darsStevciStorage.getDefaultView().setSort(comparer);
  var darsStevciLayer = new RMap.DrawingLayer('stevci', darsStevciStorage.getDefaultView(), stevciStyler);
  map.addLayer(darsStevciLayer);  
  //darsStevciLayer.setOrder(RMap.OrderPosition.Back);
    
  rmapLayers.stevci=new RMap.LayerPanel(darsStevciLayer, lngDict["counters"], {reverse:true})
  panel.add(rmapLayers.stevci);
}

//=================================================================================
//Tujina
function initRmapLayer_tujina()
{
//  var iContent=function(feature)
//  {    
//    return feature.properties.title + "<br/>" + feature.properties.description;
//  }
	var styler = new RMap.CustomStyler(Delegate.create(this, function(feature)
	{
		var ps = new RMap.MarkerStyle();
		ps.iconSrc=applicationSettings.iconsRepository+"countries/"+feature.getId()+".gif";
		ps.iconSize={width:26,height:17};
		ps.anchor={left:13,top:9};
//		if (feature.getId().substring(0, 4) == "info")
//		{ 
//			ps.iconSrc = applicationSettings.iconsRepository + "info.gif";
//			ps.iconSize = { width: 22, height: 24 };
//			ps.anchor = { left: 11, top: 12 };
//		}		
		return ps;
	}));
  var layer=map.addDrawingLayer("tujina");
  layer.setStyler(styler);
  //layer.getFeatureView().getStorage().getSchema().setInfoWindowContentTemplate(Delegate.create(this, iContent));
  var arr=[];
  arr[0]={id:"a", x:510000, y:183000};
  arr[1]={id:"i", x:360000, y:100000};
  arr[2]={id:"h", x:630000, y:180000};
  arr[3]={id:"hr", x:570000, y:50000};
  for(var f=0;f<arr.length;f++)
  {
		var cnt="";
		var lnk=applicationSettings["tujinaLink_"+arr[f].id][0];
		var ftr=new RMap.Feature(arr[f].id, new RMap.Geometry(RMap.GeometryType.Point,[arr[f].x, arr[f].y]), {title:lngDict["tujina_"+arr[f].id], link:lnk});                                 
		layer.getFeatureView().getStorage().add(ftr);
  }
}
