var selectFeatureButton, routingStartButton, routingEndButton, routingEditButton, routingDragFlags, notifyControl;
var layerRouting, styleMapRouting;
var routingStartFeature, routingEndFeature, routingLineFeature;
var requestSatusLocateAndInterpolatePoint, requestStatusRouting;
var REQUEST_STATUS_RUNNING = 'RUNNING';

function handleToolBar(button) {
    var controls = map.getControlsBy('type', OpenLayers.Control.TYPE_BUTTON);
    for(key in controls) {
        controls[key].deactivate();
    }
    if (clickVector !== undefined)
        clickVector.deactivate();
    if (hoverVector !== undefined)
        hoverVector.deactivate();

    button.activate();
}

function deactivateRoutingTools() {
    routingStartButton.deactivate();
    routingEndButton.deactivate();
    routingEditButton.deactivate();
    routingDragFlags.deactivate();
    notifyControl.trigger();
}
function activateCurrentRoutingTool() {
    notifyControl.deactivate();
    jQuery('.ui-button.ui-state-active').prev().trigger('click');
}

function initRoutingMapStyles() {

    var styleRouting = {
        graphicZIndex: 3,
        cursor: 'move',
        pointRadius: 8,
        fillOpacity: 1,
        externalGraphic: "${getIcon}",
        graphicXOffset: -3,
        graphicYOffset: -15,

        label: "${getName}",

        labelXOffset: "-12",
        labelYOffset: "3",
        //fontColor: "red",
        fontSize: "14px",
        fontFamily: "Verdana",
        fontWeight: "bold",
        labelAlign: "lb"

    }




    var context = {
        context: {
            getIcon: function(feature) {
                switch(feature.attributes.type) {
                    case 'start':
                        return '../images/GREEN.png';
                    case 'end':
                        return '../images/RED.png';
                    case 'test':
                        return '';
                    default:
                        return '../images/YELLOW.png';
                }
            },
            getName: function(feature) {
                if (feature.attributes.name)
                    return feature.attributes.name;
                else
                    return '';
            }
        }
    }
    var styleHighlite = {
        strokeColor: "#00FFFF",
        strokeWidth: 3,
        pointRadius: 6,
        pointerEvents: "visiblePainted",
        graphicZIndex: 6,

        label: "${getName}",

        labelXOffset: "-400px",
        labelYOffset: "-10px",
        //fontColor: "red",
        fontSize: "12px",
        fontFamily: "Verdana",
        fontWeight: "bold",
        labelAlign: "lb"
    };
    styleMapRouting = new OpenLayers.StyleMap({
        'default': new OpenLayers.Style(styleRouting, context),
        'select': new OpenLayers.Style(styleHighlite, context),
        'temporary': new OpenLayers.Style(styleHighlite, context)
    });
}

