mainNgApp.directive('onenterkey', function () {
    return function (scope, element, attrs) {
        element.bind("keyup", function (event) {
            if(event.which === keyCodes.getKeyCode('enter')) {
                scope.$apply(function (){
                    scope.$eval(attrs.onenterkey);
                });

                event.preventDefault();
            }
        });
    };
});
mainNgApp.directive('onremovekey', function () {
    return function (scope, element, attrs) {
        element.bind("keyup", function (event) {
            if(event.which === keyCodes.getKeyCode('backspace') || event.which === keyCodes.getKeyCode('delete')) {
                scope.$apply(function (){
                    scope.$eval(attrs.onremovekey);
                });

                event.preventDefault();
            }
        });
    };
});

mainNgApp.directive('inserttemplate', function($compile) {
    return {
        restrict: "E",
        link: function(scope, element, attr, ctrl){
            attr.$observe('template', function(value){
                element.html(value);
                $compile(element.contents())(scope.$new());
            });
            //if(attr.template){temp = String(attr.template); console.log(attr.template)}

        }

    }
})

mainNgApp.directive('drawingoptionsthumb', function($compile) {
    return {
        restrict: "E",
        link: function(scope, element, attr, ctrl){
            attr.$observe('template', function(value){
                var drawingOptions = null;
                var htmlStr = ""
                try{drawingOptions = JSON.parse(value)}catch(err){}
                if(drawingOptions){
                    htmlStr = interfaceData.getStyleThumbnail(drawingOptions);
                }else{
                    htmlStr = "<div class='styleThumbnail'></div>";
                }
                element.html(htmlStr);
                $compile(element.contents())(scope.$new());
            });
            //if(attr.template){temp = String(attr.template); console.log(attr.template)}
            element.bind('contextmenu', function(event){
                event.preventDefault();
                try{drawingOptions = JSON.parse(attr.template)}catch(err){}
                if(drawingOptions){
                    editDrawingOptions(drawingOptions)
                }
            });
        }

    }
})

mainNgApp.directive('drawingoptionsgrid', function($compile) {
    return {
        restrict: "E",
        link: function(scope, element, attr) {
            scope.$watch("preferences", function(preferences){
                //preferences = JSON.parse(preferences);
                var htmlStr = ""
                    htmlStr += '<span ng-repeat="drawingOptions in preferences.drawingOptionsAry track by $index" style="position:relative;background-color:rgba(0,0,0,0);display:inline-block;margin-right:3px;" class="styleThumbnail clickable" ng-click="' + attr.onItemClick + '(drawingOptions)">'+
                        '<div ng-class="{' + "'" + 'styleThumbnailSelected' + "'" + ': (drawingOptions.id === ' + String(attr.selectedid || 0) + ')}" uib-popover="{{drawingOptions.name}}" popover-trigger="mouseenter" popover-placement="top" class ="overlay"><drawingoptionsthumb template="{{drawingOptions}}"></drawingoptionsthumb></div>' +
                    '</span>'
                element.html(htmlStr);
                $compile(element.contents())(scope.$new());
            });
            attr.$observe('selectedid', function(value){
                var htmlStr = ""

                    htmlStr += '<span ng-repeat="drawingOptions in preferences.drawingOptionsAry track by $index" style="position:relative;background-color:rgba(0,0,0,0);display:inline-block;margin-right:3px;" class="styleThumbnail clickable" ng-click="' + attr.onItemClick + '(drawingOptions)">'+
                        '<div ng-class="{' + "'" + 'styleThumbnailSelected' + "'" + ': (drawingOptions.id === ' + String(value || 0) + ')}" uib-popover="{{drawingOptions.name}}" popover-trigger="mouseenter" popover-placement="top" class ="overlay"><drawingoptionsthumb template="{{drawingOptions}}"></drawingoptionsthumb></div>' +
                    '</span>'
                element.html(htmlStr);
                $compile(element.contents())(scope.$new());
            });
        }
    }
})

