/*jshint sub:true, eqnull:true, browser:true */
/*global URI:true, cookie:true */
//
// Language switching controls
//

//= require twitch/api

(function (Twitch, $) {

  var language = {};

  language.setCookieAndReload = function (language) {
    var previousLanguage = cookie.get('language') || 'en',
        successfullyWroteToCookie;
    Twitch.language.setCookie(language);
    successfullyWroteToCookie = !!cookie.get('language');
    if (previousLanguage !== language && successfullyWroteToCookie) {
      location.reload();
    }
  };

  language.setCookie = function (lang) {
    /** 10 year expiration */
    cookie.set('language', lang, {domain: '.' + document.domain, expires: 10 * 365});
  };

  language.setByAsyncPut = function (lang) {
    if (Twitch.user.isLoggedIn()) {
      return Twitch.api.put('/api/users/' + Twitch.user.login() + '/language', {lang: lang});
    }
  };

  Twitch.mixin({
    language: language
  });

})(Twitch, jQuery);
