lbgm.point = {
    // Hardcoded icons
    addIconPath: 'src/images/marker-green.png',
    addPMIconPath: 'src/images/marker-blue.png',
    defaultIconPath: 'src/images/marker-green.png',
    naviIconPath: 'src/images/navigation/instr_np.png',
    //addRessicon: 'src/images/marker-green.png',
    // Change icon size and offset here
    iconSize: null,
    iconOffset: null,

    //lbgm.poi.pp = new OpenLayers.Popup('test', new OpenLayers.LonLat(0,0), new OpenLayers.Size(200,200), 'test');
    addpoint: false,
    adding: false,
    pointslayerPrepared: false,
    menuVisible: false,
    down: false,
    arPoints: null,
    arSearchPoints: null,
    arPoiPoints: null,
    arExtraPoints: null,
    movingFeature: null,
    addPlacemark: false,
    addingPlacemark: false,


    init: function() {
        this.iconSize = new OpenLayers.Size(21,24);
        this.iconOffset = new OpenLayers.Pixel(-(this.iconSize.w/2), -this.iconSize.h);
        this.addIcon = new OpenLayers.Icon(this.addIconPath, this.iconSize, this.iconOffset);

        this.arPoints = [];
        this.arSearchPoints = [];
        this.arPoiPoints = [];
        this.arExtraPoints = [];
    },

    /**
     * Function
     */
    preparePointLayer: function() {
        //this.pointslayer = new OpenLayers.Layer.Markers("Points", {

        var style = new OpenLayers.Style({
                    externalGraphic: "${icon}",
                    label: "${label}",
                    graphicOpacity: 1,
                    graphicWidth: 36,
                    graphicHeight: 36,
                    graphicXOffset: -18,
                    graphicYOffset: -18,
                    cursor: "pointer"
                }, {
                    context: {
                        radius: function(feature) {
                            var pix = 2;
                            if(feature.cluster) {
                                pix = Math.min(feature.attributes.count, 7) + 10;
                            }
                            return pix;
                        },
                        label: function(feature) {
                            if(feature.cluster) {
                                feature.attributes.name = feature.cluster.length;
                                return feature.cluster.length;
                            }
                        },
                        icon: function(feature) {
                            if(feature.cluster) {
                                if(feature.attributes.count < 5) return 'src/images/clust-blue.png';
                                else if(feature.attributes.count >= 5 && feature.attributes.count < 10) return 'src/images/clust-green.png';
                                else if(feature.attributes.count >= 10 && feature.attributes.count < 100) return 'src/images/clust-yellow.png';
                                else if(feature.attributes.count >= 100 ) return 'src/images/clust-red.png';
                            }
                        }
                    }
                });
              
        var strategy = new OpenLayers.Strategy.Cluster({distance: 30, threshold: 3});

        this.pointslayer = new OpenLayers.Layer.Vector("Points", {
            displayInLayerSwitcher: false,
            'transparent': true,
            //strategies: [strategy],
            styleMap: new OpenLayers.StyleMap({
                "default": style,
                "select": {
                    fillColor: "#8aeeef",
                    strokeColor: "#32a8a9"
                }
            })
        });
        lbgm.maplets.mapobject.map.addLayer(this.pointslayer);
        this.pointslayer.setVisibility(true);

        //add the second select for tooltips:
       this.hoverControl = new OpenLayers.Control.SelectFeature(this.pointslayer,
            {
                hover: true,
                clickout: true,
                highlightOnly: true,
                renderIntent: "temporary",
                eventListeners: {
                    featurehighlighted: this.onHoverOn,
                    featureunhighlighted: this.onHoverOut
                }
            }
        );

        this.selectControl = new OpenLayers.Control.SelectFeature(this.pointslayer, 
            {
                multiple: false,
                clickout: true
            }
        );

        // drag control
        this.dragControl = new OpenLayers.Control.DragFeature(this.pointslayer, 
                {
                    onStart: this.onStart,
                    onDrag: this.onDrag,
                    onComplete: this.onComplete
                });

        lbgm.maplets.mapobject.map.addControl(this.hoverControl);
        lbgm.maplets.mapobject.map.addControl(this.selectControl);
        lbgm.maplets.mapobject.map.addControl(this.dragControl);
        this.hoverControl.activate();
        this.selectControl.activate();
        this.dragControl.deactivate();

        this.pointslayer.events.on({
            "featureselected": this.onPointSelect,
            "featureunselected": this.onPointUnselect,
            "mousedown": this.onMouseDown,
            "mousemove": this.onMouseMove,
            "mouseup": this.onMouseUp
        });

        //var l = lbgm.point.init("Points", false);
        //this.pointslayer = lbgm.point.init("Points", false);

        this.pointslayerPrepared = true;
    },


    /**************************************************************************
     *
     * Display Point Functions
     *
     **************************************************************************/
    featureFromPoint: function(point, idprefix) {
        if(idprefix == undefined) idprefix = 'poi';

        if(point.longitude == undefined) point.longitude = point.poilongitude;
        if(point.latitude == undefined) point.latitude = point.poilatitude;
//alert(point.longitude);
        // Get LonLat from point
        var lonlat  = new OpenLayers.LonLat(point.longitude,point.latitude);
        lonlat.transform(lbgm.maplets.mapobject.map.displayProjection,lbgm.maplets.mapobject.map.getProjectionObject());

        // Get icon from point
        var iconPath = '';
        if(point.createdbyuserid == lbgm.login.userid && point.poistatus == 0) {
            iconPath = this.addIconPath;
        }
        else {
            iconPath = point.icondisplay;
        }

        // Prepare point style
        var pointStyleMap = {
            pointRadius: 10,
            graphicOpacity: 1,
            externalGraphic: iconPath,
            graphicWidth: 21,
            graphicHeight: 24,
            graphicXOffset: -10,
            graphicYOffset: -24,
            cursor: "pointer"//,
            //graphicTitle: name
        };

        var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat), null, pointStyleMap);

        if(point.id == undefined) point.id = point.poiid;
        feature.id = idprefix + point.id;
        feature.attributes.id = point.id;
        feature.attributes.type = 'point';
        if(point.name == undefined) point.name = point.poiname;
        feature.attributes.name = point.name;
        feature.attributes.createdbyuserid = point.createdbyuserid;
        feature.attributes.status = point.status;
        feature.attributes.accesslevel = point.accesslevel;
        feature.attributes.ownercompanyid = point.ownercompanyid;
        feature.attributes.isLine = false;
        feature.attributes.ispoi = true;

        return feature;
    },

    featureFromLonLat: function(lonlat) {
        var iconPath = this.defaultIconPath;

        // Prepare point style
        var pointStyleMap = {
            pointRadius: 10,
            graphicOpacity: 1,
            externalGraphic: iconPath,
            graphicWidth: 21,
            graphicHeight: 24,
            graphicXOffset: -10,
            graphicYOffset: -24,
            cursor: "pointer"//,
            //graphicTitle: name
        };

        var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat), null, pointStyleMap);

        var tmpLonLat = lonlat;
        tmpLonLat.transform(lbgm.maplets.mapobject.map.getProjectionObject(), lbgm.maplets.mapobject.map.displayProjection);

        feature.id = 'lonlat' + String(tmpLonLat.lon).substring(0, 11) + String(tmpLonLat.lat).substring(0, 11);
        feature.attributes.id = 'lonlat' + String(tmpLonLat.lon).substring(0, 11) + String(tmpLonLat.lat).substring(0, 11);
        feature.attributes.name = String(tmpLonLat.lat).substring(0, 9)  + '  ' +
                        String(tmpLonLat.lon).substring(0, 9);
        feature.attributes.isLine = false;
        feature.attributes.type = 'lonlat';

        return feature;

    },

    cloneFeature: function(feat, newIcon) {
        // Get icon from point
        var iconPath = newIcon == '' ? feat.style.externalGraphic : newIcon;

        // Prepare point style
        var pointStyleMap = {
            pointRadius: 10,
            graphicOpacity: 1,
            externalGraphic: iconPath,
            graphicWidth: 21,
            graphicHeight: 24,
            graphicXOffset: -10,
            graphicYOffset: -24//,
            //graphicTitle: name
        };

        var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(feat.geometry.getBounds().getCenterLonLat().lon,
                    feat.geometry.getBounds().getCenterLonLat().lat), null, pointStyleMap);

        feature.id = feat.id;
        feature.attributes.id = feat.attributes.id;
        feature.attributes.name = feat.attributes.name;
        feature.attributes.address = feat.attributes.address;
        feature.attributes.ispoi = feat.attributes.ispoi;
        feature.attributes.type = feat.attributes.type;
        /*feature.attributes.createdbyuserid = point.createdbyuserid;
        feature.attributes.status = point.status;
        feature.attributes.accesslevel = point.accesslevel;
        feature.attributes.ownercompanyid = point.ownecompanyid;*/

        return feature;
    },

    showInitPoint: function() {

        if(!this.pointslayerPrepared) this.preparePointLayer();

        var url = document.URL;
        url = url.replace("#", "");
        var getParams = url.split("?");
        if(getParams.length > 1 ) {
            this.urlparams = Ext.urlDecode(getParams[1]);
            //key = this.urlparams['key'];
            var pointid = this.urlparams['p'];
            var addressid = this.urlparams['a'];
            var lon = this.urlparams['lon'];
            var lat = this.urlparams['lat'];
            var zoom = true;

            if(this.urlparams['z']!= undefined) zoom = false;

            if(pointid != undefined && pointid != '') {
                //if(!this.pointslayerPrepared) this.preparePointLayer();
                //this.displayPointByIdEx(pointid, this.pointslayer);
                this.displayPointById(pointid);
            }
            else if(addressid != undefined && addressid != '') {
                this.showAddressPoint(addressid);
            }
            else if(lon != undefined && lat != undefined) {
                this.displayLonLatPoint(lon, lat, zoom);
            }

        }
    },

    displayFeature: function(feature, showPopup, centerPoint, zoomIn) {
        if(centerPoint) {
            //lbgm.maplets.mapobject.map.setCenter(feature.lonlat);
            if(zoomIn != undefined && zoomIn == true) lbgm.maplets.mapobject.map.setCenter(feature.geometry.getBounds().getCenterLonLat(), 16 - lbgm.maplets.mapobject.getZoomOffset());
            else lbgm.maplets.mapobject.map.setCenter(feature.geometry.getBounds().getCenterLonLat());
        }

        if(!this.pointslayerPrepared) this.preparePointLayer();
        this.pointslayer.addFeatures([feature]);
        this.arPoints.push(feature);
        this.feature = feature;

        if(showPopup)  {
            //if(centerPoint && zoomIn == true) lbgm.maplets.popupcallbackF = feature; // Removed due to loading layer removal
            //else
            lbgm.popup.showPopup(feature);
        }

    },