mainNgApp.directive('serverprofilethumbnail', function($compile) {
    return {
        restrict: "E",
        replace: true,
        link: function(scope, element, attr) {
            attr.$observe('serverprofile', function(value){
                var serverprofile = null;
                try{serverprofile = JSON.parse(value)}catch(err){}
                if(serverprofile){
                    if(scope.data && scope.data.currentViewPoints){
                        var quad = getPreviewQuadFromServerprofileAndViewpoints(serverprofile, scope.data.currentViewPoints);
                    }else{
                        var quad = "0";
                    }
                    getTileserverApi(serverprofile).initialize(function(){
                        var srcUrl = getTileserverApi(serverprofile).getTileUri(quad, true);
                        var htmlStr = '<img class="overlay opactitybg" src="' + srcUrl + '" height="' + element.prop('offsetHeight') + '" width="' + element.prop('offsetHeight') + '">'
                        if(serverprofile.auth && serverprofile.auth.username.length > 0 && serverprofile.auth.password.length > 0){
                            htmlStr = '<div class="overlay opactitybg" height="' + element.prop('offsetHeight') + '" width="' + element.prop('offsetHeight') + '"></div>'
                        }
                        element.html(htmlStr);
                        $compile(element.contents())(scope.$new());
                    })
                }

            });
            scope.$watch("data.currentViewPoints", function(currentPreviewQuadcode){
                var serverprofile = null;
                try{serverprofile = JSON.parse(attr.serverprofile)}catch(err){}
                if(serverprofile){
                    if(scope.data && scope.data.currentViewPoints){
                        var quad = getPreviewQuadFromServerprofileAndViewpoints(serverprofile, scope.data.currentViewPoints);
                    }else{
                        var quad = "0";
                    }
                    getTileserverApi(serverprofile).initialize(function(){
                        var srcUrl = getTileserverApi(serverprofile).getTileUri(quad, true);
                        var htmlStr = '<img class="overlay opactitybg" src="' + srcUrl + '" height="' + element.prop('offsetHeight') + '" width="' + element.prop('offsetHeight') + '">'
                        if(serverprofile.auth && serverprofile.auth.username.length > 0 && serverprofile.auth.password.length > 0){
                            htmlStr = '<div class="overlay opactitybg" height="' + element.prop('offsetHeight') + '" width="' + element.prop('offsetHeight') + '"></div>'
                        }
                        element.html(htmlStr);
                        $compile(element.contents())(scope.$new());
                    })
                }
            })
        }
    }
})

mainNgApp.directive('mapcompthumbnail', function($compile) {
    return {
        restrict: "E",
        replace: true,
        link: function(scope, element, attr) {
            attr.$observe('mapcomp', function(value){
                var mapcomp = null;
                try{mapcomp = JSON.parse(value)}catch(err){}
                if(mapcomp && mapcomp.mapcompprofile){
                    var quad = getPreviewQuadFromMapcomp(mapcomp);
                    var serverprofile = mapcomp.mapcompprofile.serverprofile;
                    getTileserverApi(serverprofile).initialize(function(){
                        var srcUrl = getTileserverApi(serverprofile).getTileUri(quad, true);
                        var htmlStr = '<img class="overlay opactitybg" src="' + srcUrl + '" height="' + element.prop('offsetHeight') + '" width="' + element.prop('offsetHeight') + '">'
                        if(serverprofile.auth && serverprofile.auth.username.length > 0 && serverprofile.auth.password.length > 0){
                            htmlStr = '<div class="overlay opactitybg" height="' + element.prop('offsetHeight') + '" width="' + element.prop('offsetHeight') + '"></div>'
                        }
                        element.html(htmlStr);
                        $compile(element.contents())(scope.$new());
                    })
                }

            });
        }
    }
})