function initRouting() {
    initRoutingMapStyles();
    
    selectFeatureButton = new OpenLayers.Control.Button({
        displayClass: "selectFeature",
        trigger: function() {
            handleToolBar(selectFeatureButton);
            
            abortRouting();
            
            if (hoverVector !== undefined)
                hoverVector.activate();
            
            if (clickVector !== undefined)
                clickVector.activate();
        }
    });

    /* init start button control */
    routingStartButton = new OpenLayers.Control.Button({
        displayClass: "routingStart",
        trigger: function() {
            if (jQuery('#frmRoutingInfo').length == 0) {
                showLoading($.r3msgs.routing_init);
                hideAllRouteLayer();
                openRoutingInfo(null, routingStartButton);

                return false;
            }

            handleToolBar(routingStartButton);
            routingDragFlags.activate();
        }
    });
    
    routingStartButton.onClick = function(evt) {
        var pt = map.getLonLatFromViewPortPx(evt.xy);
        requestLocateAndInterpolatePoint(pt, 'start');
    };
    routingStartButton.handlerOptions = OpenLayers.Util.extend({}, this.defaultHandlerOptions);
    routingStartButton.handler = new OpenLayers.Handler.Click(routingStartButton, {
        'click': routingStartButton.onClick
    }, routingStartButton.handlerOptions);

    /* init end button control */
    routingEndButton = new OpenLayers.Control.Button({
        displayClass: "routingEnd",
        trigger: function() {
            if (jQuery('#frmRoutingInfo').length == 0) {
                showLoading($.r3msgs.routing_init);
                hideAllRouteLayer();
                openRoutingInfo(null, routingEndButton);
                return false;
            }

            handleToolBar(routingEndButton);
            routingDragFlags.activate();
        }
    });
    routingEndButton.onClick = function(evt) {
        var pt = map.getLonLatFromViewPortPx(evt.xy);
        requestLocateAndInterpolatePoint(pt, 'end');
    };
    routingEndButton.handlerOptions = OpenLayers.Util.extend({}, this.defaultHandlerOptions);
    routingEndButton.handler = new OpenLayers.Handler.Click(routingEndButton, {
        'click': routingEndButton.onClick
    }, routingEndButton.handlerOptions);

    /* init edit button control */
    routingEditButton = new OpenLayers.Control.Button({
        displayClass: "routingEdit",
        trigger: function() {
            if (jQuery('#frmRoutingInfo').length == 0) {
                showLoading($.r3msgs.routing_init);
                hideAllRouteLayer();
                openRoutingInfo(null, routingEditButton);
                return false;
            }

            handleToolBar(routingEditButton);
            routingDragFlags.activate();
        }
    });
    routingEditButton.onClick = function(evt) {
        var pt = map.getLonLatFromViewPortPx(evt.xy);
        requestLocateAndInterpolatePoint(pt, 'intermediate');
    };
    routingEditButton.handlerOptions = OpenLayers.Util.extend({}, this.defaultHandlerOptions);
    routingEditButton.handler = new OpenLayers.Handler.Click(routingEditButton, {
        'click': routingEditButton.onClick
    }, routingEditButton.handlerOptions);

    notifyControl = new OpenLayers.Control.Button({
        trigger: function() {
            notifyControl.onClick = function(evt) {
                notifyInfo({
                    message: {
                        title: $.r3msgs.attention,
                        text: $.r3msgs.requestIsRunning
                    }
                });
            };
            notifyControl.handlerOptions = OpenLayers.Util.extend({}, this.defaultHandlerOptions);
            notifyControl.handler = new OpenLayers.Handler.Click(notifyControl, {
                'click': notifyControl.onClick
            }, notifyControl.handlerOptions);
            notifyControl.activate();
        }
    });
    controlPanel.addControls([selectFeatureButton, routingStartButton, routingEndButton, routingEditButton, notifyControl]);

    layerRouting = new OpenLayers.Layer.Vector("Routing", {
        styleMap: styleMapRouting,
        displayInLayerSwitcher: false,
        rendererOptions: {
            zIndexing: true
        }
    });
    
    map.addLayer(layerRouting);
    
    

    /* init custom toolbar */
    jQuery("#toolbarOpenLayersButtons").buttonset();
    jQuery('#btnSelectFeature').button({
        icons: {
            primary: 'ui-icon-selectFeature'
        },
        text: false
    }).bind('click', function() {
        if (layerRouting.features.length > 0) {
            jQuery('#dialog-confirm-abort').dialog('open');
            if (routingStartButton.active)
                $('#btnRoutingStart').trigger('click');
            if (routingEndButton.active)
                $('#btnRoutingEnd').trigger('click');
            if (routingEditButton.active)
                $('#btnRoutingEdit').trigger('click');
        } else {
            jQuery(this).attr('checked', true).trigger('change');
            if (!selectFeatureButton.active) // Don't reactivate if already active, otherwise n-actions will be executed
                selectFeatureButton.trigger();
        }

        
    } );
    jQuery('#btnRoutingStart').button({
        icons: {
            primary: 'ui-icon-routingStart'
        },
        text: false
    }).bind('click', function() {
        if ($('#spt_id').val() == '') {
            forceSetSportType();
            return false;
        }
            

        jQuery(this).attr('checked', true).trigger('change');
        if (!routingStartButton.active) // Don't reactivate if already active, otherwise n-actions will be executed
            routingStartButton.trigger();
    } );
    jQuery('#btnRoutingEnd').button({
        icons: {
            primary: 'ui-icon-routingEnd'
        },
        text: false
    }).bind('click', function() {
        if ($('#spt_id').val() == '') {
            forceSetSportType();
            return false;
        }
        jQuery(this).attr('checked', true).trigger('change');
        if (!routingEndButton.active) // Don't reactivate if already active, otherwise n-actions will be executed
            routingEndButton.trigger();
    } );
    jQuery('#btnRoutingEdit').button({
        icons: {
            primary: 'ui-icon-routingEdit'
        },
        text: false
    }).bind('click', function() {
        if ($('#spt_id').val() == '') {
            forceSetSportType();
            return false;
        }
        jQuery(this).attr('checked', true).trigger('change');
        if (!routingEditButton.active) // Don't reactivate if already active, otherwise n-actions will be executed
            routingEditButton.trigger();
    } );
    jQuery('#btnHelp').button({
        icons: {
            primary: 'ui-icon-help'
        },
        text: false
    }).bind('click', function() {
        jQuery('#dlgHelp').load('../file/help', function() {
            jQuery(this).dialog('open');
        })
    } );

    $('#btnOpenMenu').button().menu({
        content: $('#toolbarOpenLayersMenu').html(), // grab content from this page
        showSpeed: 400
    });
}
function forceSetSportType() {
    $('#btnSelectFeature').trigger('click');
    $('#btnToggleSettings').trigger('click');
    notifyInfo({
        message: {
            title: $.r3msgs.attention,
            text: $.r3msgs.select_sport_type
        }
    });
}

