source: cats/SCHEMAcat/trunk/urn.org.isocat.schemacat.site/site/scripts/controllers.js @ 4200

Last change on this file since 4200 was 4200, checked in by andmor, 10 years ago

Typo

File size: 34.0 KB
Line 
1'use strict';
2
3//SCHEMAcat angular controllers
4SCHEMAcat.controller('WorkspaceCtrl', ['$scope', '$location', '$routeParams', '$timeout', 'SchemasList', 'Schema', 'UserService', 'Settings',
5    function($scope, $location, $routeParams, $timeout, SchemasList, Schema, UserService, Settings) {
6
7        //these models have to be stored in the parent scope since they are used across page changes and
8        //this controller is reloaded everytime the users changes page, thus reseting the $scope models.
9        var parentScope = $scope.$parent;
10        parentScope.pageSize = 10;
11
12        //these models are stored in the local $scope since they are not used across page changes
13        $scope.selectedSchemaIndex = $routeParams.schemaIndex;
14
15        //keep the workspace page hidden until all data is loaded           
16        $scope.animateWorkspacePageChange = 'invisible';
17
18
19
20        //watch for our AJAX data to arrive and fade in workspace afterwards.
21        //when changing page, the data is requested before the workspace controller is reloaded
22        //so we should fade in the workspace in the new controller instance after reload.
23        var watchListener = $scope.$watch('resultHasArrived', function(newValue, oldValue) {
24            if (newValue) {
25                if (Settings.getAnimationStatus()) {
26                    //fade in the workspace page
27                    switch (parentScope.toNextPage) {
28                        case false:
29                            $scope.animateWorkspacePageChange = 'animated slideInLeft';
30                            break;
31                        case true:
32                            $scope.animateWorkspacePageChange = 'animated slideInRight';
33                            break;
34                            //if it is a reload toNextPage will be undefined
35                        default:
36                            $scope.animateWorkspacePageChange = 'animated fadeInDown';
37                    }
38
39                    $timeout(function() {
40                        $scope.animateWorkspacePageChange = '';
41                    }, 250);
42                } else
43                    $scope.animateWorkspacePageChange = '';
44                //derregister the listener since the workspace page is now loaded
45                watchListener();
46            }
47        });
48
49
50        //load the schemas page and the selected schema metadata.
51        //if reading the workspace for the first time i.e. not due to page change click
52        if (!parentScope.workspaceFirstLoaded)
53            loadSchemasList($routeParams.pageNumber);
54
55
56        //update the current route when user clicks in another page in the paginator.
57        //This triggers a $routeChangeStart event since we are changing the route path part.
58        $scope.selectPage = function(page) {
59            $location.search().schemaIndex = '0';
60            delete $location.search().show;
61            $location.path('workspace/page/' + page + '/').search($location.search());
62        };
63
64
65        //update the current route when the uses clicks one schema in the list. This triggers
66        //a $routeUpdate event since we are just changing the route search part.
67        $scope.selectSchema = function(rowIndex) {
68            $location.search().schemaIndex = rowIndex.toString();
69            delete $location.search().show;
70            $location.search($location.search());
71        };
72
73
74        //listen for the $routeChangeStart event. Triggered when route path is changed (page change).
75        $scope.$on('$routeChangeStart', function(event, next, current) {
76            parentScope.resultHasArrived = false;
77            if (Settings.getAnimationStatus()) {
78                if (next.params !== undefined &&
79                    next.params.pageNumber !== undefined &&
80                    next.params.pageNumber > current.params.pageNumber)
81                    parentScope.toNextPage = true;
82                else
83                    parentScope.toNextPage = false;
84
85                //slide out workspace page
86                switch (next.templateUrl) {
87                    case 'partials/workspace.html':
88                        $scope.animateWorkspacePageChange =
89                            parentScope.toNextPage ?
90                            'animated slideOutLeft' : 'animated slideOutRight';
91                        break;
92                    case 'partials/contact.html':
93                    case 'partials/about.html':
94                        $scope.animateWorkspacePageChange = 'animated slideOutLeft';
95                        break;
96                    default:
97                        $scope.animateWorkspacePageChange = 'animated fadeOutDown';
98                }
99            }
100            if (next.templateUrl === 'partials/workspace.html')
101                loadSchemasList(next.params.pageNumber);
102            else
103                parentScope.workspaceFirstLoaded = false;
104        });
105
106        $scope.$on('$routeChangeSuccess', function(event, current, previous) {
107            //when coming back to the workspace from other routes, the workspace should apear from the left to the right
108            if (Settings.getAnimationStatus()) {
109                if (previous === undefined || previous.templateUrl === undefined ||
110                    previous.templateUrl === 'partials/accountDetails.html')
111                    parentScope.toNextPage = undefined;
112            }
113        });
114
115        //listen for the $routeUpdate event and update the selected schema metadata.
116        //(if not done, the selection highlight is not updated e.g. when
117        //navigating back and forth)
118        $scope.$on('$routeUpdate', function(event, route) {
119            if (route.templateUrl === 'partials/workspace.html' && route.params.schemaIndex !== $scope.selectedSchemaIndex) {
120                parentScope.resultHasArrived = false;
121                if (Settings.getAnimationStatus()) {
122                    $scope.toNextSchema =
123                        route.params.schemaIndex > $scope.selectedSchemaIndex ?
124                        true : false;
125
126                    $scope.animateSchemaChange =
127                        $scope.toNextSchema ?
128                        'animated fadeOutUp' : 'animated fadeOutDown';
129                    $timeout(function() {
130                        loadSchemaMetadata(route.params.schemaIndex);
131                    }, 250);
132                } else
133                    loadSchemaMetadata(route.params.schemaIndex);
134            }
135        });
136
137
138        function loadSchemasList(page) {
139            //check if pageNumber is not a number (can happen e.g. due to manual input)
140            //reload on page 1 schema index 0 if so
141            if (isNaN(parseInt(page, 10))  || page < 1) {
142                $location.path('workspace/page/' + 1 + '/').search({
143                    'schemaIndex': 0
144                });
145                return;
146            }
147
148            //When the user changes page, the new AJAX data (next page) is requested by
149            //the unloading controller (previous page) and used by the next loaded
150            //controller (next page), thus we have to keep the server data across controller
151            //reloads by saving it in the parent scope.
152            SchemasList.get({
153                    userID: UserService.id,
154                    startPage: page,
155                    pageSize: $scope.pageSize
156                },
157                function(result) {
158                    //we now have the pages range so we can configure the paginator and check if pageNumber is out of
159                    //range (can happen e.g. due to manual input) reload on page 1 schema index 0 if so
160                    if (page > Math.ceil(result['sc:result']['sc:total-schemas'] / $scope.pageSize)) {
161                        $location.path('workspace/page/' + 1 + '/').search({
162                            'schemaIndex': 0
163                        });
164                        return;
165                    }
166
167                    parentScope.totalSchemaItems = result['sc:result']['sc:total-schemas'];
168                    parentScope.currentPage = Number(page);
169
170
171                    //when there is just one element we create an array with it, so ng-repeat repeats just once
172                    parentScope.schemasList = prepareArrayForNgRepeat(result['sc:result']['sc:schemas']['sc:schema']);
173
174                    loadSchemaMetadata($location.search().schemaIndex);
175
176                    parentScope.schemasResult = result;
177                });
178        }
179
180
181        //loads (trough a 'Schema' AJAX call) the schema metadata of the schema placed
182        //in the 'index' position of the schemas list.
183        function loadSchemaMetadata(index) {
184            //if just changing the selected schema hide the metadata pane until the metadata is loaded
185            if ($scope.animateWorkspacePageChange !== 'invisible')
186                $scope.animateSchemaChange = 'invisible';
187            //check if schemaIndex is out of range (can happen e.g. due to manual input)
188            //reload on schema index 0 if so
189            if (isNaN(parseInt(index, 10)) || index < 0 || index > $scope.schemasList.length - 1) {
190                $scope.selectedSchemaIndex = undefined;
191                $location.search({
192                    'schemaIndex': 0
193                });
194                return;
195            }
196            //update the selected row to the route search part.
197            $scope.selectedSchemaIndex = index;
198
199            //make AJAX call to get the schema metadata for the selected row
200            var selectedSchemaRow = parentScope.schemasList[Number(index)];
201            Schema.get({
202                    schemaID: selectedSchemaRow['xml:id']
203                },
204                function(result) {
205                    //when there is just one element we create an array with it, so ng-repeat repeats just once
206                    parentScope.filesList = prepareArrayForNgRepeat(result['sc:schema']['sc:files']['sc:file']);
207
208                    if (Settings.getAnimationStatus()) {
209                        //fade in the schema metadata
210                        switch ($scope.toNextSchema) {
211                            case true:
212                                $scope.animateSchemaChange = 'animated fadeInUp';
213                                break;
214                            case false:
215                                $scope.animateSchemaChange = 'animated fadeInDown';
216                                break;
217                                //if it is a reload toNextPage will be undefined
218                            case undefined:
219                                $scope.animateSchemaChange = 'animated fadeInDown';
220                        }
221                    } else
222                        $scope.animateSchemaChange = '';
223
224                    parentScope.selectedSchema = result;
225                    parentScope.resultHasArrived = true;
226                });
227
228        }
229
230        function prepareArrayForNgRepeat(data) {
231            var array;
232            if (data instanceof Array)
233                array = data;
234            else
235                array = new Array(data);
236            return array;
237        }
238
239        parentScope.workspaceFirstLoaded = true;
240
241    }
242]);
243
244
245SCHEMAcat.controller('FileController', ['$scope', '$http', '$timeout', '$location',
246    function($scope, $http, $timeout, $location) {
247
248        updateShowFiles();
249
250        //show-hide file toggle handler
251        $scope.showFile = function(fileName) {
252            //update the search part of the route
253            //triggers '$routeUpdate'
254            $scope.showFileAjaxError = false;
255            $timeout(function() { //(wrapping in $timeout is neded for Firefox)
256                var locationSearch = $location.search();
257                if ($scope.showSchemaBtn === true) {
258                    if (locationSearch.show === undefined)
259                        locationSearch.show = '#' + fileName;
260                    else if (locationSearch.show.indexOf(fileName) === -1)
261                        locationSearch.show = locationSearch.show + '#' + fileName;
262                } else {
263                    for (var prop in locationSearch) {
264                        if (prop === 'show') {
265                            var newLocationSearchShowArray = locationSearch[prop].split('#');
266                            for (var i in newLocationSearchShowArray) {
267                                if (newLocationSearchShowArray[i] === fileName)
268                                    newLocationSearchShowArray.splice(i, 1);
269                            }
270
271                            var newLocationSearchShowString = newLocationSearchShowArray.join('#');
272                            if (newLocationSearchShowString !== '') {
273                                locationSearch[prop] = newLocationSearchShowString;
274                            } else
275                                delete locationSearch[prop];
276                        }
277                    }
278                }
279                $location.search(locationSearch);
280            });
281        };
282
283        $scope.$on('$routeUpdate', function(event, route) {
284            if ($scope.resultHasArrived)
285                updateShowFiles();
286        });
287
288        function updateShowFiles() {
289            if ($location.search().show !== undefined && $location.search().show.indexOf($scope.file['sc:name']) !== -1) {
290                $scope.showSchemaBtn = true;
291                displayFile($scope.selectedSchema['sc:schema']['xml:id'], $scope.file['sc:name']);
292            } else {
293                $scope.showSchemaBtn = false;
294                $scope.file.open = false;
295            }
296        }
297
298        function displayFile(schemaID, fileName) {
299            if ($scope.schemaFileContent === undefined) {
300                $http.get('/schemacat/schemas/' + schemaID + '/files/' + fileName).
301                success(function(data, status, headers, config) {
302                    $scope.prettify = 'prettyprint linenums';
303
304                    //execute prettyPrint asynchronously. We use $timeout since prettyPrint()
305                    //must run after DOM rendering
306                    $timeout(function() {
307                        prettyPrint();
308                        $scope.file.open = true;
309                    });
310
311                    $scope.schemaFileContent = data;
312                }).
313                error(function(data, status, headers, config) {
314                    $scope.showSchemaBtn = false;
315                    $scope.showFile(fileName);
316                    $scope.showFileAjaxError = true;
317                });
318            } else
319                $scope.file.open = true;
320        }
321
322    }
323]);
324
325
326SCHEMAcat.controller('TopMenuCtrl', ['$scope', '$modal', '$location', 'UserService', 'Settings', 'ShibService',
327    function($scope, $modal, $location, UserService, Settings, ShibService) {
328
329        $scope.displayName = UserService.displayName;
330        $scope.shibURL = ShibService.url;
331
332        //watch for changes in the displayName since it can be changed by the user in the account details page
333        $scope.$watch(
334            function() {
335                return UserService.displayName;
336            },
337            function(newValue, oldValue) {
338                if (newValue !== oldValue) {
339                    $scope.displayName = newValue;
340                }
341            });
342
343        updateTopMenu();
344
345        $scope.isActive = function(viewLocation) {
346            if (viewLocation === '/workspace' && $location.path().indexOf('/workspace/') !== -1)
347                return true;
348            return viewLocation === $location.path();
349        };
350
351        $scope.updateAnimationStatus = function() {
352            $scope.animationsChecked = !$scope.animationsChecked;
353            if ($scope.animationsChecked)
354                delete $location.search().animationsDisabled;
355            else
356                $location.search().animationsDisabled = true;
357            $location.search($location.search());
358        };
359
360        $scope.toggleTopMenu = function() {
361            $scope.topMenuCollapsed = !$scope.topMenuCollapsed;
362            if ($scope.topMenuCollapsed)
363                delete $location.search().topMenuExpanded;
364            else
365                $location.search().topMenuExpanded = true;
366
367            $location.search($location.search());
368        };
369
370        $scope.animationsUrlPart = function() {
371            if ($location.search().animationsDisabled)
372                return 'animationsDisabled';
373            else
374                return '';
375        };
376
377        $scope.topMenuExpandedUrlPart = function() {
378            if ($location.search().topMenuExpanded)
379                return 'topMenuExpanded';
380            else
381                return '';
382        };
383
384        $scope.$on('$routeUpdate', function(event, route) {
385            updateTopMenu();
386        });
387
388        //Modal window handlers and options
389        $scope.loginClick = function() {
390            var modalInstance = $modal.open({
391                scope: $scope,
392                templateUrl: 'partials/loginModal.html',
393                controller: 'LoginModalCtrl'
394            });
395
396            modalInstance.result.then(function(loginName) {
397                alert('Now set the user cookie to [' + loginName + ']');
398                document.cookie = 'USER=' + loginName + ';domain=;path=/';
399                document.location.hash = '';
400                document.location.reload(true);
401            });
402        };
403
404        function updateTopMenu() {
405            $scope.topMenuCollapsed = !$location.search().topMenuExpanded;
406
407            Settings.setAnimationStatus(!$location.search().animationsDisabled);
408            $scope.animationsChecked = Settings.getAnimationStatus();
409        }
410
411    }
412]);
413
414SCHEMAcat.controller('LoginModalCtrl', ['$scope', '$modalInstance',
415    function($scope, $modalInstance) {
416        $scope.loginClose = function() {
417            $modalInstance.dismiss('cancel');
418        };
419
420        //set cookie code. REMOVE in production
421        $scope.loginSubmit = function() {
422            $modalInstance.close(this.loginNameInput.text);
423        };
424    }
425]);
426
427SCHEMAcat.controller('AboutPageCtrl', ['$scope', 'Settings',
428    function($scope, Settings) {
429
430        //When the user loads (or reloads) the 'About' page as the first page to be accessed, the 'toNextPage' variable
431        //used by the workspace to determine the direction of its enter animation is: 'undefined'. Thus we set it so
432        //that if the user moves to the workspace ('Home'), the workspace will enter with the right animation.
433        //This is done independently of 'Settings.getAnimationStatus()' so when the animations are turned on, their
434        //governing variables are already set.
435        $scope.$parent.toNextPage = false;
436
437        if (Settings.getAnimationStatus()) {
438            $scope.animateInOut = 'animated slideInRight';
439        }
440
441        $scope.$on('$routeChangeStart', function(event, next, current) {
442            if (Settings.getAnimationStatus()) {
443                switch (next.templateUrl) {
444                    case 'partials/workspace.html':
445                        $scope.animateInOut = 'animated slideOutRight';
446                        break;
447                    case 'partials/contact.html':
448                        $scope.animateInOut = 'animated slideOutLeft';
449                        break;
450                    default:
451                        $scope.animateInOut = 'animated fadeOutDown';
452                }
453            }
454        });
455
456        $scope.$on('$routeChangeSuccess', function(event, current, previous) {
457            if (Settings.getAnimationStatus()) {
458                var previousUrl = previous !== undefined ?
459                    previous.templateUrl : undefined;
460                switch (previousUrl) {
461                    case 'partials/workspace.html':
462                        $scope.animateInOut = 'animated slideInRight';
463                        break;
464                    case 'partials/contact.html':
465                        $scope.animateInOut = 'animated slideInLeft';
466                        break;
467                    default:
468                        $scope.animateInOut = 'animated fadeInDown';
469                }
470            }
471        });
472    }
473]);
474
475SCHEMAcat.controller('ContactPageCtrl', ['$scope', 'Settings',
476    function($scope, Settings) {
477
478        //When the user loads (or reloads) the 'Contact' page as the first page to be accessed, the 'toNextPage' variable
479        //used by the workspace to determine the direction of its enter animation is: 'undefined'. Thus we set it so
480        //that if the user moves to the workspace ('Home'), the workspace will enter with the right animation.
481        //This is done independently of 'Settings.getAnimationStatus()' so when the animations are turned on, their
482        //governing variables are already set.
483        $scope.$parent.toNextPage = false;
484
485        if (Settings.getAnimationStatus()) {
486            $scope.animateInOut = 'animated slideInRight';
487        }
488
489        $scope.$on('$routeChangeStart', function(event, next, current) {
490            if (Settings.getAnimationStatus()) {
491                switch (next.templateUrl) {
492                    case 'partials/about.html':
493                    case 'partials/contact.html':
494                    case 'partials/workspace.html':
495                        $scope.animateInOut = 'animated slideOutRight';
496                        break;
497                    default:
498                        $scope.animateInOut = 'animated fadeOutDown';
499                }
500            }
501        });
502
503        $scope.$on('$routeChangeSuccess', function(event, current, previous) {
504            //when coming back to the workspace from other routes, the workspace should apear from the left to the right
505            if (Settings.getAnimationStatus()) {
506                var previousUrl = previous !== undefined ?
507                    previous.templateUrl : undefined;
508                switch (previousUrl) {
509                    case 'partials/about.html':
510                    case 'partials/contact.html':
511                    case 'partials/workspace.html':
512                        $scope.animateInOut = 'animated slideInRight';
513                        break;
514                    default:
515                        $scope.animateInOut = 'animated fadeInDown';
516                }
517            }
518        });
519    }
520]);
521
522SCHEMAcat.controller('AccountDetailsPageCtrl', ['$scope', '$location', 'User', 'UserService', 'Settings',
523    function($scope, $location, User, UserService, Settings) {
524
525        //this function is used to clean outdated emails from the route search part
526        //i.e. after editing an email the user can still go back in the browser but
527        //the old email addess does not exist anymore, thus we clean it when back is clicked.
528        function cleanOutdatedSearchPathEmails() {
529            var locationSearch = $location.search();
530            for (var prop in locationSearch) {
531                if (prop === 'edditingEmail') {
532                    var newLocationSearchEdditingEmailArray = locationSearch[prop].split('#');
533                    for (var i = 0; i < newLocationSearchEdditingEmailArray.length; i++) {
534                        var found = false;
535                        for (var j = 0; j < UserService.email.length; j++) {
536                            if (newLocationSearchEdditingEmailArray[i] === UserService.email[j])
537                                found = true;
538                        }
539                        if (!found)
540                            newLocationSearchEdditingEmailArray.splice(i, 1);
541                    }
542                    var newLocationSearchEdditingEmailString = newLocationSearchEdditingEmailArray.join('#');
543                    if (newLocationSearchEdditingEmailString !== '') {
544                        locationSearch[prop] = newLocationSearchEdditingEmailString;
545                    } else
546                        delete locationSearch[prop];
547                }
548            }
549            $location.search(locationSearch);
550        }
551
552        function updateEdditingDisplayName() {
553            $scope.waitingForServerEditDisplayName = false;
554            $scope.editDisplayNameAjaxError = false;
555            if ($location.search().edditingDisplayName) {
556                $scope.editDisplayNameText = $scope.displayName;
557                $scope.edditingDisplayName = true;
558            } else
559                $scope.edditingDisplayName = false;
560        }
561
562        function updateAddingEmail() {
563            $scope.waitingForServer = false;
564
565            if ($location.search().addingEmail)
566                $scope.addingEmail = true;
567            else
568                $scope.addingEmail = false;
569        }
570
571        $scope.principal = UserService.principal;
572        $scope.displayName = UserService.displayName;
573        $scope.email = UserService.email;
574
575        $scope.addingEmail = false;
576
577        $scope.addNewEmail = function() {
578            $location.search().addingEmail = true;
579            $location.search($location.search());
580        };
581
582        $scope.terminateAddEmail = function() {
583            $scope.ajaxError = false;
584            delete $location.search().addingEmail;
585            $location.search($location.search());
586        };
587
588        $scope.addEmail = function(newEmail) {
589            $scope.waitingForServer = true;
590            var user = new User();
591            user.emails = UserService.email.slice(0);
592            user.emails.push(newEmail);
593
594            user.$save({
595                    userID: UserService.id
596                },
597                function(result) {
598                    if (result['sc:response'] !== undefined && result['sc:response'].success) {
599                        UserService.email.push(newEmail);
600                        $scope.terminateAddEmail();
601                    } else {
602                        //server reports an handeled error
603                        $scope.waitingForServer = false;
604                        $scope.ajaxError = true;
605                    }
606                },
607                //no response, or response error flagged in http response headers
608                function() {
609                    $scope.waitingForServer = false;
610                    $scope.ajaxError = true;
611                });
612        };
613
614        $scope.editDisplayName = function() {
615            $location.search().edditingDisplayName = true;
616            $location.search($location.search());
617        };
618
619        $scope.terminateEditDisplayName = function() {
620            delete $location.search().edditingDisplayName;
621            $location.search($location.search());
622        };
623
624        $scope.updateDisplayName = function(newDisplayName) {
625            $scope.waitingForServerEditDisplayName = true;
626            var user = new User();
627            user.displayName = newDisplayName;
628
629            user.$save({
630                    userID: UserService.id
631                },
632                function(result) {
633                    if (result['sc:response'] !== undefined && result['sc:response'].success) {
634                        $scope.displayName = UserService.displayName = newDisplayName;
635                        $scope.terminateEditDisplayName();
636                    } else {
637                        //server reports an handeled error
638                        $scope.waitingForServerEditDisplayName = false;
639                        $scope.editDisplayNameAjaxError = true;
640                    }
641                },
642                //no response, or response error flagged in http response headers
643                function() {
644                    $scope.waitingForServerEditDisplayName = false;
645                    $scope.editDisplayNameAjaxError = true;
646                });
647        };
648
649        if (Settings.getAnimationStatus()) {
650            $scope.animateAccountDetails = 'animated fadeInDown';
651        }
652
653        $scope.$on('$routeChangeStart', function(event, next, current) {
654            if (Settings.getAnimationStatus()) {
655                $scope.animateAccountDetails = 'animated fadeOutUp';
656            }
657        });
658
659        $scope.$on('$routeChangeSuccess', function(event, current, previous) {
660            if (Settings.getAnimationStatus()) {
661                $scope.animateAccountDetails = 'animated fadeInDown';
662            }
663            updateAddingEmail();
664            updateEdditingDisplayName();
665            cleanOutdatedSearchPathEmails();
666        });
667
668        $scope.$on('$routeUpdate', function(event, route) {
669            updateAddingEmail();
670            updateEdditingDisplayName();
671            cleanOutdatedSearchPathEmails();
672        });
673    }
674]);
675
676SCHEMAcat.controller('EmailInstanceCtrl', ['$scope', '$location', 'User', 'UserService',
677    function($scope, $location, User, UserService) {
678
679        function updateEdditingEmail() {
680            $scope.waitingForServerEditEmail = false;
681            if ($location.search().edditingEmail !== undefined && $location.search().edditingEmail.indexOf($scope.emailInstance) !== -1) {
682                $scope.editEmailText = $scope.emailInstance;
683                $scope.edditingEmail = true;
684            } else
685                $scope.edditingEmail = false;
686        }
687
688        updateEdditingEmail();
689
690        $scope.editEmail = function(emailInstance) {
691            var locationSearch = $location.search();
692            $scope.removeEmailAjaxError = false;
693            if (locationSearch.edditingEmail === undefined)
694                locationSearch.edditingEmail = emailInstance;
695            else
696                locationSearch.edditingEmail = $location.search().edditingEmail + '#' + emailInstance;
697
698            $location.search(locationSearch);
699        };
700
701        $scope.removeEmail = function(index) {
702            $scope.waitingForServerEditEmail = true;
703
704            var user = new User();
705            user.emails = UserService.email.slice(0);
706            user.emails.splice(index, 1);
707
708            user.$save({
709                    userID: UserService.id
710                },
711                function(result) {
712                    if (result['sc:response'] !== undefined && result['sc:response'].success) {
713                        UserService.email.splice(index, 1);
714                    } else {
715                        //server reports an handeled error
716                        $scope.waitingForServerEditEmail = false;
717                        $scope.removeEmailAjaxError = true;
718                    }
719                },
720                //no response, or response error flagged in http response headers
721                function() {
722                    $scope.waitingForServerEditEmail = false;
723                    $scope.removeEmailAjaxError = true;
724                });
725        };
726
727        $scope.updateEmail = function(index) {
728            $scope.waitingForServerEditEmail = true;
729
730            var user = new User();
731            user.emails = UserService.email.slice(0);
732            user.emails[index] = $scope.editEmailText;
733
734            user.$save({
735                    userID: UserService.id
736                },
737                function(result) {
738                    if (result['sc:response'] !== undefined && result['sc:response'].success) {
739                        var newEmail = $scope.editEmailText;
740                        $scope.cancelEditEmail(UserService.email[index]);
741                        UserService.email[index] = newEmail;
742                    } else {
743                        //server reports an handeled error
744                        $scope.waitingForServerEditEmail = false;
745                        $scope.editEmailAjaxError = true;
746                    }
747                },
748                //no response, or response error flagged in http response headers
749                function() {
750                    $scope.waitingForServerEditEmail = false;
751                    $scope.editEmailAjaxError = true;
752                });
753        };
754
755
756        $scope.cancelEditEmail = function(emailInstance) {
757            var locationSearch = $location.search();
758            $scope.editEmailAjaxError = false;
759
760            for (var prop in locationSearch) {
761                if (prop === 'edditingEmail') {
762                    var newLocationSearchEdditingEmailArray = locationSearch[prop].split('#');
763                    for (var i in newLocationSearchEdditingEmailArray) {
764                        if (newLocationSearchEdditingEmailArray[i] === emailInstance)
765                            newLocationSearchEdditingEmailArray.splice(i, 1);
766                    }
767                    var newLocationSearchEdditingEmailString = newLocationSearchEdditingEmailArray.join('#');
768                    if (newLocationSearchEdditingEmailString !== '') {
769                        locationSearch[prop] = newLocationSearchEdditingEmailString;
770                    } else
771                        delete locationSearch[prop];
772                }
773            }
774            $location.search(locationSearch);
775        };
776
777        $scope.$on('$routeChangeSuccess', function(event, current, previous) {
778            updateEdditingEmail();
779        });
780
781        $scope.$on('$routeUpdate', function(event, route) {
782            updateEdditingEmail();
783        });
784    }
785]);
786
787//SCHEMAcat controlers for completeUserDetails.html page
788SCHEMAcat.controller('CompleteUserDetailsCtrl', ['$scope', '$modal',
789    function($scope, $modal) {
790
791        $scope.ajaxError = false;
792        $scope.waitingForServer = false;
793
794        var userDetailsModalInstance = $modal.open({
795            scope: $scope,
796            backdrop: 'static',
797            templateUrl: 'partials/fillDetailsModal.html',
798            controller: 'CompleteUserDetailsModalCtrl'
799        });
800    }
801]);
802
803SCHEMAcat.controller('CompleteUserDetailsModalCtrl', ['$scope', '$modalInstance', 'User', 'UserService',
804    function($scope, $modalInstance, User, UserService) {
805
806        $scope.userDetailsSubmit = function() {
807            $scope.waitingForServer = true;
808            $scope.ajaxError = false;
809
810            var user = new User();
811
812            user.emails = [];
813            user.emails[0] = this.emailInput.text;
814            user.displayName = this.displayNameInput.text;
815
816            user.$save({
817                    userID: UserService.id
818                },
819                function(result) {
820                    if (result['sc:response'] !== undefined && result['sc:response'].success)
821                        document.location.pathname = 'schemacat/site/index.html';
822                    else {
823                        //server reports an handeled error
824                        $scope.waitingForServer = false;
825                        $scope.ajaxError = true;
826                    }
827                },
828                //no response, or response error flagged in http response headers
829                function() {
830                    $scope.waitingForServer = false;
831                    $scope.ajaxError = true;
832                });
833        };
834    }
835]);
Note: See TracBrowser for help on using the repository browser.