/*
  Copyright (C) 2001 - 2008 Astro Share BV, The Netherlands.
  All rights reserved.

  This file is part of the Astro-Online Software as defined in the License
  Agreement, found in file "license.txt".

  Astro-Online is distributed with NO WARRANTY OF ANY KIND.  No author
  or distributor accepts any responsibility for the consequences of using it,
  or for whether it serves any particular purpose or works at all, unless he
  or she says so in writing.

  Every copy of Astro-Online must include a copy of the License Agreement,
  normally in a plain ASCII text file named "license.txt". The License Agreement
  grants you the right to copy and modify the Astro-Online source code and
  documentation, but only under certain conditions described in the License
  Agreement. You are allowed to copy the content delivered with the source code
  and documentation. You are NOT ALLOWED to modify the content or use the content
  in other services without the written permission of Astro Share. Among other
  things, the License Agreement requires that the copyright notices and this
  notice be preserved on all copies.

  Author: Peter Schulz
*/

/*
  This JavaScript code implements a dynamic list of cities. This implementation
  uses the Astro-Online servlet with id "lovdynamic", which is a specialized
  template of the class Lov. This class gives the list of cities in a list
  of "div" tags which are then handled by this JavaScript code.
*/

// Used to connect to Astro-Online server.
var serverConnection;

// Items used to read the values from the input form.
var CountryItem      = null;
var CityItem         = null;
var LatItem          = null;
var LonItem          = null;
var CityListBox      = null;

// Variables used for navigation through the list of cities.
var CityItemPrevious = -1;
var CityItemCurrent  = -1;

// Variable to enable/disable onchange JS triggers.
var doOnChange       = 0;

// Indicator for the type of lov.
// D1 = Dynamic list for person 1.
// D2 = Dynamic list for person 2.
var lovType          = null;

// This is the main function called from the input form.
function getCityList(person, event) {
    if (navigator && navigator.userAgent.toLowerCase().indexOf("safari")!=-1) {
        // InnerHTML does not work under all cercumstances testet with Safari.
        // Problem is to be solved later...
        return;
    }
    if (person=="1") {
        // (Re)Set input form items to items belonging to person 1.
        CountryItem = document.getElementById("AO_BirthCountry");
        CityItem    = document.getElementById("AO_BirthPlace");
        LatItem     = document.getElementById("AO_BirthLatitude");
        LonItem     = document.getElementById("AO_BirthLongitude");
        CityListBox = document.getElementById("CityListBox");
        lovType     = "D1";
    }
    else {
        // (Re)Set input form items to items belonging to person 2.
        CountryItem = document.getElementById("AO_BirthCountry2");
        CityItem    = document.getElementById("AO_BirthPlace2");
        LatItem     = document.getElementById("AO_BirthLatitude2");
        LonItem     = document.getElementById("AO_BirthLongitude2");
        CityListBox = document.getElementById("CityListBox2");
        lovType     = "D2";
    }
    if (getKeyEventCode(event)==13) {
        // key ENTER = select item
        doitemevent = document.getElementById("cityItem." + lovType + "." + CityItemCurrent);
        if (doitemevent)
            doitemevent.onclick();
    }
    else if (getKeyEventCode(event)==40) {
        // key 40 = down
        ItemNo = CityItemCurrent;
        ItemNo++;
        if (document.getElementById("cityItem." + lovType + "." + ItemNo)) {
            CityItemPrevious = CityItemCurrent;
            CityItemCurrent++;
            resetCurrentCityItem();
        }
    }
    else if (getKeyEventCode(event)==38) {
        // key 38 = up
        if (CityItemCurrent>0) {
            CityItemPrevious = CityItemCurrent;
            CityItemCurrent--;
            resetCurrentCityItem();
        }
    }
    else {
        if(CityItem.value.length>1)
            // Build dynamic listbox.
            setTimeout("getCityListFromServer()", 250);
        else
            // Hide dynamic listbox is it was already visible.
            hideCityListBox();
    }
}

