$translations = {
  en: {
    models: <%= I18n.t('activemodel.models', locale: :en).to_json %>,
    attributes: <%= I18n.t('activemodel.attributes', locale: :en).to_json %>,
    helpers: <%= I18n.t('helpers', locale: :en).to_json %>,
    pagination: <%= I18n.t('views.pagination', locale: :en).to_json %>,
  },
  nl: {
    models: <%= I18n.t('activemodel.models', locale: :nl).to_json %>,
    attributes: <%= I18n.t('activemodel.attributes', locale: :nl).to_json %>,
    helpers: <%= I18n.t('helpers', locale: :nl).to_json %>,
    pagination: <%= I18n.t('views.pagination', locale: :nl).to_json %>,
  }
}

$transformation_mappings = {
  downcase: 'toLowerCase',
  upcase: 'toUpperCase'
}

function t(path, vars){
  vars || (vars = {});
  var result, m, translatable, isafety,replacable;
  var parts = path.split('.');
  var accessor = '$translations.'+$locale+'["' + parts.join('"]["')+ '"]';
  try{ 
    result = eval(accessor);
  } catch(err){ 
    result = parts[parts.length - 1].capitalize();
  }
  if(result == '') return '';
  if(!result) return parts[parts.length - 1].capitalize(); 
  $.each(vars, function(v, value){ result = result.replace('%{'+v+'}', value)});
  isafety = 0;
  while(result.indexOf('${') > -1){
    m = result.match(/\${([\w\.]+(\|\w+)?)}/);
    if(m[2]){
      translatable = m[1].replace(m[2], '');
      operation = $transformation_mappings[m[2].substr(1) || m[2].substr(1)];
    }else{
      translatable = m[1];
      operation = null;
    }
    replacable = t(translatable);
    if(operation) replacable = replacable[operation]();
    result = result.replace(m[0], replacable);
    if(isafety > 10) break;
    isafety += 1;
  }
  return result;
}
function setLocale(locale){
  Qstorage.setItem('locale', locale);
  $locale = locale;
  setTranslations();
}
function setTranslations(selector){
  var list = $('#top-navigation-list');
  list.find('.locale').show();
  list.find('.locale-'+$locale).hide();
  moment.lang($locale);
  if(selector){
    $(selector).find('[data-t]').each(function(){$(this).html(t($(this).data('t'), $(this).data('tAttributes')))})
    $(selector).find('*[data-time]').each(function(){
      $(this).text(moment($(this).data('time')).format($(this).data('timeFormat') || 'dd D MMM HH:MM'))
    })
  }else{
    $('[data-t]').each(function(){$(this).html(t($(this).data('t'),$(this).data('tAttributes')))})
    $('*[data-time]').each(function(){
      $(this).text(moment($(this).data('time')).format($(this).data('timeFormat') || 'dd D MMM HH:MM'))
    })
  }
  $('.datepicker').datepicker("option", $.datepicker.regional[$locale])
}
