/**
 * @author "Trevor Parscal" <trevorparscal@gmail.com>
 * @license CC0 1.0 Universal - http://creativecommons.org/publicdomain/zero/1.0
 */
// TODO: Perhaps only show these icons when at an actual MediaWiki-powered site?
jetpack.statusBar.append({
  html: '<img rel="en"><img rel="de"><img rel="ja">',
  width: 78, // 3 x 16px wide icons each with 5px margins
  onReady: function(doc) {
    $(doc).find('img')
      .each(function() {
        // Set image sources relative to the script
        $(this).attr( 'src',
          location.replace(/[a-z\-]+\.js$/gi, $(this).attr('rel') + '.png')
        );
      })
      .css({ 'margin': '5px', 'cursor': 'pointer' })
      .click(function() {
        var lang = $(this).attr('rel');
        var url = String(jetpack.tabs.focused.contentWindow.location);
        if (url.indexOf('?') >= 0) {
          // Modify uselang parameter of URL
          url = url.indexOf('uselang=') >= 0 ?
            url.replace(/uselang=[^&#]*/gi, 'uselang=' + lang) :
            url = url.replace('?','?uselang=' + lang + '&');
        } else {
          // Add uselang parameter to URL
          url = url.indexOf('#') >= 0 ?
            url = url.replace('#','?uselang=' + lang + '#') :
            url += '?uselang=' + lang;
        }
        jetpack.tabs.focused.contentWindow.location = url;
      });
  }
});
