// Generated by CoffeeScript 1.10.0

/*
LemonLDAP::NG Portal jQuery scripts
 */

(function() {
  var datas, getCookie, getOrder, getValues, isHiddenFormValueSet, ping, restoreOrder, setCookie, setSelector, translate, translatePage, translationFields,
    indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

  translationFields = {};

  translatePage = function(lang) {
    return $.getJSON(window.staticPrefix + "languages/" + lang + ".json", function(data) {
      translationFields = data;
      $("[trspan]").each(function() {
        var args, i, len, txt, v;
        args = $(this).attr('trspan').split(',');
        txt = translate(args.shift());
        for (i = 0, len = args.length; i < len; i++) {
          v = args[i];
          txt = txt.replace(/%[sd]/, v);
        }
        return $(this).text(txt);
      });
      $("[trmsg]").each(function() {
        return $(this).text(translate("PE" + ($(this).attr('trmsg'))));
      });
      $("[trplaceholder]").each(function() {
        return $(this).attr('placeholder', translate($(this).attr('trplaceholder')));
      });
      return $("[localtime]").each(function() {
        var d;
        d = new Date($(this).attr('localtime') * 1000);
        return $(this).text(d.toLocaleString());
      });
    });
  };

  translate = function(str) {
    if (translationFields[str]) {
      return translationFields[str];
    } else {
      return str;
    }
  };

  window.translate = translate;

  getValues = function() {
    var values;
    values = {};
    $("script[type='application/init']").each(function() {
      var e, error, k, results, tmp;
      try {
        tmp = JSON.parse($(this).text());
        results = [];
        for (k in tmp) {
          results.push(values[k] = tmp[k]);
        }
        return results;
      } catch (error) {
        e = error;
        console.log('Parsing error', e);
        return console.log('JSON', $(this).text());
      }
    });
    return values;
  };

  setSelector = "#appslist";

  getOrder = function() {
    return $.ajax({
      type: "PUT",
      url: datas['scriptname'] + '/mysession/persistent',
      data: {
        _appsListOrder: $(setSelector).sortable("toArray").join()
      },
      dataType: 'json'
    });
  };

  restoreOrder = function() {
    var IDs, child, i, item, itemID, items, l, len, len1, list, rebuild, savedOrd, v;
    list = $(setSelector);
    if (!((list != null) && datas['appslistorder'])) {
      return null;
    }
    IDs = datas['appslistorder'].split(',');
    items = list.sortable("toArray");
    rebuild = [];
    for (i = 0, len = items.length; i < len; i++) {
      v = items[i];
      rebuild[v] = v;
    }
    for (l = 0, len1 = IDs.length; l < len1; l++) {
      itemID = IDs[l];
      if (indexOf.call(rebuild, itemID) >= 0) {
        item = rebuild[itemID];
        child = $(setSelector + ".ui-sortable").children("#" + item);
        savedOrd = $(setSelector + ".ui-sortable").children("#" + itemID);
        child.remove();
        $(setSelector + ".ui-sortable").filter(":first").append(savedOrd);
      }
    }
    return 1;
  };

  isHiddenFormValueSet = function(option) {
    return $('#lmhidden_' + option).length;
  };

  ping = function() {
    return $.ajax({
      type: "POST",
      url: datas['scriptname'],
      data: {
        ping: 1
      },
      dataType: 'json',
      success: function(data) {
        if ((data.result != null) && data.result === 1) {
          return setTimeout(ping, datas['pingInterval']);
        } else {
          return location.reload(true);
        }
      },
      error: function(j, t, e) {
        return location.reload(true);
      }
    });
  };

  window.ping = ping;

  getCookie = function(cname) {
    var c, ca, i, len, name, re;
    name = cname + "=";
    ca = decodeURIComponent(document.cookie).split(';');
    re = new RegExp('^ *' + cname + '=');
    for (i = 0, len = ca.length; i < len; i++) {
      c = ca[i];
      if (c.match(re)) {
        c = c.replace(re, '');
        return c;
      }
    }
    return '';
  };

  setCookie = function(name, value, exdays) {
    var d;
    d = new Date();
    d.setTime(d.getTime() + exdays * 86400000);
    return document.cookie = name + "=" + value + "; expires=" + (d.toUTCString()) + "; path=/";
  };

  datas = {};

  $(document).ready(function() {
    var action, al, authMenuTabs, back_url, i, l, lang, langdiv, langs, langs2, len, len1, len2, link, m, menuIndex, menuTabs, method, nl, nlangs, ref, ref1;
    datas = getValues();
    window.datas = datas;
    if (datas['antiframe'] && top !== self) {
      top.location.href = location.href;
    }
    $("#appslist").sortable({
      axis: "y",
      cursor: "move",
      opacity: 0.5,
      revert: true,
      items: "> div.category",
      update: function() {
        return getOrder();
      }
    });
    restoreOrder();
    $("div.message").fadeIn('slow');
    $("input[name=timezone]").val(-(new Date().getTimezoneOffset() / 60));
    menuTabs = $("#menu").tabs({
      active: 0
    });
    menuIndex = $('#menu a[href="#' + datas['displaytab'] + '"]').parent().index();
    if (menuIndex < 0) {
      menuIndex = 0;
    }
    menuTabs.tabs("option", "active", menuIndex);
    authMenuTabs = $("#authMenu").tabs({
      active: 0
    });
    if (datas['choicetab']) {
      authMenuTabs.tabs("option", "active", $('#authMenu a[href="#' + datas['choicetab'] + '"]').parent().index());
    }
    if (datas['login']) {
      $("input[type=password]:first").focus();
    } else {
      $("input[type!=hidden]:first").focus();
    }
    if (datas['newwindow']) {
      $('#appslist a').attr("target", "_blank");
    }
    if ($("p.removeOther").length) {
      action = $("form.login").attr("action");
      method = $("form.login").attr("method");
      back_url = "";
      if (action.indexOf("?") !== -1) {
        action.substring(0, action.indexOf("?")) + "?";
      } else {
        back_url = action + "?";
      }
      $("form.login input[type=hidden]").each(function(index) {
        return back_url += "&" + $(this).attr("name") + "=" + $(this).val();
      });
      link = $("p.removeOther a").attr("href") + "&method=" + method + "&url=" + btoa(back_url);
      $("p.removeOther a").attr("href", link);
    }
    lang = getCookie('llnglanguage');
    if (!lang) {
      if (navigator) {
        langs = [];
        langs2 = [];
        nlangs = [navigator.language];
        if (navigator.languages) {
          nlangs = navigator.languages;
        }
        ref = window.availableLanguages;
        for (i = 0, len = ref.length; i < len; i++) {
          al = ref[i];
          langdiv += "<img class=\"langicon\" src=\"" + window.staticPrefix + "common/" + al + ".png\" title=\"" + al + "\" alt=\"[" + al + "]\"> ";
          for (l = 0, len1 = nlangs.length; l < len1; l++) {
            nl = nlangs[l];
            if (al === nl) {
              langs.push(al);
            } else if (al.substring(0, 1) === nl.substring(0, 1)) {
              langs2.push(al);
            }
          }
        }
        lang = langs[0] ? langs[0] : langs2[0] ? langs2[0] : window.availableLanguages[0];
      } else {
        lang = window.availableLanguages[0];
      }
    } else if (indexOf.call(window.availableLanguages, lang) < 0) {
      lang = window.availableLanguages[0];
    }
    setCookie('llnglanguage', lang);
    translatePage(lang);
    langdiv = '';
    ref1 = window.availableLanguages;
    for (m = 0, len2 = ref1.length; m < len2; m++) {
      al = ref1[m];
      langdiv += "<img class=\"langicon\" src=\"" + window.staticPrefix + "common/" + al + ".png\" title=\"" + al + "\" alt=\"[" + al + "]\"> ";
    }
    $('#languages').html(langdiv);
    $('.langicon').on('click', function() {
      lang = $(this).attr('title');
      setCookie('llnglanguage', lang);
      return translatePage(lang);
    });
    if (datas['pingInterval'] && datas['pingInterval'] > 0) {
      window.setTimeout(ping, datas['pingInterval']);
    }
    return $(".localeDate").each(function() {
      var s;
      s = new Date($(this).attr("val") * 1000);
      return $(this).text(s.toLocaleString());
    });
  });

}).call(this);
