// Generated by CoffeeScript 1.12.8

/*
LemonLDAP::NG Portal jQuery scripts
 */

(function() {
  var datas, delKey, getCookie, getQueryParam, getValues, isHiddenFormValueSet, ping, removeOidcConsent, restoreOrder, setCookie, setKey, setOrder, 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) {
      var k, ref, ref1, v;
      translationFields = data;
      ref = window.datas.trOver.all;
      for (k in ref) {
        v = ref[k];
        translationFields[k] = v;
      }
      if (window.datas.trOver[lang]) {
        ref1 = window.datas.trOver[lang];
        for (k in ref1) {
          v = ref1[k];
          translationFields[k] = v;
        }
      }
      $("[trspan]").each(function() {
        var args, l, len1, txt;
        args = $(this).attr('trspan').split(',');
        txt = translate(args.shift());
        for (l = 0, len1 = args.length; l < len1; l++) {
          v = args[l];
          txt = txt.replace(/%[sd]/, v);
        }
        return $(this).html(txt);
      });
      $("[trmsg]").each(function() {
        var msg;
        $(this).html(translate("PE" + ($(this).attr('trmsg'))));
        msg = translate("PE" + ($(this).attr('trmsg')));
        if (msg.match(/_hide_/)) {
          return $(this).parent().hide();
        }
      });
      $("[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, k, results, tmp;
      try {
        tmp = JSON.parse($(this).text());
        results = [];
        for (k in tmp) {
          results.push(values[k] = tmp[k]);
        }
        return results;
      } catch (error1) {
        e = error1;
        console.log('Parsing error', e);
        return console.log('JSON', $(this).text());
      }
    });
    console.log(values);
    return values;
  };

  getQueryParam = function(name) {
    var match;
    match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    if (match) {
      return decodeURIComponent(match[1].replace(/\+/g, ' '));
    } else {
      return null;
    }
  };

  setSelector = "#appslist";

  setOrder = function() {
    return setKey('_appsListOrder', $(setSelector).sortable("toArray").join());
  };

  removeOidcConsent = function(partner) {
    var e;
    e = function(j, s, e) {
      return alert(s + " " + e);
    };
    return delKey("_oidcConsents", partner, function() {
      return $("[partner='" + partner + "']").hide();
    }, e);
  };

  setKey = function(key, val, success, error) {
    return $.ajax({
      type: "GET",
      url: datas['scriptname'] + '/mysession/?gettoken',
      dataType: 'json',
      error: error,
      success: function(data) {
        var d;
        d = {
          token: data.token
        };
        d[key] = val;
        return $.ajax({
          type: "PUT",
          url: datas['scriptname'] + '/mysession/persistent',
          dataType: 'json',
          data: d,
          success: success,
          error: error
        });
      }
    });
  };

  delKey = function(key, sub, success, error) {
    return $.ajax({
      type: "GET",
      url: datas['scriptname'] + '/mysession/?gettoken',
      dataType: 'json',
      error: error,
      success: function(data) {
        return $.ajax({
          type: "DELETE",
          url: datas['scriptname'] + "/mysession/persistent/" + key + "?sub=" + sub + "&token=" + data.token,
          dataType: 'json',
          success: success,
          error: error
        });
      }
    });
  };

  restoreOrder = function() {
    var IDs, child, item, itemID, items, l, len1, len2, list, m, rebuild, savedOrd, v;
    list = $(setSelector);
    if (!((list != null) && datas['appslistorder'])) {
      return null;
    }
    IDs = datas['appslistorder'].split(',');
    items = list.sortable("toArray");
    rebuild = [];
    for (l = 0, len1 = items.length; l < len1; l++) {
      v = items[l];
      rebuild[v] = v;
    }
    for (m = 0, len2 = IDs.length; m < len2; m++) {
      itemID = IDs[m];
      if (rebuild[itemID]) {
        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, l, len1, name, re;
    name = cname + "=";
    ca = decodeURIComponent(document.cookie).split(';');
    re = new RegExp('^ *' + cname + '=');
    for (l = 0, len1 = ca.length; l < len1; l++) {
      c = ca[l];
      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 = {};

  $(window).on('load', function() {
    var action, al, authMenuIndex, authMenuTabs, back_url, checkpassword, checksamepass, hiddenParams, isAlphaNumeric, l, lang, langdiv, langs, langs2, len1, len2, len3, len4, link, m, menuIndex, menuTabs, method, n, nl, nlangs, o, queryLang, re, ref, ref1, ref2, setCookieLang, togglecheckpassword;
    datas = getValues();
    if ("datas" in window && "choicetab" in window.datas) {
      datas.choicetab = window.datas.choicetab;
    }
    window.datas = datas;
    $("#appslist").sortable({
      axis: "y",
      cursor: "move",
      opacity: 0.5,
      revert: true,
      items: "> div.category",
      update: function() {
        return setOrder();
      }
    });
    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
    });
    authMenuIndex = $('#authMenu a[href="#' + datas['displaytab'] + '"]').parent().index();
    if (authMenuIndex < 0) {
      authMenuIndex = 0;
    }
    authMenuTabs.tabs("option", "active", authMenuIndex);
    if (datas['choicetab']) {
      authMenuTabs.tabs("option", "active", $('#authMenu a[href="#' + datas['choicetab'] + '"]').parent().index());
    }
    if (datas['login']) {
      $("input[type=password]:first").focus();
    } else {
      if ($("input[autofocus]").length === 0) {
        $("input[type!=hidden]:first").focus();
      }
    }
    if (datas['newwindow']) {
      $('#appslist a').attr("target", "_blank");
    }
    if ($("p.removeOther").length) {
      action = $("#form").attr("action");
      method = $("#form").attr("method");
      console.log('method=', method);
      hiddenParams = "";
      if ($("#form input[type=hidden]")) {
        console.log('Parse hidden values');
        $("#form input[type=hidden]").each(function(index) {
          console.log(' ->', $(this).attr("name"), $(this).val());
          return hiddenParams += "&" + $(this).attr("name") + "=" + $(this).val();
        });
      }
      back_url = "";
      if (action) {
        console.log('action=', action);
        if (action.indexOf("?") !== -1) {
          action.substring(0, action.indexOf("?")) + "?";
        } else {
          back_url = action + "?";
        }
        back_url += hiddenParams;
        hiddenParams = "";
      }
      link = $("p.removeOther a").attr("href") + "&method=" + method + hiddenParams;
      if (back_url) {
        link += "&url=" + btoa(back_url);
      }
      $("p.removeOther a").attr("href", link);
    }
    if (window.location.search) {
      queryLang = getQueryParam('llnglanguage');
      if (queryLang) {
        console.log('Get lang from parameter');
      }
      setCookieLang = getQueryParam('setCookieLang');
      if (setCookieLang === 1) {
        console.log('Set lang cookie');
      }
    }
    if (!lang) {
      lang = getCookie('llnglanguage');
      if (lang && !queryLang) {
        console.log('Get lang from cookie');
      }
    }
    if (!lang) {
      if (navigator) {
        langs = [];
        langs2 = [];
        nlangs = [navigator.language];
        if (navigator.languages) {
          nlangs = navigator.languages;
        }
        ref = window.availableLanguages;
        for (l = 0, len1 = ref.length; l < len1; l++) {
          al = ref[l];
          langdiv += "<img class=\"langicon\" src=\"" + window.staticPrefix + "common/" + al + ".png\" title=\"" + al + "\" alt=\"[" + al + "]\"> ";
        }
        for (m = 0, len2 = nlangs.length; m < len2; m++) {
          nl = nlangs[m];
          console.log('Navigator lang', nl);
          ref1 = window.availableLanguages;
          for (n = 0, len3 = ref1.length; n < len3; n++) {
            al = ref1[n];
            console.log(' Available lang', al);
            re = new RegExp('^' + al + '-?');
            if (nl.match(re)) {
              console.log('  Matching lang =', al);
              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];
        if (lang && !queryLang) {
          console.log('Get lang from navigator');
        }
      } else {
        lang = window.availableLanguages[0];
        if (lang && !queryLang) {
          console.log('Get lang from window');
        }
      }
    } else if (indexOf.call(window.availableLanguages, lang) < 0) {
      lang = window.availableLanguages[0];
      if (!queryLang) {
        console.log('Lang not available -> Get default lang');
      }
    }
    if (queryLang) {
      if (indexOf.call(window.availableLanguages, queryLang) < 0) {
        console.log('Lang not available -> Get default lang');
        queryLang = window.availableLanguages[0];
      }
      console.log('Selected lang ->', queryLang);
      if (setCookieLang) {
        console.log('Set cookie lang ->', queryLang);
        setCookie('llnglanguage', queryLang);
      }
      translatePage(queryLang);
    } else {
      console.log('Selected lang ->', lang);
      setCookie('llnglanguage', lang);
      translatePage(lang);
    }
    langdiv = '';
    ref2 = window.availableLanguages;
    for (o = 0, len4 = ref2.length; o < len4; o++) {
      al = ref2[o];
      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);
    });
    isAlphaNumeric = function(chr) {
      var code;
      code = chr.charCodeAt(0);
      if (code > 47 && code < 58 || code > 64 && code < 91 || code > 96 && code < 123) {
        return true;
      }
      return false;
    };
    checkpassword = function(password) {
      var digit, hasforbidden, i, len, lower, nonwhitespechar, numspechar, ref3, ref4, result, upper;
      result = true;
      if (window.datas.ppolicy.minsize > 0) {
        if (password.length >= window.datas.ppolicy.minsize) {
          $('#ppolicy-minsize-feedback').addClass('fa-check text-success');
          $('#ppolicy-minsize-feedback').removeClass('fa-times text-danger');
        } else {
          $('#ppolicy-minsize-feedback').removeClass('fa-check text-success');
          $('#ppolicy-minsize-feedback').addClass('fa-times text-danger');
          result = false;
        }
      }
      if (window.datas.ppolicy.minupper > 0) {
        upper = password.match(/[A-Z]/g);
        if (upper && upper.length >= window.datas.ppolicy.minupper) {
          $('#ppolicy-minupper-feedback').addClass('fa-check text-success');
          $('#ppolicy-minupper-feedback').removeClass('fa-times text-danger');
        } else {
          $('#ppolicy-minupper-feedback').removeClass('fa-check text-success');
          $('#ppolicy-minupper-feedback').addClass('fa-times text-danger');
          result = false;
        }
      }
      if (window.datas.ppolicy.minlower > 0) {
        lower = password.match(/[a-z]/g);
        if (lower && lower.length >= window.datas.ppolicy.minlower) {
          $('#ppolicy-minlower-feedback').addClass('fa-check text-success');
          $('#ppolicy-minlower-feedback').removeClass('fa-times text-danger');
        } else {
          $('#ppolicy-minlower-feedback').removeClass('fa-check text-success');
          $('#ppolicy-minlower-feedback').addClass('fa-times text-danger');
          result = false;
        }
      }
      if (window.datas.ppolicy.mindigit > 0) {
        digit = password.match(/[0-9]/g);
        if (digit && digit.length >= window.datas.ppolicy.mindigit) {
          $('#ppolicy-mindigit-feedback').addClass('fa-check text-success');
          $('#ppolicy-mindigit-feedback').removeClass('fa-times text-danger');
        } else {
          $('#ppolicy-mindigit-feedback').removeClass('fa-check text-success');
          $('#ppolicy-mindigit-feedback').addClass('fa-times text-danger');
          result = false;
        }
      }
      if (window.datas.ppolicy.allowedspechar) {
        nonwhitespechar = window.datas.ppolicy.allowedspechar.replace(/\s/g, '');
        hasforbidden = false;
        i = 0;
        len = password.length;
        while (i < len) {
          if (!isAlphaNumeric(password.charAt(i))) {
            if (nonwhitespechar.indexOf(password.charAt(i)) < 0) {
              hasforbidden = true;
            }
          }
          i++;
        }
        if (hasforbidden === false) {
          $('#ppolicy-allowedspechar-feedback').addClass('fa-check text-success');
          $('#ppolicy-allowedspechar-feedback').removeClass('fa-times text-danger');
        } else {
          $('#ppolicy-allowedspechar-feedback').removeClass('fa-check text-success');
          $('#ppolicy-allowedspechar-feedback').addClass('fa-times text-danger');
          result = false;
        }
      }
      if (window.datas.ppolicy.minspechar > 0 && window.datas.ppolicy.allowedspechar) {
        numspechar = 0;
        nonwhitespechar = window.datas.ppolicy.allowedspechar.replace(/\s/g, '');
        i = 0;
        while (i < password.length) {
          if (nonwhitespechar.indexOf(password.charAt(i)) >= 0) {
            numspechar++;
          }
          i++;
        }
        if (numspechar >= window.datas.ppolicy.minspechar) {
          $('#ppolicy-minspechar-feedback').addClass('fa-check text-success');
          $('#ppolicy-minspechar-feedback').removeClass('fa-times text-danger');
        } else {
          $('#ppolicy-minspechar-feedback').removeClass('fa-check text-success');
          $('#ppolicy-minspechar-feedback').addClass('fa-times text-danger');
          result = false;
        }
      }
      if (window.datas.ppolicy.minspechar > 0 && !window.datas.ppolicy.allowedspechar) {
        numspechar = 0;
        i = 0;
        while (i < password.length) {
          if (!isAlphaNumeric(password.charAt(i))) {
            numspechar++;
          }
          i++;
        }
        if (numspechar >= window.datas.ppolicy.minspechar) {
          $('#ppolicy-minspechar-feedback').addClass('fa-check text-success');
          $('#ppolicy-minspechar-feedback').removeClass('fa-times text-danger');
        } else {
          $('#ppolicy-minspechar-feedback').removeClass('fa-check text-success');
          $('#ppolicy-minspechar-feedback').addClass('fa-times text-danger');
          result = false;
        }
      }
      if (result) {
        $('.ppolicy').removeClass('border-danger').addClass('border-success');
        if ((ref3 = $('#newpassword').get(0)) != null) {
          ref3.setCustomValidity('');
        }
      } else {
        $('.ppolicy').removeClass('border-success').addClass('border-danger');
        if ((ref4 = $('#newpassword').get(0)) != null) {
          ref4.setCustomValidity(translate('PE28'));
        }
      }
    };
    if ((window.datas.ppolicy != null) && $('#newpassword').length) {
      checkpassword('');
      $('#newpassword').keyup(function(e) {
        checkpassword(e.target.value);
      });
    }
    togglecheckpassword = function(e) {
      var ref3;
      if (e.target.checked) {
        $('#newpassword').off('keyup');
        return (ref3 = $('#newpassword').get(0)) != null ? ref3.setCustomValidity('') : void 0;
      } else {
        $('#newpassword').keyup(function(e) {
          checkpassword(e.target.value);
        });
        return checkpassword('');
      }
    };
    checksamepass = function() {
      var ref3, ref4, ref5, ref6;
      if (((ref3 = $('#confirmpassword').get(0)) != null ? ref3.value : void 0) === ((ref4 = $('#newpassword').get(0)) != null ? ref4.value : void 0)) {
        if ((ref5 = $('#confirmpassword').get(0)) != null) {
          ref5.setCustomValidity('');
        }
        return true;
      } else {
        if ((ref6 = $('#confirmpassword').get(0)) != null) {
          ref6.setCustomValidity(translate('PE34'));
        }
        return false;
      }
    };
    $('#newpassword').change(checksamepass);
    $('#confirmpassword').change(checksamepass);
    if ((window.datas.ppolicy != null) && $('#newpassword').length) {
      $('#reset').change(togglecheckpassword);
    }
    if (datas['pingInterval'] && datas['pingInterval'] > 0) {
      window.setTimeout(ping, datas['pingInterval']);
    }
    $(".localeDate").each(function() {
      var s;
      s = new Date($(this).attr("val") * 1000);
      return $(this).text(s.toLocaleString());
    });
    $('.oidcConsent').on('click', function() {
      return removeOidcConsent($(this).attr('partner'));
    });
    $('#show-hide-button').on('click', function() {
      if ($("#newpassword").attr('type') === 'password') {
        console.log('Show passwords');
        $("#newpassword").attr('type', 'input');
        $("#confirmpassword").attr('type', 'input');
        $("#show-hide-icon-button").removeClass('fa-eye');
        return $("#show-hide-icon-button").addClass('fa-eye-slash');
      } else {
        console.log('Hide passwords');
        $("#newpassword").attr('type', 'password');
        $("#confirmpassword").attr('type', 'password');
        $("#show-hide-icon-button").removeClass('fa-eye-slash');
        return $("#show-hide-icon-button").addClass('fa-eye');
      }
    });
    if (window.location.href.match(/\/finduser/)) {
      console.log('Set Portal URL: ' + portal);
      return window.history.pushState({
        page: 'Portal'
      }, 'Portal', portal);
    }
  });

}).call(this);
