var startupEarlyList = new Array();
var startupList = new Array();
var startupLateList = new Array();

var buttonLoginList = new Array();
var buttonLogoutList = new Array();

var sizeWorkareaWidth = 0;
var sizeWorkareaHeight = 0;

var resizeList = new Array();

var timeoutTime = new Date();
timeoutTime.setSeconds(timeoutTime.getSeconds()+admintimeoutcounter);

function AddStartupFunction(funcCode) {
  startupList[startupList.length] = funcCode;
}

function AddEarlyStartupFunction(funcCode) {
  startupEarlyList[startupEarlyList.length] = funcCode;
}

function AddLateStartupFunction(funcCode) {
  startupLateList[startupLateList.length] = funcCode;
}

function AddResizeObject(id, parentid, width, height, left, top) {
  resizeList[resizeList.length] = new Array(id,parentid,width,height,left,top);
}

function WindowResize() {
  var winWidth = xClientWidth();
  var winHeight = xClientHeight();
  var resizeItem = null;
  
  winWidth = 970;
  winHeight = 575;
  
  xResizeTo('adminLogo', 200, 35);
  xResizeTo('adminTop', winWidth - 205, 35);
  xResizeTo('adminTree', 200, winHeight - 35);
  xResizeTo('adminWorkarea', winWidth - 205, winHeight - 35);

  xMoveTo('adminLogo', 0, 0);
  xMoveTo('adminTop', 215, 0);
  xMoveTo('adminTree', 0, 35);
  xMoveTo('adminWorkarea', 205, 35);
  
  sizeWorkareaWidth = winWidth - 205;
  
  sizeWorkareaHeight = winHeight - 35;
  sizeTreeWidth = 200;
  sizeTreeHeight = winHeight - 35;
 
  sizeTopWidth = winWidth - 205;
 
  sizeTopHeight = 35;
  
  // Add userdefined size here
  for(var i in resizeList) {
    resizeItem = resizeList[i];
    var resizeObject = GetElementByID(resizeItem[0]);
    var resizeReference = GetElementByID(resizeItem[1]);
    var resizeWidth = resizeItem[2];
    var resizeHeight = resizeItem[3];
    var resizeLeft = resizeItem[4];
    var resizeTop = resizeItem[5];
    if(resizeWidth == '*') {
      resizeWidth = sizeWorkareaWidth;
    }
    if(resizeHeight == '*') {
      resizeHeight = sizeWorkareaHeight;
    }
    if(typeof(resizeObject.ResizeTo) == 'function') {
      resizeObject.ResizeTo(resizeWidth, resizeHeight);
    } else {
      xResizeTo(resizeObject, resizeWidth, resizeHeight);
    }
  }
}

var altFunc = new Array();

function RegisterAltFunction(alt, funcCode) {
  altFunc[alt] = funcCode;
}

function EventKeyUp(evt) {
  if(window.event) {
    xEvt = new xEvent(window.event);
  } else {
    xEvt = new xEvent(evt);
  }
  var funcKey = xEvt.keyCode;
  if(funcKey >= 48) {
    funcKey -= 48;
    if(funcKey < 10) {
      if(xEvt.ctrlKey && xEvt.altKey && xEvt.shiftKey) {
        funcKey += 30;
        if(typeof(altFunc[funcKey]) == 'string') {
          eval(altFunc[funcKey]);
        } else {
          // alert('No function assigned to CTRL+ALT+SHIFT+'+funcKey);
        }
      } else if(xEvt.ctrlKey && xEvt.altKey) {
        funcKey += 20;
        if(typeof(altFunc[funcKey]) == 'string') {
          eval(altFunc[funcKey]);
        } else {
          // alert('No function assigned to CTRL+ALT+'+funcKey);
        }
      } else if(xEvt.altKey && xEvt.shiftKey) {
        funcKey += 10;
        if(typeof(altFunc[funcKey]) == 'string') {
          eval(altFunc[funcKey]);
        } else {
          // alert('No function assigned to ALT+SHIFT+'+funcKey);
        }
      } else if(xEvt.altKey) {
        if(typeof(altFunc[funcKey]) == 'string') {
          eval(altFunc[funcKey]);
        } else {
          // alert('No function assigned to ALT+'+funcKey);
        }
      }
    } else {
      if(xEvt.ctrlKey && !(xEvt.altKey || xEvt.shiftKey)) {
        switch(xEvt.keyCode) {
          case 83:
          if(typeof('CtrlSFunction') == 'function') {
            CtrlSFunction();
          }
          break;
        }
      }
    }
  }
}

function HideAllSubMenus() {
  var topMenu = GetElementByID('tabs-main');
  var topNode = null;
  var subNode = null;
  for(var i = 0; i < topMenu.childNodes.length; i++) {
    topNode = topMenu.childNodes.item(i);
    if(topNode.nodeName.toLowerCase() == 'li') {
      for(var j = 0; j < topNode.childNodes.length; j++) {
        subNode = topNode.childNodes.item(j);
        if(subNode.nodeName.toLowerCase() == 'ul') {
          subNode.style.display = 'none';
        }
      }
    }
  }
}

