// 通过传入的选择器给元素增加属性
var windowArea = 'shichuangqu';
// 用于导航区匹配的正则
var reg = /<a[^>]*href=[ '"]([^"]*)[' "][^>]*>(.*?)<\/a>/g;
// 参数形式 ['ul li a','ul li shichuangqu?动态']
function resolveAccessibility (DOMArr) {
  var splitArgReg = /\?|&/;
  // 用于切割用户传递参数的正则
  try {
    DOMArr.forEach(function (selectElement, index, arr) {
      // node为元素节点，query为传递的参数
      var nodeEl = selectElement.split(splitArgReg)[0];
      // 获取元素然后判断传入的类名是否包含指定的类名
      var queryLen = document.querySelectorAll(nodeEl).length;
      if (queryLen > 0) {
        document.querySelectorAll(nodeEl).forEach(function (cur) {
          addCustomParams(cur, selectElement);
        });
      }
    });
  } catch (err) {
    console.log(err.message);
  }
}
function addCustomParams (ele, s) {
  var splitReg = /\?|&/;
  var query = s.split(splitReg)[1];
  var wzaType = s.split(splitReg)[2] ? s.split(splitReg)[2] : '1';
  var el = s.split(splitReg)[0];
  if (ele) {
    // 如果有元素未设参，只是占位的情况，不添加
    var getEleText = ele.innerText.replace(/(\s+)|(<\/?.+?\/?\/?.+>)/gi, "");
    if (getEleText != "" || isContain(ele,"img") || isContain(ele,"input")) {
      if (el.includes(windowArea) || query && wzaType === '1') {  // 判断当前下标的选择器中是否包含视窗区专属类名
        // 给当前元素增加视窗区专属类名
        ele.setAttribute('aria-regiontype', '1');
        ele.setAttribute('ergodic', 'view');
        // ele.setAttribute('tabindex', '0');
        ele.setAttribute('barrierfree_zone_dsc', '视窗区,提示：您已进入' + query + '视窗区,按下tab键浏览信息');
      } else if (wzaType == '2') {
        // 导航区，由于导航区选择器结构一般是div  ul li a
        var nodeString = ele.innerHTML;
        // 去除注释文本、换行、前后空格
        nodeString = nodeString.replace(/(<\!--\/?.+?\/?-->)|(\n)/gi, "").trim();
        // 去除标签之间的空格
        nodeString = nodeString.replace(/>\s*(\S*)\s*</g, ">$1<");
        var nodeText = [];
        nodeString.replace(reg, function (str, p1, p2) { // 获取导航区中a标签中的内容
          // str为正则匹配到的字符串,p1为a标签中的内容
          nodeText.push(p2.replace(/<[^>]+>|&[^>]+;/g, ''));
        });
        // 将导航区中a标签的内容设置给当前属性
        if (nodeText.toString().trim() != "") {
          // ele.setAttribute('aria-regiontype', '2');
          ele.setAttribute('ergodic', 'navigation');
         // ele.setAttribute('tabindex', '0');
          ele.setAttribute('barrierfree_zone_dsc', '您已进入' + query + '导航区,有' + nodeText.toString() + ',按下tab键浏览信息');
        }
      } else if (wzaType > 2 && wzaType < 7) { // 进入到这里说明它既不是视窗区也不是导航区
        if (wzaType == 3) { // 等于3则进入正文区
          // ele.setAttribute('aria-regiontype', '3')
          ele.setAttribute('ergodic', 'article')
          ele.setAttribute('tabindex', '0')
          ele.setAttribute('barrierfree_zone_dsc', '正文区,提示：您已进入正文区,按下tab键浏览信息')
        } else if (wzaType == 4) { // 则进入服务区
          ele.setAttribute('aria-regiontype', '4')
          ele.setAttribute('ergodic', 'serve')
          // ele.setAttribute('tabindex', '0')
          ele.setAttribute('barrierfree_zone_dsc', '服务区,提示：您已进入' + query + '服务区,按下tab键浏览信息')
        }
        else if (wzaType == 5) { // 则进入服务区
                    ele.setAttribute('aria-regiontype', '4')
                    ele.setAttribute('ergodic', 'serve')
                    ele.setAttribute('tabindex', '0')
                    ele.setAttribute('barrierfree_zone_dsc', '服务区,提示：您已进入' + query + ',按下tab键浏览信息')
                }
      }
    }
  }
}
// 处理浮动窗体的工具方法
/**
* @param  arr  ['tab切换选择器1&对应的信息列表选择器1','tab切换选择器2&对应的信息列表选择器2'] 
* 例如 ['.tab1&.libiao1','.tab2&.libiao2'] 
*/
function flotWindow (arr) {
  var len = arguments.length;
  var soruce, target, soruceNode, targetNode;
  if (len > 1) {
    var newArguments = arguments;
  }
  // 给哪个元素加浮动窗体提示，他所对应的浮动窗口是哪一个
  arr.forEach(function (elementNodeSelect) {
    try {
      if (len == 1) {
        soruce = elementNodeSelect.split('&')[0];
        target = elementNodeSelect.split('&')[1];
        soruceNode = document.querySelectorAll(soruce);
        targetNode = document.querySelectorAll(target);
        if (soruceNode.length == 1) {
          soruceNode = soruceNode[0];
          targetNode = targetNode[0];
          addFloatParams(soruceNode, targetNode);
        } else if (soruceNode.length > 1) {
          for (var i = 0; i < soruceNode.length; i++) {
            flotWindow(arr, soruceNode[i], targetNode[i]);
          }
        }
      } else {
        soruceNode = newArguments[1];
        targetNode = newArguments[2];
        addFloatParams(soruceNode, targetNode);
      }
    } catch (err) {
      console.log(err.message);
    }
  });
}
function addFloatParams (s, t) {
  var id = null;
  //var setText = s.innerText.trim().replace(/\s+|(\n)+|( )|(\|)/g, "");
  var setText = s.innerHTML.trim().replace(/(<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>)|(<style\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/style>)|(<[^>]*>|<\/[^>]*>)|(\s+)/gi, "");
  if (setText != "") {
    // 判断传入的元素是否有id属性，获取targetNode的id
    if (s && t) {
      if (t.id) {
        id = t.id  // 存入id
        s.setAttribute('aria-owns', '#' + id)
      } else {
        // 动态生成一个id
        id = Math.random().toString().slice(10)
        s.setAttribute('aria-owns', '#' + 'flotWindow' + id)
        t.setAttribute('id', 'flotWindow' + id)
      }
      if (s.nodeName.toLowerCase() === 'a' || s.nodeName.includes('<a')) {
        s.setAttribute('barrierfree_zone_dsc', '链接：' + setText + ',当前有浮动窗口,按ctrl+下键进入窗口,按方向键在浮动层中遍历信息,按esc键返回上一菜单')
      } else {
        s.setAttribute('barrierfree_zone_dsc', setText + ',当前有浮动窗口,按ctrl+下键进入窗口,按方向键在浮动层中遍历信息,按esc键返回上一菜单')
      }
      // 给soruceNode设置属性
      s.setAttribute('role', 'tab')
      s.setAttribute('aria-haspopup', 'true')
      s.setAttribute('aria-enterownsmethod', '1');
      s.setAttribute('aria-eschide', 'true');
      // 进入方法
      s.setAttribute('aria-expandshowmethod', 'hover');
      s.setAttribute('aria-eschide', 'true');
      s.setAttribute('tabindex', '0');
      s.setAttribute('aria-atomic', 'true');
      s.setAttribute('aria-autolabel', 'true');
      // 给targetNode设置属性
      t.setAttribute('role', 'tabpanel');
      t.setAttribute('tabindex', '0');
      t.setAttribute('barrierfree_zone_dsc', setText);
      t.setAttribute('ergodic', "view");
      t.setAttribute('aria-regiontype', 1);
    }
  }
}
/**
 *
 * @param {String,Array} el    选取元素
 * @param {String} regText     url地址正则
 * @param {Number} ariaNum     aria的值，视窗区-1，导航区-2，正文区-3，服务区-4，
 * @param {String} str         要添加的无障碍barrierfree_zone_dsc文本描述
 * @param {String,Array} title 标题所在的元素
 */
function ariaAdd (el, regText, ariaNum, str, title) {
  this.el = el;
  this.regText = regText;
  this.ariaNum = ariaNum;
  this.str = str;
  this.title = title;
}
ariaAdd.prototype.run = function () {
  var $el;
  try {
    if (!this.el) {
      throw new Error("函数未传入选取的元素！");
    } else {
      $el = this.el;
      var elType = Object.prototype.toString.call($el).slice(8, -1);
      if (elType === "String") {
        $el = document.querySelector($el);
      } else if (elType === "Array") {
        for (var j = 0; j < $el.length; j++) {
          if (document.querySelector($el[j])) {
            $el = document.querySelector($el[j]);
            break;
          }
        }
        if (Object.prototype.toString.call($el).slice(8, -1) === "Array") {
          $el = null;
        }
      }
      if ($el) {
        if (!this.regText) {
          throw new Error("未定义正则表达式！");
        } else {
          var reg = new RegExp(this.regText);
          if (reg.test(window.location.href)) {
            $el.setAttribute("ergodic", "article");
            $el.setAttribute("aria-regiontype", this.ariaNum);
            $el.setAttribute("tabindex", 0);
            if (this.title) {
              var title = this.title;
              var titleType = Object.prototype.toString.call(title).slice(8, -1);
              if (titleType === "String") {
                $el.setAttribute("barrierfree_zone_dsc", this.str + ",文章标题为：" + document.querySelector(title).innerText);
              } else if (titleType === "Array") {
                for (var i = 0; i < title.length; i++) {
                  if (document.querySelector(title[i])) {
                    if (document.querySelector(title[i]).innerText.trim() != "") {
                      $el.setAttribute("barrierfree_zone_dsc", this.str + ",文章标题为：" + document.querySelector(title[i]).innerText);
                      break;
                    }
                  }
                }
              }
            } else {
              $el.setAttribute("barrierfree_zone_dsc", this.str);
            }
          }
        }
      } else {
        //throw new Error("页面中不包含选取的元素！");
      }
    }
  } catch (err) {
    console.log(err.message);
  }
};
// 信息公开指南，自动添加无障碍文本，如果没有加上自行增加
// 获取当前栏目名
var currColumnName = "";
if (document.querySelector("meta[name='ColumnName']")) {
  currColumnName = document.querySelector("meta[name='ColumnName']").getAttribute("content");
}
// 获取信息公开左侧列表
var xxgkLeftList = "";
for (var len = 0; len < document.querySelectorAll(".dl_nav h3").length; len++) {
  var curText = document.querySelectorAll(".dl_nav h3")[len].innerText.trim().replace(/(\s)|(\\n)|(<|\<\;)br\s*[\/]?(>|\>\;)/gi, "");
  if (curText != "") {
    xxgkLeftList += curText + ";";
  }
}
xxgkLeftList = xxgkLeftList.split(";");
if (xxgkLeftList[xxgkLeftList.length - 1].trim() == "") {
  xxgkLeftList.pop();
}
xxgkLeftList = xxgkLeftList.join("、");

var xxgkAriaSearch = new ariaAdd(".search-area", "\/col\/", 3, "当前为" + currColumnName + "信息检索");
var xxgkAriaLeft = new ariaAdd(".dl_nav", "\/col\/", 2, "当前为" + currColumnName + "左侧列表导航,包含" + xxgkLeftList + "等内容。");
if (document.querySelector("#zfxxgkzn")) {
  var xxgkAriaZn = new ariaAdd(".zn_cont", "\/col\/", 6, "当前为政府信息公开指南正文内容区。");
  xxgkAriaZn.run();
}

xxgkAriaSearch.run();
xxgkAriaLeft.run();


function znzdnbList (s, t, str, associated, regiontype) {
  if (document.querySelector(s)) {
    document.querySelector(s).setAttribute('role', 'tab');
    document.querySelector(s).setAttribute('aria-haspopup', 'true');
    document.querySelector(s).setAttribute('aria-owns', associated);
    document.querySelector(s).setAttribute('barrierfree_zone_dsc', str + ',当前有浮动窗口,按ctrl+下键进入窗口,按方向键在浮动层中遍历信息,按esc键返回上一菜单');
    document.querySelector(s).setAttribute('aria-atomic', 'true');
    document.querySelector(s).setAttribute('aria-expandshowmethod', 'click');
    document.querySelector(s).setAttribute('aria-enterownsmethod', '1');
    document.querySelector(s).setAttribute('tabindex', '0');
    if (document.querySelector(t)) {
      document.querySelector(t).setAttribute("aria-region", "true");
      document.querySelector(t).setAttribute("aria-regiontype", regiontype);
      document.querySelector(t).setAttribute("barrierfree_zone_dsc", str);
    }
  }
}
document.addEventListener("DOMNodeInserted", function (e) {
  if (document.querySelectorAll("#zp_list .zfxxgk_zdgkc").length > 0) {
    fdzdgkTips();
  }
});
window.onload = function () {
  if (document.querySelectorAll(".zfxxgk_zdgkc").length > 0) {
    for (var ren = 0; ren < document.querySelectorAll(".zfxxgk_zdgkc").length; ren++) {
      if (document.querySelectorAll(".zfxxgk_zdgktit")[ren].innerText.trim() != "") {
        document.querySelectorAll(".zfxxgk_zdgkc")[ren].setAttribute("ergodic", "view");
        document.querySelectorAll(".zfxxgk_zdgkc")[ren].setAttribute("aria-regiontype", 1);
        document.querySelectorAll(".zfxxgk_zdgkc")[ren].setAttribute("tabindex", 0);
        document.querySelectorAll(".zfxxgk_zdgkc")[ren].setAttribute("barrierfree_zone_dsc", document.querySelectorAll(".zfxxgk_zdgktit")[ren].innerText.trim());
      }
    }
  } else if (document.querySelectorAll(".zfxxgk_zdgktit").length > 0) {
    for (var bmlen = 0; bmlen < document.querySelectorAll(".zfxxgk_zdgktit").length; bmlen++) {
      if (document.querySelectorAll(".zfxxgk_zdgktit")[bmlen].innerText.trim() != "") {
        document.querySelectorAll(".zfxxgk_zdgktit")[bmlen].parentNode.nextElementSibling.setAttribute("ergodic", "view");
        document.querySelectorAll(".zfxxgk_zdgktit")[bmlen].parentNode.nextElementSibling.setAttribute("aria-regiontype", 1);
        document.querySelectorAll(".zfxxgk_zdgktit")[bmlen].parentNode.nextElementSibling.setAttribute("tabindex", 0);
        document.querySelectorAll(".zfxxgk_zdgktit")[bmlen].parentNode.nextElementSibling.setAttribute("barrierfree_zone_dsc", document.querySelectorAll(".zfxxgk_zdgktit")[bmlen].innerText.trim());
      }
    }
  }
  if (document.querySelectorAll(".title_nbzt").length > 0 && hasClass(document.querySelector(".nb"), "on")) {
    var xxgkAriaNb = new ariaAdd(".Rcont", "\/col\/", 5, "当前为政府信息公开年报右侧内容区。");
    xxgkAriaNb.run();
  }
}
//$(function () {
//  znzdnbTips();
//});

function hasClass (elem, cls) {
  cls = cls || '';
  if (cls.replace(/\s/g, '').length == 0) return false;
  return new RegExp(' ' + cls + ' ').test(' ' + elem.className + ' ');
}
// 法定主动公开内容添加无障碍文本
function fdzdgkTips () {
  document.querySelectorAll("#zp_list .zfxxgk_zdgkc").forEach(function (cur) {
    cur.setAttribute("ergodic", "view");
    cur.setAttribute("aria-regiontype", 1);
    cur.setAttribute("tabindex", 0);
    if (cur.previousElementSibling) {
      cur.setAttribute("barrierfree_zone_dsc", cur.previousElementSibling.innerText.trim());
    } else {
      var ariaDescribe;
      if (document.querySelector("#searchform + div > a:last-child")) {
        ariaDescribe = document.querySelector("#searchform + div > a:last-child").innerText;
      } else {
        ariaDescribe = "法定主动公开右侧信息列表。";
      }
      ariaDescribe = ariaDescribe.trim().replace(/(\(|\（)\d+(\)|\）)/g, "")
      cur.setAttribute("barrierfree_zone_dsc", "视窗区," + ariaDescribe);
    }
  });
}
// includes() polyfill
if (!String.prototype.includes) {
  String.prototype.includes = function (search, start) {
    if (typeof start !== 'number') {
      start = 0;
    }
    if (start + search.length > this.length) {
      return false;
    } else {
      return this.indexOf(search, start) !== -1;
    }
  };
}
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function (searchElement, fromIndex) {
      if (this == null) { //this是空或者未定义，抛出错误
        throw new TypeError('"this" is null or not defined');
      }
      var o = Object(this); //将this转变成对象
      var len = o.length >>> 0; //无符号右移0位，获取对象length属性，如果未定义就会变成0
      if (len === 0) { //length为0直接返回false未找到目标值
        return false;
      }
      var n = fromIndex | 0; //查找起始索引
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); //计算正确起始索引，因为有可能是负值
      while (k < len) { //从起始索引处开始循环
        if (o[k] === searchElement) { //如果某一位置与寻找目标相等，返回true，找到了
          return true;
        }
        k++;
      }
      return false; //未找到，返回false
    }
  });
}
// forEach() polyfill
if (!Array.prototype.forEach) {
  Array.prototype.forEach = function (callback) {
    var _this = arguments.length <= 1 || arguments[1] === undefined ? window : arguments[1];
    // this => arr  this 指向调用它的数组
    for (var i = 0; i < this.length; i++) {
      callback.call(_this, this[i], i, this);
    }
  };
}
// 判断后代元素是否包含指定的元素
function isContain (el, con) {
  var arr = toArray(el.getElementsByTagName("*"));
  var flag = false;
  for (var i = 0; i < arr.length; i++){
    if (arr[i].nodeName.toLowerCase() == con) {
      flag = true;
      break;
    };
  }
  return flag;
}
// 将一个类数组转为真正的数组
function toArray (lickArr) {
  var arr = [];
  for (var i = 0; i < lickArr.length; i++) {
    arr.push(lickArr[i]);
  }
  return arr;
}