﻿// Initialize the news ticker
var newsLink = null;
var newsTimer = null;
var newsRefreshTime = 5000; // Refresh the news ticker each 5 seconds
var newsCur = -1;
function initNewsTicker()
{
  newsLink = document.getElementById('pathitems').getElementsByTagName('a');
  if (typeof newsLink != "undefined" && newsLink.length > 0 && typeof newsList != "undefined" && newsList.length > 0)
  {
    newsLink = newsLink[0];
    newsLink.parentNode.insertBefore(document.createTextNode('Actueel: '), newsLink);
    //newsLink.parentNode.style.paddingLeft = '27px';
    nextNewsItem();
  }
}

function nextNewsItem()
{
  ++newsCur;
  if (newsCur >= newsList.length)
    newsCur = 0;
  newsLink.innerHTML = newsList[newsCur].title;
  newsLink.href = newsList[newsCur].link;
  newsTimer = window.setTimeout("nextNewsItem()", newsRefreshTime);
}

// Switch the font to the given size, or to the stored size
function switchFont(size)
{
  var cookieName = 'woonplaats-font-size';

  // If no size is given, read cookie
  if (!size)
    size = readCookie(cookieName);

  switch (size)
  {
    case 'large':
      document.body.className = 'largefont';
      break;
    default:
      size = 'small';
      document.body.className = 'smallfont';
  }

  // Remember the chosen font size for 100 days (will be reset by each page
  // refresh)
  createCookie(cookieName, size, 100);
}

// Place a standard text in all 'searchquery' input fields
function initSearchText()
{
  var inputs = document.getElementsByTagName("input");
  for (var i=0; i<inputs.length; ++i)
    if (inputs[i].className == "searchquery")
      setSearchText(inputs[i]);
}
function setSearchText(node)
{
  if (node.value == "" || node.value == node.getAttribute('defaulttext'))
  {
    node.style.color = "#beb2d6";
    node.value = node.getAttribute('defaulttext');
  }
}
function resetSearchText(node)
{
  if (node.style.color != "")
  {
    node.value = "";
    node.style.color = "";
  }
}
function checkSearchText(form)
{
  var inputs = form.getElementsByTagName("input");
  for (var i=0; i<inputs.length; ++i)
    if (inputs[i].className == "searchquery" && inputs[i].value == inputs[i].getAttribute('defaulttext'))
      inputs[i].value = "";//return false;
  return true;
}

// Cookie code from http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}

function addEvent(obj, type, fn)
{
  if (obj.attachEvent)
  {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function()
    {
      obj['e'+type+fn]( window.event );
    }
    obj.attachEvent('on'+type, obj[type+fn]);
  }
  else
  {
    obj.addEventListener(type, fn, false);
  }
}

// Initialization
var repository_url = "";
function initVars(repurl)
{
  repository_url = repurl;
}

// Google maps integration code
var map = null;
var geocoder = null;

// Center the map on the given city
function showCity(city)
{
  if (!geocoder && GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));
    geocoder = new GClientGeocoder();
  }
  if (geocoder)
  {
    geocoder.getLatLng(city, function(point)
    {
      if (!point)
      {
        // The address was not found, display an error message instead of the map
        document.getElementById("map_canvas").style.display = "none";
        document.getElementById("map_nopoint").style.display = "block";
      }
      else
      {
        // Center the address
        map.setCenter(point, 12);

        // Add controls
        map.addControl(new GMapTypeControl());
        map.addControl(new GSmallZoomControl());
//        map.addControl(new GLargeMapControl());
      }
    });
  }
}

// Add a marker with info window to the map
function addMarker(address, description)
{
  if (geocoder)
  {
    geocoder.getLatLng(address, function(point)
    {
      if (point)
      {
        // Create a marker for this address
        var marker = new GMarker(point);
        map.addOverlay(marker);

        // If there is a description, show it in the info window
        if (description)
        {
          GEvent.addListener(marker, "click", function()
          {
            marker.openInfoWindowHtml(description);
          });
        }
      }
    });
  }
}

// Quicklinks
var quicklinksCookie = "intranet_quicklinks";