mainNgApp.directive('serverprofilebackground', function($compile) {
    return {
        restrict: "A",
        replace: false,
        //priority: 10000,
        link: function(scope, element, attr) {
            attr.$observe('serverprofilebackground', function(value){
                var serverprofile = null;
                try{serverprofile = JSON.parse(value)}catch(err){}
                if(serverprofile){
                    var quad = scope.data.currentPreviewQuadcode.substr(0,Math.min(serverprofile.maxZL-1, scope.data.currentPreviewQuadcode.length))
                    getTileserverApi(serverprofile).initialize(function(){
                        var srcUrl = getTileserverApi(serverprofile).getTileUri(quad, true);
                        var changes = {
                            backgroundImage: 'url(' + srcUrl + ')',
                        }
                        element.css(changes)
                        $compile(element.contents())(scope.$new());
                    })
                }
            });
            scope.$watch("data.currentPreviewQuadcode", function(currentPreviewQuadcode){

                var serverprofile = null;
                try{serverprofile = JSON.parse(attr.serverprofilebackground)}catch(err){}
                if(serverprofile){
                    var quad = scope.data.currentPreviewQuadcode.substr(0,Math.min(serverprofile.maxZL-1, scope.data.currentPreviewQuadcode.length))
                    getTileserverApi(serverprofile).initialize(function(){
                        var srcUrl = getTileserverApi(serverprofile).getTileUri(quad, true);
                        var changes = {
                            backgroundImage: 'url(' + srcUrl + ')',
                        }
                        element.css(changes)
                        $compile(element.contents())(scope.$new());
                    })
                }
            })
        }
    }
})

mainNgApp.directive('colorpicker', function($compile) {
    return {
    restrict: "E",
    require: 'ngModel',
    replace: true,
    template: '<button class="colorPicker btn"></button>',
    link: function(scope, element, attrs, ngModel) {
        var changeCss = function(color){
            var colorCode = hexToHexCode(color);
            var changes = {
                backgroundColor: colorCode,
            }
            element.css(changes)
            //$compile(element.contents())(scope.$new());
        }
        element.bind('click', function(){
            AEcolorPickerPromise(ngModel.$modelValue)
            .then(function(color){
                scope.$apply(function() {
                    changeCss(color);
                    ngModel.$setViewValue(color);
                });
            })
            .catch(function(reason){
                //no color picked
            })
        });
        // update the color picker whenever the value on the scope changes
        ngModel.$render = function() {
            changeCss(ngModel.$modelValue);
            element.val(ngModel.$modelValue);
            element.change();
        };
    }
  }
})

