/*
 * draggableMarker: true/false (marker is draggable or not)
 * 
 * centerMarkerAfterMoveEndMap: "moveend" or "" - this centered marker after move map over map area 
 */
var companyName,companyAddress,draggableMarker,centerMarkerAfterMoveEndMap,isTrader,viewer_postcode,directions;

function id_maplocation_uploader__getLocation(){
    var location = document.getElementById('id_company_coordinates').value
    $.log.debug('location: ' + location);
    return location;
}

function id_maplocation_uploader__setLocation(location){
    document.getElementById('id_company_coordinates').value = location
}

function id_maplocation_uploader__getType(){
    return G_NORMAL_MAP
}

function id_maplocation_uploader__getZoom(){
    return 12
}

function id_maplocation_uploader__getLat(){
    if (id_maplocation_uploader__getLocation()) {
        return parseFloat(id_maplocation_uploader__getLocation().split(',')[0])
    }
    return NaN;
}

function id_maplocation_uploader__getLong(){
    if (id_maplocation_uploader__getLocation()) {
        return parseFloat(id_maplocation_uploader__getLocation().split(',')[1])
    }
    return NaN;
}

function id_maplocation_uploader__setLatLong(){
    var center = id_maplocation_uploader__map.getCenter()
    id_maplocation_uploader__setLocation(center.lat() + ',' + center.lng())
}

var try_to_find_coordinates_by_postcode = true
var id_maplocation_uploader__map = null
function id_maplocation_uploader__load(){
    if (GBrowserIsCompatible()) {
        id_maplocation_uploader__map = new GMap2(document.getElementById("id_maplocation_uploader__map"))
        var lat = id_maplocation_uploader__getLat();
        var long = id_maplocation_uploader__getLong();
        if (isNaN(lat) || isNaN(long)) {
            var geocoder = new GClientGeocoder();
            var mapLocation = $('#id_company_postcode').val() || id_maplocation_uploader__getLocation();
            $.log.debug('Fallback to map location: ' + mapLocation);
            geocoder.getLatLng(mapLocation, getLocationCallback); 
        } else {
            getLocationCallback(new GLatLng(lat, long, 
                        id_maplocation_uploader__getZoom(), 
                        id_maplocation_uploader__getType())
                    );
        }
        id_maplocation_uploader__map.addControl(new GLargeMapControl())
        function getAdLocationCallback(latlng) {
            id_maplocation_uploader__map.setCenter(latlng)
            GEvent.addListener(id_maplocation_uploader__map, centerMarkerAfterMoveEndMap, function(){
                if (id_maplocation_uploader__marker && !id_maplocation_uploader__map.getBounds().containsLatLng(id_maplocation_uploader__marker.getLatLng())) 
                    id_maplocation_uploader__marker.setLatLng(id_maplocation_uploader__map.getCenter())
            })
            id_maplocation_uploader__map.addControl(new GScaleControl())
            id_maplocation_uploader__map.addControl(new GMapTypeControl())
            id_maplocation_uploader__map.addControl(new GOverviewMapControl());
            if(companyName!="" && companyAddress!=""){
                id_maplocation_uploader__map.openInfoWindowHtml(id_maplocation_uploader__map.getCenter(), "<center><b>"+ companyName +"</b></center><br /><b>Address:</b><br /><center>"+ companyAddress +"</center>");
            }else if(companyName!="" && companyAddress==""){
                id_maplocation_uploader__map.openInfoWindowHtml(id_maplocation_uploader__map.getCenter(), "<center><b>"+ companyName +"</b></center>");
            }
            id_maplocation_uploader__map.enableDoubleClickZoom()
            id_maplocation_uploader__map.enableContinuousZoom()
            if (document.getElementById('id_company_coordinates').value == '' && try_to_find_coordinates_by_postcode == true) {
                if (isTrader == "True") {
                    switch_address_to_point(document.getElementById('id_company_postcode').value)
                }else{
                    var _tmp = $("#id_company_postcode").val().split(",");
                    var _postCode = _tmp[0].split(" ")[0] + "," + _tmp[1];
                    $("#id_company_postcode").val(_postCode);
                    switch_address_to_point(_postCode);
                }
            }
            var lat = id_maplocation_uploader__getLat();
            var long = id_maplocation_uploader__getLong();
            if (isNaN(lat) || isNaN(long)) {
                var geocoder = new GClientGeocoder();
                var mapLocation = $('#id_company_postcode').val() || id_maplocation_uploader__getLocation();
                $.log.debug('Fallback to map location: ' + mapLocation);
                geocoder.getLatLng(mapLocation, getLocationCallback); 
            } else {
                getLocationCallback(new GLatLng(lat, long));
            }
        }
    }
}

function getLocationCallback(gLatLng) {
    if (!gLatLng) {
        $.log.debug('getLocationCallback: null gLatLng given. Fallback to Bristol');
        gLatLng = new GLatLng(51.45400691005981, -2.5927734375);
    }
    id_maplocation_uploader__map.setCenter(gLatLng, 
            id_maplocation_uploader__getZoom(), id_maplocation_uploader__getType());
    $.log.debug('Setting location: ' + gLatLng);
    id_maplocation_uploader__add_marker(draggableMarker);
}

