var shortestPath = {};
shortestPath.initialized = false;
shortestPath.POIsZoom = null;
shortestPath.bbox = null;

var routingSuffix = null;


var offset = function(size) {
    var pixel = new OpenLayers.Pixel(-size.w*2/3,-size.h*2/3);
    return pixel;
};

shortestPath.init = function() {

    shortestPath.pointLayer = new OpenLayers.Layer.Markers("Shortest path points",
                                                {displayInLayerSwitcher:false});
    map.addLayer(shortestPath.pointLayer);

    shortestPath.initialized = true;
    map.events.register('mousemove', map,shortestPath.onMouseMove);
    
};

shortestPath.deactivate = function() {
    map.removeLayer(shortestPath.pointLayer);
    shortestPath.pointLayer.destroy();
    map.removeLayer(shortestPath.routeLayer);
    shortestPath.routeLayer.destroy();

    shortestPath.initialized = false;
};

shortestPath.remove = function() {
    map.removeLayer(shortestPath.pointLayer);
    shortestPath.pointLayer.destroy();
    map.removeLayer(shortestPath.routeLayer);
    shortestPath.routeLayer.destroy();

    shortestPath.initialized = false;
};

shortestPath.addPoint = function(lonlat, type) {

    // create and add
    var size = new OpenLayers.Size(16,16);
    var icon = null;
    var marker = null;

    switch(type) {
        case "start":
                if (!shortestPath.startPoint ) {
                    icon = new OpenLayers.Icon(markerImageUrl+"/trip-start.gif", size, null, offset);
                    marker = new OpenLayers.Marker(lonlat,icon);
                    shortestPath.startPoint = marker;

                    try {
                    startPointClickedInMap();
                    } catch(e) {}
                }
                break;
        case "end":
                if (!shortestPath.endPoint ) {
                    icon = new OpenLayers.Icon(markerImageUrl+"/trip-end.gif", size, null, offset);
                    marker = new OpenLayers.Marker(lonlat,icon);
                    shortestPath.endPoint = marker;

                    try {
                    endPointClickedInMap();
                    } catch(e) {}
                }
                break;
        case "middle":
                if (!shortestPath.middlePoint ) {
                    icon = new OpenLayers.Icon(markerImageUrl+"/trip-middle.gif", size, null, offset);
                    marker = new OpenLayers.Marker(lonlat,icon);
                    shortestPath.middlePoint = marker;

                    try {
                    middlePointClickedInMap();
                    } catch(e) {}
                }
                break;
    }

    shortestPath.pointLayer.addMarker(marker);
    marker.events.register('mousedown', marker, shortestPath.onMouseDown);
    marker.events.register('mouseup', marker, shortestPath.onMouseUp);

    if (shortestPath.endPoint && shortestPath.startPoint) {
        shortestPath.calculate();
    }
    // remove the vector point
    // hsLayers.getHsVectorLayer().destroyFeatures();
};

// kafkuf upraf
shortestPath.addMiddlePoint = function(lonlat) {

    if (shortestPath.middlePoint) {
        shortestPath.pointLayer.removeMarker(shortestPath.middlePoint);
        shortestPath.middlePoint.destroy();
        shortestPath.middlePoint = null;
    }
    if(lonlat){
        shortestPath.addPoint(lonlat,"middle");
        //shortestPath.calculate();
    }
};
shortestPath.addStartPoint = function(lonlat) {
    if (shortestPath.startPoint) {
        shortestPath.pointLayer.removeMarker(shortestPath.startPoint);
        shortestPath.startPoint.destroy();
        shortestPath.startPoint = null;
    }
    if(lonlat){
        shortestPath.addPoint(lonlat,"start");
    }
}
shortestPath.addEndPoint = function(lonlat) {
    if (shortestPath.endPoint) {
        shortestPath.pointLayer.removeMarker(shortestPath.endPoint);
        shortestPath.endPoint.destroy();
        shortestPath.endPoint = null;
    }
    if(lonlat){
        shortestPath.addPoint(lonlat,"end");
    }
}

shortestPath.calculate = function () {

    if (!shortestPath.startPoint || !shortestPath.endPoint) {
        return;
    }
    if ((!shortestPath.middlePoint)&&(shortestPath.startPoint.lonlat.lon == shortestPath.endPoint.lonlat.lon)&&(shortestPath.startPoint.lonlat.lat == shortestPath.endPoint.lonlat.lat)){
	//alert('!!! cil a start nesmi byt jsou totozne !!!');
	return;
    }	
    shortestPath.toggleLoadingInfo(true);


    //var url = "http://www.hsrs.cz/mapserv/posazavi/routing/?mode=gml&coords="+
    var url = "http://www.hsrs.cz/mapserv/posazavi/routing/?coords="+
    	shortestPath.startPoint.lonlat.lon+","+shortestPath.startPoint.lonlat.lat+",";
    if(shortestPath.middlePoint){
     	url += shortestPath.middlePoint.lonlat.lon+","+shortestPath.middlePoint.lonlat.lat+",";
    }           
    url += shortestPath.endPoint.lonlat.lon+"," + shortestPath.endPoint.lonlat.lat;
    if (routingSuffix) {
        url+= routingSuffix;
    }
    OpenLayers.loadURL(url, '', this, shortestPath.parseShortestPath);
};

