var map;
var geo;
var southwest_lat;
var southwest_lng;

var northeast_lat;
var northeast_lng;

var old_nearest_city;
var old_category_filter;

var disableAjaxList;

var userLatLng;


function createMarker(point,item,open) {
	var default_marker = new GIcon(G_DEFAULT_ICON);
	if(item.CATEGORY_ID == '1'){
		default_marker.image = '/images/map/markers/icon_pizza.png'	
	} else if(item.CATEGORY_ID == '2'){
  		default_marker.image = '/images/map/markers/icon_general.png';	
	} else if(item.CATEGORY_ID == '3'){
  		default_marker.image = '/images/map/markers/icon_sushi.png';	
	} else if(item.CATEGORY_ID == '4'){
  		default_marker.image = '/images/map/markers/icon_china.png';	
	} else if(item.CATEGORY_ID == '5'){
  		default_marker.image = '/images/map/markers/icon_pasta.png';	
	} else if(item.CATEGORY_ID == '7'){
  		default_marker.image = '/images/map/markers/icon_polskie.png';	
	} else if(item.CATEGORY_ID == '8'){
  		default_marker.image = '/images/map/markers/icon_kebab.png';	
	} else if(item.CATEGORY_ID == '9'){
  		default_marker.image = '/images/map/markers/icon_fastfood.png';	
	} else if(item.CATEGORY_ID == '10'){
  		default_marker.image = '/images/map/markers/icon_medium.png';
	} else if(item.CATEGORY_ID == '11'){
  		default_marker.image = '/images/map/markers/icon_veg.png';	
	} else{
		default_marker.image = '/images/map/markers/icon_medium.png'
	}
  default_marker.shadow = '/images/map/markers/shadow_medium.png';
  default_marker.iconSize = new GSize(43, 49);
  default_marker.shadowSize = new GSize(74, 52);
  default_marker.iconAnchor = new GPoint(21, 49);
  default_marker.imageMap = [0,0, 43,0, 43,49, 0,49];
  default_marker.infoWindowAnchor = new GPoint(9, 2)


  // Set up our GMarkerOptions object

  myIcon = new GIcon(default_marker)
  markerOptions = {
    icon: myIcon
  };

  var marker = new GMarker(point, markerOptions);
  GEvent.addListener(marker, "click", function () {
    openInfoWindow(marker,item.ID)
  });

  if (open) {
    openInfoWindow(marker,item.ID);
  }


  return marker;
}

function createUserMarker(point) {
	var default_marker = new GIcon(G_DEFAULT_ICON);
	default_marker.image = '/images/map/markers/icon_user.png'
	default_marker.shadow = '/images/map/markers/shadow_medium.png';jQuery('#q').val()
	default_marker.iconSize = new GSize(43, 49);
	default_marker.shadowSize = new GSize(74, 52);
	default_marker.iconAnchor = new GPoint(21, 49);
	default_marker.imageMap = [0,0, 43,0, 43,49, 0,49];
	default_marker.infoWindowAnchor = new GPoint(9, 2)
		
  // Set up our GMarkerOptions object

  myIcon = new GIcon(default_marker)
  markerOptions = {
    icon: myIcon,
    draggable: true,
    zIndexProcess: function(){
		return 99999999
	}
  };

  var marker = new GMarker(point, markerOptions);
  marker.enableDragging();
  GEvent.addListener(marker, "dragend", function () {
      userLatLng = marker.getLatLng();
      //reverseGeocode(userLatLng);
      saveLocation(map, '');
      refreshResults(map, false);
  });

  
  return marker;
}

function reverseGeocode(latlng)
{
        if (latlng) {
          geo.setBaseCountryCode('PL');
        
        geo.getLocations(latlng, function(addresses) {
          if(addresses.Status.code != 200) {
            alert("reverse geocoder failed to find an address for " + latlng.toUrlValue());
          }
          else {
            address = addresses.Placemark[0];
            
            var address_text = address.address;
              //jQuery('#q').val(address_text);
             saveLocation(map, address_text);
          }
        });
      }

}

function openInfoWindow(marker,id) {
    marker.openExtInfoWindow(
      map,
      "niegotuj_window",
      "<div class=\"loading\">Loading...</div>",
      {
        ajaxUrl: loadInfoWindowUrl+"?id="+id,
        beakOffset: 3
      }
    );

}

function updateJSON(ajax)
{
  map.clearOverlays();

  // populate map markers
  jQuery.each(ajax,  function() {

	 m = createMarker(new GLatLng(this.LATITUDE, this.LONGITUDE), this, false)
    map.addOverlay(m);

  });
      m = createUserMarker(userLatLng);
    map.addOverlay(m);
}

function showaddress(adress)
{

  if (adress) {
	 try{
		pageTracker._trackPageview('/search/?q='+adress);		
	 } catch(err){
		// error
	 }
	
    if(!geo) return;
    geo.getLocations('Polska, '+adress,function(punkt)
    {
      //console.log(punkt);
      if (!punkt.Placemark)
      {
        alert(adress + " nie został znaleziony!");
      }
      else
      {
        point = new GLatLng(punkt.Placemark[0].Point.coordinates[1],
                            punkt.Placemark[0].Point.coordinates[0]);

        map.setCenter(point, 14);
        userLatLng = point;
        saveLocation(map, adress);
        refreshResults(map, true);
      }
    });
  } else {
    alert("Wprowadź jakiś tekst!");
  }
}

