//app

app = angular.module('applicationApp', ['vcRecaptcha']);

//tokens

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}]);

//helpers

function notyfication(type,timeout){
    return function(msg){
        noty({ 
            'text': msg,
            'layout': "bottomRight",
            'type': type,
            'timeout': timeout
        });
    };
}
var notyError = notyfication('error',2500);
var notySuccess = notyfication('success',2500);

//controllers

app.controller("applicationController", function($scope, $http, $location, $window, vcRecaptchaService) {
	$scope.member = {};
    $scope.response = null;
    $scope.widgetId = null;
    $scope.model = {
        key: "6LevHAcUAAAAAA45B7c-7qja-2aSwHztr9xb4K2Z"
    };
    $scope.setResponse = function(response) {
        $scope.response = response;
    };
    $scope.setWidgetId = function(widgetId) {
        $scope.widgetId = widgetId;
    };
    $scope.cbExpiration = function() {
        vcRecaptchaService.reload($scope.widgetId);
        $scope.response = null;
    };
	$scope.send = function() {
		var valid;
        //server side validation
        $scope.member.reCaptchaResponse = vcRecaptchaService.getResponse()
        console.log($scope.member.reCaptchaResponse);
	if($scope.member.reCaptchaResponse === "") {
            notyError("Ole hyvä ja täytä kuvavarmennus");
        } else {
            $http.post("/members/api/request", $scope.member).then(function(data){
                notySuccess("Hakemus lähetetty!");
                $window.location.href = "/application/success";
            }, function(data){
                notyError("Jokin meni vikaan. Yritä uudelleen.");
                vcRecaptchaService.reload($scope.widgetId);
            });
        }
	}
});
