MapUtil = {
    tempMark:null,
    cornerMark:null,
    getIcon: function (color,w,h) {
        if( !w )w=32;
        if( !h )h=32;
        var icon = new GIcon();
        icon.image = "http://google.com/mapfiles/ms/micons/" + color + ".png";
        icon.iconSize = new GSize(w, h);
        icon.iconAnchor = new GPoint(15, 32);
        return icon;
    },
    createGroundOverlay: function( urlImg,x1,y1,x2,y2 ){
        var boundaries = new GLatLngBounds(new GLatLng(y1,x1), new GLatLng(y2,x2));
        map.setCenter( boundaries.getCentrer() );
        var oldmap = new GGroundOverlay(urlImg, boundaries);
        map.addOverlay(oldmap);
    },
    /* Adding function to parser wkt into geometry */
    COLOR_DEFAULT: "#FF0000",
    ICON_DEFAULT: (new GIcon(G_DEFAULT_ICON)),
    OPACITY_DEFAULT: 0.5,
    WEIGHT_DEFAULT: 5,
    STROKE_OPACITY_DEFAULT: 0.8,
    wktOverlayer: [],
    wktClearOverlayers: function(){
        for( var i=0;i<this.wktOverlayer.length;i++ ){
            map.removeOverlay(this.wktOverlayer[i]);
            this.wktOverlayer[i] = null;
        }
        this.wktOverlayer = [];
    },
    geom: null,
    markers:Array(),
    nearMarkers:Array(),
    parseWKT: function(wkt,draw,title,des){
        if( MapUtil.geom ){
            for( var i=0;i<MapUtil.geom.length;i++ ){
                map.removeOverlay(MapUtil.geom[i]);
            }
        }
        if( !wkt && wkt.indexOf("EMPTY") > 0)return null;
        if(wkt.indexOf('MULTIPOLYGON') > -1){
            MapUtil.geom = new Array(1);
            MapUtil.geom[0] = this.parseMULTIPOLYGON(wkt);
            //alert(MapUtil.geom[0].getVertexCount() );
            map.addOverlay(MapUtil.geom[0]);
            map.setCenter(MapUtil.geom[0].getBounds().getCenter(), map.getBoundsZoomLevel(MapUtil.geom[0].getBounds()))
        }
        if( wkt.indexOf('MULTILINESTRING') > -1 ){
            MapUtil.geom = this.parseMULTILINESTRING(wkt);
        }else{
            if( wkt.indexOf('LINESTRING') > -1 ){
                this.wktOverlayer.push(this.parseLINESTRING( wkt ));
                map.addOverlay(this.wktOverlayer[this.wktOverlayer.length-1]);            
            }else{
                if( wkt.indexOf('POINT') > -1){
                    MapUtil.geom = new Array(1);
                    MapUtil.geom[0] = new GMarker(this.parsePOINT( wkt ),{
                        draggable:true
                    });
                    MapUtil.geom[0].disableDragging();
                }
            }
        }
        if(MapUtil.geom && MapUtil.geom[0]){
            for( var i=0;i<MapUtil.geom.length;i++ ){
                map.addOverlay(MapUtil.geom[i]);
            }
            if(wkt.indexOf('POINT') > -1){
                map.setCenter(MapUtil.geom[0].getLatLng(), 18);
            }else{
                map.setCenter(MapUtil.geom[0].getBounds().getCenter(), map.getBoundsZoomLevel(MapUtil.geom[0].getBounds()));
            }
        }
        return true;
    },
    //Coloca puntos sobre el mapa borrando los anteriores.
    putNearPoints: function(wkt,logo, index, cod){
        if( MapUtil.nearMarkers ){
            for( var i=0;i<MapUtil.nearMarkers.length;i++ ){
                map.removeOverlay(MapUtil.nearMarkers[i]);
            }
        }
        if( !wkt && wkt.indexOf("EMPTY") > 0)return null;
        //MapUtil.markers = Array();
        if( wkt.indexOf('LINESTRING') > -1 ){
            MapUtil.geom = [this.parseLINESTRING( wkt )];
        }else{
            if( wkt.indexOf('POINT') > -1){
                var icon = new GIcon(G_DEFAULT_ICON);
                icon.image = logo;
                icon.shadow = null;
                icon.iconSize =new GSize(20,20);
                MapUtil.nearMarkers[index] = new GMarker(this.parsePOINT( wkt ),{
                    icon:icon
                });
                GEvent.addListener(MapUtil.nearMarkers[index], "click", function() {
                    $.ajax({
                        url: 'yellowPageSearch?action=information',
                        type: 'post',
                        dataType: 'html',
                        data:{
                            cod:cod
                        },
                        success: function(data) {
                            MapUtil.tempMark = MapUtil.nearMarkers[index];
                            MapUtil.nearMarkers[index].openInfoWindowHtml(data);
                        }
                    })
                });
            }
        }
          
        if(MapUtil.nearMarkers[index]){
            for( var i=0;i<MapUtil.nearMarkers.length;i++ ){
                map.addOverlay(MapUtil.nearMarkers[i]);
            }
        }
        return true;
    },
    //Coloca puntos sobre el mapa borrando los anteriores.
    putPoints: function(wkt,logo, index, cod){
        if( MapUtil.markers ){
            for( var i=0;i<MapUtil.markers.length;i++ ){
                map.removeOverlay(MapUtil.markers[i]);
            }
        }
        if( !wkt && wkt.indexOf("EMPTY") > 0)return null;
        //MapUtil.markers = Array();
        if( wkt.indexOf('LINESTRING') > -1 ){
            MapUtil.geom = [this.parseLINESTRING( wkt )];
        }else{
            if( wkt.indexOf('POINT') > -1){
                var icon = new GIcon(G_DEFAULT_ICON);
                icon.image = logo;
                icon.iconSize =new GSize(50,50);
                icon.imageMap  = [0,0, 50,0, 50,50, 0,50];
                MapUtil.markers[index] = new GMarker(this.parsePOINT( wkt ),{
                    icon:icon
                });
                GEvent.addListener(MapUtil.markers[index], "click", function() {
                    $.ajax({
                        url: 'yellowPageSearch?action=information',
                        type: 'post',
                        dataType: 'html',
                        data:{
                            cod:cod
                        },
                        success: function(data) {
                            MapUtil.markers[index].openInfoWindowHtml(data);
                        }
                    })
                });
            }
        }
          
        if(MapUtil.markers[index]){
            for( var i=0;i<MapUtil.markers.length;i++ ){
                map.addOverlay(MapUtil.markers[i]);
            }
        }
        return true;
    },
    parseMULTIPOLYGON: function ( text, color,weight,opacity){
        if(!color)color = this.COLOR_DEFAULT;
        if(!weight)weight = this.WEIGHT_DEFAULT;
        if(!opacity)opacity = this.OPACITY_DEFAULT;

        if( text.indexOf('MULTIPOLYGON') > -1 ){
            var idx = text.indexOf('(((');
            text = text.substring(idx+3);
            idx = text.indexOf(')))');
            text = text.substring(0,idx);
        }
        
        var points = text.split(',');
        var components = [];
        for(var i=0; i< points.length; ++i) {
            var point = points[i].split(' ');
            components.push( new GLatLng(point[1],point[0]) );
        }
        if( components.length > 0 )
            return new GPolyline( components, color, weight, opacity);
        return null;
    },
    parseMULTILINESTRING: function ( text, color,weight,opacity){
        if(!color)color = this.COLOR_DEFAULT;
        if(!weight)weight = this.WEIGHT_DEFAULT;
        if(!opacity)opacity = this.OPACITY_DEFAULT;
        if( text.indexOf('MULTILINESTRING') > -1 ){
            var idx = text.indexOf('(');
            text = text.substring(idx+1);
            idx = text.length;
            text = text.substring(0,idx-1);
        }
        var line;
        var lines = text.split('),(');
        var polyline = [];
        for(var i=0; i< lines.length; ++i) {
            line = lines[i].replace('(', '');
            line = lines[i].replace(')', '');
            polyline.push( this.parseLINESTRING(line) );
        }
        return polyline;
    },
    parseLINESTRING: function ( text, color,weight,opacity ){
        if(!color)color = this.COLOR_DEFAULT;
        if(!weight)weight = this.WEIGHT_DEFAULT;
        if(!opacity)opacity = this.OPACITY_DEFAULT;

        if( text.indexOf('LINESTRING') > -1 ){
            var idx = text.indexOf('(');
            text = text.substring(idx+1);
            idx = text.indexOf(')');
            text = text.substring(0,idx);
        }
        
        var points = text.split(',');
        var components = [];
        for(var i=0; i< points.length; ++i) {
            var point = this.parsePOINT(points[i]);
            components.push( point );
        //alert(point);
        }
        if( components.length > 0 ){
            return new GPolyline( components, color, weight, opacity);
        }
        return null;
    },
    parsePOINT: function ( text ){
        var idx;
        if( text.indexOf('POINT') > -1){
            idx = text.indexOf('(');
            text = text.substring(idx+1);
            idx = text.indexOf(')');
            text = text.substring(0,idx);
        }
        if( text.indexOf('(') > -1){
            idx = text.indexOf('(');
            text = text.substring(idx+1);
        }
        text = $.trim(text);
        var coords = text.split(" ");
        if( coords[1].length > 10 )
            coords[1] = coords[1].substring(0, (coords[1].indexOf('.')+6) );
        if( coords[0].length > 10 )
            coords[0] = coords[0].substring(0, (coords[0].indexOf('.')+6) );
        //var p = new GLatLng(parseFloat(coords[1]),parseFloat(coords[0]));
        var p = new GLatLng(parseFloat(coords[1]),coords[0]);
        //var p = new GMarker(new GLatLng(parseFloat(coords[1]),parseFloat(coords[0])));
        if( p )
            return p;
        return null;
    },
    /*
         *  Function create mark on map
         *  @param lat
         *  @param lng
         *  @param zoom
         *  @param title
         *  @param description
         *  @param imageMark
         **/
    gotoLocationMark: function ( markerObj,lat,lng,zoom,title,description,imageMark){
        var icon;
        if(markIcon){
            if( markIcon instanceof GIcon){
                icon = markIcon
            }else{
                icon = this.ICON_DEFAULT;
                icon.image = imageMark;
                icon.iconSize = new GSize(32, 32);
            }
        }else{
            icon = this.ICON_DEFAULT;
        }
        var point = new GLatLng(lat,lng);
        map.removeOverlay(markerObj);
        markerObj = new GMarker(point, {
            title: title,
            icon: icon
        });
        
        map.addOverlay(markerObj);
        GEvent.addListener(markerObj, "click", function() {
            markerObj.openInfoWindowHtml(description);
        });
        if( description != null )
            markerObj.openInfoWindow(point, description );

        map.setCenter(point,15);
        
        
    /*
        if(this.tempMark != null){
            map.removeOverlay(this.tempMark);
        }

        this.tempMark = new GMarker(point, {
            title: title,
            icon: icon
        });
        map.addOverlay(this.tempMark);
        //window.setTimeout(function(){map.removeOverlay( tempMark );} ,60000);
        
        GEvent.addListener(this.tempMark, "click", function() {
            tempMark.openInfoWindowHtml(description);
        });
        if( description != null )
            this.tempMark.openInfoWindow(point, description );

        map.setCenter(point,15);
             */
    },
    
    addMarker: function(latlng) {
        marker[markerCount] = new GMarker(latlng, markIcon);
        map.addOverlay(marker[markerCount]);
        GEvent.addListener(marker[markerCount], "click", function() {
            /*mark.openInfoWindowHtml("Punto en: <br />Latitud: " + mark.getLatLng().lat()+ "<br />Longitud: " + mark.getLatLng().lng() );*/
            var description = "Punto en: <br />Latitud: "+latlng.lat() + " <br />Longitud: "+latlng.lng();
            marker[markerCount].openInfoWindowHtml(description);
        });
        //markerCount = markerCount+1;
        //document.getElementById("message").innerHTML = "Marker added at latitude "+latlng.lat() + " longitude "+latlng.lng() ;
        return marker[(markerCount)];
    },
    changeMapType: function(index){
        if( map.getMapTypes()[index] != null ){
            map.setMapType( map.getMapTypes()[index] );
        }
    },
    /*
         * Zoom to box
         * @param bbox String box2d
         * BOX(-65.4187393188477 -16.9698047637939,-65.41845703125 -16.9682693481445)
         * (-65.4184494018555,-16.9682674407959),(-65.4187469482422,-16.9698066711426)
         * @param desc optional description in infoWindow on map
         * Everything inside a CDATA section is ignored by the parser.
         * A CDATA section starts with "<![CDATA[" and ends with "]]>":
         * @return none
         **/
    zoomToBBOX: function ( bbox, desc){
        if(bbox.indexOf("BOX")>-1){
            bbox=bbox.replace("BOX","");
            bbox=bbox.replace(" ",",");
            bbox=bbox.replace(" ",",");
        }
        bbox=bbox.replace("(","");
        bbox=bbox.replace(")","");
        bbox=bbox.replace("(","");
        bbox=bbox.replace(")","");
        var r = bbox.split(",");
        var ro = new GLatLngBounds(
            new GLatLng(parseFloat(r[1]),parseFloat(r[0])),
            new GLatLng(parseFloat(r[3]),parseFloat(r[2])));
        map.setCenter(ro.getCenter(), map.getBoundsZoomLevel(ro));
        if( desc ){
            gotoLocation(lat,lon,zoomLevel, desc);
        }
    },
    /* Zoom to level */
    getZL: function (lati,loni,latf,lonf) {
        var rectObj = new GLatLngBounds(new GLatLng(lati,loni), new GLatLng(latf,lonf));
        var zm = map.getBoundsZoomLevel(rectObj);
        return zm;
    },
    /* Manage overlayer */
    clearAllOverlays: function(){
        map.clearOverlays();
    },
    
    clearMarkers:function(){
        if( MapUtil.markers ){
            for( var i=0;i<MapUtil.markers.length;i++ ){
                map.removeOverlay(MapUtil.markers[i]);
            }
        }
    },
    clearNearPoints:function(){
        if( MapUtil.nearMarkers ){
            for( var i=0;i<MapUtil.nearMarkers.length;i++ ){
                map.removeOverlay(MapUtil.nearMarkers[i]);
            }
            MapUtil.nearMarkers = Array();
        }
    }
}