mainNgApp.directive('folderpicker', function($compile) {
    return {
    restrict: "E",
    require: 'ngModel',
    replace: true,
    template: '<button class="btn btn-default btn-sm">...</button>',
    link: function(scope, element, attrs, ngModel) {
        element.bind('click', function(){
            var prompt = attrs.prompt || "";
            AEfolderPickerPromise(prompt, ngModel.$modelValue)
            .then(function(path){
                scope.$apply(function() {
                    ngModel.$setViewValue(path);
                });
            })
            .catch(function(reason){
                //no folder picked
            })
        });
    }
  }
})
mainNgApp.directive('filepicker', function($compile) {
    return {
    restrict: "E",
    require: 'ngModel',
    replace: true,
    template: '<button class="btn btn-default btn-sm">...</button>',
    link: function(scope, element, attrs, ngModel) {
        element.bind('click', function(){
            var prompt = attrs.prompt || "";
            var filter = attrs.filter && attrs.filter.split(",") || [];
            AEfilePickerPromise(prompt, filter, ngModel.$modelValue, false)
            .then(function(path){
                scope.$apply(function() {
                    ngModel.$setViewValue(path);
                });
            })
            .catch(function(reason){
                //no file picked
            })
        });
    }
  }
})
mainNgApp.directive('numberrange', function($compile) {
    return {
    restrict: "E",
    require: 'ngModel',
    replace: true,
    template: '<input class="form-control" type="text">',
    link: function(scope, element, attrs, ngModel, $parse) {
        element.bind('change', function(){
            var input = parseFloat(ngModel.$viewValue.replace(",",".")) || 0;
            if(attrs.step && attrs.step >= 1){input = Math.round(input);}
            var min = attrs.min;
            var max = attrs.max;
            var validValue = input;
            if(min !== undefined){
                validValue = Math.max(min, validValue);
            }
            if(max !== undefined){
                validValue = Math.min(max, validValue);
            }
            if(attrs.ngChange){
                $parse(attrs.ngChange)
            }
            scope.$apply(function() {
                ngModel.$setViewValue(validValue);
                ngModel.$render()
            });
        });
    }
  }
})
mainNgApp.directive('changevalbyclick', function($compile) {
    return {
    restrict: "E",
    replace: true,
    template: '<div class="activecolor clickable input-group-sm posrel flexcontainer"></div>',
    link: function(scope, element, attrs, ngModel) {
        var onchangeHtmlStr = "";
        if(attrs.ngChange){
            onchangeHtmlStr = ' ng-change="' + attrs.ngChange + '"';
        }
        var htmlStr = '<span class="nowrapellipsis">{{' + attrs.ngModel + '}}' + attrs.suffix.replace("_", " ") + '</span>'+
            '<numberrange class="overlay visibleonfocus onfocusinput" ng-model="' + attrs.ngModel + '" min="' + attrs.min + '" step="' + attrs.step + '" max="' + attrs.max + '"' + onchangeHtmlStr +'></numberrange>'
        element.prepend(htmlStr);
        $compile(element.contents())(scope.$new());
    }
  }
})
mainNgApp.directive('changetextbyclick', function($compile) {
    return {
    restrict: "E",
    replace: true,
    template: '<div class="activecolor clickable input-group-sm posrel flexcontainer"></div>',
    link: function(scope, element, attrs, ngModel) {
        var onchangeHtmlStr = "";
        if(attrs.ngChange){
            onchangeHtmlStr = ' ng-change="' + attrs.ngChange + '"';
        }
        var htmlStr = '<span class="nowrapellipsis">{{' + attrs.ngModel + '.length > 0 && ' + attrs.ngModel + ' || "..."}}' + '</span>'+
            '<input type="text" class="overlay visibleonfocus onfocusinput form-control" ng-model="' + attrs.ngModel + '" ' + onchangeHtmlStr +'>'
        element.prepend(htmlStr);
        $compile(element.contents())(scope.$new());
    }
  }
})