function ShowSubMenus() {
  var subNode = null;
  var subLINode = null;
  var ulWidth = 0;
  var liWidth = 0;
  var subPos = 0;
  
  HideAllSubMenus();
  for(var j = 0; j < this.childNodes.length; j++) {
    subNode = this.childNodes.item(j);
    if(subNode.nodeName.toLowerCase() == 'ul') {
      subNode.style.display = 'inline';
      ulWidth = xWidth(subNode.parentNode.parentNode);
      // Calc subwidth
      liWidth = 0;
      for(var k = 0; k < subNode.childNodes.length; k++) {
        subLINode = subNode.childNodes.item(k);
        if(subLINode.nodeName.toLowerCase() == 'li') {
          liWidth = liWidth + xWidth(subLINode);
        }
      }
      subNode.style.width = liWidth;
      liWidth = liWidth;
      subPos = xOffsetLeft(this) - (liWidth / 2) + (xWidth(this) / 2);
      if((subPos + liWidth) > ulWidth) {
        subPos = ulWidth - liWidth;
      }
      if(subPos < 0) {
        subPos = 0;
      }
      xMoveTo(subNode, subPos, xOffsetTop(this) + topMenuOffset);
    }
  }
}

function HideSubMenus() {
  var subNode = null;
  for(var j = 0; j < this.childNodes.length; j++) {
    subNode = this.childNodes.item(j);
    if(subNode.nodeName.toLowerCase() == 'ul') {
      subNode.style.display = 'none';
    }
  }
}

function Startup() {
  var topMenu = GetElementByID('tabs-main');
  var topNode = null;
  if((topMenu != null) && (topMenu.childNodes != null)) {
    for(var i = 0; i < topMenu.childNodes.length; i++) {
      topNode = topMenu.childNodes.item(i);
      if(topNode.nodeName.toLowerCase() == 'li') {
        topNode.onmouseover = ShowSubMenus;
        // topNode.onmouseout = HideSubMenus;
      }
    }
  }  
  
  
  for(var i = 0; i < startupEarlyList.length; i++) {
    try {
      eval(startupEarlyList[i]);
    } catch(e) {
      alert('Early startup: '+e);
      alert(startupEarlyList[i]);
    }
  }
  for(var j = 0; j < startupList.length; j++) {
    try {
      eval(startupList[j]);
    } catch(e) {
      alert('xNormal startup: '+e);
      alert(startupList[j]);
    }
  }
  WindowResize();
  WindowResize();
  xAddEventListener(window, 'resize', WindowResize, false);
  xAddEventListener(document, 'keyup', EventKeyUp, false);
  for(var k = 0; k < startupLateList.length; k++) {
    try {
      eval(startupLateList[k]);
    } catch(e) {
      alert('Late startup: '+startupLateList[k]+e.message);
      alert(startupLateList[k]);
    }
  }
  RunTickers();
  HandlePresets();
}

function GetElementByID(id) {
  if(document.getElementById) {
    return document.getElementById(id);
  }
  return null;
}

function SetFieldValue(id, value) {
  var field = GetElementByID(id);
  if(field != null) {
    var tagName = field.nodeName.toLowerCase();
    if(tagName == 'select') {
      for(var i = 0; i < field.options.length; i++) {
        if(field.options[i].value == value) {
          field.selectedIndex = i;
          break;
        }
      }
    } else {
      field.value = value;
      if(field.value != value) {
        alert('Missing code for: '+tagName);
      }
    }
  }
}



//=======================================
function UpdateConnection() {
  var req = new XMLHttpRequest();
  if (req) {
    req.onreadystatechange = function() {
      if (req.readyState == 4 && req.status == 200) {
        var newTimeout = parseInt(req.responseText);
        if(newTimeout > 0) {
          admintimeoutcounter = newTimeout;
          timeoutTime = new Date();
          timeoutTime.setSeconds(timeoutTime.getSeconds()+admintimeoutcounter);
        } else {
          alert('Failed');
        }
      }
    };
    // req.open('GET', '/updatecon.php?x=z');
    // req.send(null);
    req.open('POST', '/updatecon.php?x=z');
    req.send("dologin=1");
  }
}

function LogoutConnection() {
  if(confirm(sLogoutText)) {
    var req = new XMLHttpRequest();
    if (req) {
      req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status == 200) {
          var newTimeout = parseInt(req.responseText);
          warningIssued = true;
          if(newTimeout > 0) {
            admintimeoutcounter = newTimeout;
            timeoutTime = new Date();
            timeoutTime.setSeconds(timeoutTime.getSeconds()+admintimeoutcounter);
          } else {
            admintimeoutcounter = -1;
          }
          if(admintimeoutcounter < 0) {
            adminuserid = -1;
            window.location.href = sAdminPath;
          }
        }
      };
      req.open('GET', '/updatecon.php?action=logout');
      req.send(null);
    }
  }
}


