/***Google Maps ***/
/** odpalam jesli istnieje div zawierajacy mape **/
google.maps.event.addDomListener(window, 'load', initialize );

function initialize(){
    //Sprawdzam czy jest sens odpalac dalszaczesc skryptu
    if( document.getElementById('map_canvas') == null ) return;
    
    var initialLocalization;
    var map;
    var geocoder = new google.maps.Geocoder();
    var markerArr = [];
    var centerMap = new google.maps.LatLng(52.268157,19.024658);
    var circle;
    var myOptions = {
        zoom        : 14,
        mapTypeId   : google.maps.MapTypeId.ROADMAP,
        //center      : warsaw,
        streetViewControl   : false,
        //scaleControl: true,
        zoomControlOptions  : {
            position    : google.maps.ControlPosition.LEFT_CENTER
        },
        panControl  : false
    }
    /*****Podpinam zdarzenie wyszukiwania lokalizacji, wymaga jQuery********/
    var findLocalization = document.getElementById('szukaj_lokalizacji');
    $(findLocalization).click(function(){
        getAdress();
    });
    //Akcja focus_out
    $('#city, #address').focusout(function(){
        getAdress();
    });
    $('#d_province_id').change(function (){
        getAdress();
    });
    //Znacznik usun lokalizacje
    $('#usun_lokalizacje').click(function(){
        removeLatLng();
    });
    /************/
    
    map = new google.maps.Map(document.getElementById('map_canvas'), myOptions );
    
    //Sprawdzam czy istnieje informacja o lokalizacji.
    var latitudeHtml = $('#latitude');
    var longitudeHtml = $('#longitude');
    
    runGeoLocalization();

    google.maps.event.addListener(map, 'click', function(event){
        savePoint(event.latLng);
        addMarker(event.latLng, google.maps.Animation.BOUNCE);
        endBounce();
        map.panTo(event.latLng);
    });
    
    /****** Funkcja deolokalizacji *****
     *Funkcja przyjmuje argum,enty lat, lng.
     *Jesli sa niezdefiniowane wowczas sprawdza w strukturze dom czy isniteja.
     * W pierwszej kolejnosci wskazuje polozenie argumentow. 
     * @param int|bool latitiude
     * @param int|bool longitude
     * @param bool removeLocalization - usun lokalizacje
     **/
    function runGeoLocalization( latitude, longitude, removeLocalization){
        
        if( typeof latitude == 'number'  && typeof longitude == 'number'){
            latitudeHtml.val(latitude);
            longitudeHtml.val(longitude);
        }
        
        if( parseFloat(latitudeHtml.val()) != 0 && parseFloat(longitudeHtml.val()) != 0 && latitudeHtml.val()!= '' && longitudeHtml.val()!='') {
            initialLocalization = new google.maps.LatLng(parseFloat(latitudeHtml.val()), parseFloat(longitudeHtml.val()));
            map.setCenter(initialLocalization);
            addMarker(initialLocalization);
        }else if(navigator.geolocation){ /**W3C Geolocalization**/
            navigator.geolocation.getCurrentPosition(function(position){ 
                initialLocalization = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                map.setCenter(initialLocalization);
                //Przypadek zapisu zlokalizaowanych wspolrzednych
                if(typeof removeLocalization == 'undefined' || removeLocalization == false ){
                    // addMarker(initialLocalization);
                    savePoint(initialLocalization);
                }else{
                    //Czyszcze tablice marekrow.
                    if(markerArr){
                        for( i in markerArr ){
                            markerArr[i].setMap(null);
                            markerArr.splice(0,1);
                        }
                    }
                    map.setCenter(centerMap);
                    map.setZoom(5);
                }
            }, function(){//error handle
                map.setCenter(centerMap);
            });
        }else {
            map.setCenter(centerMap);
            map.setZoom(14);
            if(typeof removeLocalization == 'undefined' || removeLocalization == FALSE ){
                initialLocalization = new google.maps.LatLng(52.066,19.28833)
                savePoint(initialLocalization);
            }
        }
    /** End W3C Geolocation **/
    }
    
    /******** Dodaje marker na mapie *****/
    function addMarker(location, animationMarker ){
        //Sprawdzam czy jest circle
        if(typeof circle === 'object' ) {
            circle.setMap(null);
        }
        //Zeruje circle
        circle = 'undefined';
        //Czyszcze tablice marekrow.
        if(markerArr){
            for( i in markerArr ){
                markerArr[i].setMap(null);
                markerArr.splice(0,1);
            }
        }
        
        typeof(animationMarker) === 'undefined' ? animationMarker = google.maps.Animation.DROP : null;
      
        marker = new google.maps.Marker({
            title       : 'Tu się znajduję?',
            map         : map,
            position    : location,
            draggable   : true,
            animation   : animationMarker
        //icon        : '/img/icons/sprite/pin_green.png'
        });
        markerArr.push(marker);
        
        //Add circle
        circle = new google.maps.Circle({ 
            radius  : 100,
            strokeColor : "#F57A00",
            strokeWeight: 2,
            strokeOpacity : 0.7,
            fillColor   : '#F57A00',
            center  : location,
            zIndex  : 0
        });
           
           
        circle.setMap(map);
        
        //Add event
        google.maps.event.addListener( markerArr[0], 'drag', function(event){
            circle.setCenter(event.latLng);
        });
        google.maps.event.addListener(markerArr[0], 'dragend', function(event){
            map.panTo(event.latLng);
            addMarker(event.latLng, google.maps.Animation.BOUNCE);
            savePoint(event.latLng);
            endBounce();
        });
    }
    
    /**** Pobiera informacje o wpisanej lokalizacji *****/
    function getAdress(){
        /*** Pobieram dane ***/
        var region      = document.getElementById('d_province_id').options[document.getElementById('d_province_id').selectedIndex].value;
        var regionName  = document.getElementById('d_province_id').options[document.getElementById('d_province_id').selectedIndex].text;
        var city        = document.getElementById('city').value;
        var postCode    = document.getElementById('post_code').value;
        var street      = document.getElementById('address').value;
        
        //Aktualne ustawienie latitude i longitude
        var latitude = document.getElementById('latitude').value;
        var longitude = document.getElementById('longitude').value;
        
        //Sprawdzam region aby nie przekazac do googla wyszukiwania po prowincji -- wybierz --
        region == 0 ? region = '' : region;
        
        geocoder.geocode({
            'address'    : regionName+', '+city+', '+postCode+', '+street
        }, function(result, status){
            
            switch(status){
                case google.maps.GeocoderStatus.OK :
                   
                    /******************
              *Jesli wyszukane wspolrzedne sa inne od tych juz zdefiniowanych.
             * W celu unikniecia ciaglego pojawioania sie pinezki
             *******************/
                    if( latitude != result[0].geometry.location.lat() || longitude != result[0].geometry.location.lng()){
                        savePoint(result[0].geometry.location);
                        map.setZoom(15);
                        map.panTo(result[0].geometry.location);
                        addMarker(result[0].geometry.location);
                    }
                    break;
                case google.maps.GeocoderStatus.ERROR :
                    alert('Problem z połączeniem do Google Maps');
                    break;
                case google.maps.GeocoderStatus.ZERO_RESULTS:
                    //TODO w jakiej formie komunikat o nie odnalezieniu lokalizacji
                    // alert('Podana lokalizacja nie została odnaleziona');
                    break;
                case google.mapsGeocoderStatus.OVER_QUERY_LIMIT:
                    alert('Przekroczono limit zapytań. Spróbuj ponownie za 5 minut');
                    break;
            }
        });

    }
   
    //Usuwam informacje o lokalizcaji
    function removeLatLng(){
        latitudeHtml.val('0'); 
        longitudeHtml.val('0'); 
        runGeoLocalization( 0, 0, true);
    }
    
    function savePoint(result){
        //Zapisuje współrzędne punktów
        latitudeHtml.val(result.lat());
        longitudeHtml.val(result.lng());
    }
    
    function endBounce(){
        setTimeout(function(){
            markerArr[0].setAnimation(null)
        }, 1000);
    }
}