function getFilterIds()
{
  var ids_list = '';
  jQuery("#filter li a.active").each(function(index, category) {

    if(index) ids_list=ids_list+',';
    ids_list=ids_list+jQuery(category).attr('rel');
  });
  //console.log(ids_list);
  return ids_list;
}

function refreshResults(map, reload)
{

  var bounds = map.getBounds();



  var southwest = bounds.getSouthWest();
  var northeast = bounds.getNorthEast();

  southwest_lat = southwest.lat();
  southwest_lng = southwest.lng();

  northeast_lat = northeast.lat();
  northeast_lng = northeast.lng();

  var center = userLatLng;

  nearest_city = getNearestCity(center.lat(), center.lng());

  jQuery('#current_city').html(nearest_city['name']);

  category_filter = getFilterIds() ;

  if (jQuery('#is_open').hasClass('active')) is_open = 1; else is_open = 0;
  if (jQuery('#with_delivery').hasClass('active')) with_delivery = 1; else with_delivery = 0;
  if (jQuery('#with_leaflet').hasClass('active')) with_leaflet = 1; else with_leaflet = 0;
  
  if(isCategorySet) filter_save = 0; else filter_save = 1;
  
  if(old_nearest_city != nearest_city || reload){
    jQuery.getJSON(loadJSONPlacesUrl,{
      city_id: nearest_city['id'],
      latitude: center.lat(),
      longitude: center.lng(),
      filter_ids: category_filter,
      is_open: is_open,
      with_leaflet: with_leaflet,
      with_delivery: with_delivery,
      filter_save: filter_save,
      southwest_lat: southwest_lat,
      southwest_lng: southwest_lng,
      northeast_lat: northeast_lat,
      northeast_lng: northeast_lng
    }, updateJSON);
  }

  if(!disableAjaxList) {
    jQuery('#results').load(loadPlacesListUrl,{
    city_id: nearest_city['id'],
    latitude: center.lat(),
    longitude: center.lng(),
    filter_ids: category_filter,
    is_open: is_open,
    with_leaflet: with_leaflet,
    with_delivery: with_delivery,
    southwest_lat: southwest_lat,
    southwest_lng: southwest_lng,
    northeast_lat: northeast_lat,
    northeast_lng: northeast_lng
  });
  } else {
    disableAjaxList = false;
  }
  old_nearest_city = nearest_city;

  old_category_filter = category_filter;
}

function saveLocation(map, address)
{

  jQuery.get(saveLocationUrl,{
    center_lat:userLatLng.lat(),
    center_lng:userLatLng.lng(),
    address:address
  });
}

function getNearestCity(lat, lng)
{

  min = 100000000000;
  jQuery.each(cities,  function() {
    //xdiff = this['longitude'] - lng;
    //ydiff = this['latitude'] - lat;
    //distance = Math.pow((xdiff * xdiff + ydiff * ydiff), 0.5);
    distance = (((Math.acos(Math.sin((lat*Math.PI/180)) * Math.sin((this['latitude']*Math.PI/180))+Math.cos((lat*Math.PI/180)) * Math.cos((this['latitude']*Math.PI/180)) * Math.cos(((lng- this['longitude'])*Math.PI/180))))*180/Math.PI)*60*1.1515*1.609344);

    if (distance < min) {
      nearest_city = this;
      min = distance;
    }
  });
  return nearest_city;


}

function niegotuj() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    geo = new GClientGeocoder();

    if(isPlaceSet) {

      showaddress(place_search);
      jQuery('#q').val(place_search);

    } else if(isCitySet) {
      map.setCenter(new GLatLng(cityLatitude, cityLongitude), 12);
      userLatLng = new GLatLng(cityLatitude, cityLongitude);
      disableAjaxList = true;
    } else {

      if(!hasPointSaved) {
        if (google.loader.ClientLocation != null) {
          lng = google.loader.ClientLocation.longitude;
          lat = google.loader.ClientLocation.latitude;
          nearest_city = getNearestCity(lat, lng);
          map.setCenter(new GLatLng(nearest_city['latitude'], nearest_city['longitude']), 12);
          userLatLng = new GLatLng(nearest_city['latitude'], nearest_city['longitude']);
        } else {

          map.setCenter(new GLatLng(cities[1]['latitude'], cities[1]['longitude']), 12);
          userLatLng = new GLatLng(cities[1]['latitude'], cities[1]['longitude']);
        }
      
      } else {

      map.setCenter(new GLatLng(myLatitude,myLongitude), 14);
      userLatLng = new GLatLng(myLatitude,myLongitude);
      }
    }

    // working with MAP UI
    var customUI = map.getDefaultUI();
    customUI.maptypes.normal = true
    customUI.maptypes.satellite = true
    //customUI.maptypes.hybrid = true
    customUI.maptypes.physical = false
    map.setUI(customUI);
	 map.disableScrollWheelZoom();

   if(!isPlaceSet) {
    refreshResults(map, false);
   }
    GEvent.addListener(map, "dblclick", function(overlay, latlng) {


      userLatLng = latlng;
      //reverseGeocode(userLatLng);
      saveLocation(map, '');
      refreshResults(map, true);
    });


  }
}

jQuery(document).ready(function($){
  niegotuj();
});