shortestPath.parseShortestPath = function(xmlhttp) {
    var xml = xmlhttp.responseXML;

    if (shortestPath.routeLayer ) {
        map.removeLayer(shortestPath.routeLayer);
        shortestPath.routeLayer.destroy();
    }

    if (!xml) {
        shortestPath.toggleLoadingInfo(false);
        return;
    }

    var gml = xml.getElementsByTagName("gml")[0];
    var url = gml.getAttribute("href");
    
    shortestPath.routeLayer  = new OpenLayers.Layer.GML("Nejkratší cesta",
                                                        url,
                                                    {displayInLayerSwitcher: false,
                                                    style:{strokeColor:"red",
                                                    strokeOpacity:"0.5",
                                                    strokeWidth:"5px"}});
    shortestPath.routeLayer.onFeatureInsert = shortestPath.onFeatureInsert;
    map.addLayer(shortestPath.routeLayer);
    if (map.getLayerIndex(shortestPath.pointLayer) > 0) {
        map.setLayerIndex(shortestPath.routeLayer, map.getLayerIndex(shortestPath.pointLayer));
    }

    //map.zoomToExtent(shortestPath.getBBox(shortestPath.routeLayer.features));

    var profile = xml.getElementsByTagName("xml")[0];
    url = profile.getAttribute("href");
    shortestPath.toggleLoadingInfo(false);

    shortestPath.POIsZoom = map.getZoom();
    
    var pathProf = false;
    try {
        if (displayPathProfile){
            pathProf = true;
        }
    }
    catch(e) {}

    if (pathProf) {
        displayPathProfile(url); 
    }
    //document.getElementById("trasaXMLUrl").value = url;
};


clicked = function(e) {
        if(shortestPath.initialized == false) {
            shortestPath.init();
        }

        var lonlat = map.getLonLatFromViewPortPx(e.xy);

        if (!shortestPath.startPoint) {
            shortestPath.addPoint(lonlat,"start");
        }
        else if (!shortestPath.endPoint) {
            shortestPath.addPoint(lonlat,"end");
        }

};

shortestPath.startPointOrEndPoint = "start";
shortestPath.startPoint = null;
shortestPath.endPoint = null;

shortestPath.mouseDown = false;
shortestPath.movingMarker = null;

shortestPath.onMouseDown = function(evt) {
    shortestPath.mouseDown = true;
    OpenLayers.Event.stop(evt);
    shortestPath.movingMarker = this;
}

shortestPath.onMouseMove = function(evt) {
    if (!shortestPath.mouseDown && !shortestPath.movingMarker) {
        return;
    }
   	var container = document.getElementById('map_OpenLayers_Container');
	var px = new OpenLayers.Pixel(evt.xy.x-container.offsetLeft,evt.xy.y-container.offsetTop);
    shortestPath.movingMarker.icon.moveTo(px);
    OpenLayers.Event.stop(evt);
}

shortestPath.onMouseUp = function(evt) {

    /* nastaveni poli formularu */
    if (shortestPath.movingMarker == shortestPath.startPoint) {
        setStartPoint(null);
    }
    else if (shortestPath.movingMarker == shortestPath.middlePoint) {
        setMiddlePoint(null);
    }
    else if (shortestPath.movingMarker == shortestPath.endPoint) {
        setEndPoint(null);
    }

    /* pocitani cesty */
    if (shortestPath.mouseDown) {
        shortestPath.mouseDown = false;
        var lonlat = map.getLonLatFromViewPortPx(this.icon.px);

        this.moveTo(this.icon.px);

        shortestPath.mouseDown = false;
        shortestPath.movingMarker = null;

        shortestPath.calculate();
    }

    OpenLayers.Event.stop(evt);
}

shortestPath.getBBox = function() {
    var minx = null;
    var miny = null; 
    var maxx = null;
    var maxy = null;
    var points = [shortestPath.startPoint, shortestPath.endPoint, shortestPath.middlePoint];
    for (var i = 0; i < points.length; i++) {
        if (points[i]) {
            var lonlat = points[i].lonlat;
            if (minx == null || lonlat.lon < minx) minx = lonlat.lon;
            if (miny == null || lonlat.lat < miny) miny = lonlat.lat;
            if (maxx == null || lonlat.lon > maxx) maxx = lonlat.lon;
            if (maxy == null || lonlat.lat > maxy) maxy = lonlat.lat;
        }
    }
    return new OpenLayers.Bounds(minx,miny,maxx,maxy);
};

