angular.module("FICApp", ["ngRoute", "ngSanitize"])
    .config(function($routeProvider, $locationProvider) {
	$routeProvider
	    .when("/rules", {
		controller: "HomeController",
		templateUrl: "views/rules.html"
	    })
	    .when("/edit", {
		controller: "MyTeamController",
		templateUrl: "views/team-edit.html"
	    })
	    .when("/issue/:eid", {
		controller: "IssueController",
		templateUrl: "views/issue.html"
	    })
	    .when("/issues", {
		controller: "IssueController",
		templateUrl: "views/issue.html"
	    })
	    .when("/issues/:iid", {
		controller: "IssueController",
		templateUrl: "views/issue.html"
	    })
	    .when("/rank", {
		controller: "RankController",
		templateUrl: "views/rank.html"
	    })
	    .when("/register", {
		controller: "RegisterController",
		templateUrl: "views/register.html"
	    })
	    .when("/videos", {
		controller: "VideosController",
		templateUrl: "views/videos.html"
	    })
	    .when("/tags/:tag", {
		controller: "TagController",
		templateUrl: "views/tag.html"
	    })
	    .when("/:theme", {
		controller: "ExerciceController",
		templateUrl: "views/theme.html"
	    })
	    .when("/:theme/:exercice", {
		controller: "ExerciceController",
	        templateUrl: function(e) {
		  if (e.theme == "BlueMoney" && e.exercice == "JackSpearrow")
		    return "views/defi-SE.html"
		  else
		    return "views/defi.html";
	        }
	    })
	    .when("/", {
		controller: "HomeController",
		templateUrl: "views/home.html"
	    })
	    .otherwise({
		redirectTo: "/"
	    });
	$locationProvider.html5Mode(true);
    })
    .run(function($rootScope) {
	$rootScope.current_theme = 0;
	$rootScope.current_exercice = 0;
	$rootScope.current_tag = undefined;
	$rootScope.notify_field = 0;
        $rootScope.issues_known_responses = 0;

	if ('Notification' in window)
	    Notification.requestPermission(function(result) {
		if (result == "granted") {
		    if (localStorage && localStorage.notification)
			$rootScope.notify_field = localStorage.notification;
		    else
			$rootScope.notify_field = 63;
		}
		else
		    $rootScope.notify_field = 0;
	    });
    })
    .controller("DataController", function($sce, $scope, $http, $rootScope, $interval, $location) {
	var actMenu = function() {
	    if ($scope.my && $scope.themes) {
		var tags = {};
		angular.forEach($scope.themes, function(theme, key) {
		    $scope.themes[key].exercice_solved = 0;
		    var last_exercice = null;
		    angular.forEach(theme.exercices, function(exercice, k) {
			if (last_exercice != null)
			    last_exercice.next = k;
			last_exercice = exercice;

			if ($scope.my.exercices && $scope.my.exercices[k] && $scope.my.exercices[k].solved) {
			    $scope.themes[key].exercice_solved++;
			}
			angular.forEach(exercice.tags, function(tag) {
			    if (!tags[tag])
				tags[tag] = {count: 1, solved: 0};
			    else
				tags[tag].count += 1;
			    if ($scope.my.exercices && $scope.my.exercices[k] && $scope.my.exercices[k].solved)
				tags[tag].solved += 1;
			});
		    });
		});
		$scope.tags = tags;
		$scope.tagsl = Object.keys(tags).sort();
	    }
	}

	var refreshSettingsInterval
	var refreshSettings = function() {
	    if (refreshSettingsInterval)
		$interval.cancel(refreshSettingsInterval);
	    refreshSettingsInterval = $interval(refreshSettings, Math.floor(Math.random() * 24000) + 32000);

	    $http.get("settings.json").then(function(response) {
		var time = $rootScope.recvTime(response);
		if (response.data.start)
		    response.data.start = new Date(response.data.start);
		if (response.data.end)
		    response.data.end = new Date(response.data.end);
		if (response.data.generation)
		    response.data.generation = new Date(response.data.generation);
		if (response.data.activateTime)
		    response.data.activateTime = new Date(response.data.activateTime);
		if ($rootScope.settings === undefined || response.data.activateTime === undefined || response.data.activateTime <= new Date(Date.now() + (time.cu - time.he))) {
		    $rootScope.settings = response.data;
		    if (response.data.eventKindness && refreshEventsInterval) {
			$interval.cancel(refreshEventsInterval);
			refreshEventsInterval = null;
		    }
		    else if (!response.data.eventKindness && !refreshEventsInterval) {
			refreshEvents();
		    }
		}
		else
		    $rootScope.settings.activateTime = response.data.activateTime;
	    });
	}

	var refreshIssuesInterval
	var refreshIssues = function() {
	    if (refreshIssuesInterval)
		$interval.cancel(refreshIssuesInterval);
	    refreshIssuesInterval = $interval(refreshIssues, Math.floor(Math.random() * 24000) + 32000);

	    $http.get("issues.json").then(function(response) {
	        $rootScope.issues_idx = {};
	        $rootScope.issues_nb_responses = 0;
	        $rootScope.issues_need_info = 0;
	        $rootScope.issues = response.data;
	        $rootScope.issues.forEach(function(issue) {
		  $rootScope.issues_idx[issue.id] = issue;
		  $rootScope.issues_nb_responses += issue.texts.length;
		  if (issue.state == 'need-info') $rootScope.issues_need_info++;
	        })
	    });
	}

	var refreshThemesInterval
	var refreshThemes = function() {
	    if (refreshThemesInterval)
		$interval.cancel(refreshThemesInterval);
	    refreshThemesInterval = $interval(refreshThemes, Math.floor(Math.random() * 24000) + 32000);

	    $http.get("themes.json").then(function(response) {
		$scope.themes = response.data;
		$scope.max_gain = 0;
		$scope.max_solved = 0;
		$scope.themesUrl = {};
		$scope.exercicesUrl = {};
		angular.forEach(response.data, function(theme, key) {
		    $scope.themesUrl[theme.urlid] = key;
		    this[key].exercice_count = Object.keys(theme.exercices).length;
		    this[key].exercice_coeff_max = 0;
		    this[key].gain = 0;
		    this[key].solved = 0;
		    angular.forEach(theme.exercices, function(ex, k) {
			$scope.exercicesUrl[theme.urlid + "/" + ex.urlid] = k;
			this.gain += ex.gain;
			this.solved += ex.solved;
			this.exercice_coeff_max = Math.max(this.exercice_coeff_max, ex.curcoeff);
		    }, theme);
		    $scope.max_gain += theme.gain;
		    $scope.max_solved = Math.max($scope.max_solved, theme.solved);
		}, response.data);
		actMenu();
	    });
	}

	var refreshTeamsInterval;
	$rootScope.refreshTeams = function() {
	    if (refreshTeamsInterval)
		$interval.cancel(refreshTeamsInterval);
	    refreshTeamsInterval = $interval($rootScope.refreshTeams, Math.floor(Math.random() * 24000) + 32000);

	    $http.get("teams.json").then(function(response) {
		var teams = response.data;
		$scope.teams_count = Object.keys(teams).length
		$scope.teams = teams;

		$scope.rank = [];
		angular.forEach($scope.teams, function(team, tid) {
		    team.id = tid;
		    this.push(team);
		}, $scope.rank);
	    });
	}

	var refreshEventsInterval;
	var eventsLastRefresh;
	var eventsLastTreated;
	var refreshEvents = function() {
	    if (refreshEventsInterval)
		$interval.cancel(refreshEventsInterval);
	    var refreshRate = 1200;
	    if ($rootScope.notify_field == 0 && eventsLastTreated)
		refreshRate = 30000;
	    if ($scope.my && !$scope.my.team_id)
		return;
	    refreshEventsInterval = $interval(refreshEvents, Math.floor(Math.random() * refreshRate * 2) + refreshRate);

	    if (!eventsLastTreated) {
		eventsLastTreated = $rootScope.getSrvTime();
		if (!eventsLastTreated)
		    return;
	    }

	    $http.get("events.json").then(function(response) {
		if (eventsLastRefresh != undefined && eventsLastRefresh == response.headers()["last-modified"])
		    return;
		eventsLastRefresh = response.headers()["last-modified"];

		var maxTimeSeen = eventsLastTreated;
		for (var i = response.data.length - 1; i >= 0; i--) {
		    var event = response.data[i];

		    event.time = new Date(event.time);
		    if (event.time <= eventsLastTreated)
			continue;
		    else if (event.time > maxTimeSeen)
			maxTimeSeen = event.time;

		    // Determine the kind of event
		    var kind = 1;

		    if (event.txt.match(/<\/strong> qui vient de nous rejoindre/)) {
			kind = 64;
		    } else {
			var res = event.txt.match(/(\w+) le <strong>\d+<sup>e<\/sup><\/strong> défi [^&]+/)
			if (res) {
			    if (res[1] == "résolu")
				kind = 8;
			    else if (res[1] == "pour")
				kind = 16;
			    else if (res[1] == "tente")
				kind = 32;
			}
		    }
		    if (kind != 1) {
			if ($scope.my && $scope.my.name && event.txt.indexOf($scope.my.name) >= 0)
			    kind |= 2;
			else
			    kind |= 4;
		    }

		    if ((kind & $rootScope.notify_field) == kind) {
			var notification = new Notification("Challenge forensic", {body: event.txt.replace(/&#(\d+);/g, function(match, dec) {return String.fromCharCode(dec);}).replace(/(<([^>]+)>)/ig,""), badge: "/img/icon-" + event.kind + ".ico", icon: "/img/icon-" + event.kind + ".ico"});
			notification.onclick = function(ev) {
			    $location.url("edit");
			};
			setTimeout(notification.close.bind(notification), 4000);
		    }
		};

		if (maxTimeSeen > eventsLastTreated)
		    eventsLastTreated = maxTimeSeen;
	    });
	}

	var refreshMyInterval;
	var refreshMy = function() {
	    if (refreshMyInterval)
		$interval.cancel(refreshMyInterval);
	    refreshMyInterval = $interval(refreshMy, Math.floor(Math.random() * 24000) + 24000);

	    $http.get("my.json").then(function(response) {
		$rootScope.recvMy(response.data);
	    }, function(response) {
		if (!$scope.my && response.status == 404) {
		    $location.url("register");
		}
	    });
	}
	$rootScope.recvMy = function(data) {
		if (data.team_id == 0) {
		    angular.forEach(data.exercices, function(exercice, eid) {
			angular.forEach(exercice.hints, function(hint, hid) {
			    if ($scope.my && $scope.my.exercices[eid] && $scope.my.exercices[eid].hints[hid] && $scope.my.exercices[eid].hints[hid].hidden !== undefined)
				data.exercices[eid].hints[hid].hidden = $scope.my.exercices[eid].hints[hid].hidden;
			    else
				data.exercices[eid].hints[hid].hidden = true;
			});
		    });
		}
		angular.forEach(data.exercices, function(exercice, eid) {
		    if ($scope.my && $scope.my.exercices[eid] && $scope.my.exercices[eid].submitted)
			data.exercices[eid].timeouted = true;
		    if ($scope.my && $scope.my.exercices[eid] && $scope.my.exercices[eid].solved !== undefined)
			data.exercices[eid].solved = $scope.my.exercices[eid].solved;
		    if ($scope.my && $scope.my.exercices[eid] && $scope.my.exercices[eid].solved_time !== undefined && data.exercices[eid].solved_time === undefined)
			data.exercices[eid].solved_time = $scope.my.exercices[eid].solved_time;
		    if ($scope.my && $scope.my.exercices[eid] && $scope.my.exercices[eid].tries !== undefined && data.exercices[eid].tries === undefined)
			data.exercices[eid].tries = $scope.my.exercices[eid].tries;
		    angular.forEach(exercice.flags, function(flag, fid) {
			if ($scope.my && $scope.my.exercices[eid] && $scope.my.exercices[eid].flags && $scope.my.exercices[eid].flags[fid] && $scope.my.exercices[eid].flags[fid].found !== undefined)
			    data.exercices[eid].flags[fid].found = $scope.my.exercices[eid].flags[fid].found;
			if ($scope.my && $scope.my.exercices[eid] && $scope.my.exercices[eid].flags && $scope.my.exercices[eid].flags[fid] && $scope.my.exercices[eid].flags[fid].value !== undefined)
			    data.exercices[eid].flags[fid].value = $scope.my.exercices[eid].flags[fid].value;
			if ($scope.my && $scope.my.exercices[eid] && $scope.my.exercices[eid].flags && $scope.my.exercices[eid].flags[fid] && $scope.my.exercices[eid].flags[fid].values !== undefined)
			    data.exercices[eid].flags[fid].values = $scope.my.exercices[eid].flags[fid].values;
			else if (data.exercices[eid].flags[fid].nb_lines)
			    data.exercices[eid].flags[fid].values = Array(data.exercices[eid].flags[fid].nb_lines);
			else
			    data.exercices[eid].flags[fid].values = [""];
		    });
		    angular.forEach(exercice.mcqs, function(mcq, mid) {
			if ($scope.my && $scope.my.exercices[eid] && $scope.my.exercices[eid].mcqs && $scope.my.exercices[eid].mcqs[mid] && $scope.my.exercices[eid].mcqs[mid].solved !== undefined)
			    data.exercices[eid].mcqs[mid].solved = $scope.my.exercices[eid].mcqs[mid].solved;
		    });
		});
		angular.forEach(data.exercices, function(exercice, eid) {
		    angular.forEach(exercice.mcqs, function(mcq, mid) {
			angular.forEach(mcq.choices, function(choice, cid) {
			    if (!(choice instanceof Object))
				this[cid] = {
				    label: choice,
				};

			    this[cid].disabled = mcq.solved || mcq.part_solved || (this[cid].justification && this[cid].justification.solved);

			    if (!this[cid].disabled)
				this[cid].value = $scope.my && $scope.my.exercices[eid] && $scope.my.exercices[eid].mcqs[mid] && $scope.my.exercices[eid].mcqs[mid].choices[cid] && $scope.my.exercices[eid].mcqs[mid].choices[cid].value

			    if (mcq.justify) {
				if (!this[cid].justification)
				    this[cid].justification = {};

				if (!this[cid].justification.label) {
				    this[cid].justification.label = "Flag correspondant";
				    this[cid].justification.help2 = "Trouvez et validez les choix du QCM pour avoir des indications supplémentaires";
				}

				if ($scope.my && $scope.my.exercices[eid] && $scope.my.exercices[eid].mcqs[mid] && $scope.my.exercices[eid].mcqs[mid].choices[cid] && $scope.my.exercices[eid].mcqs[mid].choices[cid].justification) {
				    if ($scope.my.exercices[eid].mcqs[mid].choices[cid].justification.value !== undefined)
					data.exercices[eid].mcqs[mid].choices[cid].justification.value = $scope.my.exercices[eid].mcqs[mid].choices[cid].justification.value;
				    if ($scope.my.exercices[eid].mcqs[mid].choices[cid].justification.values !== undefined)
					data.exercices[eid].mcqs[mid].choices[cid].justification.values = $scope.my.exercices[eid].mcqs[mid].choices[cid].justification.values;
				    else
					data.exercices[eid].mcqs[mid].choices[cid].justification.values = [""];
				}
				else
				    data.exercices[eid].mcqs[mid].choices[cid].justification.values = [""];
			    }
			}, mcq.choices);
		    });
		});
		$scope.my = data;
		angular.forEach($scope.my.exercices, function(exercice, eid) {
		    exercice.solved = exercice.solved_rank > 0;
		    if (exercice.video_uri) {
			exercice.video_uri = $sce.trustAsResourceUrl(exercice.video_uri);
		    }
		});
		actMenu();
	}

	$rootScope.refresh = function(justMy, justSettings) {
	    if (!justMy) {
		refreshSettings();
		refreshThemes();
		$rootScope.refreshTeams();
		refreshEvents();
		refreshIssues();
	    }
	    else if (justSettings) {
		refreshSettings();
	    }
	    refreshMy();
	}
        $rootScope.refreshIssues = refreshIssues;
	$rootScope.refresh();
    })
    .controller("ExerciceController", function($scope, $routeParams, $http, $rootScope, $timeout) {
	if (window.scrollY > 112)
	    window.scrollTo(window.scrollX, 112);

	$rootScope.current_tag = undefined;

	$scope.$watch("themesUrl", function(themesUrl) {
	    if (themesUrl != undefined)
		$rootScope.current_theme = themesUrl[$routeParams.theme];
	})

	if ($routeParams.exercice) {
	    $scope.$watch("exercicesUrl", function(exercicesUrl) {
		if (exercicesUrl != undefined)
		    $rootScope.current_exercice = exercicesUrl[$routeParams.theme + "/" + $routeParams.exercice];
	    })
	    $scope.$watchGroup(["themes", "current_theme", "current_exercice"], function(newValues) {
		var themes = newValues[0];
		var current_theme = newValues[1];
		var current_exercice = newValues[2];
		if (themes != undefined && themes[current_theme] != undefined && themes[current_theme].exercices != undefined && themes[current_theme].exercices[current_exercice] != undefined)
		    $rootScope.title = themes[current_theme].name + " > " + themes[current_theme].exercices[current_exercice].title;
	    });
	} else {
	    $rootScope.current_exercice = 0;
	    $scope.$watchGroup(["themes", "current_theme"], function(newValues) {
		var themes = newValues[0];
		var current_theme = newValues[1];
		if (themes != undefined && themes[current_theme] != undefined)
		    $rootScope.title = themes[current_theme].name;
	    });
	}

	var cbh;
	$scope.hsubmit = function(hint) {
	    hint.submitted = true;
	    $scope.hinterror = null;
	    $http({ url: "openhint/" + $rootScope.current_exercice, method: "POST", data: { id: hint.id } }).then(function(response) {
		var checkDiffHint = function() {
		    $http.get("my.json").then(function(response) {
			var my = response.data;
			angular.forEach(my.exercices[$rootScope.current_exercice].hints, function(h,hid){
			    if (hint.id == h.id) {
				if (hint.content != h.content) {
				    $rootScope.recvMy(my);
				} else {
				    if (cbh)
					$timeout.cancel(cbh);
				    cbh = $timeout(checkDiffHint, 750);
				}
			    }
			});
		    });
		};
		checkDiffHint();
	    }, function(response) {
		$scope.hinterror = response.data.errmsg;
		hint.submitted = false;
	    });
	};
    })
    .controller("SubmissionController", function($scope, $http, $rootScope, $timeout) {
	$scope.sberr = null;

	var cbs;
	var cbd;

	$scope.ssubmit = function() {
	    var resp = {}
	    var check = undefined
	    $scope.sberr = null;

	    if ($scope.my.exercices[$rootScope.current_exercice].flags && Object.keys($scope.my.exercices[$rootScope.current_exercice].flags).length)
	    {
		resp["flags"] = {};
		angular.forEach($scope.my.exercices[$rootScope.current_exercice].flags, function(flag,kid) {
		    if (check === undefined) check = true;

		    check &= treatFlagKey(flag) || flag.found;
		    if (flag.soluce === undefined) {
			check = undefined;
			if (flag.found == null) {
			    resp["flags"][kid] = flag.value;
			}
		    }
		});
	    }

	    if ($scope.my.exercices[$rootScope.current_exercice].mcqs && Object.keys($scope.my.exercices[$rootScope.current_exercice].mcqs).length)
	    {
		resp["mcqs"] = {};
		angular.forEach($scope.my.exercices[$rootScope.current_exercice].mcqs, function(mcq) {
		    var soluce = "";
		    if (mcq.solved == null) {
			angular.forEach(mcq.choices, function(choice, cid) {
			    if (mcq.soluce !== undefined) {
				if (check === undefined) check = true;

				soluce += choice.value ? "t" : "f";
			    } else {
				if (choice.value) {
				    resp["mcqs"][cid] = choice.value;
				    if (choice.justification !== undefined) {
					if (resp["justifications"] == undefined)
					    resp["justifications"] = {};
					treatFlagKey(choice.justification);
					resp["justifications"][cid] = choice.justification.value;
				    }
				}
			    }
			});
			if (mcq.soluce !== undefined) {
			    if (mcq.soluce == b2sum(soluce))
				mcq.solved = new Date();
			    check &= mcq.solved;
			}
		    }
		});
	    }

	    if (check !== undefined)
	    {
		if (!$scope.my.exercices[$rootScope.current_exercice].tries)
		    $scope.my.exercices[$rootScope.current_exercice].tries = 0;
		$scope.my.exercices[$rootScope.current_exercice].tries += 1;
		$scope.my.exercices[$rootScope.current_exercice].solved_time = new Date();

		if (check) {
		    $scope.my.exercices[$rootScope.current_exercice].solved = true;
		}
		return;
	    }

	    $http({ url: "submit/" + $rootScope.current_exercice, method: "POST", data: resp }).then(function(response) {
		$scope.messageClass = {"text-success": true};
		$scope.message = response.data.errmsg;
		$scope.sberr = null;

		angular.forEach($scope.flags, function(flag,kid) {
		    flag.value = "";
		});

		var checkDiff = function() {
		    $http.get("my.json").then(function(response) {
			var my = response.data;
			if ($scope.my.exercices[$rootScope.current_exercice].tries != my.exercices[$rootScope.current_exercice].tries || $scope.my.exercices[$rootScope.current_exercice].solved_time != my.exercices[$rootScope.current_exercice].solved_time) {
			    $scope.my.exercices[$rootScope.current_exercice].submitted = false;
			    $rootScope.recvMy(my);
			    $rootScope.refreshTeams();
			} else {
			    if (cbd)
				$timeout.cancel(cbd);
			    cbd = $timeout(checkDiff, 750);
			}
		    });
		};
		checkDiff();
	    }, function(response) {
		if (response.status >= 500) {
		    $scope.my.exercices[$rootScope.current_exercice].submitted = false;
		}
		$scope.messageClass = {"text-danger": true};
		$scope.sberr = "Oups !";
		$scope.message = response.data.errmsg;
	    });
	    $scope.my.exercices[$rootScope.current_exercice].timeouted = false;
	    $scope.my.exercices[$rootScope.current_exercice].submitted = true;
	};

	$scope.wantchoices = function(kid) {
	    $scope.my.exercices[$rootScope.current_exercice].flags[kid].wcsubmitted = true;
	    $http({ url: "wantchoices/" + $rootScope.current_exercice, method: "POST", data: { id: Math.floor(kid) } }).then(function(response) {
		var checkDiffWC = function() {
		    $http.get("my.json").then(function(response) {
			var my = response.data;
			if (my.exercices[$rootScope.current_exercice].flags[kid].choices)
			    $rootScope.recvMy(my);
			else {
			    if (cbd)
				$timeout.cancel(cbd);
			    cbd = $timeout(checkDiffWC, 750);
			}
		    });
		};
		checkDiffWC();
	    }, function(response) {
		$scope.messageClass = {"text-danger": true};
		$scope.sberr = "Oups !";
		$scope.message = response.data.errmsg;
		$scope.my.exercices[$rootScope.current_exercice].flags[kid].wcsubmitted = false;
	    });
	}
    })
    .controller("IssueController", function($scope, $http, $rootScope, $routeParams) {
      $rootScope.current_tag = undefined;
      $rootScope.current_exercice = $routeParams.eid;
      $rootScope.issues_known_responses = $rootScope.issues_nb_responses;

      $scope.issue = {
	id: parseInt($routeParams.iid, 10),
	id_exercice: parseInt($routeParams.eid, 10),
	subject: "",
	description: "",
      }

      $scope.isubmit = function() {
	$rootScope.sberr = "";
	if (!$scope.issue.id && $scope.issue.subject.length < 3) {
	  $rootScope.messageClass = {"text-danger": true};
	  $rootScope.sberr = "L'objet de votre rapport d'anomalie est trop court !";
	  return false;
	}

	$http({
	  url: "submit/issue",
	  method: "POST",
	  data: $scope.issue
	}).then(function(response) {
	  $rootScope.messageClass = {"text-success": true};
	  $rootScope.message = response.data.errmsg;
	  $scope.issue.subject = "";
	  $scope.issue.description = "";
	  setTimeout($rootScope.refreshIssues, 1750);
	}, function(response) {
	  $rootScope.messageClass = {"text-danger": true};
	  $rootScope.message = response.data.errmsg;
	  if (response.status != 402) {
	    $rootScope.sberr = "Une erreur est survenue lors de l'envoi. Veuillez réessayer dans quelques instants.";
	  }
	});
      };
    })
    .controller("MyTeamController", function($scope, $http, $rootScope, $timeout, $location) {
	$rootScope.current_theme = 0;
	$rootScope.current_exercice = 0;
	$rootScope.current_tag = undefined;
	if ($scope.my) {
	    $rootScope.title = $scope.my.name;
	    $rootScope.authors = $scope.my.members.map(function (cur) {
		return cur.firstname.capitalize() + " " + cur.lastname.capitalize();
	    }).join(", ");
	}
	$rootScope.message = "";
	$rootScope.sberr = "";

	$scope.notify = {
	    info: ($rootScope.notify_field & 1) != 1,
	    team: ($rootScope.notify_field & 2) != 2,
	    others: ($rootScope.notify_field & 4) != 4,
	    solve: ($rootScope.notify_field & 8) != 8,
	    hint: ($rootScope.notify_field & 16) != 16,
	    tries: ($rootScope.notify_field & 32) != 32,
	    rename: ($rootScope.notify_field & 64) != 64,
	}

	$scope.alternotify = function() {
	    $rootScope.notify_field =
		($scope.notify.info?0:1) |
		($scope.notify.team?0:2) |
		($scope.notify.others?0:4) |
		($scope.notify.solve?0:8) |
		($scope.notify.hint?0:16) |
		($scope.notify.tries?0:32) |
		($scope.notify.rename?0:64);
	    if ($rootScope.notify_field != 0)
		localStorage.notification = $rootScope.notify_field;
	    else
		delete localStorage.notification;
	    $location.url(".");
	}

	var cbt;

	$scope.tsubmit = function() {
	    $rootScope.sberr = "";
	    if ($scope.my.newName.length < 1) {
		$rootScope.messageClass = {"text-danger": true};
		$rootScope.sberr = "Nom d'équipe invalide: pas d'entrée.";
		return false;
	    }
	    else if ($scope.my.newName.length > 32) {
		$rootScope.messageClass = {"text-danger": true};
		$rootScope.sberr = "Nom d'équipe invalide: pas plus de 32 caractères.";
		return false;
	    }
	    else if (!$scope.my.newName.match(/^[A-Za-z0-9 àéèêëîïôùûü_-]+$/)) {
		$rootScope.messageClass = {"text-danger": true};
		$rootScope.sberr = "Nom d'équipe invalide: seuls les caractères alpha-numériques sont autorisés.";
		return false;
	    }

	    $http({
		url: "submit/name",
		method: "POST",
		data: {newName: $scope.my.newName}
	    }).then(function(response) {
		$rootScope.messageClass = {"text-success": true};
		$rootScope.message = response.data.errmsg;

		var checkDiff = function() {
		    $http.get("my.json").then(function(response) {
			if ($scope.my.name != response.data.name) {
			    $scope.my.newName = undefined;
			    $rootScope.message = "";
			    $rootScope.recvMy(response.data);
			    $rootScope.refreshTeams();
			} else {
			    if (cbt)
				$timeout.cancel(cbt);
			    cbt = $timeout(checkDiff, 750);
			}
		    });
		};
		checkDiff();
	    }, function(response) {
		$rootScope.messageClass = {"text-danger": true};
		$rootScope.message = response.data.errmsg;
		if (response.status != 402) {
		    $rootScope.sberr = "Une erreur est survenue lors de l'envoi. Veuillez réessayer dans quelques instants.";
		}
	    });
	};
    })
    .controller("RegisterController", function($scope, $rootScope, $location, $http, $interval) {
	$rootScope.current_theme = 0;
	$rootScope.current_exercice = 0;
	$rootScope.current_tag = undefined;
	$rootScope.title = "Bienvenue au challenge forensic !";
	$rootScope.authors = null;

	$scope.form = {"teamName": "", "jTeam": 0, "members": [{}]};

	$scope.AddMember = function() {
	    $scope.form.members.push({});
	}
	$scope.RemoveMember = function(k) {
	    $scope.form.members.splice(k, 1);
	}
	$scope.Validate = function() {
	    if ($scope.form.teamName.length <= 3) {
		$('#teamName').addClass("is-invalid")
		return;
	    } else {
		$('#teamName').removeClass("is-invalid")
		$('#vldBtn').removeClass("input-group-btn");
		$('#vldBtn').css("display", "none");
		$('#jvldBtn').css("display", "none");
		$scope.partR = true;
		$scope.partJ = false;
	    }
	}
	$scope.JValidate = function() {
	    if (!$scope.teams[$scope.form.jTeam]) {
		$('#jTeam').addClass("is-invalid")
		return;
	    } else {
		$('#jTeam').removeClass("is-invalid")
		$('#jvldBtn').removeClass("input-group-btn");
		$('#jvldBtn').css("display", "none");
		$('#vldBtn').css("display", "none");
		$scope.partR = false;
		$scope.partJ = true;
	    }
	}

	var commonsubmit = function(registration) {
	    // Remove empty members
	    $scope.form.members = $scope.form.members.filter(function(m) {
		return ((m.lastname != undefined && m.lastname != "") || (m.firstname != undefined && m.firstname != "") || (m.nickname != undefined && m.nickname != ""));
	    });

	    if ($scope.form.members.length == 0) {
		$scope.messageClass = {"text-danger": true};
		$scope.message = "Veuillez ajouter au moins un membre dans votre équipe !";

		$scope.form.members.push({});
		return;
	    }

	    $scope.form.jTeam = parseInt($scope.form.jTeam);

	    $http({
		url: "registration",
		method: "POST",
		data: $scope.form
	    }).then(function(response) {
		$scope.messageClass = {"text-success": true};
		$scope.message = response.data.errmsg;

		$interval(function(){
		    $http.get("my.json").then(function(response) {
			$rootScope.refresh();
		    });
		}, 1500);

	    }, function(response) {
		$scope.messageClass = {"text-danger": true};
		if (response.data && response.data.errmsg)
		    $scope.message = response.data.errmsg;
		else
		    $scope.message = "Une erreur est survenue lors de l'inscription de l'équipe. Veuillez réessayer dans quelques instants.";
	    });
	}

	$scope.rsubmit = function() {
	    if (!$scope.partR)
		return $scope.Validate();
	    else
		return commonsubmit(true);
	}

	$scope.jsubmit = function() {
	    if (!$scope.partJ)
		return $scope.JValidate();
	    else
		return commonsubmit(false);
	}

	$scope.$watch("my", function(my){
	    if (my)
		$location.url(".");
	});
    })
    .controller("TagController", function($scope, $rootScope, $routeParams, $location) {
	$rootScope.current_theme = 0;
	$rootScope.current_exercice = 0;
	$rootScope.current_tag = $routeParams.tag;
	$rootScope.title = "Challenges " + $routeParams.tag;
	$rootScope.authors = "";

	$scope.tag = $routeParams.tag;
	$scope.exercices = [];

	$scope.$watch("themes", function(themes) {
	    $scope.exercices = [];
	    angular.forEach(themes, function(theme, tid) {
		angular.forEach(theme.exercices, function(exercice, eid) {
		    if (exercice.tags.indexOf($scope.tag) >= 0)
			$scope.exercices.push({"exercice": exercice, "theme": theme, "eid": eid, "tid": tid});
		})
	    })
	})

	$scope.goDefi = function() {
	    $location.url(this.ex.theme.urlid + "/" + this.ex.exercice.urlid);
	}

    })
    .controller("RankController", function($scope, $rootScope) {
	$rootScope.current_theme = 0;
	$rootScope.current_exercice = 0;
	$rootScope.current_tag = undefined;
	$rootScope.title = "Classement général";
	$rootScope.authors = "";

	$scope.fields = ["rank", "name", "score"];
	$scope.rankOrder = "rank";
	$scope.reverse = false;
	$scope.order = function(fld) {
	    if ($scope.rankOrder == fld) {
		$scope.reverse = !$scope.reverse;
	    } else {
		$scope.rankOrder = fld;
		$scope.reverse = (fld == "score");
	    }
	};
    })
    .controller("VideosController", function($scope, $rootScope) {
	$rootScope.current_theme = 0;
	$rootScope.current_exercice = 0;
	$rootScope.current_tag = undefined;
	$rootScope.title = "Vidéos de résolution";
	$rootScope.authors = "";
    })
    .controller("HomeController", function($scope, $rootScope, $location) {
	$rootScope.current_theme = 0;
	$rootScope.current_exercice = 0;
	$rootScope.current_tag = undefined;
	$rootScope.title = "Bienvenue au challenge forensic de l'ÉPITA !";
	$rootScope.authors = "";

	$scope.goTheme = function() {
	    $location.url(this.theme.urlid);
	}
    });

function sready() {
    if ($("#solution").val().length) {
	$("#sbmt").removeClass("disabled");
    } else {
	$("#sbmt").addClass("disabled");
    }
};