mainNgApp.directive('geofeature', function($compile) {
    return {
    restrict: "E",
    require: 'ngModel',
    replace: true,
    scope: {
        feature: "=ngModel"
    },
    controller: function($scope){
        $scope.inputStr = $scope.feature && $scope.feature.properties && $scope.feature.properties.GEOlayersDisplayName || "";
        $scope.showResults = false;
        $scope.searchInProgress = false;
        $scope.iconClasses = interfaceData.iconClasses;
        $scope.preferences = preferences;
        $scope.safeApply = function(fn) {
          var phase = this.$root.$$phase;
          if(phase == '$apply' || phase == '$digest') {
            if(fn && (typeof(fn) === 'function')) {
              fn();
            }
          } else {
            this.$apply(fn);
          }
        };
        $scope.getGeoJSONFeatureIcon = getGeoJSONFeatureIcon;
        $scope.inputOnChange = function(inputStr) {
            $scope.searchInProgress = true;
            if($scope.timeoutID){clearTimeout($scope.timeoutID);}
            $scope.timeoutID = setTimeout(
                function(){
                    var parsedCoordinates = parseCoordinateStr(inputStr);
                    var featureFromParsedCoordinatesAry = [];
                    if(parsedCoordinates){
                        featureFromParsedCoordinatesAry = [getFeatureFromLatLon(parsedCoordinates, inputStr)];
                    }
                    getSearchApi(preferences.activeSearchprofile).getGeoJSONByAdressPromise(interfaceData.selectedMapcomp, inputStr).then(function(results){
                        $scope.safeApply(function(){
                            $scope.searchInProgress = false;
                            $scope.searchResults = featureFromParsedCoordinatesAry.concat(results);
                            $scope.showResults = true;
                        });
                    }).catch(function(err){
                        $scope.searchInProgress = false;
                        $scope.showResults = false;
                        console.log(err)
                    })
                },
                500
            )
        }
        $scope.applySearchResult = function(searchResult){
            $scope.feature = searchResult;
            $scope.inputStr = searchResult.properties.GEOlayersDisplayName;
            $scope.showResults = false;
        }
        $scope.clearSearch = function(){
            $scope.inputStr = $scope.feature && $scope.feature.properties && $scope.feature.properties.GEOlayersDisplayName || "";
            $scope.showResults = false;
        }
    },
    template: '<div class="flexcontainer flexplus1 dropdown open">'+
        '<div class="input-group input-group-sm flexcontainer flexplus1">'+
        '<input placeholder="Search online..." type="text" ng-style="(getGeoJSONFeatureIcon(feature).length > 0) && {' + "'padding-left':" + "'20px'" + '}" class="form-control input-sm flexplus1" ng-model="inputStr" ng-change="inputOnChange(inputStr)">'+
        '<div class="flexfixed" style="color:white;position:absolute;left:6px;top:5px;z-index:99;"><span ng-class="getGeoJSONFeatureIcon(feature)"></span></div>'+
        '<div ng-show="showResults" class="cancelsearch" ng-click="clearSearch();"><span ng-class="iconClasses.x"></span></div>'+
        '<div ng-show="searchInProgress" class="progress progress-striped active overlay" style="height: 4px;border-radius:0px;background-color:rgba(0,0,0,0);"><div class="progress-bar" style="height: 4px; width:100%;"></div></div>'+
        '</div>'+
        '<ul class="dropdown-menu" style="width:100%;" ng-show="showResults">'+
        '<div ng-show="searchResults.length < 1" style="text-align:center;">no Features found</div>'+
        '<li class="clickable featurelistitem" style="cursor:pointer" ng-repeat="searchResult in searchResults track by $index" ng-click="applySearchResult(searchResult)">'+
        '<h5>{{searchResult.properties.GEOlayersDisplayName}}</h5>'+
        '<h5><small>{{searchResult.properties.GEOlayersDisplayName2}}</small></h5>'+
        '</li>'+
        '<div class="poweredby">{{preferences.activeSearchprofile.attribution}}</div>'+
        '</ul>'+
        '</div>',
    link: function($scope) {
        $scope.$watch("feature",function(feature){
            if (feature){
                $scope.inputStr = feature.properties && feature.properties.GEOlayersDisplayName || "";
            }
        });
    }
  }
})


