Skip to content

Instantly share code, notes, and snippets.

@cwtuan
Created September 22, 2014 12:29
Show Gist options
  • Select an option

  • Save cwtuan/938a068dcf65c523d40b to your computer and use it in GitHub Desktop.

Select an option

Save cwtuan/938a068dcf65c523d40b to your computer and use it in GitHub Desktop.
/**
* Locale.js 1.0 is a client side Javascript Localization library.
* Author: Chia-Wei Tuan (linkedin.com/in/cwtuan)
* Github: https://github.com/cwtuan/Locale.js
* Demo: http://opensource.tonytuan.org/locale.js/
* License: Apache License
* Build: Mon, 22 Sep 2014 12:07:30 GMT
*/
var Locale=function(){"use strict";function n(n){this.langUrls=n}function t(n){var t,e;if(this.map[n]){if(t=[],1==arguments.length)return this.map[n];for(e=1;e<arguments.length;e++)t.push(arguments[e]);return this.map[n].replace(/\{(\d+)\}/g,function(n,e){return t[e]})}return n+".UNDEFINED"}function e(n){this.currentLang=n}function r(){var n=this.currentLang||d(location.search,"lang")||c("lang")||f();return p(n)}function a(n){l("lang",n)}function o(n){return null!==this.map[n]}function i(){s.call(this,!1)}function u(n){s.call(this,!0,n)}function s(n,t){var e,a,o,i,u,s,l,c,g,f=this;for(this.map={},this.langUrls||console.error("You should call setLanguageUrls() before loading lagnuage file."),e=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),e.onreadystatechange=function(){if(4==e.readyState&&200==e.status){for(a=e.responseText.split(/\r\n|\r|\n/g),o=0;o<a.length;++o)i=a[o].indexOf("="),u=a[o].substr(0,i),s=a[o].substr(i+1),u&&s&&(s=s.replace(/\r/g,"").replace(/\n/g,""),f.map[u]=s);n&&t()}},l=r.call(this),o=0,g=this.langUrls.length;g>o;o++)if(-1!==this.langUrls[o].indexOf(l)){c=this.langUrls[o];break}c=c||f.langUrls[0],e.open("GET",c+"?"+h(),n),e.send()}function l(n,t){document.cookie=n+"="+encodeURIComponent(t)}function c(n){for(var t,e=n+"=",r=0,a=0;r<document.cookie.length;){if(a=r+e.length,document.cookie.substring(r,a)===e)return g.call(this,a);if(t=document.cookie.indexOf(" ",r),-1===t)return null;r=1+t}return null}function g(n){var t=document.cookie.indexOf(";",n);return-1==t&&(t=document.cookie.length),encodeURIComponent(document.cookie.substring(n,t))}function f(){return navigator.language||navigator.browserLanguage||navigator.userLanguage}function h(){return"_rand="+(new Date).getTime()}function p(n){return n=n.split("_"),1==n.length&&(n=n[0].split("-")),n[0].toLowerCase()+"_"+n[1].toUpperCase()}function d(n,t){var e,r,a;if(n=location.search.split("?")[1],n&&(e=n.split("&")))for(r=0;r<e.length;++r)if(a=e[r].split("="),a[0]===t)return a[1];return null}var m={setLanguageUrls:n,getMsg:t,setCurrentLanguage:e,saveLanguage:a,getCurrentLanguage:r,hasKey:o,loadSync:i,loadAsync:u};return m}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment