// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.


function addAddressToMap(response) {
  map.clearOverlays();
  var list_view = document.getElementById("google_adresses_list");
  
  if(list_view)
  {
	  list_view.innerHTML = '';	  
  }
  
	  if (!response || response.Status.code != 200) {
	      if(next_address<7){
	          next_address++;   
	          getNextAddress();  
	      }      
	      else{        
	          geocodeFailedDialog.show();
	      }
	  } else
	  {
		  placemarks = response.Placemark;
		  if(placemarks.length == 1)
		  {
			  fillAddress(0);
        
			  if(isPreviewSubmited)
			  {
				  sendNext();
			  }
		  }		  
		  
		  if(list_view)
		  {
			  list_view.innerHTML = '';
			  if (placemarks.length) {
				  var noticeText = document.createElement('li');
				  noticeText.style.color = "red";
				  noticeText.innerHTML = "Select found address:";
				  list_view.appendChild(noticeText);    
			  }
		  }
		  
		  for(var i=0; i < placemarks.length; i++)
		  {
			  place = placemarks[i];
			  point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
			  marker = new GMarker(point);
			  map.addOverlay(marker);
			  map.setCenter(point,1);
			  
			  if(list_view)
			  {
				  var li = document.createElement('li');
				  var handler = new Object();
				  handler.li = li;
				  handler.i = i;
				  handler.handle = function(evt)
				  {
					  selectAddress(this.i, this.li);
				  }
				  dojo.connect(li, "onclick", handler, "handle");
				  li.className = "selectAddress";
            
            //li.style.cursor = "pointer";                        
            //li.style.text-decoration = "underline";
                        
			      li.innerHTML = place.address;
				  list_view.appendChild(li);
			  }
		  }
  }
}

function selectAddress(id, li)
{
    fillAddress(id);
    var address = li.innerHTML;
    var list_view = document.getElementById("google_adresses_list");
    if(list_view)
    {
        list_view.innerHTML = '';
        var li = document.createElement('li');
        li.innerHTML = address;
        list_view.appendChild(li);
    }
}

function fillAddress(id)
{
    map.clearOverlays();
    var place = placemarks[id];
    var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
    var marker = new GMarker(point);
    map.addOverlay(marker);
    map.setCenter(point,10);
    
    dojo.byId("address-address_json").value = dojo.toJson(place);
    document.getElementById("address-longitude").value = place.Point.coordinates[0];
    document.getElementById("address-latitude").value = place.Point.coordinates[1];
    document.getElementById("address-address_string").value = place.address;

    var neighbours = getNeighbours(point);
    filled = true;
}

function getNeighbours(Point)
{
    var params = { 'lat' : Point.lat(),
                   'lng' : Point.lng()
    };

    var bind_args = {
        url:        "/member/ajax/get-neighbours",
        content:    params,
        handleAs:   "json",
        handle:     function(response, kwargs)
        {
            var neighbours = dojo.fromJson(response.neighbours);

            if (response.success) {

                var neighbours_container = dojo.byId('neighbours-container');

                remove_all_childs(neighbours_container);

                for(var i = 0; i < neighbours.length; i++) {

                    var neigh = document.createElement('input');

                    neigh.type = "text";
                    neigh.name = "neighbours["+neighbours[i].id+"]";
                    neigh.value = neighbours[i].name;

                    neighbours_container.appendChild(neigh);
                }
            }
        }
    };
    dojo.xhrGet(bind_args);
}

function init_neighbours()
{
    var neighbours_container = dojo.byId('neighbours-container');

    remove_all_childs(neighbours_container);

    for(var i = 0; i < neighbours.length; i++) {

        var neigh = document.createElement('input');

        neigh.type = "text";
        neigh.name = "neighbours["+neighbours[i].id+"]";
        neigh.value = neighbours[i].name;

        neighbours_container.appendChild(neigh);
    }
}

function remove_all_childs(el)
{
    if ( el.hasChildNodes() )
    {
        while ( el.childNodes.length > 0 )
        {
            el.removeChild( el.firstChild );
        }
    }
}


function checkForGeoLocate()
{
    if (filled) {
    	return true;
    }
    
    showLocation();
    
    return false;
}

// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showLocation() { 
  zip = document.getElementById("address-zip").value;
  country = document.getElementById("address-country").value;
  state = document.getElementById("address-state").value;
  city = document.getElementById("address-city").value;
  street_1 = document.getElementById("address-street_1").value;
  street_2 = document.getElementById("address-street_2").value;
  
  next_address = 0;
  getNextAddress();
}

function getNextAddress()
{
  var addresSrt = "";
  
  switch(next_address)
  {
	case 0:
	   if (street_1 || street_2) {
	       address = zip + ", " +street_1 + ", " + street_2 + ", " + city + ", " + state + ", " + country;
	   } else {
	       address = street_1 + ", " + street_2 + ", " + city + ", " + state + ", " + country;
	       if (!(street_1 || street_2  || city || state) && zip) {
	           address = zip;
	       }
	   }
	   break;
	      
	case 1:
	  address = street_1 + ", " + street_2 + ", " + city + ", " + state + ", " + country;
	  break;
	   
	case 2:
	   if (street_1 || street_2) {	
	       address = zip + ", " +street_1 + ", " + street_2 + ", "  + state + ", " + country;
	   } else {
	       address = street_1 + ", " + street_2 + ", "  + state + ", " + country;
	       if (!(street_1 || street_2  || city || state) && zip) {
               address = zip;
           }
	   }
	  break;
	  
	case 3:
	  address = city + ", " + state + ", " + country;
	  break;
	  
	case 4:
	  address = state + ", " + country;
	  break;
	  
	case 5:
	  address = country;
	  break;
	  
	case 6:
	  address = '';
	  break;
  }
   
  geocoder.getLocations(address, addAddressToMap);   
}

function implode( glue, pieces ) {

    return ( ( pieces instanceof Array ) ? pieces.join ( glue ) : pieces );
}