var quicklinks = new Array();
function initQuickLinks()
{
  // quicklinks is one string, with fileids and links, separated by "|", e.g.:
  // "fileid|title of the quicklink|fileid|another quicklink"
  var savedlinks = readCookie(quicklinksCookie);
  if (savedlinks)
  {
    savedlinks = savedlinks.split("|");
    for (var i = 0; i < savedlinks.length - 1; i += 2)
    {
      var nametoks = savedlinks[i].split(' ');
      var fileid = parseInt(nametoks[0]);
      var pagename = nametoks.length>=2 ? nametoks[1] : 'index.html';
      if (fileid == fileid && fileid > 0)
        quicklinks.push({ fileid: fileid, title: savedlinks[i + 1], pagename: pagename });
    }
  }
  updateQuickLinks();
}
function saveQuickLinks()
{
  var savedlinks = "";
  for (var i = 0; i < quicklinks.length; ++i)
    savedlinks += (savedlinks != "" ? "|" : "") + quicklinks[i].fileid + ' '  + quicklinks[i].pagename + "|" + quicklinks[i].title;
  createCookie(quicklinksCookie, savedlinks, 365);
}
function getQuickLinkHref(quicklink)
{
  return repository_url + "scripts/quicklink.shtml?link=" + quicklink.fileid + "&page="+ quicklink.pagename;
}
function updateQuickLinks()
{
  var node = document.getElementById("quicklinks");
  if (node)
  {
    var div = document.createElement("div");
    if (quicklinks.length > 0)
    {
      for (var i=0; i<quicklinks.length; ++i)
      {
        var a = document.createElement("a");
        a.href = getQuickLinkHref(quicklinks[i]);

        var span = document.createElement("span");
        span.className = "smallerfont";
        var biggerthan = document.createTextNode('> ');
        span.appendChild(biggerthan);
        a.appendChild(span);
        a.appendChild(document.createTextNode(quicklinks[i].title));
        div.appendChild(a);
        div.appendChild(document.createElement("br"));
      }
    }
    else
    {
      var p = document.createElement("p");
      p.appendChild(document.createTextNode("Je hebt nog geen snelkeuzes aangemaakt."));
      p.appendChild(document.createElement("br"));
      p.appendChild(document.createTextNode("Klik op het snelkeuze-pictogram rechtsbovenaan om de pagina als snelkeuze toe te voegen."));
      div.appendChild(p);
    }
    node.replaceChild(div, node.firstChild);
  }
  node = document.getElementById("quicklinks-editor-content");
  if (node)
  {
    node.innerHTML = "";
    for (var i=0; i<quicklinks.length; ++i)
    {
      var div = document.createElement("div");
      div.idx = i;

      var img = document.createElement("img");
      img.src = repository_url + "images/icon_delete.png";
      img.width = 16;
      img.height = 16;
      img.className = "hasmargin";
      img.alt = "Verwijderen";
      img.onclick = deleteQuickLink;
      div.appendChild(img);

      img = document.createElement("img");
      img.src = repository_url + "images/icon_edit.png";
      img.width = 16;
      img.height = 16;
      img.className = "hasmargin";
      img.alt = "Hernoemen";
      img.onclick = renameQuickLink;
      div.appendChild(img);

      img = document.createElement("img");
      img.src = repository_url + "images/icon_up.png";
      if (i > 0)
      {
        img.alt = "Naar boven verplaatsen";
        img.onclick = moveUpQuickLink;
      }
      else
        img.style.cursor = "default";
      img.width = 16;
      img.height = 16;
      div.appendChild(img);

      img = document.createElement("img");
      img.src = repository_url + "images/icon_down.png";
      if (i < quicklinks.length-1)
      {
        img.alt = "Naar beneden verplaatsen";
        img.onclick = moveDownQuickLink;
      }
      else
        img.style.cursor = "default";
      img.width = 16;
      img.height = 16;
      div.appendChild(img);

      var a = document.createElement("a");
      a.href = getQuickLinkHref(quicklinks[i]);
      a.appendChild(document.createTextNode(quicklinks[i].title));
      div.appendChild(a);

      node.appendChild(div);
    }
  }
}
function filterQuickLinkText(text)
{
  // Replace reserved characters
  return text.split(";").join("").split("|").join("");
}
function addQuickLink(fileid, title, pagename)
{
  title = filterQuickLinkText(title);
  if (fileid > 0 && title != "")
  {
    quicklinks.push({ fileid: fileid, title: title, pagename:pagename });
    updateQuickLinks();
    saveQuickLinks();
  }
}
function openQuickLinksEditor()
{
  var node = document.getElementById("quicklinks-editor");
  if (node)
  {
    node.style.display = "block";
  }
}
function closeQuickLinksEditor()
{
  var node = document.getElementById("quicklinks-editor");
  if (node)
    node.style.display = "none";
}
function deleteQuickLinkById(id)
{
  id = parseInt(id);
  if (id != id || id < 0 || id >= quicklinks.length)
    return;
  quicklinks.splice(id, 1);
  saveQuickLinks();
  updateQuickLinks();
}
/*function deleteQuickLinkByFileid(fileid)
{
  for (var i=0; i<quicklinks.length; ++i)
    if (quicklinks[i].fileid == fileid)
      return deleteQuickLinkById(i);
}*/
function deleteQuickLink()
{
  var i = this.parentNode.idx;
  deleteQuickLinkById(i);
}
var renamingNode = null;
var renamingInput = null;
function renameQuickLink()
{
  renamingInput = document.createElement("input");
  renamingInput.value = quicklinks[this.parentNode.idx].title;
  renamingInput.onblur = renameCancel;
  renamingInput.onkeydown = renameKeydown;
  renamingNode = this.parentNode.replaceChild(renamingInput, this.parentNode.lastChild);
  renamingInput.select();
  renamingInput.focus();
}
function renameSubmit()
{
  if (renamingInput.value != "")
  {
    quicklinks[renamingInput.parentNode.idx].title = renamingInput.value;
    saveQuickLinks();
    updateQuickLinks();
  }
  else
    renameCancel();
}
function renameCancel()
{
  renamingInput.parentNode.replaceChild(renamingNode, renamingInput);
  renamingNode = null;
  renamingInput = null;
}
function renameKeydown(e)
{
  if(!e)
    e=window.event;

  if (e.keyCode == 27)
    renameCancel();
  else if (e.keyCode == 13)
    renameSubmit();
}
function moveDownQuickLink()
{
  var i = this.parentNode.idx;
  if (i < quicklinks.length-1)
  {
    var temp = quicklinks.splice(i, 1)[0];
    quicklinks.splice(i + 1, 0, temp);
    saveQuickLinks();
    updateQuickLinks();
  }
}
function moveUpQuickLink()
{
  var i = this.parentNode.idx;
  if (i > 0)
  {
    var temp = quicklinks.splice(i, 1)[0];
    quicklinks.splice(i - 1, 0, temp);
    saveQuickLinks();
    updateQuickLinks();
  }
}