var autoHiddenRoutenLayer = new Array();
function hideAllRouteLayer() {
    var vectorLayers = map.getLayersByClass("OpenLayers.Layer.Vector");
    $.each(vectorLayers, function(layerIndex, vectorLayer) {
        if (typeof vectorLayer.layerType != 'undefined' && $.inArray(vectorLayer.layerType, ['official', 'unofficial', 'my', 'temporary']) != -1 && vectorLayer.getVisibility()) {
            autoHiddenRoutenLayer.push(vectorLayer.layerType);
            vectorLayer.setVisibility(false);
        } else if (typeof vectorLayer.layerType != 'undefined' && $.inArray(vectorLayer.layerType, ['temporary2']) != -1 && vectorLayer.getVisibility()) {
            // show selected Route as temporary route (request from martin)
            if (selectedFeature !== null && typeof selectedFeature != 'undefined') {
                // get high quality of the route
                var format = new OpenLayers.Format.WKT();
                var feature = format.read($('#frmRoute').find('input[name=the_geom]').val());
                vectorLayer.addFeatures([feature]);
            }
        }
    });
}

function showAllRouteLayer() {
    var vectorLayers = map.getLayersByClass("OpenLayers.Layer.Vector");
    $.each(vectorLayers, function(layerIndex, vectorLayer) {
        if (typeof vectorLayer.layerType != 'undefined' && $.inArray(vectorLayer.layerType, autoHiddenRoutenLayer) != -1 && !vectorLayer.getVisibility()) {
            vectorLayer.setVisibility(true);
        } else if (typeof vectorLayer.layerType != 'undefined' && $.inArray(vectorLayer.layerType, ['temporary2']) != -1 && vectorLayer.getVisibility()) {
            // remove all temporary routes  (request from martin)
            vectorLayer.removeAllFeatures();
        }
    });
    autoHiddenRoutenLayer = new Array();
}