mainNgApp.directive('onlinesampleproject', function($compile) {
    return {
    restrict: "E",
    replace: true,
    scope:{},
    template: '<div class="sampleproject" ng-class="{clickable : !isBusy}" style="min-height:100px;min-width:150px;position:relative">'+
        '<div ng-show="isBusy" class="overlay hostElt isbusy"></div>' +
        '<div id="gradient" class="overlay bggradient"></div>' +
        '<div style="position:absolute;bottom:4px;left:5px;">' +
            '<h5 id="name" style="margin-bottom:2px;text-shadow: 1px 1px 1px #000000;">{{project.name}}</h5>' +
            '<h5 ng-show="statusDescription" style="margin:0px;margin-bottom:1px"><small style="margin-bottom:0px;text-shadow: 1px 1px 1px #000000;color:white;">{{statusDescription}}</small></h5>' +
            '<h5 ng-if="!statusDescription" id="description" style="margin:0px;margin-bottom:1px"><small style="margin-bottom:0px;text-shadow: 1px 1px 1px #000000;color:white;">{{project.description}}</small></h5>' +
        '</div>' +
        '<div class="overlay flexcontainervertical">' +
            '<div class="flexfixed flexcontainer">' +
                '<div ng-click="openProject()" class="flexplus1">' +
                    '<div ng-show="project.type === ' + "'labelTemplates'" + '" class="flexfixed projecttype"><span class="' + interfaceData.iconClasses.label + '"></span> Label Templates Project</div>' +
                '</div>' +
                '<div ng-show="project.videoUrl"class="flexfixed">' +
                    '<button ng-click="openVideo()" style="margin:6px;" type="button" class="btn btn-sm btn-primary"><span class="geolayersicon-film"></span></button>' +
                '</div>' +
            '</div>' +
            '<div ng-click="openProject()" class="flexplus1"></div>' +
        '</div>' +
        '<div ng-show="isBusy" ng-class="{' + "'" + 'progress-striped' + "'" + ' : progressWidth === 100}" class="progress active overlay" style="border-radius:0px;background-color:rgba(0,0,0,0);">' +
            '<div class="progress-bar" style="height: 4px; width:{{progressWidth}}%;"></div>' +
        '</div>' +
        '</div>',
    controller: function($scope){
        $scope.isBusy = false;
        $scope.statusDescription = null
        $scope.project = {}
        $scope.openVideo = function(){
            if($scope.project.videoUrl){window.cep.util.openURLInDefaultBrowser($scope.project.videoUrl)}
        }
        $scope.openProject = function(){

            if($scope.isBusy == false){
                $scope.isBusy = true;
                $scope.safeApply(function(){
                    $scope.isBusy = true;
                    $scope.statusDescription = "downloading and opening Project...";
                })
                openOnlineProjectPromise($scope.project.uri, $scope.project.id + "_V" + String($scope.project.version || 0), $scope.project.type, function(err, progress){
                    if(progress.percentage < $scope.progressWidth || progress.percentage > $scope.progressWidth + 2 || progress.percentage === 100){
                    $scope.safeApply(function(){
                        $scope.progressWidth = Math.max(progress.percentage,2)
                    })
                    }

                }).then(function(fileName){
                    $scope.safeApply(function(){
                        $scope.isBusy = false
                        $scope.progressWidth = 100
                        $scope.statusDescription = null
                    })
                }).catch(function(err){
                    $scope.safeApply(function(){
                        $scope.isBusy = false
                        $scope.progressWidth = 100
                        $scope.statusDescription = null
                    })
                    console.log(err)
                    if(dlg_simpleAlert){
                        dlg_simpleAlert("Error opening Project", err)
                    }

                })
            }
        }
        $scope.progressWidth = 100;
        $scope.safeApply = function(fn) {
          var phase = this.$root.$$phase;
          if(phase == '$apply' || phase == '$digest') {
            if(fn && (typeof(fn) === 'function')) {
              fn();
            }
          } else {
            this.$apply(fn);
          }
        };
    },
    link: function($scope, element, attrs) {
        var initializeProject = function(){
            if(attrs.project){
                $scope.project = JSON.parse(attrs.project)
            }else{
                $scope.project = attrs.projectid && getItemById(sampleProjects, attrs.projectid);
            }
            var imageSrcUrl = $scope.project.previewImageUri
            $scope.curElem = element
            var changes = {
                backgroundImage: 'url(' + imageSrcUrl + ')',
                backgroundSize: "cover",
                backgroundPosition: "center"
            }
            element.css(changes)
            //$compile(element.contents())($scope.$new());
        }
        attrs.$observe("project",function(project){
            if (project){
                try{project = JSON.parse(project)}catch(e){}
                initializeProject(project)
            }
        });
        attrs.$observe("projectid",function(projectid){
            var project = getItemById(sampleProjects, projectid)
            if (project){
                initializeProject(project)
            }
        });
        initializeProject()

    }
  }
})

