// function getBaseIcon() {
    // if( window.baseIcon ) return window.baseIcon;
    // window.baseIcon = new GIcon();
    // window.baseIcon.image = '/images/map/blue-dot.png';
// }
var _bounds, map, marker, markerCluster;

function addMarker( lat, lng, html, options ) {
    var point = new GLatLng(lat, lng);
    
    var marker = new GMarker(point, options);
    if( html ) {
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml( html );
        });
    }
    
    map.addOverlay( marker );
    
    return marker;
}

function createMarker( lat, lng, html, options ) {
    var point = new GLatLng(lat, lng);
    
    var marker = new GMarker(point, options);
    if( html ) {
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml( html );
        });
    }

    return marker;
}

function addPropertyMarker( lat, lng, options ) {
    options = options || {};
    
    var Icon = new GIcon();
    
    Icon.image = '/images/map/property-pin.png';
    Icon.iconSize = new GSize(88, 68);
    Icon.shadow = '/images/map/property-shadow.png';
    Icon.shadowSize = new GSize(88, 68);
    Icon.iconAnchor = new GPoint(30, 60);
    Icon.infoWindowAnchor = new GPoint(30, 2);
    options.icon = Icon;
    options.clickable = 0;
    return addMarker( lat, lng, null, options );
}

function addSearchMarker( lat, lng, index, html, options ) {
    options = options || {};
    
    var Icon = new GIcon();
    var width = 57;
    var height = 44;
    var anchorX = Math.round(width/3);
    var anchorY = Math.round(height/2);
    Icon.image = options.image;
    Icon.iconSize = new GSize(width, height);
    Icon.shadow = '/images/map/property-shadow-small.png';
    Icon.shadowSize = new GSize(width, height);
    Icon.iconAnchor = new GPoint(anchorX, anchorY);
    Icon.infoWindowAnchor = new GPoint(anchorX, anchorY);
    options.icon = Icon;
    
    return createMarker( lat, lng, html, options );
}

function autoZoomMap( point ) {
    if( map.getBounds().containsLatLng( point ) && _bounds.containsLatLng( point ) ) return false;
    _bounds.extend( point );
    map.setZoom( map.getBoundsZoomLevel( _bounds ) );
    map.panTo( _bounds.getCenter() );
}

//shows a point on the map
//returns true if the point is visible
function showPoi( id, lat, lng, html ) {
    if( null == window.poiList ) {
        window.poiList = {};
    }
    
    if( null != window.poiList[id] ) {
        poiMarker = window.poiList[id];
        poiMarker.isHidden() ? poiMarker.show() : poiMarker.hide();
        return !poiMarker.isHidden();
    }

    //var icon = new GIcon( );
    var poiMarker = addMarker(lat, lng, html );
    poiMarker.setImage ( '/images/map/blue-dot.png' );
    
    window.poiList[id] = poiMarker;
    return true;
}

function findByAddress( address ) {
    window.clientGeocoder = new GClientGeocoder();
    if( !clientGeocoder ) return;
    
    clientGeocoder.getLocations( address, function(data) {
        if( !data || 200 != data.Status.code ) {
            return indicateAddressIsFound( false );
        }
        
        try {
            var place = data.Placemark[0];
            var address = place.AddressDetails;
            var accuracy = address.Accuracy;
            var coords  = place.Point.coordinates;
            var point = new GLatLng( coords[1], coords[0] );
            setPoint( point );
            var foundStreet = ( accuracy >= 6 );
            
            indicateAddressIsFound( foundStreet );
            if(foundStreet) {
                map.setZoom(15);
            }
            map.panTo( point );
        }
        catch(err) {
            indicateAddressIsFound( false );
        }
    });
}

function indicateAddressIsFound( found ) {
    if( found ) {
        $('#add-property-could-not-find').slideUp('fast');
        $('#add-property-step-3').slideDown('fast');
        $('#add-property-found').fadeIn('fast');
    }
    else {
        $('#add-property-found').slideUp('fast');
        $('#add-property-step-3').slideUp('fast');
        $('#add-property-could-not-find').fadeIn('fast');
    }
    return found;
}
function setCoordsByGeoCoderCoords( latlng ) {
    globalLoader.setMessage( lang('Loading') + '...' ).show();
    $.getJSON('/ajax/reverse-geocoding', {
            'lat' : latlng.lat(), 
            'lng': latlng.lng(),
            'zoom': map.getZoom()
        }, 
        function (data, status) {
            globalLoader.hide();
            if( !data || !data.ok ) {
                return false;
            }
            processPlace( data.data, false );
    });
    
}