function UpdateAdminTimeout() {
  var req = new XMLHttpRequest();
  if (req) {
    req.onreadystatechange = function() {
      if (req.readyState == 4 && req.status == 200) {
        var newTimeout = parseInt(req.responseText);
        if(newTimeout > 0) {
          admintimeoutcounter = newTimeout;
          timeoutTime = new Date();
          timeoutTime.setSeconds(timeoutTime.getSeconds()+admintimeoutcounter);
        }
      }
    };
    req.open('GET', '/updatecon.php?action=isactive');
    req.send(null);
  }
}

function PostToServer(url, dataArray, targetElement) {
  var req = new XMLHttpRequest();
  if (req) {
    req.onreadystatechange = function() {
      if (req.readyState == 4 && req.status == 200) {
        targetElement.innerHTML = req.responseText;
      }
    };
    var strToSend = '';
    for(var s in dataArray) {
      key = s;
      value = dataArray[s];
      if(strToSend.length > 0) {
        strToSend += '&';
      }
      strToSend += key + '=' + value;
    }
    req.open('POST', url);
    req.send(strToSend);
  }
}

//=======================================


function RegisterButtonLogin(id) {
  buttonLoginList[buttonLoginList.length] = id;
}

function RegisterButtonLogout(id) {
  buttonLogoutList[buttonLogoutList.length] = id;
}

function HandleClickLogin() {
  UpdateConnection();
}

function HandleClickLogout() {
  LogoutConnection();
}

var tickerCount = 0;
var adminState = 0;
var timeoutState = 0;

function RunTickers() {
  // Check timeout
  var currentTime = new Date();
  admintimeoutcounter = parseInt((timeoutTime - currentTime) / 1000);
  if((admintimeoutcounter < 300) && (admintimeoutcounter >= 120) && (timeoutState != 300)) {
    UpdateAdminTimeout();
    timeoutState = 300;
  } else if((admintimeoutcounter < 120) && (admintimeoutcounter >= 15) && (timeoutState != 120)) {
    UpdateAdminTimeout();
    timeoutState = 120;
  } else if((admintimeoutcounter < 15) && (admintimeoutcounter > 0) && (timeoutState != 15)) {
    UpdateAdminTimeout();
    timeoutState = 15;
  }
  if((admintimeoutcounter > 0) && (adminuserid != -1)) {
    if(adminState != 1) {
      ShowAllLogout();
      adminState = 1;
      warningIssued = false;
    }
    UpdateAllLogin();
  } else {
    if(adminState != 2) {
      HideAllLogout();
      var oldAdminState = adminState;
      adminState = 2;
      SetLoginTexts();
      if((oldAdminState != 0) && (warningIssued == false))  {
        warningIssued = true;
        alert(sTimeout);
      }
    }
  }
  // Run tickers again in 250ms
  setTimeout('RunTickers();', 250);
}

function ShowAllLogout() {
  for(var i in buttonLogoutList) {
    var id = buttonLogoutList[i];
    var e = GetElementByID(id);
    if(e != null) {
      e.style.display = 'inline';
    }
  }
}

function HideAllLogout() {
  for(var i in buttonLogoutList) {
    var id = buttonLogoutList[i];
    var e = GetElementByID(id);
    if(e != null) {
      e.style.display = 'none';
    }
  }
}

var updateLoginTickerState = false;

function UpdateAllLogin() {
  for(var i in buttonLoginList) {
    var id = buttonLoginList[i];
    var e = GetElementByID(id);
    if(e != null) {
      if(admintimeoutcounter > 0) {
        if(updateLoginTickerState == true) {
          var iTemp = parseInt(admintimeoutcounter / 60);
          var sTimeout = iTemp+':';
          iTemp = admintimeoutcounter - (60 * iTemp);
          if(iTemp < 10) {
            sTimeout = sTimeout + '0' + iTemp;
          } else {
            sTimeout = sTimeout + iTemp;
          }
          updateLoginTickerState = false;
        } else {
          var iTemp = parseInt(admintimeoutcounter / 60);
          var sTimeout = iTemp+' ';
          iTemp = admintimeoutcounter - (60 * iTemp);
          if(iTemp < 10) {
            sTimeout = sTimeout + '0' + iTemp;
          } else {
            sTimeout = sTimeout + iTemp;
          }
          updateLoginTickerState = true;
        }
        e.innerHTML = sTimeout;
      } else {
        e.innerHTML = sLogin;
      }
    }
  }
}

function SetLoginTexts() {
  for(var i in buttonLoginList) {
    var id = buttonLoginList[i];
    var e = GetElementByID(id);
    if(e != null) {
      e.innerHTML = sLogin;
    }
  }
}

function RefreshPageWithSelectedValue(origin, href) {
  var value = origin.value;
  href = href.replace(/\@\@value\@\@/gi, value);
  href = href.replace(/\%40\%40value\%40\%40/gi, value);
  window.location = href;
}

function LoadPreview(id, href) {
  var iframeObj = GetElementByID(id);
  iframeObj.src = href;
}