mainNgApp.directive('recentproject', function($compile) {
    return {
    restrict: "E",
    replace: true,
    //require: "ngClick",
    scope:{},
    template: '<div class="sampleproject" ng-class="{clickable : !isBusy}" style="min-height:100px;min-width:150px;position:relative">'+
        '<div ng-show="isBusy" class="overlay hostElt isbusy"></div>' +
        '<div ng-show="isBusy" ng-class="{' + "'" + 'progress-striped' + "'" + ' : progressWidth === 100}" class="progress active overlay" style="border-radius:0px;background-color:rgba(0,0,0,0);">' +
            '<div class="progress-bar" style="height: 4px; width:{{progressWidth}}%;"></div>' +
        '</div>' +
        '<div class="overlay bggradient"></div>' +
        '<div class="overlay flexcontainervertical">' +
            '<div class="flexfixed flexcontainer">' +
                '<div ng-click="openProject()" class="flexplus1"></div>' +
                '<div class="flexfixed">' +
                    '<button ng-click="removeFromList()" style="margin:6px;" type="button" class="btn btn-sm btn-primary"><span class="glyphicon glyphicon-remove"></span></button>' +
                '</div>' +
            '</div>' +
            '<div ng-click="openProject()" class="flexplus1"></div>' +
        '</div>' +
        '<div style="position:absolute;bottom:4px;left:5px;"><h5 id="name" style="margin-bottom:2px;text-shadow: 1px 1px 1px #000000;">{{decodeURI(project.name)}}</h5><h5 id="description" style="margin-bottom:2px;text-shadow: 1px 1px 1px #000000;"><small style="margin-bottom:0px;text-shadow: 1px 1px 1px #000000;color:white;">{{shortenPath(project.projectPath, 100)}}</small></h5></div>' +
        '</div>',
    controller: function($scope){
        $scope.isBusy = false;
        $scope.project;
        $scope.decodeURI = decodeURI;
        $scope.shortenPath = shortenPath;
        $scope.removeFromList = function(){
            preferences.recentProjects.forEach(function(recentProject, index){
                if($scope.project.projectPath == recentProject.projectPath){
                    preferences.recentProjects.splice(index,1)
                }
            })
        };
        $scope.openProject = function(){
            if($scope.isBusy == false){
                $scope.isBusy = true
                $scope.safeApply(function(){
                    $scope.isBusy = true
                })
                    openProjectPromise($scope.project.projectPath).then(function(fileName){
                    $scope.safeApply(function(){
                        $scope.isBusy = false
                    })
                    dlg_projects_hide()
                    dispatchInitializeTemplateProjectEvent()
                }).catch(function(err){
                    $scope.safeApply(function(){
                        $scope.isBusy = false
                    })
                    if(dlg_simpleAlert){
                        dlg_simpleAlert("Error opening Project", err)
                    }
                    console.log(err)
                })
            }
        };
        $scope.progressWidth = 100;
        $scope.safeApply = function(fn) {
          var phase = this.$root.$$phase;
          if(phase == '$apply' || phase == '$digest') {
            if(fn && (typeof(fn) === 'function')) {
              fn();
            }
          } else {
            this.$apply(fn);
          }
        };
    },
    link: function($scope, element, attrs) {
        var initializeProject = function(project){
            if(!project){try{project = JSON.parse(attrs.project)}catch(e){}}
            if(!project){return null}
            $scope.safeApply(function(){
                $scope.project = project
            })
            var imageSrcUrl = replaceAll(project.snapshotPath, "\\", "/")
            //var projectUrl = project.projectPath
            var name = decodeURI(project.name)
            if(fs.existsSync(project.projectPath)){
                var changes = {
                    backgroundImage: 'url("file:///' + imageSrcUrl + '")',
                    backgroundSize: "cover",
                    backgroundPosition: "center"
                }
            }else{
                var changes = {
                    display: 'none',
                }
            }
            element.css(changes)
            //$compile(element.contents())($scope.$new());
        }
        attrs.$observe("project",function(project){
            if (project){
                try{project = JSON.parse(project)}catch(e){}
                initializeProject(project)
            }
        });
        initializeProject()
    }
  }
})
