/*
Map and form funcionality definition for event/create_form view
	
*/
$(function() {



    function initEventCreateForm()
    {
        mapOverlayTarget = '#event_create_quotes';
        initMap();
        $("#location").blur(updateMap)
        $("#location").focus(function(){previousValue = $(this).val();})
    }

    // Core JS validation and error feedback
    $('#event_create_form').validate({
        showErrors: function(errorMap, errorList) {
			$('.error').removeClass('error').children('p.errors').remove();
            for (error in errorList)
            {
				$(errorList[error].element).qtip({content:errorList[error].message,show: 'mouseover',
			   hide: 'mouseout',
			show:{ready:true},
				 position: {
				                  corner: {
				                     tooltip: 'leftMiddle', // Use the corner...
				                     target: 'rightMiddle' // ...and opposite corner
				                  }
				               },
				
			     style: {
				                  border: {
				                     width: 5,
				                     radius: 10
				                  },
				                  padding: 10, 
				                  textAlign: 'center',
				                  tip: true, // Give it a speech bubble tip with automatic corner detection
				                  name: 'red' // Style it according to the preset 'cream' style
				               }
				
			
			   });
                //$(errorList[error].element).parents('.element').addClass('error').append('<p class="errors">' + errorList[error].message + '</p>');
            }

        }
    });
    //--------------------------------------------------------------------
    var previousValue;
    var locationMarker;
    var mapOverlayTarget;

    // reset status and re-draw the map
    function initMap()
    {
        $('#map').jmap('init', {
            'mapEnableScrollZoom': true,
            'mapShowjMapsIcon': false
        });
        positionMap();
        $(window).resize(positionMap);
    }

    // orient the map to completely occlude the #home_content (x,y/w,h)
    function positionMap()
    {
        var pos = $(mapOverlayTarget).offset();
        var width = $(mapOverlayTarget).width();
        var height = $(mapOverlayTarget).height()
        var left = pos.left + "px";
        var top = pos.top + "px";

        $('#map').css({
            position: 'absolute',
            zIndex: 2,
            width: width,
            height: height,
            left: left,
            top: top
        });
    }

    function redrawMap()
    {
        $('#map').jmap('CheckResize');
        $('#map').fadeIn();
        positionMap();
        $('#map').jmap('CheckResize');
    };

    // This clears the map state and then updates it based on the current values
    function updateMap()
    {
        redrawMap();
        if ($(this).val() == previousValue)
        {
            previousValue = null;
            return;
        }

        locationValue = $("#location").val() != "";

        // Directions draws points,radii, and polyline
        if (locationValue)
        {
            $('#map').jmap('ClearMap');
            locationMarker = null;
            $('#location_lat').val('');
            $('#location_lon').val('');
            $('#map').jmap('SearchAddress', {
                'query': $('#location').val(),
                'returnType': 'getLocations',
                location: 'to'
            },
            onAddressResult);
        }

    }

    function onAddressResult(result, options)
    {
        var valid = Mapifies.SearchCode(result.Status.code);
        if (valid.success) {
            var mapCenter;
            jQuery.each(result.Placemark,
            function(i, point) {
                markerOptions = {
                    'pointLatLng': [point.Point.coordinates[1], point.Point.coordinates[0]],
                    'centerMap': true
                }
                $('#map').jmap('AddMarker', markerOptions, onMarkerAdd);
                $('#location').val(point.address);
            });
            redrawMap();

        } else {
            $("#event_create_form").validate().showErrors({
                'location': "Location not found on the map: " + $("#location").val()
            });
            $('#from_name').val('');
            $('#from_lat').val('');
            $('#from_lon').val('');
        }
    }

    function onMarkerAdd(marker, options)
    {
        marker = marker;
        $('#location_lat').val(marker.getLatLng().lat());
        $('#location_lon').val(marker.getLatLng().lng());
    }

    initEventCreateForm()

});