function openRoutingInfo(rte_id, controlTrigger) {
    clickVector.unselectAll();
    selectedFeature = null;
    selctedFeatureLayerType = null;
    selectedFeatureID = null;
    
    if (jQuery('#frmRoutingInfo').length==0) {
        var dateObj = new Date();
        var url = "loadRoutingInfo.php?cache="+dateObj.getTime()+"&";
        if (rte_id)
            url += "rte_id="+rte_id;
        
        jQuery('#mapInfoFullContent').load(url, function() {
            jQuery('#mapInfoFull').find('span.ui-icon-close').hide();
            jQuery('#btnSave').attr('disabled', true);
            jQuery('#btnAbort').attr('disabled', true);
            
            jQuery('#mapInfoTitle').html($.r3msgs.personalRoute + '<br><div id="mySportType">'+$.r3msgs.routingtype + ': ' + $('#spt_id').find('option:selected').text()+'</div>');
            jQuery.getScript('../javascript/mtbRoutingInfo.js', function() {
                jQuery('#mapInfoLite').fadeOut('slow', function() {
                    jQuery('#mapInfoFull').fadeIn('slow');
                });
                if (typeof controlTrigger != 'undefined' && controlTrigger !== null) {
                    stopLoading();
                    controlTrigger.trigger();
                }
            });
        });
    } else if (jQuery('#mapInfoFull').css('display') == 'none') {
        jQuery('#mapInfoLite').fadeOut('slow', function() {
            jQuery('#mapInfoFull').fadeIn('slow');
        });
    }
}

function isRoutingActive() {
    var toolId = $($('#toolbarOpenLayersButtons').find('.ui-state-active')).prev().attr('id');
    if ($.inArray(toolId, ['btnRoutingStart', 'btnRoutingEnd', 'btnRoutingEdit']) != -1)
        return true;
    return false;
}

function abortRouting() {
    if (!isRoutingActive())
        return false;

    jQuery('#mapInfoFull').find('span.ui-icon-close').show();
    
    destroyRoutingFeatures();

    jQuery('#mapInfoFull').hide();
    jQuery('#mapInfoFullContent').html('');
    
    jQuery("#dialog-confirm-abort").dialog('destroy').remove();
    jQuery("#dialog-confirm-save").dialog('destroy').remove();

    showAllRouteLayer();
}

function destroyRoutingFeatures() {
    if (routingLineFeature) {
        routingLineFeature.destroy();
        routingLineFeature = null;
    }
    if (layerRouting && layerRouting.features.length > 0) {
        layerRouting.destroyFeatures();
    }
        
    routingStartFeature = null;
    routingEndFeature = null;
}

function createRoutingFeature(data, type) {
    var format = new OpenLayers.Format.WKT();
    var feature = format.read(data.the_geom);
    OpenLayers.Util.extend(feature, {
        id: data.id,
        attributes: {
            type: type,
            old_x: feature.geometry.x,
            old_y: feature.geometry.y
        }
    });
    return feature;
}