// Important message
var importantNewsCookie = "intranet-importantnews";

function showImportant(fileid)
{
  var lastshowed = readCookie(importantNewsCookie);
  if (lastshowed != fileid)
  {
    var div = document.getElementById('importantnews');
    if (div)
    {
      div.style.display = "block";
    }
    div = document.getElementById('importantnewsbg');
    if (div)
    {
      div.style.display = "block";
    }
    document.body.style.overflow = "hidden"; // Suppress scrollbars
    document.body.scroll = "no";
  }
}
function closeImportant(fileid, url)
{
  createCookie(importantNewsCookie, fileid, 365);
  if (url)
  {
    document.location = url;
    return;
  }
  var div = document.getElementById('importantnews');
  if (div)
    div.style.display = "none";
  div = document.getElementById('importantnewsbg');
  if (div)
    div.style.display = "none";
  document.body.style.overflow = ""; // Show scrollbars again
  document.body.scroll = "yes";
}

function initProjectMap(location)
{
  var mapdiv = document.getElementById("projectmap");
  if (location && mapdiv)
  {
    var coords = location.split(",");
    toddGM_Initialize("projectmap", { center: location
                                    , zoom: 15
                                    , moveable: true
                                    , OnInitialized: function()
                                      {
                                        this.map.setOptions({ zoomControl: true });
                                        this.UpdateAllOverlays([{ rowkey: "project"
                                                                , type: "marker"
                                                                , lat: parseFloat(coords[0])
                                                                , lng: parseFloat(coords[1])
                                                                , selectable: false
                                                                , moveable: false
                                                                }]);
                                      }
                                    });
  }
}

