var IE = (navigator.appName == "Microsoft Internet Explorer") ? 1 : 0;

var bOpenFolder;
var bAddForlder;
var bAddPage;
var bEdit;
var bMoveUp;
var bMoveDown;
var bView;
var bComments;
var bHome;
var bMeta;
var bEditContent;
var bEditPreContent;
var bActive;
var bLock;
var bDelete;
var activeImg;
var activeTitle;
var menuTitle;
var message;

function getUrl(url) {
  window.location = url;
}

function cutLength(str, len) {
  if (str.length > len) return str.substring(0, len)+"...";
  else return str;
}

function icon_click(id, pid, menu_id, atype, rights, active, title, mod) {

  //alert("!");  return;

  var x=9;
  var y=9;

  var menu = getobj("contMenu");

  if (event) {
    x = event.x + document.body.scrollLeft;
    y = event.y + document.body.scrollTop;
  } else {
    x = e.pageX;
    y = e.pageY;
  }

  menu.left = x - 10;
  menu.top = y + 10;


  // Заголовок
  if (menuTitle) menuTitle.innerText = cutLength(title, 15);

  bEditLink = path+"?mod=pages&menu_id="+menu_id+"&pid="+pid+"&eid="+id;

  // Открыть папку справа
  bOpenFolder.onclick = function() {
    parent.main.location = path+"pid="+id;
    parent.main.location = path+"?mod=pages&menu_id="+menu_id+"&pid="+id;
    hide('contMenu');
    return false;
  }

  // Добавить папку
  bAddForlder.onclick = function() {
    parent.main.location = path+"?mod=pages&menu_id="+menu_id+"&pid="+id+"&atype=0&new=true";
    hide('contMenu');
    return false;
  }

  // Добавить страницу
  bAddPage.onclick = function() {
    parent.main.location = path+"?mod=pages&menu_id="+menu_id+"&pid="+id+"&atype=1&new=true";
    hide('contMenu');
    return false;
  }

  // Редактирование
  bEdit.onclick = function() {
    parent.main.location = path+"?mod=pages&menu_id="+menu_id+"&pid="+pid+"&eid="+id;
    hide('contMenu');
    return false;
  }

  // Редактирование контента
  bEditContent.onclick = function() {
    parent.main.location = path+"?mod="+mod+"&page_id="+id;
    hide('contMenu');
    return false;
  }

  // Редактирование пре-контента
  bEditPreContent.onclick = function() {
    parent.main.location = path+"?mod="+mod+"&page_id="+id+"&pre=1";
    hide('contMenu');
    return false;
  }

  // Передвинуть вверх
  bMoveUp.onclick = function() {
    parent.main.location = path+"?mod=pages&menu_id="+menu_id+"&pid="+pid+"&moveid="+id+"&direct=up";
    hide('contMenu');
    return false;
  }

  // Передвинуть вниз
  bMoveDown.onclick = function() {
    parent.main.location = path+"?mod=pages&menu_id="+menu_id+"&pid="+pid+"&moveid="+id+"&direct=down";
    hide('contMenu');
    return false;
  }

  // Просмотреть страницу
  bView.onclick = function() {
    window.open("/" + id + "/");
    hide('contMenu');
    return false;
  }

  // Комментарии
  bComments.onclick = function() {
    parent.main.location = path+"?mod=comments&page_id="+id;
    hide('contMenu');
    return false;
  }

  // Вывести на главную
  bHome.onclick = function() {
    parent.main.location = path+"?mod=home&onhomeid="+id;
    hide('contMenu');
    return false;
  }

  // Редактировать meta-теги
  bMeta.onclick = function() {
    parent.main.location = path+"?mod=meta&eid="+id;
    hide('contMenu');
    return false;
  }

  // Смена активности
  if (active == 1) {
    if (activeImg) activeImg.src = corepath+"images/admin/no-active.gif";
    if (activeTitle) activeTitle.innerText = "Скрыть";
    activeURL = path+"?mod=pages&menu_id="+menu_id+"&pid="+pid+"&aid="+id+"&active=0";
  } else {
    if (activeImg) activeImg.src = corepath+"images/admin/active.gif";
    if (activeTitle) activeTitle.innerText = "Отобразить";
    activeURL = path+"?mod=pages&menu_id="+menu_id+"&pid="+pid+"&aid="+id+"&active=1";
  }

  bActive.onclick = function() {
    parent.main.location = activeURL;
    hide('contMenu');
    return false;
  }

  // Ограничить доступ
  bLock.onclick = function() {
    parent.main.location = path+"?mod=rights&menu_id="+menu_id+"&page_id="+id+"&usermode=1";
    hide('contMenu');
    return false;
  }
  
  // Удалить
  bDelete.onclick = function() {
    if (window.confirm("Вы действительно хотите удалить этот пункт?")) {
      parent.main.location = path+"?mod=pages&menu_id="+menu_id+"&pid="+pid+"&delid="+id;
    }
    hide('contMenu');
    return false;
  }

  bEdit.style.display = "";
  bEditContent.style.display = "";
  bActive.style.display = "";
  bDelete.style.display = "";
  bOpenFolder.style.display = "";
  bAddForlder.style.display = "";
  bAddPage.style.display = "";
  bLock.style.display = "";
  bMoveUp.style.display = "";
  bMoveDown.style.display = "";
  bMeta.style.display = "";
  bView.style.display = "";
  bComments.style.display = "";
  
  
  message.style.display = "none";
  
  // Права только на просмотр
  if (rights == 1) {

    bEdit.style.display = "none";
    bEditContent.style.display = "none";
    bActive.style.display = "none";
    bDelete.style.display = "none";
    bOpenFolder.style.display = "none";
    bAddForlder.style.display = "none";
    bAddPage.style.display = "none";
    bLock.style.display = "none";
    bMoveUp.style.display = "none";
    bMoveDown.style.display = "none";

    message.style.display = "";
    message.innerText = "У вас нет прав для редактирования этого пункта";

  } else {
  
    // Корень
    if (atype == 2) {

      bEdit.style.display = "none";
      bEditContent.style.display = "none";
      bActive.style.display = "none";
      bDelete.style.display = "none";
      bMoveUp.style.display = "none";
      bMoveDown.style.display = "none";
      bView.style.display = "none";
      bMeta.style.display = "none";
      bComments.style.display = "none";

    // Папка
    } else if (atype == 0) {

    // Страница
    } else {

      bOpenFolder.style.display = "none";
      bAddForlder.style.display = "none";
      bAddPage.style.display = "none";

    }

    if (rights == 2) {
      bRights.style.display = "none";
    }
  }

  document.getElementById("contMenu").style.visibility = "visible";

}

