// 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);
}

// Show the font switcher (it will be hidden if JavaScript is disabled)
function showFont()
{
  var font = document.getElementById('font');
  if (font)
    font.style.display = 'block';
}

// 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
var searchText = "";
function initSearchText(text)
{
  searchText = text;
  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 == searchText)
  {
    node.style.color = "#beb2d6";
    node.value = searchText;
  }
}
function resetSearchText(node)
{
  if (node.style.color != "")
  {
    node.value = "";
    node.style.color = "";
  }
}
function checkSearchText(form)
{
  for (var i=0; i<form.elements.length; ++i)
    if (form.elements[i].className == "searchquery" && form.elements[i].value == searchText)
      form.elements[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);
}

// Google maps integration code
var map = null;
var geocoder = null;

// Show a given address on a map in the div with id "map_canvas"
function showAddress(address, description)
{
  if (!geocoder && GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));
    geocoder = new GClientGeocoder();
  }
  if (geocoder)
  {
    geocoder.getLatLng(address, 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, 13);

        // 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()
          {
            if (map.getInfoWindow().isHidden())
              marker.openInfoWindowHtml(description);
          });
          marker.openInfoWindowHtml(description);
        }

        // Add controls
        map.addControl(new GMapTypeControl());
        map.addControl(new GSmallZoomControl());
      }
    });
  }
}

// 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());
      }
    });
  }
}

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);
          });
        }
      }
    });
  }
}

function addCustomIconMarker(address, description, type)
{
  if (geocoder)
  {
    geocoder.getLatLng(address, 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
      {
        // Create a custom marker for this address
        var customIcon = new GIcon();
        if (type == "house")
        {
          customIcon.image = repository_url + 'images/icon_blue_house.png';
          //customIcon.shadowSize = new GSize(37, 34);
          customIcon.iconSize = new GSize(24, 32);
          customIcon.iconAnchor = new GPoint(9, 34);
        }
        else if (type == "bog")
        {
          customIcon.image = repository_url + 'images/icon_blue_bog.png';
          //customIcon.shadowSize = new GSize(37, 34);
          customIcon.iconSize = new GSize(27, 32);
          customIcon.iconAnchor = new GPoint(9, 34);
        }
        customIcon.infoWindowAnchor = new GPoint(210 /* left/right */ , 35 /* top/bottom */);

        markerOptions = { icon:customIcon };
        var marker = new GMarker(point, markerOptions);

        map.addOverlay(marker);

        if (description)
        {
          GEvent.addListener(marker, 'click', function(){
            marker.openExtInfoWindow(
              map,
              "gmarker_info_window",
              description
            );
          });
        }

        // Add controls
        map.addControl(new GMapTypeControl());
        map.addControl(new GSmallZoomControl());
      }
    });
  }
}

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);
  }
}

function showCustomIconAddress(address, description, type, openInfoWindowOnStart)
{
  if (!geocoder && GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));
    geocoder = new GClientGeocoder();
  }
  if (geocoder)
  {
    geocoder.getLatLng(address, 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, 13);

        // Create a custom marker for this address
        var customIcon = new GIcon();
        if (type == "house")
        {
          customIcon.image = repository_url + 'images/icon_orange_house.png';
          //customIcon.shadowSize = new GSize(37, 34);
          customIcon.iconSize = new GSize(24, 32);
          customIcon.iconAnchor = new GPoint(9, 34);
        }
        else if (type == "bog")
        {
          customIcon.image = repository_url + 'images/icon_orange_bog.png';
          //customIcon.shadowSize = new GSize(37, 34);
          customIcon.iconSize = new GSize(27, 32);
          customIcon.iconAnchor = new GPoint(9, 34);
        }
        customIcon.infoWindowAnchor = new GPoint(210 /* left/right */ , 35 /* top/bottom */);

        markerOptions = { icon:customIcon };
        var marker = new GMarker(point, markerOptions);

        map.addOverlay(marker);

        if (description)
        {
          GEvent.addListener(marker, 'click', function(){
            marker.openExtInfoWindow(
              map,
              "gmarker_info_window",
              description
            );
          });
        }

        if (openInfoWindowOnStart)
        {
          marker.openExtInfoWindow(
                        map,
                        "gmarker_info_window",
                        description
              );
        }

        // Add controls
        map.addControl(new GMapTypeControl());
        map.addControl(new GSmallZoomControl());
      }
    });
  }
}

