
var componentForm =
{
    street_number: 'short_name',
    route: 'long_name',
    locality: 'long_name',
    administrative_area_level_1: 'short_name',
    country: 'long_name',
    postal_code: 'short_name'
};

var googleAutoComplete = {};

function addGoogleAddressListener(domSelector)
{    
    var autocomplete = new google.maps.places.Autocomplete($(domSelector)[0]);
    googleAutoComplete[domSelector] = autocomplete;
    var place;

    $(domSelector).change(function(){
        if(!$(this).val() || !trim($(this).val()) || autocomplete.getPlace() == null || autocomplete.getPlace() == undefined || !autocomplete.getPlace().geometry)
        {
            var parentDiv = $(domSelector).closest('.googleAddress');

            parentDiv.find(".latitude").val('');
            parentDiv.find(".longitude").val('');

            for (var component in componentForm)
            {
                parentDiv.find("." + component).val('');
            }
        }
    })

    $(domSelector).keypress(function(e) {
      if (e.which == 13) {
          e.preventDefault();
      }
    });

    autocomplete.addListener('place_changed', function()
    {
        place = autocomplete.getPlace();
        googleAutoComplete[domSelector] = place;
        placeChanged(domSelector);
    });
}

function placeChanged(domSelector)
{
    var place   = googleAutoComplete[domSelector]; 
    if(place === undefined || !place.geometry)
    {
        return;
    }

    var parentDiv = $(domSelector).closest('.googleAddress');

    parentDiv.find(".latitude").val(place.geometry.location.lat());
    parentDiv.find(".longitude").val(place.geometry.location.lng());
    
    for (var component in componentForm)
    {
        parentDiv.find("." + component).val('');
    }

    for (var i = 0; i < place.address_components.length; i++)
    {
        var addressType = place.address_components[i].types[0];
        if (componentForm[addressType])
        {
            var val = place.address_components[i][componentForm[addressType]];
            parentDiv.find("."+ addressType).val(val);
        }
    }
}

//remove left and right space
function trim(str)
{
  return str.replace(/(^\s*)|(\s*$)/g, "");
}


function toggleAddressMode(gAddressid)
{
    var selection = $('input[googleid='+gAddressid+']').prop('checked');
    var parentDiv = $('#'+gAddressid).closest('.googleAddress');
    for (var component in componentForm)
    {
        if(!selection)
        {
            parentDiv.find("." + component).prop('readonly', 'true');
        }
        else
        {
            parentDiv.find("." + component).removeProp('readonly');
        }
    }
    
    if(!selection)
    {
        $('#'+gAddressid).removeProp('readonly');
        placeChanged('#'+gAddressid);
    }
    else
    {
        $('#'+gAddressid).prop('readonly', 'true');
    }
}