function reverseAddress( cityId ) {
    $.getJSON('/ajax/reverse-address', {
            'id' : cityId 
        }, 
        function (data, status) {
            if( !data || !data.ok ) {
                return false;
            }
            showAddress( data.data, false );
    });
    
}

function initMap(lat, lng, zoom ) {
    if ( 'undefined' == typeof GBrowserIsCompatible ) {
        alert('Google Maps are not loaded');
        return false;
    }
    if( !GBrowserIsCompatible() ) return;
        
    if( null == lat ) {
        lat = 47.5;
    }
    
    if( null == lat ) {
        lng  = lng  || 7.7;
    }
    
    zoom = zoom || 4;

  
    window.map = new GMap2(document.getElementById("map"));
    //map.setMapType( G_HYBRID_MAP );

    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GScaleControl());
    
    map.addControl(new GOverviewMapControl());
    //map.enableScrollWheelZoom();
    //map.enableGoogleBar();
    
    var point = new GLatLng(lat, lng);
    map.setCenter(point, zoom );
    
    _bounds = new GLatLngBounds();
    _bounds.extend(point);
        
    return map;
}

var mapApi = {
    map: false,
    point: false,
    geocoder: false, 
    processClick:function (overlay, latlng) {
        if (!mapApi.point) {
            mapApi.point = new GMarker (latlng, {draggable: true});
            mapApi.map.addOverlay(mapApi.point);
            GEvent.addListener (mapApi.point, "drag", mapApi.updateTextCoords);
        }
        else {
            mapApi.point.setLatLng (latlng);
        }
        
        mapApi.updateTextCoords(latlng);
    },
    navigateToAddress: function (address, zoom) {
        mapApi.geocoder.getLatLng(address,function (point) {
            if (point) {
                mapApi.updateTextCoords (point);
                mapApi.processChange (zoom);
            }
        });
    },
    processChange: function (zoom) {
        var latlng = new GLatLng ($('#lat').attr ('value'),$('#lng').attr ('value'), false);
        if (latlng.lat ().toString () != 'NaN' && latlng.lng ().toString () != 'NaN') {
            
            mapApi.processClick (null, latlng);
            mapApi.map.setCenter(latlng, zoom);
        }
        else {
            alert (lang('Wrong value'));
        }
    },
    updateTextCoords: function (latlng) {
        $('#lat').attr ('value', latlng.lat ());
        $('#lng').attr ('value', latlng.lng ());
    },
    init:function () {
        mapApi.map = new google.maps.Map2(document.getElementById("map"));
        mapApi.map.setUIToDefault();
        mapApi.geocoder = new GClientGeocoder();
        GEvent.addListener (mapApi.map, "click", function (overlay, latlng) {mapApi.processClick (overlay, latlng);});
        
        if (jQuery.trim ($('#lat').attr ('value')) != '' && jQuery.trim ($('#lng').attr ('value')) != '') {
            mapApi.processChange (14);
        }
        else {
            mapApi.map.setCenter(new google.maps.LatLng(37, 0), 1);
        }
    },
    start:function () {
        google.load ("maps", "2");
        google.setOnLoadCallback(mapApi.init);
    }
}

function displayLocation () {
    var address = '';
    var zoom = 1;
    if (jQuery.trim ($('#country').attr ('value')) != '') {
        address += ' '+$('#country').attr ('value');
        zoom = 3;
    }
    
    if (jQuery.trim ($('#province').attr ('value')) != '') {
        address += ' '+$('#province').attr ('value');
        zoom = 5;
    }
    
    if (jQuery.trim ($('#city_name').attr ('value')) != '') {
        address += ' '+$('#city_name').attr ('value');
        zoom = 9;
    }
    
    if (jQuery.trim ($('#street').attr ('value')) != '') {
        address += ' '+$('#street').attr ('value');
        zoom = 14;
    }
    
    mapApi.navigateToAddress (address, zoom);
}

function splitAddress (value) {
    var parts = value.split (",");
    for (i = 0; i < parts.length; i++) {
        parts [i] = jQuery.trim (parts [i]);
    }
    
    if (parts.length == 2) {
        $('#country').attr ('value', parts [1]);
    }
    else if (parts.length >= 3) {
        $('#country').attr ('value', parts [2]);
        $('#province').attr ('value', parts [1]);
    }
    
    $('#city_name').attr ('value', parts [0]);
    displayLocation ();
}


