coreFramework.directive('cfGoogleMap', function ($timeout) {
    return {
        restrict: 'A',
        scope: {
            ngModel: '='
        },
        controller: ['$scope', '$attrs', function ($scope, $attrs) {

        }],
        link: function (scope, element, attrs) {
            
            var holder = $('<div style="height: 500px; margin: 0; padding: 0;">')[0];
            
            element.after(holder);

            var mapOptions = {
                zoom: 2,
                minZoom: 2,
                center: new google.maps.LatLng(45.8167, 15.9833)
            };

            var map = new google.maps.Map(holder, mapOptions);

            var marker = new google.maps.Marker({
                map: map,
                draggable: true,
                position: mapOptions.center
            });

            google.maps.event.addListener(marker, 'dragstart', function (e) {
                if (scope.watchModelCancel) {
                    scope.watchModelCancel();
                }
            });

            google.maps.event.addListener(marker, 'dragend', function (e) {
                scope.$apply(function () {
                    scope.ngModel = e.latLng.lat() + ', ' + e.latLng.lng() + ', ' + map.getZoom();
                });
                watchModel();
            });

            google.maps.event.addListener(map, 'zoom_changed', function() {
                $timeout(function () {
                   var loc = scope.ngModel.split(", ");
                   scope.ngModel = loc[0]+', '+loc[1]+', '+map.getZoom();
                });
            });

            function watchModel() {
                scope.watchModelCancel = scope.$watch('ngModel', function (value) {
                    if (value) {
                        var loc = value.split(', ');
                        var coo = new google.maps.LatLng(loc[0], loc[1]);
                        map.setCenter(coo);
                        marker.setPosition(coo);

                        if (typeof loc[2] != 'undefined') {
                            map.setZoom(parseInt(loc[2]));
                        }
                    }
                });
            }

            watchModel();

        }
    };
});