shortestPath.toggleLoadingInfo = function(visible) {

    /* vytvorit divy */
    if (!shortestPath.loadingDivElements) {
        try {
        shortestPath.loadingDivElements = [];

        var parDiv = document.getElementById("map");

        /* sedivy div na pozadi */
        var div = document.createElement("div");
        parDiv.appendChild(div);
        div.style.width=map.size.w+"px";
        div.style.height=map.size.h+"px";
        div.style.background = "#ccc";
        var opacity = 0.5;
        div.style.filter = 'alpha(opacity=' + (opacity * 100) + ')';
        div.style.opacity = opacity;
        div.style.position = "absolute";
        div.style.left = "0px";
        div.style.top = "0px";
        div.style.textAlign = "center";
        div.style.verticalAlign = "bottom";
        div.style.zIndex="10000";
        
        shortestPath.loadingDivElements.push(div);

        /* bily mensi div v popredi */
        div = document.createElement("div");
        div.style.zIndex="10001";
        div.style.border="2px green solid";
        div.style.background="white";
        div.style.position="absolute";
        div.style.padding="20px";
        div.style.width="150px";
        div.style.height="75px";
        div.style.left="50%";
        div.style.top="50%";
        div.style.marginLeft="-75px";
        div.style.marginTop="-37px";
        div.style.fontFamily="sans-serif";
        div.style.fontWeight="bold";
        div.style.fontSize="10px";
        div.style.color="green";
        div.style.textAlign="center";

        shortestPath.loadingDivElements.push(div);

        parDiv.appendChild(div);

        var img = document.createElement("img");
        img.src = "img/loading.gif";
        div.appendChild(img);

        div.appendChild(document.createElement("br"));
        div.appendChild(document.createTextNode("Probíhá výpočet..."));

        shortestPath.loadingDivElements.push(img);

        //div.style.left= parDiv.offsets[0]+map.size.w/2-div.clientWidth/2+"px";
        //div.style.top= parDiv.offsets[1]+map.size.h/2-div.clientHeight/2+"px";
        }catch(e){console.log(e)}
    }

    /* zobrazovani */
    for (var i = 0; i < shortestPath.loadingDivElements.length; i++) {
        shortestPath.loadingDivElements[i].style.display = (visible ? "block" : "none");
    }
};

/**
 * smazat neco z mapy
 * @param what {String} co se smaze: start, end, middle,path,pois
 */

shortestPath.remove = function(what) {
    try {
        switch(what) {
            case "start":
                shortestPath.pointLayer.removeMarker(shortestPath.startPoint);
                shortestPath.startPoint = null;
                break;
            case "end":
                shortestPath.pointLayer.removeMarker(shortestPath.endPoint);
                shortestPath.endPoint = null;
                break;
            case "middle":
                shortestPath.pointLayer.removeMarker(shortestPath.middlePoint);
                shortestPath.middlePoint = null;
                break;
            case "path":
                shortestPath.routeLayer.eraseFeatures(shortestPath.routeLayer.features);
                map.removeLayer(shortestPath.routeLayer);
                shortestPath.routeLayer.destroy();
                shortestPath.routeLayer= null;
                break;
            case "markers":
                shortestPath.pointLayer.clearMarkers();
                map.removeLayer(shortestPath.pointLayer);
                shortestPath.pointLayer.destroy();
                shortestPath.pointLayer= null;
                break;
            case "pois":
                map.removeLayer(shortestPath.pois);
                shortestPath.pois.destroy();
                shortestPath.pois = null;
                break;
        }
    }
    catch (e) {};
};

/**
 * pridat body zajmu
 * @param url
 */

shortestPath.addPOIs = function(url) {

    if (shortestPath.pois){
    	shortestPath.pois.setVisibility(false);
        map.removeLayer(shortestPath.pois);
        //map.events.unregister("zoomend",shortestPath.pois,onZoomChanged);
        shortestPath.pois.destroy();
        shortestPath.pois = null;
    }

    shortestPath.pois = new OpenLayers.Layer.Text("Points of interest",{location: url,visibility:true,displayInLayerSwitcher:false});
    map.addLayer(shortestPath.pois);
    shortestPath.pois.markerClick = markerClick;
    //map.events.register("zoomend",shortestPath.pois,shortestPath.onZoomChanged);
    map.setLayerIndex(shortestPath.pointLayer, map.getLayerIndex(shortestPath.pois));
};

shortestPath.onZoomChanged = function(evt) {
   var url = shortestPath.pois["location"].replace(/zoom=[0-9]*/,"zoom="+map.getZoom());
   OpenLayers.Event.stop(evt);
   shortestPath.addPOIs(url);
   return;
    if (!this.map) {return;}
    shortestPath.pois.clearFeatures();
    //return;
    /*shortestPath.pois.initialize(
        shortestPath.pois.name,
        {'location': url,
        visibility:true} );*/
   shortestPath.pois.location=url;
   shortestPath.pois.redraw();
};

shortestPath.getRouteById = function(id,x,y) {

    shortestPath.toggleLoadingInfo(true);

    if (id) {
        var url = "http://www.hsrs.cz/mapserv/posazavi/routing/?id="+id+"&x="+x+"&y="+y;
        OpenLayers.loadURL(url, '', this, shortestPath.parseShortestPath);
    }
};

shortestPath.onFeatureInsert = function(feature) {
    map.zoomToExtent(feature.geometry.getBounds());

};