var id_maplocation_uploader__marker = null
function id_maplocation_uploader__add_marker(draggable){
    id_maplocation_uploader__marker = new GMarker(id_maplocation_uploader__map.getCenter(), {
        draggable: draggable,
        title: companyName + ", " + companyAddress
    })
    GEvent.addListener(id_maplocation_uploader__marker, "dragend", function(){
        var point = id_maplocation_uploader__marker.getPoint()
        id_maplocation_uploader__setLocation(point.lat() + ',' + point.lng())
    })
    id_maplocation_uploader__map.addOverlay(id_maplocation_uploader__marker)
}

function switch_address_to_point(address){
  var companyCoordinates = $('#id_company_coordinates');
  if (!companyCoordinates.val()) {
    geocoder = new GClientGeocoder();
    geocoder.getLatLng(address, function(point){
      if (point) {
        var newCoordinates = point.toString().replace('(', '').replace(')', '');
        $.log('setting new coordinates: ' + newCoordinates);
        $('#id_company_coordinates').val(newCoordinates);
        id_maplocation_uploader__load();
      }
      else {
        $.log('try_to_find_coordinates_by_postcode set to false');
        try_to_find_coordinates_by_postcode = false;
      }
    });
  };
};

function continue_with_coordinates_from_post_code(address, callback) {
  var companyCoordinates = $('#id_company_coordinates');
  geocoder = new GClientGeocoder();
  geocoder.getLatLng(address, function(point){
    if (point) {
      var newCoordinates = point.toString().replace('(', '').replace(')', '');
      callback(newCoordinates);
    } else {
      $.log('failed to load coordinates from post code. Callback not called.');
    };
  });
};

function initializeDirections() {
  map = new GMap2(document.getElementById("id_maplocation_uploader__map"));
  map.addControl(new GLargeMapControl())
  map.addControl(new GScaleControl())
  map.addControl(new GMapTypeControl())
  map.addControl(new GOverviewMapControl());
  map.enableDoubleClickZoom()
  map.enableContinuousZoom()
  var directionsInfoPlaceholder = document.getElementById('googleMapDirectionsInfo');
  // flush
  $('#googleMapDirectionsInfo').html('');
  directions = new GDirections(map, directionsInfoPlaceholder);
  var companyCoordinates = $('#id_company_coordinates');
  var companyCoordinatesVal = $.trim(companyCoordinates.val())
  if (companyCoordinatesVal == '' && try_to_find_coordinates_by_postcode == true) {
    if (isTrader == "True") {
      var companyPostCode = $('#id_company_postcode').val();
      $.log('using company post code: ' + companyPostCode);
      continue_with_coordinates_from_post_code(companyPostCode, initializeDirectionsEnding);
      return;
    } else {
      var _tmp = $("#id_company_postcode").val().split(",");
      var _postCode = _tmp[0].split(" ")[0] + "," + _tmp[1];
      $("#id_company_postcode").val(_postCode);
      switch_address_to_point(_postCode);
    };
  };
  var companyCoordinatesVal = $.trim(companyCoordinates.val())
  initializeDirectionsEnding(companyCoordinatesVal);
};

function initializeDirectionsEnding(companyCoordinatesVal) {
  GEvent.addListener(directions, "error", onGDirectionsError);
  $.log('companyCoordinates: ' + companyCoordinatesVal);
  $.log('coordinates by postcode: ' + try_to_find_coordinates_by_postcode);
  $.log("from: " + viewer_postcode + ", United Kingdom to: " + companyCoordinatesVal);
  directions.load("from: " + viewer_postcode + ", United Kingdom to: " + companyCoordinatesVal);
};

function onGDirectionsError() {
    switch(directions.getStatus().code) {
        case G_GEO_UNKNOWN_ADDRESS:
            alert("UNKNOWN_ADDRESS: Address is incorrect"); 
            break;
        case G_GEO_SERVER_ERROR:
            alert("SERVER_ERROR: Problem with server connection");
            break;
        case G_GEO_BAD_REQUEST:
            alert("BAD_REQUEST: Bad request")
            break;
        default:
            alert("Unknown error: " + directions.getStatus().code);
    };
 }

function loadMaps(){
    if ($("#id_maplocation_uploader__map").html() == "" && !arguments[0]) {
        google.load("maps", "2", {
            "callback": id_maplocation_uploader__load
        });
    }
}

function loadMap(){
	google.load("maps", "2", {
		"callback": id_maplocation_uploader__load
	});
}

function loadDirections(){
	google.load("maps", "2", {
		"callback": initializeDirections
	});
}

function loadBestMapType() {
    if ($('.show_directions').length > 0 && $('#id_company_coordinates').val()) {
        loadDirections();
		$("#locationInfoContent").find(".show_map").show();
		$("#locationInfoContent").find(".show_directions").hide();
    } else {
        loadMaps()
		$("#locationInfoContent").find(".show_directions").show();
		$("#locationInfoContent").find(".show_map").hide();
    };
};

function printMap(){
	if ($("#id_maplocation_uploader__map").html() == "") {
		$("#id_maplocation_uploader__map").find(".gmnoprint").each(function(){
			$(this).attr("class").replace("gmnoprint","");
		})
	}
}