function moveDistricts(fromListName, toListName, imgrootPath)
{
  var fromList = document.getElementById(fromListName);
  var toList = document.getElementById(toListName);

  var options = fromList.getElementsByTagName("option");

  var selectedoptions = [];

  for(var i=0; i<options.length; i++)
  {
    if (options[i].selected)
      selectedoptions[selectedoptions.length] = options[i];
  }

  for(var i=0; i<selectedoptions.length; i++)
  {
    var group_of_option = selectedoptions[i].parentNode;
    var groupname = group_of_option.getAttribute('label');

    var groupsatright = toList.getElementsByTagName("optgroup");
    var foundOptGroup = false;
    for(var groupcount=0; groupcount<groupsatright.length; groupcount++)
    {
      if (groupsatright[groupcount].getAttribute('label') == groupname)
      {
        // add option to existing group in the right list
        groupsatright[groupcount].appendChild(selectedoptions[i]);
        foundOptGroup = true;
        break;
      }
    }

    if (!foundOptGroup)
    {
      var groupclone = group_of_option.cloneNode(false);
      groupclone.appendChild(selectedoptions[i]);
      toList.appendChild(groupclone);
    }

    if (group_of_option.getElementsByTagName('option').length == 0)
      group_of_option.parentNode.removeChild(group_of_option);
  }

  fromList.selectedIndex = -1;
  toList.selectedIndex = -1;

  sortSelGroup(toList);

  // Disable the add/remove buttons
  var addButton = document.getElementById("add_district_image");
  addButton.src = imgrootPath + "blockarrow-right-disabled.png";

  var removeButton = document.getElementById("remove_district_image");
  removeButton.src = imgrootPath + "blockarrow-left-disabled.png";

  // Set the hidden var input, a space separated options of id's
  var selectedOptionString = "";
  var selectedOptionsList = document.getElementById("emailme-districts");
  var theOptions = selectedOptionsList.getElementsByTagName("option");
  for(var i=0; i < theOptions.length; i++)
    selectedOptionString = selectedOptionString + " " + theOptions[i].value;

  var hiddenInput = document.getElementById("selecteddistricts");
  hiddenInput.value = selectedOptionString;
}

function sortSelGroup(select_element)
{
  var optNode = select_element.getElementsByTagName('optgroup')

  // iterate all optgroups and ask to sort their options
  for(var i=0;i<optNode.length;i++)
  {
    sortNodes(optNode[i], false);
  }

  sortNodes(select_element, true);
}

function sortNodes(pNode, isOptGroup)
{
  var cNode = isOptGroup ? pNode.getElementsByTagName('optgroup') : pNode.getElementsByTagName('option');

  if(!cNode.length) return;
  sorted = false;
  while(!sorted)
  {
    sorted = true;
    for(var i=0;i<cNode.length-1;i++)
    {
      var thisValue = isOptGroup ? cNode[i].getAttribute('label') : cNode[i].innerHTML;
      var nextValue = isOptGroup ? cNode[i+1].getAttribute('label') : cNode[i+1].innerHTML;

      a = (thisValue) ? thisValue : "";
      b = (nextValue) ? nextValue : "";
      if(a>b)
      {
        pNode.insertBefore(cNode[i+1],cNode[i]);
        sorted = false;
      }
    }
  }
}

function onListSelect(listId, updateButtonId, imgrootPath, imagePointerName)
{
  // If there's a selection, enable the "Add" button
  var list = document.getElementById(listId);
  var options = list.getElementsByTagName("option");

  var selectedoptions = [];
  var selectionFound = false;
  for(var i=0; i<options.length; i++)
  {
    if (options[i].selected)
    {
      selectionFound = true;
      break;
    }
  }

  var imageButton = document.getElementById(updateButtonId);
  if (selectionFound)
    imageButton.src = imgrootPath + "blockarrow-" + imagePointerName + ".png";
  else
    imageButton.src = imgrootPath + "blockarrow-" + imagePointerName + "-disabled.png";
}

function findElementInStringArray(elementsArray, value)
{
  for (var i = 0; i < elementsArray.length; i++)
  {
    if (elementsArray[i] == value)
      return i;
  }

  return -1;
}