define([
    'jquery',
    'msg/Msg',
    'unifi/service/location/locationService',
    'ubnt/ubnt.utils',
    'libs/jquery.cookie',
    //non-exporting
    'foundation'
], function (
    $,
    Msg,
    locationService
) {
    'use strict';
    $(function () {
        $(document).foundation();

        var $loginForm = $('#LoginForm'),
            $errorMessage = $('.error-message'),
            querystring = $.parse_qs(),
            $loginButton = $('#LoginButton');

        $loginButton.click(function(e) {
            e.preventDefault();
            locationService.gotoLoginPage();
        });

        $.ajax({
            url: '/api/verify',
            type: 'POST',
            data: JSON.stringify({
                token: querystring.t,
                email: querystring.email
            }),
            success: function(data, textStatus, xhr) {
                $errorMessage.hide();

                $.get('/api/self', {}, function(data) {
                    locationService.gotoManagePage(data.last_site_name);
                });
            },
            error: function(xhr, textStatus, errorThrown) {
                var response = $.parseJSON(xhr.responseText),
                    error_msg;

                if(response.meta && response.meta.msg) {
                    error_msg = response.meta.msg;

                    if(error_msg === 'api.err.BetaQuotaReached') {
                        error_msg = Msg.E_BetaQuotaReached;
                    }

                    if(error_msg === 'api.err.InvalidVerification') {
                        error_msg = Msg.E_InvalidVerification;
                    }

                    $errorMessage.text(error_msg);
                    $errorMessage.show();
                }
            }
        });
    });
});
