

/**
* Dimedia Google Map for API version 2
*/

var DGoogleMap2 = new Object();
DGoogleMap2 = {
    
    data: {}, //podaci za kartu
    options: { 'zoom':13 }, //opcije za kartu
    loadersActive: 0, //brojač poziva loadera
    mapTypes: { 'HYBRID':'Kombinirana', 'ROADMAP':'Cestovna', 'SATELLITE':'Satelit' },
    markers: new Array, //lista markera na mapi
    mapMarkersBoundrys: { 'n':-90, 'e':-90, 's':90, 'w':90 },
    mapActionMode: 'browse',
    GBrowserIsCompatible: 0,
    mapDefaultUI: {
        'maptypes': { 'normal': true, 'hybrid': true, 'satellite': true, 'physical': false },
        'zoom': { 'scrollwheel': false, 'doubleclick': true },
        'keyboard': true,
        'controls': { 'largemapcontrol3d': true, 'smallzoomcontrol3d': false, 'maptypecontrol': false, 'menumaptypecontrol': true, 'scalecontrol': false, 'overviewmapcontrol': true }
    },
    mapControls:{}, //array of all controls on map
    mapContainerFixedChildren : { 'logocontrol': true, 'copyright': true },
    callbacks : { 'displayMap': new Array, 'fitMapToMarkers': new Array, 'displayMarkers': new Array },
    
    /**
    * konstruktor
    */
    DGoogleMap2 : function()
    {
    },
    
    getCoordsTollerance : function( x, y )
    {
        return ( Math.abs( x - y ) * 0.1 );
    },
    
    /**
    * dodavanje podaka
    */
    addData : function( data, label )
    {
        if( label )
        {
            DGoogleMap2.data[label] = data;
        }
        else
        {
            DGoogleMap2.data[ DGoogleMap2.data.length ] = data;
        }
    },
    
    /**
    * postavljanje markera
    */
    setMarker : function( latLng, title, html, icon, expanded, marker_params, delayDisplay )
    {
        marker_index = DGoogleMap2.markers.length;
        
        /**
        * latLng moze biti array ili google latLng
        */
        if( typeof latLng == 'object' )
        {
            if( typeof latLng['lat'] != 'function' )
            {
                latLng = new GLatLng( latLng['lat'], latLng['lng'] );
            }
            else if( typeof latLng['lat'] == 'function' )
            {
                latLng = new GLatLng( latLng.lat(), latLng.lng() );
            }
        }
        
        DGoogleMap2.markers[marker_index] = { 'latLng': latLng, 'title': title, 'html': html, 'icon': icon, 'expanded': expanded, 'onMap': ( ( DGoogleMap2.mapObject && !delayDisplay ) ? true : false ), 'markerRef': false, 'marker_params': marker_params };
        
        /**
        * praćenje granica markera
        */
        if( DGoogleMap2.mapMarkersBoundrys['n']<latLng.lat() ) DGoogleMap2.mapMarkersBoundrys['n'] = latLng.lat();
        if( DGoogleMap2.mapMarkersBoundrys['s']>latLng.lat() ) DGoogleMap2.mapMarkersBoundrys['s'] = latLng.lat();
        if( DGoogleMap2.mapMarkersBoundrys['w']>latLng.lng() ) DGoogleMap2.mapMarkersBoundrys['w'] = latLng.lng();
        if( DGoogleMap2.mapMarkersBoundrys['e']<latLng.lng() ) DGoogleMap2.mapMarkersBoundrys['e'] = latLng.lng();
        
        if( !DGoogleMap2.mapObject || delayDisplay )
        {
            return;
        }
        DGoogleMap2.putMarkerOnMap( marker_index );
        
        return marker_index;
    },
    
    putMarkerOnMap : function( marker_index )
    {
        var marker_params = DGoogleMap2.markers[marker_index].marker_params;
        var title = DGoogleMap2.markers[marker_index].title;
        var html = DGoogleMap2.markers[marker_index].html;
        var icon = DGoogleMap2.markers[marker_index].icon;
        var expanded = DGoogleMap2.markers[marker_index].expanded;
        var latLng = DGoogleMap2.markers[marker_index].latLng;
        
        /**
        * osnovni parametri markera
        */
        if( typeof marker_params != 'object' )
        {
            marker_params = {};
        }
        marker_params.marker_index = marker_index;
        marker_params.title = title;
        marker_params.clickable = ( ( html ) ? true : false );
        
        /**
        * custom icon
        */
        if( icon )
        {
            if( typeof icon == 'object' )
            {
                marker_params.icon = new GIcon( icon );
            }
            else
            {
                marker_params.icon = new GIcon( G_DEFAULT_ICON, icon );
            }
        }
        
        /**
        * dodavanje markera
        */

        var marker = new GMarker( latLng, marker_params );

        if( html )
        {
            /**
            * povezivanje markera i info prozora
            */
            GEvent.addListener( marker, 'click', function()
            {
                DGoogleMap2.openMarkerInfoWindowHtml( marker, html );
            });
        }
        DGoogleMap2.mapObject.addOverlay( marker );
        
        /**
        * dragable
        */
        if( marker_params['draggable'] )
        {
            GEvent.addListener(marker, "dragstart", DGoogleMap2.markerDragStart );
            GEvent.addListener(marker, "dragend", DGoogleMap2.markerDragEnd );
            
        }
        
        /**
        * auto prikaz info prozora
        */
        if( expanded && marker_params.clickable )
        {
            DGoogleMap2.openMarkerInfoWindowHtml( marker, html );
        }
        
        DGoogleMap2.markers[marker_index]['markerRef'] = marker;
    },
    
    openMarkerInfoWindowHtml : function( marker, html )
    {
        if( typeof marker == 'number' )
        {
            DGoogleMap2.markers[marker]['markerRef'].openInfoWindowHtml( '<div class="g-info-window">'+html+'</div>' );
        }
        else
        {
            marker.openInfoWindowHtml( '<div class="g-info-window">'+html+'</div>' );
        }
    },
    
    /**
    *
    */
    setOption : function ( optionLabel, optionValue )
    {
        DGoogleMap2.options[ optionLabel ] = optionValue;
    },
    
    /**
    * prikaz mape
    */
    displayMap : function( jQuerySelector )
    {
        if( DGoogleMap2.GBrowserIsCompatible == 0 ) DGoogleMap2.GBrowserIsCompatible = GBrowserIsCompatible();
        DGoogleMap2.loaderShow();
        if( DGoogleMap2.GBrowserIsCompatible )
        {
            DGoogleMap2.mapObject = new GMap2( $( jQuerySelector ).get(0) );
            if( DGoogleMap2.options['center'] )
            {
                DGoogleMap2.mapObject.setCenter( DGoogleMap2.options['center'] , DGoogleMap2.options['zoom'] );
            }
        }
        else
        {
            return false;
        }
        
        DGoogleMap2.mapObject.setUI( DGoogleMap2.mapDefaultUI );
        
        /**
        * kontrole
        */
        if( DGoogleMap2.options['MenuMapTypeControl'] )
        {
            DGoogleMap2.mapControls['MenuMapTypeControl'] = new GMenuMapTypeControl();
            DGoogleMap2.mapObject.addControl( DGoogleMap2.mapControls['MenuMapTypeControl'], new GControlPosition( DGoogleMap2.options['MenuMapTypeControl'], new GSize(10,10)) );
        }
        if( DGoogleMap2.options['LargeMapControl3D'] )
        {
            DGoogleMap2.mapControls['LargeMapControl3D'] = new GLargeMapControl3D();
            DGoogleMap2.mapObject.addControl( DGoogleMap2.mapControls['LargeMapControl3D'], new GControlPosition( DGoogleMap2.options['LargeMapControl3D'], new GSize(10,10)) );
        }
        if( DGoogleMap2.options['NavLabelControl'] )
        {
            DGoogleMap2.mapControls['NavLabelControl'] = new GNavLabelControl();
            DGoogleMap2.mapObject.addControl( DGoogleMap2.mapControls['NavLabelControl'], new GControlPosition( DGoogleMap2.options['NavLabelControl'], new GSize(80,5)) );
        }
        if( DGoogleMap2.options['ScaleControl'] )
        {
            DGoogleMap2.mapControls['ScaleControl'] = new GScaleControl();
            DGoogleMap2.mapObject.addControl( DGoogleMap2.mapControls['ScaleControl'], new GControlPosition( DGoogleMap2.options['ScaleControl'], new GSize(10,10)) );
        }
        if( DGoogleMap2.options['OverviewMapControl'] )
        {
            DGoogleMap2.mapControls['OverviewMapControl'] = new GOverviewMapControl();
            DGoogleMap2.mapObject.addControl( DGoogleMap2.mapControls['OverviewMapControl'], new GControlPosition( DGoogleMap2.options['OverviewMapControl'], new GSize(10,10)) );
        }
        if( DGoogleMap2.options['SmallMapControl'] )
        {
            DGoogleMap2.mapControls['SmallMapControl'] = new GSmallMapControl();
            DGoogleMap2.mapObject.addControl( DGoogleMap2.mapControls['SmallMapControl'], new GControlPosition( DGoogleMap2.options['SmallMapControl'], new GSize(10,10)) );
        }
        
        DGoogleMap2.loaderHide();
        DGoogleMap2.handleCallbacks('displayMap');
        return true;
    },
    
    
    removeMapControl : function( control )
    {
        if( DGoogleMap2.mapControls[control] )
        {
            DGoogleMap2.mapObject.removeControl( DGoogleMap2.mapControls[control] );
        }
    },
    
    hideMapControls : function()
    {
        $( DGoogleMap2.mapObject.getContainer() ).children().each(
            function(){
                if( $(this).attr('id') && !DGoogleMap2.mapContainerFixedChildren[$(this).attr('id')] ) $(this).hide();
            }
        );
    },
    showMapControls : function()
    {
        $( DGoogleMap2.mapObject.getContainer() ).children().each(
            function(){
                if( $(this).attr('id') ) $(this).show();
            }
        );
    },
    mapMoveBy : function( x, y )
    {
        DGoogleMap2.mapObject.panBy( new GSize( parseFloat(x) , parseFloat(y) ) );
    },
    
    /**
    * 
    */
    centerMap : function( latLng, zoom )
    {
        if( typeof latLng == 'object' )
        {
            if( typeof latLng['lat'] != 'function' )
            {
                latLng = new GLatLng( latLng['lat'], latLng['lng'] );
            }
            else if( typeof latLng['lat'] == 'function' )
            {
                latLng = new GLatLng( latLng.lat(), latLng.lng() );
            }
        }
        
        if( !zoom )
        {
            zoom = DGoogleMap2.mapObject.getZoom();
        }
        if( DGoogleMap2.mapObject.isLoaded() )
        {
            if( DGoogleMap2.mapObject.getZoom() != zoom )
            {
                DGoogleMap2.mapObject.setZoom( zoom );
            }
            DGoogleMap2.mapObject.panTo( latLng );
        }
        else
        {
            DGoogleMap2.mapObject.setCenter( latLng, zoom );
        }
        DGoogleMap2.mapObject.savePosition();
    },
    
    setMapZoom : function( zoom )
    {
        DGoogleMap2.mapObject.setZoom( zoom );
    },
    
    /**
    * function displayMarkers
    */
    displayMarkers : function()
    {
        var s = false;
        for( var marker in DGoogleMap2.markers )
        {
            if( DGoogleMap2.markers[marker]['onMap'] ) continue;
            DGoogleMap2.markers[marker]['onMap'] = true;
            //DGoogleMap2.setMarker( DGoogleMap2.markers[marker]['latLng'], DGoogleMap2.markers[marker]['title'], DGoogleMap2.markers[marker]['html'], DGoogleMap2.markers[marker]['icon'], DGoogleMap2.markers[marker]['expanded'], DGoogleMap2.markers[marker]['marker_params'] );
            s = DGoogleMap2.putMarkerOnMap( marker );
        }
        DGoogleMap2.handleCallbacks('displayMarkers');
    },
    
    /**
    * geocode za centriranje na županiju
    */
    centerToRegion : function( regionName )
    {
        DGoogleMap2.loaderShow();
        results = DGoogleMap2.geocodeAddress( regionName, DGoogleMap2.centerToRegionCallback );
        DGoogleMap2.loaderHide();
    },
    
    centerToRegionCallback : function ( results )
    {
        DGoogleMap2.loaderShow();
        var bounds = new GLatLngBounds( new GLatLng(results['south'], results['west']), new GLatLng(results['north'], results['east']) );
        DGoogleMap2.centerMap( bounds.getCenter(), DGoogleMap2.mapObject.getBoundsZoomLevel( bounds ) );
        DGoogleMap2.loaderHide();
    },
    
    /**
    * loader funkcije
    */
    loaderShow : function()
    {
        DGoogleMap2.loadersActive++;
        $('#gMapLoader').show();
    },
    loaderHide : function()
    {
        DGoogleMap2.loadersActive--;
        if( DGoogleMap2.loadersActive < 1 )
        {
            DGoogleMap2.loadersActive = 0;
            $('#gMapLoader').hide();
        }
    },
    
    drawCrosshair : function( x, y )
    {
        var lineX_p1 = new GPolyline( [ new GLatLng( x, -180 ), new GLatLng( x, 0 ) ] );
        DGoogleMap2.mapObject.addOverlay(lineX_p1);
        var lineX_p2 = new GPolyline( [ new GLatLng( x, 0 ), new GLatLng( x, 180 ) ] );
        DGoogleMap2.mapObject.addOverlay(lineX_p2);
        
        var lineY = new GPolyline( [ new GLatLng( 90, y ), new GLatLng( -90, y ) ] );
        DGoogleMap2.mapObject.addOverlay(lineY);
    },
    
    fitMapToMarkers: function( recalculate )
    {
        if( DGoogleMap2.markers.length < 1 ) return false;
        if( recalculate )
        {
            DGoogleMap2.mapMarkersBoundrys['n'] = -90;
            DGoogleMap2.mapMarkersBoundrys['e'] = -90;
            DGoogleMap2.mapMarkersBoundrys['s'] = 90;
            DGoogleMap2.mapMarkersBoundrys['w'] = 90;
            for( var marker_index in DGoogleMap2.markers )
            {
                if( DGoogleMap2.markers[marker_index].onMap && typeof DGoogleMap2.markers[marker_index].onMap != 'undefined' )
                {
                    if( DGoogleMap2.mapMarkersBoundrys['n']<DGoogleMap2.markers[marker_index].latLng.lat() ) DGoogleMap2.mapMarkersBoundrys['n'] = DGoogleMap2.markers[marker_index].latLng.lat();
                    if( DGoogleMap2.mapMarkersBoundrys['s']>DGoogleMap2.markers[marker_index].latLng.lat() ) DGoogleMap2.mapMarkersBoundrys['s'] = DGoogleMap2.markers[marker_index].latLng.lat();
                    if( DGoogleMap2.mapMarkersBoundrys['w']>DGoogleMap2.markers[marker_index].latLng.lng() ) DGoogleMap2.mapMarkersBoundrys['w'] = DGoogleMap2.markers[marker_index].latLng.lng();
                    if( DGoogleMap2.mapMarkersBoundrys['e']<DGoogleMap2.markers[marker_index].latLng.lng() ) DGoogleMap2.mapMarkersBoundrys['e'] = DGoogleMap2.markers[marker_index].latLng.lng();
                }
            }
        }
        if( DGoogleMap2.mapMarkersBoundrys['n'] == DGoogleMap2.mapMarkersBoundrys['s'] || DGoogleMap2.mapMarkersBoundrys['w'] == DGoogleMap2.mapMarkersBoundrys['e'] )
        {
            DGoogleMap2.centerMap( new GLatLng(DGoogleMap2.mapMarkersBoundrys['n'], DGoogleMap2.mapMarkersBoundrys['w']) );
        }
        else
        {
            var diff = DGoogleMap2.getCoordsTollerance ( DGoogleMap2.mapMarkersBoundrys['n'], DGoogleMap2.mapMarkersBoundrys['s'] );
            bounds = new GLatLngBounds( new GLatLng(DGoogleMap2.mapMarkersBoundrys['s']-diff, DGoogleMap2.mapMarkersBoundrys['w']-diff), new GLatLng(DGoogleMap2.mapMarkersBoundrys['n']+diff, DGoogleMap2.mapMarkersBoundrys['e']+diff) )
            DGoogleMap2.centerMap( bounds.getCenter(), DGoogleMap2.mapObject.getBoundsZoomLevel( bounds ) );
        }
        DGoogleMap2.handleCallbacks('fitMapToMarkers');
    },
    
    /**
    * geocode adrese
    */
    geocodeAddress : function( address, callback )
    {
        DGoogleMap2.loaderShow();
        
        geocoder = new GClientGeocoder();
        if (geocoder)
        {
            //geocoder.getLatLng( 
            geocoder.getLocations( 
                address, function( results )
                {
                    if (!results)
                    {
                        DGoogleMap2.loaderHide();
                        return false;
                    }
                    else
                    {
                        DGoogleMap2.loaderHide();
                        callback( results.Placemark[0].ExtendedData.LatLonBox );
                    }
                }
            );
        }
    },
    
    /**
    * prazne funkcije za pomicanje markera
    */
    markerDragStart : function()
    {
        DGoogleMap2.mapObject.closeInfoWindow();
    },
    markerDragEnd : function(latLng)
    {
    },
    
    handleCallbacks : function( func )
    {
        if( DGoogleMap2.callbacks[func].length > 0 )
        {
            for( var i in DGoogleMap2.callbacks[func] )
            {
                if( DGoogleMap2.callbacks[func][i].args != 'undefined' )
                {
                    DGoogleMap2.call_user_func_array( DGoogleMap2.callbacks[func][i].func, DGoogleMap2.callbacks[func][i].args );
                }
                else
                {
                    DGoogleMap2.callbacks[func][i].func();
                }
            }
        }
    },
    
    setCallback : function( onFunc, func )
    {
        var args = DGoogleMap2.objectToArray(arguments);
        if( args.length > 2 )
        {
            DGoogleMap2.callbacks[onFunc][DGoogleMap2.callbacks[onFunc].length] = { 'func': func, 'args': args.slice(2) };
        }
        else
        {
            DGoogleMap2.callbacks[onFunc][DGoogleMap2.callbacks[onFunc].length] = { 'func': func };
        }
    },
    
    objectToArray : function( o )
    {
        if( typeof o != 'object' ) return;
        var a = new Array;
        for( var i = 0; i < o.length; i++ ){ a[a.length] = o[i]; }
        return a;
    },
    
    /**
    * generička funkcija za callback
    */
    callback : function( callback )
    {
        if( typeof callback == 'undefined' )
        {
            return '';
        }
        var args = DGoogleMap2.objectToArray(arguments);
        if( args.length > 1 )
        {
            return DGoogleMap2.call_user_func_array( callback, args.slice(1) );
        }
        else
        {
            return callback();
        }
    },
    
    
    /**
    * php ekvivalent, poziva cb i prosljedjuje mu parameters
    */
    call_user_func_array : function( cb, parameters )
    {
        var func;
        if (typeof cb == 'string') {
            if (typeof this[cb] == 'function') {
                func = this[cb];
            } else {
                func = (new Function(null, 'return ' + cb))();
            }
        } else if (cb instanceof Array) {
            func = eval(cb[0]+"['"+cb[1]+"']");
        }
        
        if (typeof func != 'function') {
            throw new Error(func + ' is not a valid function');
        }
        return func.apply(null, parameters);
    },
    
    key : function(e)
    {
        var code;
        if (!e) var e = window.event;
        if (e.keyCode) code = e.keyCode;
        else if (e.which) code = e.which;
        var character = String.fromCharCode(code);
        DGoogleMap2.key['code'] = code;
        DGoogleMap2.key['character'] = character;
    },
    
    mouse : function(e)
    {
        var event_code;
        if (!e) var e = window.event;
        if (e.which) event_code = e.which;
        else if (e.button) event_code = e.button;
        if( event_code == 3 )
        {
            DGoogleMap2.mouse = 'rightclick';
        }
        else if( event_code == 1 )
        {
            DGoogleMap2.mouse = 'leftclick';
        }
        else if( event_code == 2 )
        {
            DGoogleMap2.mouse = 'middleclick';
        }
    }
    
}

function Clone() { }
function clone(obj) {
    Clone.prototype = obj;
    return new Clone();
}

function calert( t )
{
    $('#console div').append( ''+t+'<br /><hr>' );
}

function print_r(theObj){
  if(theObj.constructor == Array ||
     theObj.constructor == Object){
    $('#dump div').append("<ul>")
    for(var p in theObj){
        if( !theObj[p] ) continue;
      if(theObj[p].constructor == Array||
         theObj[p].constructor == Object){
$('#dump div').append("<li>["+p+"] => "+typeof(theObj)+"</li>");
        $('#dump div').append("<ul>")
        print_r(theObj[p]);
        $('#dump div').append("</ul>")
      } else {
$('#dump div').append("<li>["+p+"] => "+theObj[p]+"</li>");
      }
    }
    $('#dump div').append("</ul>")
  }
}