/*
    displayPoint: function(point, showPopup, centerPoint) {

        if(!this.pointslayerPrepared) this.preparePointLayer();
        var layer = this.pointslayer;

        // Get LonLat from point
        var lonlat  = new OpenLayers.LonLat(point.poilongitude,point.poilatitude);
        lonlat.transform(lbgm.maplets.mapobject.map.displayProjection,lbgm.maplets.mapobject.map.getProjectionObject());

        // Get icon from point
        var iconPath = '';
        if(point.createdbyuserid == lbgm.login.userid && point.poistatus == 0) {
            iconPath = this.addIconPath;
        }
        else {
            iconPath = point.icondisplay;
        }

        // Prepare point style
        var pointStyleMap = {
            pointRadius: 10,
            graphicOpacity: 1,
            externalGraphic: iconPath,
            graphicWidth: 21,
            graphicHeight: 24,
            graphicXOffset: -10,
            graphicYOffset: -24//,
            //graphicTitle: name
        };

        var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat), null, pointStyleMap);

        feature.attributes.id = point.poiid;
        feature.attributes.name = point.poiname;
        feature.attributes.createdbyuserid = point.createdbyuserid;
        feature.attributes.status = point.poistatus;
        feature.attributes.accesslevel = point.accesslevel;
        feature.attributes.ownercompanyid = point.ownecompanyid;

        layer.addFeatures([feature]);

        this.arPoints.push(feature);

        this.feature = feature;

        if(showPopup) lbgm.popup.showPopup(point.poiid, feature);
        if(centerPoint) lbgm.maplets.mapobject.map.panTo(lonlat);

        return feature;

    },
*/

    displayPointById: function(id) {
        //if(!this.pointslayerPrepared) this.preparePointLayer();
        //this.displayPointById(id, this.pointslayer);

        var conn = new Ext.data.Connection();
        conn.request({
            url: 'src/php/conn/poimarkers.conn.php',
            method: 'POST',
            params: {
                "request": "displayPointById",
                "point": id,
                "allowNavi": lbgm.layout.enablenavigation,
                key: lbgm.layout.key
            },
            success: function(responseObject) {
                obj = Ext.util.JSON.decode(responseObject.responseText);
                //eval(obj.results);
                if(obj.results != null && obj.results.length != 0) {
                    var pointRes = obj.results[0];
                    //this.displayPoint(pointRes, true, true);
                    var feature = this.featureFromPoint(pointRes);

                    this.arSearchPoints.push(feature);
                    this.displayFeature(feature, true, true, true);
                }
            },
            failure: function() {
            //Ext.Msg.alert(lbgm.options.appname, 'Unable to load layout.');
            },
            scope: this
        });
    },

    /**************************************************************************
     *
     * Add/Edit/Delete Point Functions
     *
     **************************************************************************/
    newPoint: function(lonlat) {
        if(!lbgm.point.pointslayerPrepared) lbgm.point.preparePointLayer();

        var pointStyleMap = {
            pointRadius: 10,
            graphicOpacity: 1,
            externalGraphic: this.addIconPath,
            graphicWidth: 21,
            graphicHeight: 24,
            graphicXOffset: -10,
            graphicYOffset: -24//,
            //graphicTitle: name
        };

        var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat), null, pointStyleMap);
        feature.id = "addFeature";

        lbgm.point.pointslayer.addFeatures([feature]);
        this.feature = feature;

        var newlonlat = new OpenLayers.LonLat(lonlat.lon, lonlat.lat);
        newlonlat.transform(lbgm.maplets.mapobject.map.getProjectionObject(), lbgm.maplets.mapobject.map.displayProjection);

        lbgm.popup.showAddPopup(newlonlat.lon, newlonlat.lat, feature);

        this.addingPoint();
    },

    addStart: function() {
        this.addPoint = true;
        lbgm.maplets.mapobject.map.div.style.cursor = 'default';
    },

    addCancel: function() {
        // Alert for the canceling
        if(lbgm.popup.activepopupid!=null)
            lbgm.popup.hidePopup(lbgm.popup.activepopupid);

        // If ok
        if(lbgm.point.pointslayer != undefined) {
            var feat = lbgm.point.pointslayer.getFeatureById('addFeature');

            if(feat) {
                lbgm.point.pointslayer.removeFeatures([feat], null);
                //lbgm.maplets.mapobject.map.removeLayer(layer);
            }
        }
        
        this.addPoint = false;
        this.adding = false;


        var btn = Ext.getCmp('addpoibtn');
        if(btn) btn.setText("Add POI");

        var btn2 = Ext.getCmp('addplacemarkbtn');
        if(btn2) btn2.setText("Feedback");
    },

    addingPoint: function() {
        this.adding = true;
        //var btn = Ext.getCmp('addpoibtn');
        lbgm.maplets.mapobject.map.div.style.cursor = 'url(../images/openhand.cur), url(src/images/openhand.cur), default';

    },

    addFinish: function() {
        this.adding = false;
        this.addPoint = false;
        var btn = Ext.getCmp('addpoibtn');
        btn.setText("Add POI");
    },

    savePoint: function(pointObj) {
        var conn = new Ext.data.Connection();
        conn.request({
            url: 'src/php/conn/poimarkers.conn.php',
            method: 'POST',
            params: {
                "request": "savePoint",
                "pointValues": Ext.util.JSON.encode(pointObj),
                key: lbgm.layout.key
            },
            success: function(responseObject) {
                obj = Ext.util.JSON.decode(responseObject.responseText);
                var pointid = obj.pointid;

                //
                var layer = lbgm.maplets.mapobject.map.getLayersByName('AddPoint')[0];
                if(layer) {
                    //layer.clearMarkers();
                    layer.removeFeatures(layer.features, null);
                    lbgm.maplets.mapobject.map.removeLayer(layer);
                }

                lbgm.popup.hidePopup(lbgm.popup.activepopupid);
                this.displayPointById(pointid);

            },
            failure: function() {
                //Ext.Msg.alert(lbgm.options.appname, 'Unable to load layout.');
            },
            scope: this
        });

        this.addFinish();
    },

    editPoint: function(feature) {
        //this.addingPoint();
        lbgm.point.feature = feature;
        lbgm.popup.showEditPopup(feature);
    },

    deletePoint: function(id) {

        Ext.Msg.show({
           title:'Logout?',
           msg: 'Are you sure you wish to delete point?',
           buttons: Ext.Msg.YESNO,
           fn: function(buttonid) {
               if(buttonid == 'yes' ) {
                    // AJAX to load layout
                    var conn = new Ext.data.Connection();
                    conn.request({
                        url: 'src/php/conn/poimarkers.conn.php',
                        method: 'POST',
                        params: {
                            "request": "deletePoint",
                            "pointid": id,
                            key: lbgm.layout.key
                        },
                        success: function(responseObject) {
                            obj = Ext.util.JSON.decode(responseObject.responseText);
                            var success = obj.success;

                             if(success) lbgm.maplets.poitree.loadPois();
                             else alert(obj.error);

                        },
                        failure: function() {
                            //Ext.Msg.alert(lbgm.options.appname, 'Unable to load layout.');
                        },
                        scope: this
                    });
               }
           },
           icon: Ext.MessageBox.QUESTION
        });
        
    },


    /**************************************************************************
     *
     * Point Events
     *
     **************************************************************************/
    onHoverOn: function(event) {


        var feature = event.feature;

        if(!feature.cluster) {
            lbgm.point.ovFeature = feature;

            if(!feature.attributes.isLine)
                lbgm.maplets.mapobject.ttips.show({html:"<p style='font-family:tahoma;color:#333;'><b>" + feature.attributes.name + "</b></p>"});
        }
        else {
            //feature.style.cursor = "pointer";
        }
    },

    onHoverOut: function(event) {
        lbgm.point.ovFeature = null;
        lbgm.maplets.mapobject.ttips.hide();
    },

    showMenu: function(feature, x, y) {
        lbgm.point.hideMenu();

        this.menu = new Ext.menu.Menu({
                    id: 'main_menu',
                    floating: true,
                    hidden: true,
                    defaultOffsets: [5,5],
                    shadow: false,
                    x: 100,
                    y: 100,
                    renderTo: Ext.getBody(),
                    items: []
                });

        // Add menu options

        if(lbgm.login.isLoggedIn && (
                (lbgm.login.userid == feature.attributes.createdbyuserid && feature.attributes.status == 0) ||
                (lbgm.login.userid == feature.attributes.createdbyuserid && lbgm.login.allowAccept == 1) ||
                (lbgm.login.companyid == feature.attributes.ownercompanyid && lbgm.login.allowAdd == 1 && 
                        (lbgm.login.accessLevel < feature.attributes.accesslevel || lbgm.login.accessLevel == 0) || lbgm.login.superuser == 1)
        )) {

            lbgm.point.menu.addMenuItem({
               id: 'point_edit_btn',
               text: 'Edit',
               //disabled: disabled,
               icon: 'gmadmin/images/icons/pencil.png',
               feature: feature,
               handler: lbgm.point.onMenuClick
            });

            lbgm.point.menu.addMenuItem({
               id: 'point_delete_btn',
               text: 'Delete',
               //disabled: disabled,
               icon: 'gmadmin/images/icons/cross.png',
               feature: feature,
               handler: lbgm.point.onMenuClick
            });

            lbgm.point.menu.addMenuItem({
               id: 'point_move_btn',
               text: 'Move',
               //disabled: disabled,
               icon: 'gmadmin/images/icons/arrow_out.png',
               feature: feature,
               handler: lbgm.point.onMenuClick
            });

            lbgm.point.menu.addSeparator();

        }

        if(lbgm.layout.enablenavigation == 1) {
            lbgm.point.menu.addMenuItem({
               id: 'point_navigatefrom_btn',
               text: 'Navigate From',
               icon: 'gmadmin/images/icons/flag_green.png',
               //disabled: disabled,
               feature: feature,
               handler: lbgm.point.onMenuClick
            });

            lbgm.point.menu.addMenuItem({
               id: 'point_navigateto_btn',
               text: 'Navigate To',
               icon: 'gmadmin/images/icons/flag_red.png',
               //disabled: disabled,
               feature: feature,
               handler: lbgm.point.onMenuClick
            });

            lbgm.point.menu.addSeparator();
        }

        if(lbgm.layout.enableshare == 1) {
            lbgm.point.menu.addMenuItem({
               id: 'point_share_btn',
               text: 'Share',
               //disabled: disabled,
               icon: 'gmadmin/images/icons/email.png',
               feature: feature,
               handler: lbgm.point.onMenuClick
            });
        }

        /*lbgm.point.menu.addMenuItem({
           id: 'point_add_gpx_btn',
           text: 'Add to GPX',
           //disabled: disabled,
           icon: 'gmadmin/images/icons/page_add.png',
           feature: feature,
           handler: lbgm.point.onMenuClick
        });*/

        lbgm.maplets.mapobject.ttips.hide();

        if(lbgm.point.menu.items.length > 0) {
            var newX = x;
            var newY = y;

            if(x+this.menu.getWidth()+5 > lbgm.helper.getBrowserWidth()) newX = x - (this.menu.getWidth() + 5);
            if(y+this.menu.getHeight()+5 > lbgm.helper.getBrowserHeight()) newY = y -(this.menu.getHeight() + 5);

            this.menu.showAt([newX+5, newY+5]);
            //lbgm.point.menu.showAt([x+5, y+5]);
            lbgm.point.menuVisible = true;
        }
    },

    hideMenu: function() {
        if(lbgm.point.menu != null) {
           lbgm.point.menu.removeAll(true);
           lbgm.point.menu.hide();
           lbgm.point.menuVisible = false;
           //this.selectControl.unselectAll();

           //if(lbgm.maplets.mapobject.menuVisible) lbgm.maplets.mapobject.hideMenu();

           delete lbgm.point.menu;
        }
    },

    onMenuClick: function(btn) {
        //alert(btn.feature.attributes.id);
        if(btn.id == 'point_edit_btn' && btn.feature != undefined && btn.feature != null) {
            lbgm.popup.popupfeature = btn.feature;
            lbgm.point.editPoint(btn.feature);
        }
        else if(btn.id == 'point_delete_btn' && btn.feature != undefined && btn.feature != null) {
            //lbgm.popup.popupfeature = btn.feature;
            lbgm.point.deletePoint(btn.feature.attributes.id);
        }
        else if(btn.id == 'point_navigatefrom_btn' && btn.feature != undefined && btn.feature != null) {
            lbgm.navigation.setNaviFrom(btn.feature);
        }
        else if(btn.id == 'point_navigateto_btn' && btn.feature != undefined && btn.feature != null) {
            lbgm.navigation.setNaviTo(btn.feature);
        }
        else if(btn.id == 'point_share_btn' && btn.feature != undefined && btn.feature != null) {
            if(btn.feature.attributes.type == 'address')
                lbgm.point.shareAddress(btn.feature.attributes.id);
            else
                lbgm.point.sharePoint(btn.feature.attributes.id);
        }
        else if(btn.id == 'point_move_btn' && btn.feature != undefined && btn.feature != null) {

            if( lbgm.point.movingFeature != null) {
                var feat = lbgm.point.pointslayer.getFeatureById(lbgm.point.movingFeature.id);
                if(feat) {
                    feat.style.cursor = 'default';
                    feat.attributes.move = false;
                    lbgm.point.movingFeature = null;
                }
            }

            btn.feature.attributes.move = true;
            lbgm.point.dragControl.activate();
            btn.feature.style.cursor = 'move';
            lbgm.point.movingFeature = btn.feature;
        }
        else if(btn.id == 'point_add_gpx_btn' && btn.feature != undefined && btn.feature != null) {
            lbgm.point.addPointToGPXPool(btn.feature);
        }
        

        //lbgm.point.selectControl.activate();
        lbgm.point.hideMenu();

    },

    onPointSelect: function(event) {
        //alert('Select');

        var feature = event.feature;

        if(!feature.cluster) {
            if(feature.id == 'identification') return;

            lbgm.point.feature = feature;
            if(lbgm.point.adding || feature.attributes.isLine) return;

            lbgm.maplets.mapobject.ttips.hide();

            if(feature.attributes.popuptype == "generic")
                lbgm.popup.displayGenericPopup(feature, feature.attributes.popupdata);
            else
                lbgm.popup.showPopup(feature);

            lbgm.point.selectControl.unselectAll();
        }
        else {
            var desc = '<div style="height:200px;overflow-y:scroll">';
            var cmax = feature.cluster.length - 1;
            for(var c = cmax; c >= 0; c--) {
                desc += "<div style='float:left;width: 100%;'>";
                desc += "<div style='float:left; width: 30px;'><img src='" + feature.cluster[c].style.externalGraphic + "' /></div><div style='float:left;padding-top: 5px; width: 205px;'>";
                /*if(c < cmax) {
                    desc += ", ";
                    if((cmax-c) % 6 == 0) desc += "<br>";
                }*/
                desc += feature.cluster[c].attributes.name;

                desc += '</div></div>';
            }

            desc += '</div>';
            lbgm.point.feature = feature;
            lbgm.maplets.mapobject.ttips.hide();
            lbgm.popup.displayGenericPopup(feature, desc);

        }

    },

    onPointUnselect: function(event) {
        //alert('closed');
    },

    onMouseDown: function(event) {
        lbgm.point.down = true;
        lbgm.point.hideMenu();

        if(event.button == 2) {
            lbgm.point.pointslayer.events.fallThrough = false;
            lbgm.maplets.mapobject.map.div.oncontextmenu = function() {return false;}
        }
        else
            lbgm.point.pointslayer.events.fallThrough = true;
    },

    onMouseMove: function(event) {

        if(lbgm.point.down == true) {
            //alert("Sdfsdf");
            lbgm.point.selectControl.deactivate();
            lbgm.maplets.mapobject.ttips.hide();
        }

        lbgm.point.pointslayer.events.fallThrough = true;
    },

    onMouseUp:
        function(event) {
       var feature = lbgm.point.pointslayer.getFeatureFromEvent(event);

       if(event.button != 2) {
            if(lbgm.point.movingFeature != null && lbgm.point.movingFeature == feature) {
                //lbgm.point.movingFeature = null;
                return;
            }
        }

        if(lbgm.point.down == true) {
            //lbgm.maplets.mapobject.map.getControl("tooltips").activate();
            lbgm.point.down = false;
            lbgm.point.selectControl.activate();
            //lbgm.point.selectControl.unselectAll();
        }

        if(event.button == 2) {

            var xy = lbgm.maplets.mapobject.map.events.getMousePosition(event);
            //alert(event.xy.x);

            if(feature!=null) {
                //alert(feature.attributes.name);
                lbgm.point.showMenu(feature, event.clientX, event.clientY);

                OpenLayers.Event.stop(event);
                lbgm.maplets.mapobject.map.div.oncontextmenu = function() {return false;}
            }
            else {
                lbgm.maplets.mapobject.map.events.triggerEvent("mouseup", event);
                lbgm.point.pointslayer.events.fallThrough = false;

                OpenLayers.Event.stop(event);
                lbgm.maplets.mapobject.map.div.oncontextmenu = function() {return false;}
            }
        }
        else {
            lbgm.point.pointslayer.events.fallThrough = true;
        }
    },

    /* Dragging Functions */
    onStart: function(feature, pixel) {
        if(feature.attributes.move != true) lbgm.point.dragControl.cancel();

        /*if(lbgm.point.movingFeature != null && feature != lbgm.point.movingFeature)
            lbgm.point.movingFeature.attributes.move = false;
        
        lbgm.point.movingFeature = feature;*/
    },

    onDrag: function(feature, pixel) {

    },

    onComplete: function(feature, pixel) {
        feature.attributes.move = false;
        lbgm.point.dragControl.deactivate();

        feature.style.cursor = 'default';
        var lonlat = lbgm.maplets.mapobject.map.getLonLatFromViewPortPx(pixel);
        lonlat.transform(lbgm.maplets.mapobject.map.getProjectionObject(), lbgm.maplets.mapobject.map.displayProjection);

        // Update POINT call
        // Call updatePointPos function
        OpenLayers.Request.POST({
            url: 'src/php/conn/poimarkers.conn.php',
            data: OpenLayers.Util.getParameterString({request: "updatePointPos", pointid: feature.attributes.id, lat: lonlat.lat, lon: lonlat.lon, key: lbgm.layout.key}),
            success: function(responseObject) {
               //alert(responseObject.responseText);
               obj = Ext.util.JSON.decode(responseObject.responseText);
               //eval(obj.results);

            },
            failure: function() {
               Ext.Msg.alert(lbgm.options.appname, 'Unable to move point.');
               // Move it back to its original position
            },
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            }

        });

        lbgm.point.movingFeature = null;
    },


    /*************************************************************************
     *
     *  Interface Functions
     *
     *************************************************************************/

    /* General Functions */
    clearHistory: function() {
        this.clearAddresses();
        this.clearSearchPoints();
        Ext.get('search-results').dom.innerHTML = '';
    },

    selectPoint: function(pointid) {
        //var feat = lbgm.point.pointslayer.getFeatureById(pointid);
        var feat = lbgm.point.pointslayer.getFeatureById(pointid);
        //alert(feat);
        if(feat != null )  {
            //alert(pointid);
            lbgm.maplets.mapobject.map.setCenter(feat.geometry.getBounds().getCenterLonLat());
            this.selectControl.select(feat);
            //this.displayPointById(pointid);
        }
        else {
            this.displayPointById(pointid);
        }
    },

    displayLonLatPoint: function(lon, lat) {
        this.displayLonLatPoint(lon, lat, true);
    },

    displayLonLatPoint: function(lon, lat, zoom) {
        //alert(zoom);
        // Get LonLat from point
        var lonlat  = new OpenLayers.LonLat(lon,lat);
        lonlat.transform(lbgm.maplets.mapobject.map.displayProjection,lbgm.maplets.mapobject.map.getProjectionObject());

        var f = this.featureFromLonLat(lonlat);
        this.arSearchPoints.push(f);

        this.displayFeature(f, true, true, zoom);
    },

    /* POI Functions */
    showPoiPoints: function(categories) {
        var zoomlvl = 0;
        if(lbgm.maplets.mapobject.map) zoomlvl = lbgm.maplets.mapobject.getZoomLevel();

        OpenLayers.Request.POST({
            url: 'src/php/conn/poimarkers.conn.php',
            data: OpenLayers.Util.getParameterString({request: "loadPOIS", poicategories: categories, zoomlevel: zoomlvl, key: lbgm.layout.key}),
            success: function(responseObject) {
               //alert(responseObject.responseText);
               obj = Ext.util.JSON.decode(responseObject.responseText);
               //eval(obj.results);

               // Clear All Points
               lbgm.point.clearPoiPoints();

               //var features = new Array();
               var f = null;
               Ext.each(obj.results, function(poi){
                  f = lbgm.point.featureFromPoint(poi);
                  lbgm.point.arPoiPoints.push(f);
               });

               //alert(lbgm.point.arPoiPoints.length);
               if(lbgm.point.arPoiPoints.length > 0) {
                   if(!lbgm.point.pointslayerPrepared) lbgm.point.preparePointLayer();
                   lbgm.point.pointslayer.addFeatures(lbgm.point.arPoiPoints);
               }

            },
            failure: function() {
               //Ext.Msg.alert(lbgm.options.appname, 'Unable to load layout.');
            },
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            }

        });

        /*var conn = new Ext.data.Connection();
        conn.request({
            url: 'src/php/conn/poimarkers.conn.php',
            method: 'POST',
            params: {"request": "loadPOIS", poicategories: poicate, zoomlevel: zoomlvl},
            success: function(responseObject) {
               obj = Ext.util.JSON.decode(responseObject.responseText);
               //eval(obj.results);

               Ext.each(obj.results, function(poi){
                  lbgm.point.showPoint(poi, false);
               });

            },
            failure: function() {
               //Ext.Msg.alert(lbgm.options.appname, 'Unable to load layout.');
            },
            scope: this
        });*/
    },

    clearPoiPoints: function() {
        //lbgm.maplets.mapobject.markers.clearMarkers();
        if(lbgm.point.pointslayer != null) {
            this.clearPopups();

            //lbgm.point.pointslayer.clearMarkers();
            //lbgm.point.pointslayer.removeFeatures(this.arPoiPoints, null);
            lbgm.point.pointslayer.removeAllFeatures();
            this.arPoiPoints = [];
        }
    },

    /* Search Functions */
    displaySearchPoint: function(point) {
        var tplTxt = '<tpl for="."><div class="search-selected">\n\
                <div class="search-sel-close"><a href="#" onClick="lbgm.point.removeSearchPoint(\'poi{id}\');">Remove</a></div>\n\
                <a class="search-selected-item-a" href="#" onClick="lbgm.point.selectPoint(\'poi{id}\');">\n\
                    <div class="search-selected-item">\n\
                        <p>{name} {postcode} {area} {district}</p>\n\
                    </div>\n\
                </a>';

        if(lbgm.layout.enablenavigation == 1) {
            tplTxt += '<div class="search-sel-links"><div class="sButton">\n\
                    <a href="#" onClick="lbgm.navigation.setNaviFrom(lbgm.point.pointslayer.getFeatureById(\'poi{id}\'));lbgm.point.removeSearchPoint(\'poi{id}\');">\n\
                        <div id="sButtonCont">\n\
                            <div id="sButtonIcon"><img src="gmadmin/images/icons/flag_green.png" /></div>\n\
                            <div id="sButtonText">From Here</div>\n\
                        </div>\n\
                    </a>\n\
                 </div>\n\
                 <div class="sButton">\n\
                    <a href="#" onClick="lbgm.navigation.setNaviTo(lbgm.point.pointslayer.getFeatureById(\'poi{id}\'));lbgm.point.removeSearchPoint(\'poi{id}\');">\n\
                        <div id="sButtonCont">\n\
                            <div id="sButtonIcon"><img src="gmadmin/images/icons/flag_red.png" /></div>\n\
                            <div id="sButtonText">To Here</div>\n\
                        </div>\n\
                    </a>\n\
                 </div></div>';
        }

        tplTxt += '</div></tpl>';

        var selPoiTpl = new Ext.XTemplate(tplTxt);

        selPoiTpl.compile();
        selPoiTpl.overwrite('search-results', point);

        point.icondisplay = this.addIconPath;
        var feature = this.featureFromPoint(point);
        this.arSearchPoints.push(feature);
        //lbgm.maplets.mapobject.map.zoomTo(17 - lbgm.maplets.mapobject.getZoomOffset());
        //lbgm.maplets.mapobject.map.panTo(feature.lonlat);
        
        this.displayFeature(feature, true, true, true);
        
        //lbgm.maplets.mapobject.map.setCenter(feature.lonlat);
    },
    
    clearSearchPoints: function() {
        if(lbgm.point.pointslayer != null) {
            this.clearPopups();

            //lbgm.point.pointslayer.clearMarkers();
            if(this.arSearchPoints.length > 0) {
                lbgm.point.pointslayer.removeFeatures(this.arSearchPoints, null);
                this.arSearchPoints = [];
            }
        }
    },

    removeSearchPoint: function(pointid) {
        var feat = lbgm.point.pointslayer.getFeatureById(pointid);
        if(feat != null) {
            lbgm.popup.hidePopup(pointid);
            lbgm.point.pointslayer.removeFeatures([feat], null);
            Ext.get('search-results').dom.innerHTML = '';
        }
        else {
            Ext.get('search-selected-' + pointid).dom.innerHTML = '';
        }
    },

    removeSingleSearchPoint: function(pointid) {
        var feat = lbgm.point.pointslayer.getFeatureById(pointid);
        if(feat != null) {
            lbgm.popup.hidePopup(pointid);
            //lbgm.point.pointslayer.removeFeatures([feat], null);
            //Ext.get('search-results').dom.innerHTML = '';
        }
        Ext.get('search-selected-' + pointid).dom.innerHTML = '';

    },
    
    displayAddress: function(address) {
        var tplTxt = '<tpl for="."><div class="search-selected">\n\
                <div class="search-sel-close"><a href="#" onClick="lbgm.point.removeAddress({id});">Remove</a></div>\n\
                <a class="search-selected-item-a" href="#" onClick="lbgm.point.selectAddress({id});">\n\
                    <div class="search-selected-item">\n\
                        <p>{name} {postcode} {area} {district}</p>\n\
                    </div>\n\
                </a>';

        if(lbgm.layout.enablenavigation == 1) {
            tplTxt += '<div class="search-sel-links"><div class="sButton">\n\
                    <a href="#" onClick="lbgm.navigation.setNaviFrom(lbgm.point.pointslayer.getFeatureById(\'addr{id}\'));lbgm.point.removeAddress(\'{id}\');">\n\
                        <div id="sButtonCont">\n\
                            <div id="sButtonIcon"><img src="gmadmin/images/icons/flag_green.png" /></div>\n\
                            <div id="sButtonText">From Here</div>\n\
                        </div>\n\
                    </a>\n\
                 </div>\n\
                 <div class="sButton">\n\
                    <a href="#" onClick="lbgm.navigation.setNaviTo(lbgm.point.pointslayer.getFeatureById(\'addr{id}\'));lbgm.point.removeAddress(\'{id}\');">\n\
                        <div id="sButtonCont">\n\
                            <div id="sButtonIcon"><img src="gmadmin/images/icons/flag_red.png" /></div>\n\
                            <div id="sButtonText">To Here</div>\n\
                        </div>\n\
                    </a>\n\
                 </div></div>';
        }

        tplTxt +='</div></tpl>';

        var selAddressiTpl = new Ext.XTemplate(tplTxt);

        selAddressiTpl.compile();
        selAddressiTpl.overwrite('search-results', address);

        address.icondisplay = this.defaultIconPath;

        // Request  lon / lat from Yiannis
        OpenLayers.Request.GET({
            url: 'src/php/conn/geoc.php',
            params: {
                ad: address.name,
                ct: address.area,
                st: address.district,
                po: address.postcode,
                nm: address.addrnumber
            },
            success: function(responseObject) {
                
                var res = responseObject.responseXML.documentElement;
                var lat = res.getElementsByTagName('latitude')[0].firstChild.data;
                var lon = res.getElementsByTagName('longitude')[0].firstChild.data;

                //
                address.longitude = lon;
                address.latitude = lat;
                var feature = lbgm.point.featureFromPoint(address, 'addr');
                feature.attributes.type = 'address';
                feature.attributes.address = address.name;
                feature.attributes.postcode = address.postcode;
                feature.attributes.district = address.district;
                feature.attributes.area = address.area;
                lbgm.point.arSearchPoints.push(feature);
                lbgm.point.displayFeature(feature, true, true, true);

            },
            failure: function() {
               Ext.Msg.alert(lbgm.options.appname, 'Unable to load address.');
            }

        });
        
    },

    selectAddress: function(addressid) {
        //var feat = lbgm.point.pointslayer.getFeatureById(pointid);
        var feat = lbgm.point.pointslayer.getFeatureById("addr"+addressid);
        //alert(feat);
        if(feat != null)  {
            //alert(pointid);
            lbgm.maplets.mapobject.map.setCenter(feat.geometry.getBounds().getCenterLonLat());
            this.selectControl.select(feat);
        }
    },

    removeAddress: function(addressid) {
        
        var feat = lbgm.point.pointslayer.getFeatureById("addr" + addressid);
        if(feat != null) {
            lbgm.popup.hidePopup("addr"+ addressid);
            lbgm.point.pointslayer.removeFeatures([feat], null);
            Ext.get('search-results').dom.innerHTML = '';
        }
    },

    showAddressPoint: function(addressid) {
        OpenLayers.Request.POST({
            url: 'src/php/conn/address.conn.php',
            data: OpenLayers.Util.getParameterString({request: "loadAddress", "addressid": addressid}),
            success: function(responseObject) {
               //alert(responseObject.responseText);
               obj = Ext.util.JSON.decode(responseObject.responseText);
               //eval(obj.results);
               var address = {
                   id: obj.addressid,
                   name: obj.address,
                   postcode: obj.postcode,
                   area: obj.area,
                   district: obj.district
               };
               lbgm.point.displayAddress(address);

            },
            failure: function() {
               Ext.Msg.alert(lbgm.options.appname, 'Unable to locate address.');
               // Move it back to its original position
            },
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            }

        });
    },

    clearAddresses: function() {

    },

    /* Popup Specific Functions */
    clearPopups: function() {
        if(lbgm.popup.activepopupid != null)
            lbgm.popup.hidePopup(lbgm.popup.activepopupid);
    },

    removeSearchRes: function() {
        Ext.get('search-results').dom.innerHTML = "";
    },

    sharePoint: function(id) {
        var getParams = document.URL.split("?");
        var d = '';
        if(getParams.length > 1 ) d = '&p=' + id;
        else d = 'index.html?key=' + lbgm.layout.key + '&p=' + id;
        
        this.share(d);
    },

    shareAddress: function(addressid) {
        var getParams = document.URL.split("?");
        var d = '';
        if(getParams.length > 1 ) d = '&a=' + addressid;
        else d = 'index.html?key=' + lbgm.layout.key + '&a=' + addressid;
        
        this.share(d);
    },

    shareLocation: function(lonlat) {
        var getParams = document.URL.split("?");
        var d = '';
        lonlat.transform(lbgm.maplets.mapobject.map.getProjectionObject(), lbgm.maplets.mapobject.map.displayProjection);
        var zoomlvl = lbgm.maplets.mapobject.getZoomLevel();
        if(getParams.length > 1 ) d = '&lat=' + lonlat.lat + '&lon=' + lonlat.lon + "&z=" + zoomlvl;
        else d = 'index.html?key=' + lbgm.layout.key + '&lat=' + lonlat.lat + '&lon=' + lonlat.lon + "&z=" + zoomlvl;

        this.share(d);
    },

    share: function(data) {
        var getParams = document.URL.split("&");

        if(getParams.length > 0 ) {
           var baseurl = getParams[0];//Ext.urlDecode(getParams[0]);
           baseurl = baseurl.replace('#', '');
           var shareurl = baseurl + data;

            var shareWnd = new Ext.Window({
                width:600
                ,id:'share-win'
                ,height:400
                ,autoScroll:true
                ,closable:true
                ,constrain: true
                ,closeAction: 'close'
                ,title:'Share'
                ,items: [new Ext.FormPanel({
                        id: 'sharePointForm',
                        labelWidth:  85,
                        bodyStyle:'padding:10px 10px 0',
                        width: 585,
                        defaults: {width: 470},
                        defaultType: 'textfield',
                        url: 'src/php/conn/email.conn.php?action=share',

                        items: [{
                                fieldLabel: 'Link',
                                name: 'shareLink',
                                value: shareurl,
                                readOnly: true,
                                width: 470
                            }, {
                                vtype: 'email',
                                fieldLabel: 'From E-mail Address',
                                name: 'fromEmailAddress',
                                allowBlank: false,
                                width: 470
                            },{
                                vtype: 'email',
                                fieldLabel: 'To E-mail Address',
                                name: 'toEmailAddress',
                                allowBlank: false,
                                width: 470
                            },new Ext.form.HtmlEditor({
                                id:'emailBody',
                                fieldLabel:'Message',
                                width:470,
                                height:200
                            })],

                        buttons: [{
                            text: 'Share',
                            handler: function() {
                                Ext.getCmp('sharePointForm').getForm().submit({
                                    url:'src/php/conn/email.conn.php?action=share',
                                    method:'POST',
                                    waitTitle:'Connecting',
                                    waitMsg:'Sending data...',
                                    success: function(form, action) {
                                        obj = Ext.util.JSON.decode(action.response.responseText);
                                        Ext.Msg.alert('Share Location!', obj.text);
                                        shareWnd.close();
                                    },
                                    failure: function(form, action) {
                                        obj = Ext.util.JSON.decode(action.response.responseText);
                                        Ext.Msg.alert('Share Location!', obj.text);
                                    }
                                });
                            }
                        },{
                            text: 'Cancel',
                            handler: function() {
                                shareWnd.close();
                            }
                        }]
                    })]
            });

            shareWnd.show();
        }
    },

    displayNearPoints: function(obj) {

        if(obj.success) {
            var tplTxt = '<tpl for="."><div class="search-selected" id="search-selected-poi{id}">\n\
                    <div class="search-sel-close"><a href="#" onClick="lbgm.point.removeSingleSearchPoint(\'poi{id}\');">Remove</a></div>\n\
                    <a class="search-selected-item-a" href="#" onClick="lbgm.point.selectPoint(\'poi{id}\');">\n\
                        <div class="search-selected-item">\n\
                            <p>{name} {postcode} {area} {district} {distance}</p>\n\
                        </div>\n\
                    </a>';

            if(lbgm.layout.enablenavigation == 1) {
                tplTxt += '<div class="search-sel-links"><div class="sButton">\n\
                        <a href="#" onClick="lbgm.navigation.setNaviFrom(lbgm.point.pointslayer.getFeatureById(\'poi{id}\'));lbgm.point.removeSearchPoint(\'poi{id}\');">\n\
                            <div id="sButtonCont">\n\
                                <div id="sButtonIcon"><img src="gmadmin/images/icons/flag_green.png" /></div>\n\
                                <div id="sButtonText">From Here</div>\n\
                            </div>\n\
                        </a>\n\
                     </div>\n\
                     <div class="sButton">\n\
                        <a href="#" onClick="lbgm.navigation.setNaviTo(lbgm.point.pointslayer.getFeatureById(\'poi{id}\'));lbgm.point.removeSearchPoint(\'poi{id}\');">\n\
                            <div id="sButtonCont">\n\
                                <div id="sButtonIcon"><img src="gmadmin/images/icons/flag_red.png" /></div>\n\
                                <div id="sButtonText">To Here</div>\n\
                            </div>\n\
                        </a>\n\
                     </div></div>';
            }

            tplTxt += '</div></tpl>';

            var tpl = new Ext.XTemplate(tplTxt);

            tpl.compile();
            this.removeSearchRes();

            var points = obj.points;

            //alert(points.length);

            var tabPanel = Ext.getCmp('search-panel');
            if(tabPanel.getTabEl(0).id == 'search-panel__searchPanel')
                tabPanel.setActiveTab(0);

            for(var i=0; i<points.length; i++) {
                tpl.append('search-results', points[i]);
            }
        }
        else {
            Ext.Msg.alert(lbgm.options.appname, obj.reason);
        }

    },

    displayPointIdent: function(lonlat, obj) {

        if(lbgm.point.pointslayerPrepared) {
            var feat = lbgm.point.pointslayer.getFeatureById('identification');
            if(feat) {
                lbgm.point.pointslayer.removeFeatures([feat], null);
                //lbgm.maplets.mapobject.map.removeLayer(layer);
            }
        }
        
        if(obj.success) {
            // Prepare Date
            var data = obj.polyname + '<br>' + obj.polycity + '<br>' + obj.polystate;
            var feature = lbgm.point.featureFromLonLat(lonlat);
            feature.id = 'identification';
            //lbgm.point.feature = feature;
            this.displayFeature(feature, false, true, false);
            lbgm.popup.displayGenericPopup(feature, data);
        }
        else {
            Ext.Msg.alert(lbgm.options.appname, obj.reason);
        }
    },

    /**************************************************************************
     *
     * Add/Edit/Delete Point Functions
     *
     **************************************************************************/
    featureFromPlacemark: function(placemark) {

        var lonlat  = new OpenLayers.LonLat(placemark.pmlongitude,placemark.pmlatitude);
        lonlat.transform(lbgm.maplets.mapobject.map.displayProjection,lbgm.maplets.mapobject.map.getProjectionObject());

        // Get icon from point
        var iconPath = placemark.icondisplay;
        if(placemark.icondisplay == '') {
            iconPath = this.addPMIconPath;
        }

        // Prepare point style
        var pointStyleMap = {
            pointRadius: 10,
            graphicOpacity: 1,
            externalGraphic: iconPath,
            graphicWidth: 21,
            graphicHeight: 24,
            graphicXOffset: -10,
            graphicYOffset: -24,
            cursor: "pointer"//,
            //graphicTitle: name
        };

        var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat), null, pointStyleMap);

        feature.id = 'pm' + placemark.placemarkid;
        feature.attributes.id = placemark.placemarkid;
        feature.attributes.type = 'placemark';
        feature.attributes.name = placemark.name;
        feature.attributes.isLine = false;
        feature.attributes.ispoi = false;
        feature.attributes.data = placemark.pmdescription;
        feature.attributes.popupdata = placemark.pmdescription;
        feature.attributes.popuptitle = placemark.name;
        feature.attributes.popuptype = "generic"

        return feature;
    },

    newPlacemark: function(lonlat) {
        if(!lbgm.point.pointslayerPrepared) lbgm.point.preparePointLayer();

        var pointStyleMap = {
            pointRadius: 10,
            graphicOpacity: 1,
            externalGraphic: this.addPMIconPath,
            graphicWidth: 21,
            graphicHeight: 24,
            graphicXOffset: -10,
            graphicYOffset: -24//,
            //graphicTitle: name
        };

        var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat), null, pointStyleMap);
        feature.id = "addFeature";

        lbgm.point.pointslayer.addFeatures([feature]);
        this.feature = feature;

        var newlonlat = new OpenLayers.LonLat(lonlat.lon, lonlat.lat);
        newlonlat.transform(lbgm.maplets.mapobject.map.getProjectionObject(), lbgm.maplets.mapobject.map.displayProjection);

        lbgm.popup.showAddPMPopup(newlonlat.lon, newlonlat.lat, feature);

        this.addingPM();
    },

    addPMStart: function() {
        this.addPlacemark = true;
        lbgm.maplets.mapobject.map.div.style.cursor = 'default';
    },

    addPMCancel: function() {
        // Alert for the canceling
        if(lbgm.popup.activepopupid!=null)
            lbgm.popup.hidePopup(lbgm.popup.activepopupid);

        // If ok
        if(lbgm.point.pointslayer != undefined) {
            var feat = lbgm.point.pointslayer.getFeatureById('addFeature');

            if(feat) {
                lbgm.point.pointslayer.removeFeatures([feat], null);
                //lbgm.maplets.mapobject.map.removeLayer(layer);
            }
        }

        this.addPlacemark = false;
        this.addingPlacemark = false;

        var btn = Ext.getCmp('addplacemarkbtn');
        btn.setText("Feedback");
    },

    addingPM: function() {
        this.addingPlacemark = true;
        //var btn = Ext.getCmp('addpoibtn');
        lbgm.maplets.mapobject.map.div.style.cursor = 'url(../images/openhand.cur), url(src/images/openhand.cur), default';

    },

    addPMFinish: function() {
        this.addingPlacemark = false;
        this.addPlacemark = false;
        var btn = Ext.getCmp('addplacemarkbtn');
        btn.setText("Feedback");
    },

    savePlacemark: function(pointObj) {
        var conn = new Ext.data.Connection();
        conn.request({
            url: 'src/php/conn/poimarkers.conn.php',
            method: 'POST',
            params: {
                "request": "savePlacemark",
                "pointValues": Ext.util.JSON.encode(pointObj),
                key: lbgm.layout.key
            },
            success: function(responseObject) {
                obj = Ext.util.JSON.decode(responseObject.responseText);

                if(obj.success == false) {
                    Ext.Msg.alert(lbgm.options.appname, obj.message);
                }
                else {
                    var placemarkid = obj.placemarkid;

                    //
                    var layer = lbgm.maplets.mapobject.map.getLayersByName('AddPoint')[0];
                    if(layer) {
                        //layer.clearMarkers();
                        layer.removeFeatures(layer.features, null);
                        lbgm.maplets.mapobject.map.removeLayer(layer);
                    }

                    lbgm.popup.hidePopup(lbgm.popup.activepopupid);
                    this.displayPlacemarkById(placemarkid);
                }
            },
            failure: function() {
                //Ext.Msg.alert(lbgm.options.appname, 'Unable to load layout.');
            },
            scope: this
        });

        this.addPMFinish();
    },

    displayPlacemarkById: function(id) {
        //if(!this.pointslayerPrepared) this.preparePointLayer();
        //this.displayPointById(id, this.pointslayer);

        var conn = new Ext.data.Connection();
        conn.request({
            url: 'src/php/conn/poimarkers.conn.php',
            method: 'POST',
            params: {
                "request": "displayPlacemarkById",
                "placemark": id,
                "allowNavi": lbgm.layout.enablenavigation,
                key: lbgm.layout.key
            },
            success: function(responseObject) {
                obj = Ext.util.JSON.decode(responseObject.responseText);
                //eval(obj.results);
                if(obj.results != null && obj.results.length != 0) {
                    var pointRes = obj.results[0];
                    //this.displayPoint(pointRes, true, true);
                    var feature = this.featureFromPlacemark(pointRes);
                    //feature.style.externalGraphic = lbgm.point.addPMIconPath;
                    //alert(feature.style.externalGraphic);
                    this.arSearchPoints.push(feature);
                    this.displayPMFeature(feature, true, true, true);
                }
            },
            failure: function() {
            //Ext.Msg.alert(lbgm.options.appname, 'Unable to load layout.');
            },
            scope: this
        });
    },

    displayPMFeature: function(feature, showPopup, centerPoint, zoomIn) {
        if(!this.pointslayerPrepared) this.preparePointLayer();
        this.pointslayer.addFeatures([feature]);
        this.arPoints.push(feature);
        this.feature = feature;

        if(centerPoint) {
            //lbgm.maplets.mapobject.map.setCenter(feature.lonlat);
            if(zoomIn != undefined && zoomIn == true) lbgm.maplets.mapobject.map.setCenter(feature.geometry.getBounds().getCenterLonLat(), 17 - lbgm.maplets.mapobject.getZoomOffset());
            else lbgm.maplets.mapobject.map.setCenter(feature.geometry.getBounds().getCenterLonLat());
        }
        if(showPopup)  {
            //if(centerPoint && zoomIn == true) lbgm.maplets.popupcallbackF = feature; // Removed due to loading layer removal
            //else
            lbgm.popup.displayGenericPopup(feature, feature.attributes.data);
        }

    },

    addPointToGPXPool: function(feature) {
        var lonlat = feature.geometry.getBounds().getCenterLonLat().clone();
        lonlat.transform(lbgm.maplets.mapobject.map.getProjectionObject(), lbgm.maplets.mapobject.map.displayProjection);
        lbgm.gpxStore.add(new Record({name: feature.attributes.name, lat: lonlat.lat, lon: lonlat.lon}));
    },


    
    displayFeatureFromIP: function() {
        lbgm.maplets.mapobject.geolocate.deactivate();
        lbgm.maplets.mapobject.geolocate.watch = false;
        lbgm.maplets.mapobject.geolocate.activate();

    }
    
};