// Reset the current item in the listbox.
// The previously selected item will be shown as unselected. The current
// item will be shown as selected.
function resetCurrentCityItem() {
    unsetPreviousSelection();
    setCurrentSelection();
    
    // Reset listbox in case currently selected item is not visible.
    if (CityListBoxItem)
        CityListBoxItem.scrollIntoView(false);
}

// Unselect previous selection.
function unsetPreviousSelection() {
    CityListBoxItem = document.getElementById("cityItem." + lovType + "." + CityItemPrevious);
    if (CityListBoxItem) {
        unsetFocus(CityListBoxItem);
    }
}

// Set new selection to currently selected item.
function setCurrentSelection() {
    CityListBoxItem = document.getElementById("cityItem." + lovType + "." + CityItemCurrent);
    if (CityListBoxItem) {
        setFocus(CityListBoxItem);
    }
}

// Set focus to item.
function setFocus(item) {
    if (item)
        item.className = "cityListBoxItemFocus";
}

// Unset focus to item.
function unsetFocus(item) {
    if (item)
        item.className = "cityListBoxItemNoFocus";
}

// Set focus for mouse events. This is handled different from key events, 
// since mouse events do not need to move sequentially through the list.
function setMouseFocus(item) {
    if (item)
        if (item.id) {
            CityItemPrevious = CityItemCurrent;
            CityItemCurrent  = item.id.substring(item.id.indexOf(".")+1);            
        }
    unsetPreviousSelection();
    setCurrentSelection();
    
    if (CityListBoxItem)
        CityListBoxItem.scrollIntoView(false);
}

// Unset focus for mouse events.
function unsetMouseFocus(item) {
}

// Hide listbox.
function hideCityListBox() {
    setTimeout("if (CityListBox) { CityListBox.style.overflow = 'hidden'; CityListBox.style.visibility = 'hidden' }", 250);
}

// Get listbox from server. The response is based on the arguments offered
// in the request.
function getCityListFromServer() {
    if (CityListBox) {
        // This might take some time, therefore temporarily show a message to
        // inform the user something is happening.
    	CityListBox.innerHTML        = "<div class='cityNoFocus'>Een ogenblik geduld s.v.p...</div>";
        CityListBox.style.visibility = "visible";
        CityListBox.style.overflow   = "auto";	
        try {
            // Open a connection...
            serverConnection = new XMLHttpRequest();
            serverConnection.onreadystatechange=receivedCityListFromServer;
            serverConnection.open("GET", "astroonline?id=lovdynamic&AO_Startup=N&AO_LovStartup=N&AO_LovCountry=" + CountryItem.value + "&AO_LovCity=" + CityItem.value + "&AO_LovType=" + lovType);
            serverConnection.setRequestHeader("Content-Type", "text/html");
            serverConnection.send("");
        } catch (ex) {
            // Connection failed.
            serverConnection = false;
            alert("Er is een fout opgetreden, gebruik s.v.p. zoekscherm voor plaatsnamen.");
            alert("Error: " + ex);
        }
    }
}

// Received list from server. Process list and make the results visible to the user.
function receivedCityListFromServer() {
    if (serverConnection.readyState=="4" && CityListBox) {
    	if (!serverConnection.responseText)
            CityListBox.innerHTML = "<div class='cityNoFocus'>Geen gegevens gevonden!</div>";
        else
            CityListBox.innerHTML = unescape(serverConnection.responseText);
        CityListBox.style.visibility = "visible";
        
        CityItemCurrent = 0;
        resetCurrentCityItem();
    }
}

// Pass selected values from dynamic listbox to entry form.
function selectcity(P_CITY, P_LAT, P_LON) {
    doOnChange     = -1;
    CityItem.value = P_CITY;
    LatItem.value  = P_LAT;
    LonItem.value  = P_LON;
    hideCityListBox();
}

// Get environment depending key code from event.
function getKeyEventCode(event) {
    if (window.event)
	return window.event.keyCode;
    else if (event)
	return event.keyCode;
    return null;
}