function icon_dblClick(id, menu_id, atype, mod) {
  if (atype == 1) {
    parent.main.location = path+"?mod="+mod+"&page_id="+id;
    hide('contMenu');
  } else {
    parent.main.location = path+"pid="+id;
    parent.main.location = path+"?mod=pages&menu_id="+menu_id+"&pid="+id;
    hide('contMenu');
  }
}


function link_click(id, menu_id, page_id) {
  if (turn(id)) {
    // Открываем папку в правом окне
    var currentLink = parent.main.location.pathname + parent.main.location.search;
    var openingLink = "/admin/" + path + "?mod=pages&menu_id=" + menu_id + "&pid=" + page_id;
    if (currentLink != openingLink) {
      parent.main.location = openingLink;
    }
    
    o = document.getElementById(id);
    o.innerHTML = "Загрузка...";
  
    // Создаем новый объект JSHttpRequest
    var req = new Subsys_JsHttpRequest_Js();
    // Код, АВТОМАТИЧЕСКИ вызываемый при окончании загрузки
    req.onreadystatechange = function() {
      if (req.readyState == 4) {
        if (req.responseText) {
          // Записываем в <div> весь выводимый текст
          o.innerHTML = req.responseText;
        } else if (req.responseJS.ok) {
          o.innerHTML = "";
          turn(id);
        }
      }
    }
  
    // Разрешаем кэширование (чтобы при одинаковых запросах не обращаться к серверу несколько раз)
    req.caching = true;
  
    // Подготваливаем объект.
    req.open("POST", "./ajax.php?mod=adminmenu&action=loadTree&page_id=" + page_id + "&menu_id=" + menu_id);
    // Посылаем данные запроса (задаются в виде хэша)
    
    req.send();
  }
}

function turn(id) {
  o = document.getElementById(id);
  if (o) {
    if (o.style.display == "none" || o.style.display == "") {
      o.style.display = "block";
      saveCookie(id, o.style.display);
      return true;
    } else {
      o.style.display = "none";
      saveCookie(id, o.style.display);
      return false;
    }
    
  }
}

function saveCookie(sName, val) {
  var expiry = new Date();
  expiry.setTime(expiry.getTime() + 24*60*60*1000);
  document.cookie = sName + "=" + val + "; path=/; expires=" + expiry.toGMTString();
}

function getCookie(sName) {
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i<aCookie.length; i++) {
    // a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) 
    return unescape(aCrumb[1]);
  }
  // a cookie with the requested name does not exist
  return null;
}

function init() {

  //bRevealFolder = document.getElementById("bRevealFolder");
  bOpenFolder = document.getElementById("bOpenFolder");
  bAddForlder = document.getElementById("bAddForlder");
  bAddPage = document.getElementById("bAddPage");
  bEdit = document.getElementById("bEdit");
  bMoveUp = document.getElementById("bMoveUp");
  bMoveDown = document.getElementById("bMoveDown");
  bView = document.getElementById("bView");
  bComments = document.getElementById("bComments");
  bHome = document.getElementById("bHome");
  bMeta = document.getElementById("bMeta");
  bEditContent = document.getElementById("bEditContent");
  bEditPreContent = document.getElementById("bEditPreContent");
  bActive = document.getElementById("bActive");
  bLock = document.getElementById("bLock");
  bDelete = document.getElementById("bDelete");
  activeImg = document.getElementById("activeImg");
  activeTitle = document.getElementById("activeTitle");
  menuTitle = document.getElementById("menuTitle");

  message = document.getElementById("message");

  cont_ids = cont_ids.split(";");

  /*
  for (var i = cont_ids.length-1; i >= 0; i--) {
    o = document.getElementById(cont_ids[i]);
    if (o) {
      g = getCookie(cont_ids[i]);
      if (g != null) {
        
        //cur_ids = new Array();
        //cur_ids = cont_ids[i].split("-");
        //if (g == "block") link_click(cont_ids[i], cur_ids[1], cur_ids[2]);

        o.style.display = g;
      }
    }
  }
  */

  turn("mainMenu");

}