function requestLocateAndInterpolatePoint(pt, type, id) {
    if (!requestSatusLocateAndInterpolatePoint || requestStatusLocateAndInterpolatePoint != REQUEST_STATUS_RUNNING) {
        requestStatusLocateAndInterpolatePoint = REQUEST_STATUS_RUNNING;

        showLoading();
        deactivateRoutingTools();
        
        var snapToStartPoint = '';
        if ($('input[name=toolbarOpenLayersItem]:checked').attr('id') != 'btnRoutingEdit')
            snapToStartPoint = '/snapToStartPoint';

        jQuery.getJSON('../file/road/locate-and-interpolate/x/'+pt.lon+'/y/'+pt.lat+snapToStartPoint, function(data) {
            if (data.status == 0) {
                var feature;
                var j = null;
                switch(type) {
                    case 'start':
                        if (routingStartFeature)
                            routingStartFeature.destroy();
                        routingStartFeature = createRoutingFeature(data, 'start');
                        feature = routingStartFeature;

                        routingInfoAddPoint(feature);
                        if (layerRouting.features.length > 0)
                            j = 0;
                        break;
                    case 'end':
                        if (routingEndFeature)
                            routingEndFeature.destroy();
                        routingEndFeature = createRoutingFeature(data, 'end');
                        feature = routingEndFeature;

                        routingInfoAddPoint(feature);
                        break;
                    default:
                        feature = createRoutingFeature(data, 'intermediate');

                        if (id) {
                            var oldFeature = layerRouting.getFeatureById(id);
                            j = jQuery.inArray(oldFeature, layerRouting.features);
                            $('#rpt-'+oldFeature.id).attr('rpt-'+feature.id);
                            oldFeature.destroy();
                        } else {
                            routingInfoAddPoint(feature);
                            if (layerRouting.features[layerRouting.features.length-1].attributes.type == 'end')
                                j = layerRouting.features.length-1;
                        }
                }
                //feature.attributes.name = layerRouting.features.length + 1;

                
                layerRouting.addFeatures([feature]);

                // reorder the itermediate-point
                if (j != null) {
                    var tmpFeature = layerRouting.features.pop();
                    layerRouting.features.splice(j, 0, tmpFeature);
                    try {
                        layerRouting.features[j+1].attributes.name = j + 2;
                    } catch(e) {

                    }
                        
                }

                var featureIndex = jQuery.inArray(feature, layerRouting.features);
                layerRouting.features[featureIndex].attributes.name = parseInt(featureIndex) + 1;

                layerRouting.redraw();
                    

                if (!requestRouting(typeof id == 'undefined')) {
                    notifyControl.deactivate();
                    switch(type) {
                        case 'start':
                            jQuery('#btnRoutingEdit').trigger('click');
                            break;
                        case 'end':
                            jQuery('#btnRoutingStart').trigger('click');
                            break;
                    }
                    stopLoading();
                }
            } else {
                if (id) {
                    var feature = layerRouting.getFeatureById(id);
                    feature.move(new OpenLayers.LonLat(feature.attributes.old_x, feature.attributes.old_y));
                    layerRouting.refresh();
                }
                notifyError(data);
                
                activateCurrentRoutingTool();
                stopLoading();
            }
            requestStatusLocateAndInterpolatePoint = '';

            
        });
    } else {
        notifyInfo({
            message: {
                title: $.r3msgs.attention,
                text: $.r3msgs.requestIsRunning
            }
        })
    }
}

function getAllRoutingFeatures() {
    var features = []
    var tmpStartFeature;
    var tmpEndFeature;
    for(key in layerRouting.features) {
        feature = {
            x: layerRouting.features[key].geometry.x,
            y: layerRouting.features[key].geometry.y,
            attributes: layerRouting.features[key].attributes
        };
        switch(layerRouting.features[key].attributes.type) {
            case 'start':
                tmpStartFeature = feature;
                break;
            case 'end':
                tmpEndFeature = feature;
                break;
            case 'intermediate':
                features.push(feature);
                break;
        }
    }
    features.unshift(tmpStartFeature);
    features.push(tmpEndFeature);
    return features;
}

function requestRouting(newpt) {
    var features = getAllRoutingFeatures();
    
    if (layerRouting.features.length < 2) {
        stopLoading();
        return false;
    }

    $('#btnSave').button('disable');
    $('#btnAbort').button('disable');
    
    if (!requestStatusRouting || requestStatusRouting != REQUEST_STATUS_RUNNING) {
        requestStatusRouting = REQUEST_STATUS_RUNNING;
        
        jQuery.post('../file/routing', {
            features: features,
            newpt: newpt
        }, function(data) {
            if (data.the_geom) {
                var format = new OpenLayers.Format.WKT();
                if (routingLineFeature)
                    routingLineFeature.destroy();
                routingLineFeature = format.read(data.the_geom);
                OpenLayers.Util.extend(routingLineFeature, {
                    attributes: {
                        type: 'routingLine'
                    }
                });
                var tmpLayer = getVectorLayerByType('routingline');
                tmpLayer.addFeatures([routingLineFeature]);

                routingInfoUpdateLength(data.routing_length);
                routingInfoUpdateAltitude(data.routing_altitude);
                routingInfoUpdateElevationGraph();
            }
            requestStatusRouting = '';

            $('#btnSave').button('enable');
            $('#btnAbort').button('enable');

            activateCurrentRoutingTool();
            stopLoading();
        }, "json");
    } else {
        notifyInfo({
            message: {
                title: $.r3msgs.attention,
                text: $.r3msgs.requestIsRunning
            }
        })
    }
    return true;
}