NewPropertyForm = {
    busy: false,
    
    validate: function(){
        var fields = {
            'city' : 'Please type city name',
            'street_address' : 'Please define the property street address'
        };
        
        for( var id in fields ) {
            if( '' == jQuery.trim( $('#' + id ).val() ) ) {
                var msg = lang(fields[id]);
                alert( msg );
                $('#' + id ).focus();
                return false;
            }
        }
        return true;
    },
    
    submit: function(){
        NewPropertyForm.busy = true;
        $('.nextPropertyGreen').replaceWith('<img src="/images/i/ajax-loader.gif" />');
        var point = marker.getPoint();
        var street = $('#street_address' ).hasClass ('example') ? '' : $.trim( $('#street_address' ).val() ); 
        var postData = {
            'lat' : point.lat(),
            'lng' : point.lng(),
            'zip' : '',
            'city_id' : parseInt( $('#city_id' ).val(), 10 ),
            'country' : jQuery.trim( $('#prop_country_code' ).val() ),
            'street' : street,
            'id': propertyId
        };
        
        var url = '/owner/ajax/create-property';
        
        $.post (url, postData, function (data, status) {
                NewPropertyForm.busy = false;
                
                if ( 'success' != status ) return false;
                
                if( data.error || !data.id ) {
                    msg = data.msg || lang('An error occurred. Try again later.');
                    alert(msg);
                    return false;
                }
                location.href = '/owner/property/modify/id/' + parseInt( data.id, 10 ) + '?new=1';
                
            }, "json");
            
    },
    
    suggestOnSelect: function(city) {
        globalLoader.hide();
        showCity(city, true);
        //reverseAddress( city.id );
        $('#city').focus();
        $('#add-property-step-2').slideDown('fast');
    },
    
    suggestOnChange: function() {
        globalLoader.setMessage(lang('Loading')+'...').show();
        $('#city_id').val('');
        $('#add-property-step-2, #add-property-step-3').hide('fast');
    },
    
    isBusy: function() {
        return NewPropertyForm.busy;
    }
};

function showCity(city, movePoint) {
    $('#city_id').val( city.id );
    
    $('#city').val( city.city );
    $('#prop_city').html (city.city);
    $('#prop_country').html( city.country );
    $('#prop_country_code').val( city.country_code );
    $('#prop_region').html( city.region );
    if ($('#prop_area').length) {
        $('#prop_area').val( city.area );
    }   
    showAddress( city );
    $('#locationBlock').show ();
    if( movePoint ) {
        map.setZoom( 10 );
        var point = new GLatLng( city.lat, city.lng );
        setPoint( point );
        map.panTo( point );
    }
    $('#add-property-step-2').slideDown('fast');
}

function showAddress(city) {
    if( '' == $('#street_address').val() ) {
        $('#street_address').val( city.address );
    }
    if( '' == $('#zip').val() ) {
        $('#zip').val( city.zip );
    }
}

function highlightPoi( id, lat, lng, html, sourceEl ) {
    var isVisible = showPoi( id, lat, lng, html );
    if(isVisible) {
        $(sourceEl).addClass('poi-link-highlight');
        autoZoomMap( new GLatLng(lat, lng) );
    } 
    else {
        $(sourceEl).removeClass('poi-link-highlight');
    }
}

function tinyPropertyBlock(property, currency_sign) {
    var features = [];
    if( property.bedrooms != null ) {
        var bedrooms = parseInt( property.bedrooms, 10 );
        var tag = (1 == bedrooms ) ? lang('bedroom') : lang('bedrooms');
        features.push( bedrooms + ' ' + tag );
    }
    
    if( property.bathrooms != null ) {
        var bathrooms  = parseInt( property.bathrooms, 10 );
        var tag = (1 == bathrooms ) ? lang('bathroom') : lang('bathrooms');
        features.push( bathrooms + ' ' + tag );
    }
    
    return '<div class="tinyPropertyBlock">' +
                    '<div class="picture">'+
                        '<img src="'+property.image+'" width="90" height="60" alt="Image" />'+
                    '</div>'+
                    '<div class="content_inner">'+
                        '<h1>'+property.title + '</h1>'+
                        '<div class="star_holder passive" title="'+property.rating + '">'+
                            '<div style="width: '+100*property.rating/5 + '%;" class="star_active"/></div>'+
                        '</div>'+
                        '<span>' + features.join(', ') +'</span>' +
                        '<span class="price">' +lang('From') +' ' + currency_sign + ' ' +property.price_min + ' ' +lang('/week') +'</span>' +
                        '<span><a href="'+property.url + '">'+lang('View details')+'</a></span>' +
                    '</div>'+
                    '<span class="c"></span>'+
                '</div>';
}

