/*
 * Gletschereis CMS - Functions for Browser-Differences  
 *
 * (C) 2006 Johannes Ott (cms@gletschereis.net)
 *
 * $Id: framework.js 1298 2010-03-04 11:08:22Z oetzi $
 *
 */

//IE Blinkender Cursor Bug 
try 
{
    document.execCommand("BackgroundImageCache", false, true);
} 
catch(err) {}


function enterPressed(event) {

    if (event) {
        if (event.which == 13)
        {
            stopEvent(event);
            return true;
        }
        else if (event.keyCode == 13)
        {
            stopEvent(event);
            return true;    
        }
    }

    return false;
}

function stopEvent(event)
{
    if (event.stopPropagation)
    {
        event.stopPropagation();
    }
    else
    {
        event.cancelBubble = true;
    }
}

function checkFrame()
{
    if (self != parent) 
        top.location.href=self.location; 
}

function clearUploadField(fieldID)
{
    var field = document.getElement(fieldID);

    if (field != null)
        field.value = '';
}

document.isBrowser = function(browser)
{
    return navigator.userAgent.toLowerCase().indexOf(browser.toLowerCase()) > -1;
}


document.getElement = function(obj) 
{
    if(document.getElementById)
        return document.getElementById(obj);
    else if (document.layers)
        return document.layers[obj];
    else if(document.all)
        return document.all[obj];
    else if(document.getElementsByName)
        return document.getElementsByName(obj)[0];
    else     
        return null;
}

document.targetBlank = function()
{
    var links = document.getElementsByTagName('a');
    for (var i=0; i < links.length; i++)
    { 
        if (links[i].className.indexOf('_blank') > -1) 
        {
            links[i].onclick = function() 
            {
                window.open(this.href);
                return false;
            };
        }
    }
}

Function.prototype.scopeBind = function(obj, inputs)
{
    if (inputs == null)
        inputs = new Array();

    var args = arguments;

    var method = this,
        temp = function()
        {
            return method.apply(obj, inputs.concat(args));
        };
    return temp;
}

Function.prototype.scope = function(obj)   
{       
    var args = arguments;      
    var method = this;       
    return function(event)        
    {                      
        return method.apply(obj,[( event ||     window.event)].concat(args));       
    };  
} 

function in_array(needle, arr)
{
    for (var i = 0; i < arr.length; i++)
        if (arr[i]  === needle)
            return true;

    return false;
}

function array_search(needle, arr)
{
    for (var i = 0; i < arr.length; i++)
        if (arr[i]  === needle)
            return i;

    return false;
}

function array_erase(needle, arr)
{
    var index = array_search(needle, arr);
    if (index || index == 0)
        return arr.slice(0, index).concat(arr.slice(index+1, arr.length));

    return arr;
}

//get absolute Position of an element
function getPosition(el, absoluteBreak)
{
    if (typeof(el.offsetParent) != 'undefined')
    {
        for (var x = 0, y = 0, ebene = 0; el; el = el.offsetParent, ebene++)
        {
            if (absoluteBreak && ebene > 0)
                if (style_position(el) == 'absolute')
                    return [x, y];

            x += Number(el.offsetLeft);
            y += Number(el.offsetTop);

            for (var el2 = el; el2 != el.offsetParent; el2 = el2.parentNode)
            {
                var position = getScroll(el2, x, y);

                x = position[0];
                y = position[1];

            }

        }

        return getScroll(false, x, y);
    }
    else
    {
        var position = getScroll(el, el.x, el.y)
        return getScroll(false, position[0], position[1]);
    }

}

function getScroll(el, x, y)
{
    if (el)
    {
        if (typeof(el.scrollLeft) != "undefined")
            x -= el.scrollLeft;
        
        if (typeof(el.scrollTop) != "undefined")
            y -= el.scrollTop;
    }
    else
    {
        if (document.compatMode && document.compatMode == "CSS1Compat") 
        {
            x += document.documentElement.scrollLeft;
            y += document.documentElement.scrollTop;
        } 
        else 
        {
            x += document.body.scrollLeft;
            y += document.body.scrollTop;
        }

    }

    return [x, y];
}

function style_position(el)
{
    if (window.getComputedStyle)
        return window.getComputedStyle(el, "").getPropertyValue("position");
    else if (el.currentStyle)
        return el.currentStyle.position;
    else
        return null;
}

String.prototype.trim = function(zeichenkette) 
{
      return this.replace (/^\s+/, '').replace (/\s+$/, '');
}

String.prototype.fromPreis = function()
{
    return Number(this.replace(/[\.]/, '').replace(/[,]/, '.'));
}

Number.prototype.germanFormat = function(decimals)
{
    var number = this;
    var dec_point = ',';
    var thousands_sep = '.';

    if (number == 0)
        return null;

    var exponent = "";
    var numberstr = number.toString ();
    var eindex = numberstr.indexOf ("e");
    if (eindex > -1)
    {
        exponent = numberstr.substring (eindex);
        number = parseFloat (numberstr.substring (0, eindex));
    }

    if (decimals != null)
    {
        var temp = Math.pow (10, decimals);
        number = Math.round (number * temp) / temp;
    }
    var sign = number < 0 ? "-" : "";
    var integer = (number > 0 ? 
            Math.floor (number) : Math.abs (Math.ceil (number))).toString ();

    var fractional = number.toString ().substring (integer.length + sign.length);
    dec_point = dec_point != null ? dec_point : ".";
    fractional = decimals != null && decimals > 0 || fractional.length > 1 ? 
        (dec_point + fractional.substring (1)) : "";
    if (decimals != null && decimals > 0)
    {
        for (i = fractional.length - 1, z = decimals; i < z; ++i)
            fractional += "0";
    }

    thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? 
        thousands_sep : null;
    if (thousands_sep != null && thousands_sep != "")
    {
        for (i = integer.length - 3; i > 0; i -= 3)
            integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
    }

    return sign + integer + fractional + exponent;

}

function cElement(id, type)
{
    this.obj = document.getElement(id);
    if (this.obj == null)
    {
        if (typeof(type) == "undefined")
            return;
        else
        {
            this.obj = document.createElement(type);
            this.obj.id = id;
            var body = document.getElementsByTagName('body')[0];
            body.appendChild(this.obj);
        }
    }
    this.blendInterval = null;
    this.cur_opac;
    this.props = new Array();
    this.overlayStepwidth = 10;
    this.overlaySpeed = 50;

    this.loadProps = function()
    {
        var position = getPosition(this.obj, true);
        this.props['x'] = position[0];
        this.props['y'] = position[1];
        this.props['z'] = this.obj.zIndex;
        this.props['p'] = style_position(this.obj);
        this.props['w'] = this.obj.offsetWidth;
        this.props['h'] = this.obj.offsetHeight;
    }
    
    this.loadProps();

    this.getRelativePosition = function(position)
    {
        this.loadProps();

        switch (position)
        {
            case "left,below":
            case "below":
                var x = this.props['x'];
                var y = Number(this.props['y']) + Number(this.props['h']);
                break;
            case "right,top":
            case "right":
                var x = Number(this.props['x']) + Number(this.props['w']);
                var y = this.props['y'];
                break;
            default:
                var x = this.props['x'];
                var y = this.props['y'];
        }

        return [x, y];
    }

    this.opacity = function(opacity)
    {   
        if (opacity < 0)
            opacity = 0;
        else if (opacity > 100)
            opacity = 100;

        this.cur_opac = opacity;

        if (navigator.appName.indexOf("Explorer") != -1)
            this.obj.style.filter = "alpha(opacity=" + opacity + ")";
        else
        {
            this.obj.style.MozOpacity = (opacity/100);
            this.obj.style.KHTMLOpacity = (opacity/100);
        }
        
        this.obj.style.opacity = (opacity/100);
    } 

    this.blend = function (to, speed, stepwidth, bSetStyles)
    {
        if (this.blendInterval != null)
            return;
        if (speed == null)
            speed = 100;
        if (stepwidth == null)
            stepwidth = 1;
        if (bSetStyles == null)
            bSetStyles = false;

        this.blendInterval = setInterval(this.fadeOpacityTo.scopeBind(this, [to, stepwidth, bSetStyles]), speed);
    }

    this.stopBlend = function()
    {
        if (this.blendInterval != null)
        {
            clearInterval(this.blendInterval);
            this.blendInterval = null;
        }
    }

    this.fadeOpacityTo = function (to, stepwidth, bSetStyles)
    {
        if (to == null || to < 0)
            to = 0;
        else if (to > 100)
            to = 100;

        if (to < this.cur_opac)
            var new_opac = Number(this.cur_opac) - Number(stepwidth);
        else if (to > this.cur_opac)
        {
            var new_opac = Number(this.cur_opac) + Number(stepwidth);
            if (bSetStyles)
                this.obj.style.zIndex = 2;
        }
        else
            var new_opac = Number(this.cur_opac);
        
        if (new_opac == to || new_opac <= 0 || new_opac >= 100)
        {
            if (this.blendInterval != null)
            {
                clearInterval(this.blendInterval);
                this.blendInterval = null;
            }

            if (bSetStyles)
                this.obj.style.zIndex = 1;
        }

        this.opacity(new_opac);
        if (this.cur_opac == 0)
            this.obj.style.display = 'none';
        else if (bSetStyles)
            this.obj.style.display = '';
    }

    this.setPosition = function (x, y, z, pos)
    {
        if (x != null)
        {
            this.props['x'] = x;
            this.obj.style.left = x + 'px';
        }

        if (y != null)
        {
            this.props['y'] = y;
            this.obj.style.top = y + 'px';
        }

        if (z != null)
        {   
            this.props['z'] = z;
            this.obj.style.zIndex = z;
        }

        if (pos != null)
        {
            this.props['p'] = pos;
            this.obj.style.position = pos;
        }
    }

    this.setBondage = function (w, h)
    {
        if (w != null)
        {
            this.props['w'] = w;
            this.obj.style.width = w + 'px';
        }

        if (h != null)
        {
            this.props['h'] = h;
            this.obj.style.height = h + 'px';
        }
    }

    this.hide = function ()
    {
        if (this.iframe != null)
            this.iframe.hide();

        this.obj.style.display = 'none';
    }

    this.setOverlayBlend = function(set_stepwidth, set_speed)
    {
        if (set_stepwidth != null)
            this.stepwidth = set_stepwidth;

        if (set_speed != null)
            this.speed = set_speed;
    }

    this.overlay = function(use_iframe)
    {
        this.block();
        this.stopBlend();
        this.blend(100, this.overlaySpeed, this.overlayStepwidth);

        if (navigator.appName.indexOf("Explorer") != -1)
        {
            if (this.iframe == null)
            {
                var hidder = document.getElement('hidder_' + use_iframe);
                if (hidder == null)
                {
                    hidder = document.createElement('iframe');
                    hidder.id = "hidder_" + use_iframe;

                    this.obj.parentNode.appendChild(hidder);
                }

                this.iframe = new cElement(hidder.id);
            }

            this.iframe.setPosition(this.props['x'], this.props['y'], this.props['z'] - 1, 'absolute');
            this.iframe.setBondage(this.props['w'], this.props['h']);
            this.iframe.stopBlend();
            this.iframe.opacity(0);
            this.iframe.blend(100, this.overlaySpeed, this.overlayStepwidth);
        }
    }

    this.hideBlend = function()
    {
        if (this.iframe != null)
            this.iframe.hideBlend();

        this.stopBlend();
        this.blend(0, this.overlaySpeed, this.overlayStepwidth);
    }


    this.block = function ()
    {
        this.obj.style.display = 'block';
    }

    this.appendToParent = function(brother, offset)
    {
        var parent_obj = brother.parentNode;
        
        if (typeof(offset) == "undefined" || offset == 0)
        {
            parent_obj.appendChild(this.obj);
        }
        else
        {
            var i = parent_obj.childNodes.length  - offset;
            parent_obj.insertBefore(this.obj, parent_obj.childNodes[i]);
        }
        
        if (this.iframe != null)
            parent_obj.appendChild(this.iframe.obj);
    }

    this.getRenamedClone = function(replace_string, with_string, emptyValues)
    {
        if (typeof(emptyValues) == "undefined")
            emptyValues = false;

        var newObj = this.obj.cloneNode(true);

        return this.renameRecursive(newObj, replace_string, with_string, emptyValues);
    }

    this.renameRecursive = function(node, replace_string, with_string, emptyValues)
    {
        if (typeof(replace_string) == "string")
            replace_string = eval('/' + replace_string + '/g');

        var current_node = node;

        while (current_node != null)
        {
            if (current_node.visited)
            {
                current_node.visited = false;

                if (current_node = node)
                    break;

                if (current_node.nextSibling)
                    current_node = current_node.nextSibling;
                else
                    current_node = current_node.parentNode;
            }
            else
            {
                if (current_node.nodeType == 3)
                {
                    current_node.nodeValue = current_node.nodeValue.replace(replace_string, with_string);
                }
                else
                {
                    var tagName = current_node.tagName;

                    if (current_node.name != null)
                        current_node.setAttribute("name", current_node.name.replace(replace_string, with_string));

                    if(current_node.id != null)
                        current_node.id = current_node.id.replace(replace_string, with_string);

                    if (tagName == "LABEL")
                        current_node.setAttribute("for", current_node.attributes['for'].replace(replace_string, with_string));

                    current_node = this.renameEventAttribute('onclick', replace_string, with_string, current_node);

                    if (tagName == "INPUT" || tagName == "SELECT")
                    {
                        var value = current_node.getAttribute('value');
                        if (emptyValues && value != null && tagName == "INPUT" && current_node.getAttribute("type") == "text")
                            current_node.value = '';

                        current_node = this.renameEventAttribute('onchange', replace_string, with_string, current_node);
                    }
                }

                if (curren_node.firstChild && tagName != "SELECT")
                {
                    current_node.visited = true;
                    current_node.firstChild;
                }
                else if (current_node.nextSibling)
                    current_node = current_node.nextSibling;
                else
                    current_node = current_node.parentNode;
            }
        }
    }    

    this.renameEventAttribute = function(name, replace_string, with_string, node)
    {
        if (typeof(node) == "undefined")
            node = this.obj;

        if (typeof(replace_string) == "string")
            replace_string = eval('/' + replace_string + '/g');

        var attribute = eval('node.' + name);
        if (attribute != null)
        {
            var str = attribute.toString().replace('function anonymous()', '').replace('function ' + name + '(event)', '');
            node.setAttribute(name, str);
            eval('node.' + name) = new Function(str);
        }

        return node;

    }
    this.embedSWFObject = function(swffile, flashvars, params, attributes)
    {
        var swfobj = document.createElement('object');

        swfobj.setAttribute('type', 'application/x-shockwave-flash');

        if (document.isBrowser('IE'))
        {
            var param = document.createElement('param');
            param.setAttribute('name', 'movie');
            param.setAttribute('value', swffile);

            swfobj.appendChild(param);
        }
        else 
        {
            swfobj.setAttribute('data', swffile);
        }

        for (var name in attributes)
        {
            swfobj.setAttribute(name, attributes[name]);
        }

        swfobj.setAttribute('width', this.props['w']);
        swfobj.setAttribute('height', this.props['h']);

        swfobj.id = 'swf_' + this.obj.id + '_obj';

        for (var name in params)
        {
            var param = document.createElement('param');
            param.setAttribute('name', name);
            param.setAttribute('value', String(params[name]));
            swfobj.appendChild(param);
        }

        var flashvarsStr = '';
        var i = 0;
        for (var name in flashvars)
        {
            if (i != 0)
                flashvarsStr = flashvarsStr + '&';

            i++;

            flashvarsStr = flashvarsStr + name + '=' + flashvars[name];
        }

        var param = document.createElement('param');
        param.setAttribute('name', 'flashvars');
        param.setAttribute('value', flashvarsStr);
        swfobj.appendChild(param);

        this.obj.appendChild(swfobj);
    }
}

function cFading(set_width, set_height, set_stepwidth, set_speed)
{
    this.width = set_width;
    this.height = set_height;

    this.startTimeout = null;
    this.rotateInterval = null;
    this.wait = null;
    
    this.ispaused = false;
    this.speed = set_speed;
    this.stepwidth = set_stepwidth;

    this.objects = new Array();

    this.cur = 0;


    this.addObject = function(id, hide)
    {   
        var length = this.objects.length;
        this.objects[length] = new cElement(id);

        this.objects[length].setPosition(null, null, 1, 'absolute');
        this.objects[length].setBondage(this.width, this.height);
 
        if (hide)
        {
            this.objects[length].opacity(0);
            this.objects[length].hide();
        }
        else
            this.objects[length].opacity(100);
    }

    this.rotate = function(wait)
    {
        var curObj = this.objects[this.cur].obj;
        
        this.wait = wait;
        if (this.speed == null) 
            this.speed = 100;
        if (this.stepwidth == null) 
            this.stepwidth = 1;

        for (var i = 0; i < this.objects.length; i++)
        {
            this.objects[i].obj.onmouseover = this.pause.scopeBind(this);
            this.objects[i].obj.onmouseout = this.unpause.scopeBind(this);   
        }

        this.startTimeout = setTimeout(this.setRotateInterval.scopeBind(this), this.wait * 1000);
    }

    this.setRotateInterval = function()
    {
        this.next();
        this.rotateInterval = setInterval(this.next.scopeBind(this), Number(this.wait * 1000) + Number(this.speed * Math.round(100/this.stepwidth)));
    }

    this.pause = function()
    {
        if (this.rotateInterval != null)
        {
            clearInterval(this.rotateInterval);
            this.rotateInterval = null;
        }
        else if (this.startTimeout != null)
        {
            clearTimeout(this.startTimeout);
            this.startTimeout = null;
        }
        else
            return;

        this.cur = this.calc(Number(this.cur) - Number(1));
        this.ispaused = true;
    }

    this.unpause = function()
    {
        if (this.ispaused)
        {
            this.ispaused = false;
            this.setRotateInterval();
        }
    }

    this.calc = function(to)
    { 
        var length = this.objects.length - 1;
        if (to > length)
            to = 0
        else if (to < 0)
            to = length;
        
        return to;
    }

    this.next = function()
    {
        var next = this.calc(Number(this.cur) + Number(1));
        this.objects[this.cur].blend(0, this.speed, this.stepwidth, true);
        this.objects[next].blend(100, this.speed, this.stepwidth, true);
        this.cur = next; 
    }

    this.prev = function()
    {
        var prev = this.calc(Number(this.cur) - Number(1));
        this.objects[this.cur].blend(0, this.speed, this.stepwidth, true);
        this.objects[prev].blend(100, this.speed, this.stepwidth, true);
        this.cur = prev; 
    }
}  

function cNavigation(main_id, sub_id, position, set_stepwidth, set_speed)
{
    this.main_id = main_id;
    this.sub_id = sub_id;
    this.position = position;
    this.hide_delay = 500;

    this.objs = new Array();
    this.opened = null
    this.hideTimer = null;

    if (set_stepwidth == null)
        this.stepwidth = 5;
    else
        this.stepwidth = set_stepwidth;

    if (set_speed == null)
        this.speed = 50;
    else 
        this.speed = set_speed;

    this.buildJoomlaMenuStructure = function(id, set_width, offsetX, offsetY)
    {
        var div = document.getElement(id);

        var ids = new Array();

        for (var i = 0; i < div.childNodes.length; i++)
        {
            var ul = div.childNodes[i];
            if (ul.tagName != "UL" || ul.className != "menu-nav")
                continue;

            for (var j = 0; j < ul.childNodes.length; j++)
            {
                var li = ul.childNodes[j];
                if (li.tagName != "LI" || li.className.indexOf("parent") == -1)
                    continue;

                var id = Number(j);
                ids.push(id);

                for (var k = 0; k < li.childNodes.length; k++)
                {
                    var child = li.childNodes[k];

                    if (child.tagName == "A")
                        child.id = this.main_id + id;

                    if (child.tagName == "UL")
                        child.id = this.sub_id + id;

                }
            }
        }

        for (var i = 0; i < ids.length; i++)
        {
            this.addId(ids[i], set_width, offsetX, offsetY);
        }
    }

    this.addId = function(id, set_width, offsetX, offsetY)
    {
        this.objs[id] = new Array();
        this.objs[id]['main'] = new cElement(this.main_id + id);
        if (this.objs[id]['main'].obj == null )
            return;
        this.objs[id]['sub'] = new cElement(this.sub_id + id);
        if (this.objs[id]['sub'].obj == null )
            return;

        if (offsetX == null)
            this.objs[id]['offsetX'] = 0;
        else
            this.objs[id]['offsetX'] = offsetX;

        if (offsetY == null)
            this.objs[id]['offsetY'] = 0;
        else
            this.objs[id]['offsetY'] = offsetY;

        if (set_width == 1)
            this.objs[id]['sub'].setBondage(this.objs[id]['main'].props['w']);
        
        this.objs[id]['sub'].opacity(0);
        this.objs[id]['sub'].setOverlayBlend(this.stepwidth, this.speed);

        this.objs[id]['main'].obj.onmouseover = this.open.scopeBind(this, [id]);
        this.objs[id]['main'].obj.onmouseout = this.close_timed.scopeBind(this, [id]);
  
        this.objs[id]['sub'].obj.onmouseover = this.open.scopeBind(this, [id]);
        this.objs[id]['sub'].obj.onmouseout = this.close_timed.scopeBind(this, [id]);

    }

    this.open = function(id)
    {
        if (this.hide_timer != null) 
        {
            clearTimeout(this.hide_timer);
            this.hide_timer = null;
        }

        if (this.opened != null)
            this.close(this.opened);

        var obj = this.objs[id];
        var x = 0;
        var y = 0;

        var position = obj['main'].getRelativePosition(this.position);
        x = Number(position[0]) + Number(obj['offsetX']);
        y = Number(position[1]) + Number(obj['offsetY']);

        obj['sub'].setPosition(x, y, 100, 'absolute');
        obj['sub'].overlay("navigation_" + this.sub_id);
        this.opened = id;
    }
    
    this.close = function(id)
    {
        this.objs[id]['sub'].hideBlend();
        this.opened = null;
    }

    this.close_timed = function(id) 
    {
        this.hide_timer = setTimeout(this.close.scopeBind(this, [id]), this.hide_delay);
    }
}

function cAJAX()
{
    this.request = false;
    this.requestType = 'GET';
    this.verbose = false;

    this.newRequest = function()
    {
     
        try 
        {
            this.request = new XMLHttpRequest();
        } 
        catch (trymicrosoft) 
        {
            try 
            {
                this.request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (othermicrosoft) {
                try 
                {
                    this.request = new ActiveXObject("Microsoft.XMLHTTP");
                } 
                catch (failed) 
                {
                    this.request = false;
                }
            }
        }

        if (!this.request && this.verbose)
            alert("Error initializing XMLHttpRequest!");
       
    }

    this.buildQuery = function(script, args)
    {
        var ret = script + '?rnd=' + parseInt(Math.random()*99999999);

        for (var key in args)
        {
            ret = ret + '&' + encodeURIComponent(key) + "=" + encodeURIComponent(args[key]);
        }
        return ret;
    }

    this.execute = function(script, arArgs, callback)
    {
        if (!this.request)
            this.newRequest();

        this.request.open(this.requestType, this.buildQuery(script, arArgs));

        if (callback != null)
            this.request.onreadystatechange = callback;

        this.request.send(null);
    }

    this.ajaxImage = null;
    this.textLoading = "AJAX Loading ...";

    this.setImage = function(imgFile, textLoading)
    {
        if (imgFile != null)
            this.ajaxImage = imgFile;

        if (textLoading != null)
            this.textLoading = textLoading;
    }

    this.executeFill = function(script, arArgs, obj, imgFile, textLoading)
    {
        if (typeof(obj) == "string")
            obj = document.getElement(obj);

        if (obj == null)
        {
            alert("Object not found");
            return;
        }

        this.setImage(imgFile, textLoading);

        this.setLoadImage(obj);

        this.execute(script, arArgs, this.readyFill.scopeBind(this, [obj]));
    }

    this.readyFill = function(obj)
    {
        if (this.isReady())    
        {
            obj.innerHTML = this.responseText();
        }
    }

    this.setLoadImage = function(obj)
    {
        if (obj == null)
            return;

        if (this.ajaxImage == null)
            return;

        obj.innerHTML = '<img src="' + this.ajaxImage + '" alt="' + this.textLoading + '" title="' + this.textLoading + '"/>';
    }
    
    this.isReady = function()
    {
        if (!this.request) 
            return false;

        if (this.request.readyState == 4)
        {
            return (this.request.status == 200);
        }

        return false;
    }

    this.documentElement = function()
    {
        if (!this.isReady())
            return false;

        if (!this.request.responseXML)
            return false;

        return this.request.responseXML.documentElement;
    }

    this.responseText = function()
    {
        if (!this.isReady())
            return false;

        if (!this.request.responseText)
            return false;

        return this.request.responseText;
    }
}

function gMap(canvasID, Lat, Lng, Zoom, routeID)
{
    //Initialwerte
    this.loaded = false;
    this.initLat = Lat;
    this.initLng = Lng;
    this.initZoom = Zoom;

    //Karte
    this.canvas = document.getElement(canvasID);
    this.map = null;

    //Inhalte
    this.icons = new Array();
    this.markers = new Array();

    //Routenplaner
    this.route = null;
    this.routen = null;
    this.geo = null;
    this.reasons = new Array();
    this.strecke = null;
    this.special = new Array();
 
    if (typeof(routeID) != "undefined")
    {
        this.route = document.getElement(routeID);
    }

    //Spezielle Overlays
    this.buttonLabel = "Mehr...";
    this.toogleLabel = "Alle ausblenden";
    this.layers = new Array();

    this.load = function()
    {
        google.load("maps", "2.x", {"callback" : this.apiLoaded.scopeBind(this)});
    }

    //Initialisierung der Karte nachdem die API geladen wurde
    this.apiLoaded = function()
    {
        if (GBrowserIsCompatible()) 
        {
            this.map = new google.maps.Map2(this.canvas);
            this.initializeIcons();
            this.reset();
           
            this.map.enableScrollWheelZoom();
            this.map.enableContinuousZoom();

            //Steuerungen hinzufuegen
            this.map.addControl(new GLargeMapControl());
            this.map.addControl(new GScaleControl(100));
            
            //Gelaendekarte 
            this.map.addMapType(G_PHYSICAL_MAP);

            //Satelittenbild mit Strassennamen
            var mapControl = new GHierarchicalMapTypeControl();
            mapControl.clearRelationships();
            mapControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Strassennamen", true);
            this.map.addControl(mapControl);
       
            //Uebersichtskarte
            var ovMap=new GOverviewMapControl();
            this.map.addControl(ovMap);

            //Mehr-Knopf
            this.initializeLayerControls();

            //Steuerung nur wenn die maus ueber der Karte ist.
            this.map.hideControls();
            GEvent.addListener(this.map, "mouseover", this.map.showControls );
            GEvent.addListener(this.map, "mouseout", this.map.hideControls );
           
            this.loaded = true;
        }
        else 
        {
            alert("Leider ist diese Google Maps Version nicht mit Ihrem Browser kompatibel");
        }
    }

    this.addIcon = function(type, file, size, shadowSize, iconAnchor, infoAnchor)
    {
        var icon = new Array();
        icon['file'] = file;
        icon['size'] = size;
        icon['shadow'] = shadowSize;
        icon['anchor'] = iconAnchor;
        icon['info'] = infoAnchor;

        this.icons[type] = icon;
    }

    this.initializeIcons = function()
    {
        for (var type in this.icons)
        {
            var icon = new GIcon();
            icon.image = this.icons[type]['file'];
            icon.iconSize = new GSize(this.icons[type]['size'][0], this.icons[type]['size'][1]);
            icon.shadowSize = new GSize(this.icons[type]['shadow'][0], this.icons[type]['shadow'][1]);
            icon.iconAnchor = new GPoint(this.icons[type]['anchor'][0], this.icons[type]['anchor'][1]);
            icon.infoWindowAnchor = new GPoint(this.icons[type]['info'][0], this.icons[type]['info'][1]);
            this.icons[type]['icon'] = icon;
        }
    }

    this.reset = function()
    {
        this.map.setCenter(new GLatLng(this.initLat, this.initLng), this.initZoom);
        this.map.setMapType(G_NORMAL_MAP);
        for (i = 0; i < this.markers.length; i++)
        {
            if (this.markers[i]['marker'] != null)
            {
                this.map.removeOverlay(this.markers[i]['marker']);
                this.markers[i]['marker'] = null;
                if (this.markers[i]['special'] != null)
                    this.special[this.markers[i]['special']]['marker'] = null;
            }
        }

        for (type in this.special)
        {
            if (this.special[type]['marker'] != null && this.special[type][draggable])
            {
                this.map.removeOverlay(this.special[type]['marker']);
                this.special[type]['marker'] = null;
            }
        }

        this.initializeMarkers();

        if (this.strecke != null)
        {
            this.map.removeOverlay(this.strecke);
            this.strecke = null;
        }
    }

    this.setCenter = function(point, zoom)
    {
        if (typeof(zoom) == "undefined")
            zoom = this.initZoom;

        this.map.setCenter(point, Number(zoom));
    }

    this.addMarker = function(type, Lat, Lng, title, info, special, drag)
    {
        var marker = new Array();
        marker['marker'] = null;
        marker['type'] = type;
        marker['lat'] = Lat;
        marker['lng'] = Lng;
        marker['title'] = title;
        marker['info'] = info;

        if (typeof(special) == "undefined")
            marker['special'] = null;
        else
            marker['special'] = special;

        if (typeof(drag) == "undefined")
            marker['draggable'] = false;
        else
            marker['draggable'] = drag;

        this.markers[this.markers.length] = marker;
    }

    this.initializeMarkers = function()
    {
        var marker = null;

        for (var i = 0; i < this.markers.length; i++)
        {
            marker = new GMarker(new GLatLng(this.markers[i]['lat'], this.markers[i]['lng']), 
                                     {"title":this.markers[i]['title'], "icon":this.icons[this.markers[i]['type']]['icon'], "draggable":this.markers[i]['draggable']});

            this.markers[i]['marker'] = marker;

            marker.bindInfoWindowHtml(this.markers[i]['info']);
            this.map.addOverlay(marker);

            if (this.markers[i]['special'] != null)
            {
                this.special[this.markers[i]['special']] = new Array();
                this.special[this.markers[i]['special']]['adresse'] = this.markers[i]['title'];
                this.special[this.markers[i]['special']]['marker'] = marker;
                this.special[this.markers[i]['special']]['draggable'] = false;
            }
        }

    }

    this.printMarker = function(point, type)
    {
        if (!this.special[type]['draggable'])
            return;

        if (this.special[type]['marker'] != null)
            this.map.removeOverlay(this.special[type]['marker']);

        var icon = null;

        if (type == "start")
            icon = G_START_ICON;
        else if (type == "ziel")
            icon = G_END_ICON;
        else
            icon = this.icons[type]['icon'];

        this.special[type]['marker'] = new GMarker(point, {title:this.special[type]['adresse'], icon:icon, draggable:this.special[type]['draggable']});
        this.map.addOverlay(this.special[type]['marker']);
    }
        
    //Mehr Spezialoverlays
    this.setMoreButton = function (buttonLabel, toogleLabel)
    {
        this.buttonLabel = buttonLabel;
        this.toogleLabel = toogleLabel;
    }

    this.addLayer = function(name, url, visible)
    {
        var layer = new Array();
        layer['name'] = name;
        layer['url'] = url;
        layer['visible'] = visible;

        this.layers[this.layers.length] = layer;
    }

    this.initializeLayerControls = function()
    {
        if (this.layers.length == 0) return;

        function MoreControl(layers, buttonLabel, toogleLabel) 
        {
            this.layers = layers;
            this.buttonLabel = buttonLabel;
            this.toogleLabel = toogleLabel;
            this.map = null;
            this.button = null;
            this.navigation = null;
        }

        MoreControl.prototype = new GControl();

        MoreControl.prototype.initialize = function(map) 
        {
            this.map = map;

            var container = document.createElement("div");
            container.style.color = '#000000';
            container.style.fontSize = "12px";
            container.style.fontFamily = "Arial, sans-serif";
            container.style.backgroundColor = "#ffffff";
            
            var button = document.createElement("div");
            button.id = "Main_MoreButton";
            button.style.border = "1px solid black";
            button.style.textAlign = "center";
            buttonInnen = document.createElement("div");
            buttonInnen.style.paddingLeft="8px";
            buttonInnen.style.paddingRight="8px";
            buttonInnen.style.border = "1px solid #ffffff";
            buttonInnen.style.borderRightColor = "#b0b0b0";
            buttonInnen.style.borderBottomColor = "#b0b0b0";
            this.button = buttonInnen;
            button.appendChild(buttonInnen);
            container.appendChild(button);

            var fields = document.createElement("div")
            fields.id = "Sub_MoreButton";
            fields.style.display = "none";
            fields.style.backgroundColor = "#ffffff";
            fields.style.border = '1px solid #000000';
            fields.style.padding = '5px';
            fields.style.whiteSpace = 'nowrap';

            var checkboxField = document.createElement("div");
            checkboxField.style.paddingLeft = '5px';
            checkboxField.style.paddingRight = '5px';
            checkboxField.style.paddingBottom = '5px';
            checkboxField.style.borderBottom = '1px solid #bebebe';

            fields.appendChild(checkboxField);
            
            map.getContainer().appendChild(container);
            
            for (var i=0; i<this.layers.length; i++) 
            {
                var checkbox = document.createElement("input");
                checkbox.setAttribute("type", "checkbox");
                checkboxField.appendChild(checkbox);

                if (this.layers[i]['visible'])
                {
                    if (typeof(this.layers[i]['layer']) == "undefined")
                    {
                        this.layers[i]['layer'] = new GLayer(this.layers[i]['url'])
                        map.addOverlay(this.layers[i]['layer']);
                    }
                    checkbox.checked = true;
                }
                else
                    checkbox.checked = false;
            
                checkbox.onclick = this.toggleLayer.scopeBind(this, [i]);

                this.layers[i]['checkbox'] = checkbox;

                checkboxField.appendChild(document.createTextNode(this.layers[i]['name']));
                checkboxField.appendChild(document.createElement("br"));
            
            }

            var ausblenden = document.createElement("div");
            ausblenden.style.paddingTop = '5px';
            ausblenden.style.color = '#bebebe';
            ausblenden.style.textAlign = 'center';
            ausblenden.style.cursor = 'pointer';
            ausblenden.appendChild(document.createTextNode(this.toogleLabel));
            ausblenden.onclick = this.hideAll.scopeBind(this);
            fields.appendChild(ausblenden);
            container.appendChild(fields);
            
            this.navigation = new cNavigation("Main_", "Sub_", "left,below");
            this.navigation.addId("MoreButton", 0);

            this.changeButton();
            return container;
        }

        MoreControl.prototype.getDefaultPosition = function() {
            return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(210, 7));
        }

        MoreControl.prototype.hideAll = function()
        {
            for (var i = 0; i < this.layers.length; i++)
            {
                if (typeof(this.layers[i]['layer']) != "undefined")
                {
                    this.layers[i]['layer'].hide();
                }
                
                this.layers[i]['checkbox'].checked = false;
            }
            this.changeButton();
        }

        MoreControl.prototype.toggleLayer = function(i) 
        {

            if (this.layers[i]['checkbox'].checked) 
            {
                if(typeof(this.layers[i]['layer']) == "undefined") 
                {
                    this.layers[i]['layer'] = new GLayer(this.layers[i]['url']);
                    this.map.addOverlay(this.layers[i]['layer']);
                }
                else
                {
                    this.layers[i]['layer'].show();
                }

            }
            else
            {
                this.layers[i]['layer'].hide();
            }
            this.changeButton();
        }

        MoreControl.prototype.changeButton = function()
        {
            var anzahl = 0;
            for (var i = 0; i < this.layers.length; i++) 
            {
                if (this.layers[i]['checkbox'].checked)
                    anzahl++;
            }

            this.button.innerHTML = '';

            this.button.appendChild(document.createTextNode(this.buttonLabel + " (" + anzahl + ")"));
        }

        if (this.layers.length > 0)
        {
            this.map.addControl(new MoreControl(this.layers, this.buttonLabel, this.toogleLabel));
        }
    }

    //Routenplaner
    this.directions = function() 
    {

        if (this.special['start']['marker'] == null || this.special['ziel']['marker'] == null)
            return;

        var start = this.special['start']['marker'];
        var ziel = this.special['ziel']['marker'];

        var dir = 'from: ' + start.getTitle() + '@' + start.getPoint().toUrlValue(6) + ' to: ' + ziel.getTitle() + '@' + ziel.getPoint().toUrlValue(6); 

        var routeAJAX = new cAJAX();
        var args = new Array();
        args['route'] = dir;
        routeAJAX.execute('/ajax/routenlog.php', args);

        this.initializeRouten();
        this.routen.load(dir, {getPolyline:true});
    }


    this.initializeRouten = function()
    {
        if (this.routen == null)
        {
            this.routen = new GDirections(null, this.route);
        
            this.reasons[G_GEO_SUCCESS]            = "Erfolgreich";
            this.reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
            this.reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
            this.reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
            this.reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
            this.reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
            this.reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
            this.reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
            this.reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
            this.reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";

            GEvent.addListener(this.routen, "load", this.printRoute.scopeBind(this));
            GEvent.addListener(this.routen, "error", this.routenError.scopeBind(this));
        }
    }

    this.printRoute = function()
    {
        if (this.strecke != null)   
        { 
            this.map.removeOverlay(this.strecke);
            this.strecke = null;
        }

        var marker = this.routen.getMarker(0);
        this.printMarker(marker.getPoint(), 'start');

        this.strecke = this.routen.getPolyline();
        this.map.addOverlay(this.strecke);

        var bounds = new GLatLngBounds();
        bounds.extend(this.special['start']['marker'].getLatLng());
        bounds.extend(this.special['ziel']['marker'].getLatLng());
        this.map.setZoom(this.map.getBoundsZoomLevel(bounds));
        this.map.setCenter(bounds.getCenter());
    }

    this.routenError = function()
    {
        var code = this.routen.getStatus().code;
        var reason=', wegen unbekanntem Fehler! (Fehlercode ' + code + ')';
        if (this.reasons[code]) 
        {
            reason = '. ' + this.reasons[code] + '(Fehlercode ' + code +  ' )';
        }
        alert("Route konnte nicht berechnet werden" + reason);
    }

    //Marker anzeigen.
    

    this.vonHier = function(point)
    {
        if (typeof(point) == "string")
        {
            if (this.geo == null)
            {
                this.geo = new GClientGeocoder(new GGeocodeCache()); 
            }
            if (typeof(this.special['start'] == "undefined"))
            {
                this.special['start'] = {draggable:true, marker:null};
            }

            this.special['start']['adresse'] = point;
            this.geo.getLatLng(point, this.vonHier.scope(this));
        }
        else if (point == null) 
        {
            alert("Adresse nicht gefunden!");
        }
        else
        {
            this.printMarker(point, 'start');
            this.directions();
        }

    }


    this.nachHier = function(point)
    {
        if (typeof(point) == "string")
        {
            if (this.geo == null)
            {
                this.geo = new GClientGeocoder(new GGeocodeCache()); 
            }
            
            if (typeof(this.special['ziel'] == "undefined"))
            {
                this.special['ziel'] = {draggable:true, marker:null};
            }
            this.special['ziel']['adresse'] = point;
            this.geo.getLatLng(this.zieladresse, this.vonHier.scope(this));
        }
        else if (point == null) 
        {
            alert("Adresse nicht gefunden!");
        }
        else
        {
            this.printMarker(point, 'ziel');
            this.directions();
        }

    }
 
    this.type = null;
    this.suchen = function(point, type, draggable)
    {
        if (typeof(point) == "string")
        {
            if (type == "")
            {
                alert("Type angeben!");
                return;
            }
            
            if (typeof(draggable) == "undefined")
                draggable = false;

            if (typeof(this.special[type]) == "undefined")
            {
                this.special[type] = {draggable:draggable, marker:null};
            }

            this.special[type]['marker'] = point;
            this.type = type;
            
            if (this.geo == null)
            {
                this.geo = new GClientGeocoder(new GGeocodeCache()); 
            }

            this.geo.getLatLng(point, this.suchen.scope(this));
        }
        else if (point == null)
        {
            alert("Adresse nicht gefunden!");
        }
        else
        {
            this.printMarker(point, this.type);
            this.setCenter(point, 14);
        }
    }   

    //Admin-funktionen
    this.markerInfosToFields = function(type, latID, lngID, zoomID)
    {
        if (typeof(this.special[type]) == "undefined")
        {
            alert("Erst Suche fuer den Marker-Type ausfuehren");
            return;
        }

        if (this.special[type]['marker'] == "null")
        {
            alert("Kein Marker gesetzt fuer diesen Type");
            return
        }

        if (typeof(latID) == "string")
        {
            document.getElement(latID).value = this.special[type]['marker'].getLatLng().lat();
        }
        else
        {
            var lat = this.fromBogenmass(this.special[type]['marker'].getLatLng().lat());
            document.getElement(latID[0]).value = lat[0];
            document.getElement(latID[1]).value = lat[1];
            document.getElement(latID[2]).value = lat[2];
        }
        
        if (typeof(latID) == "string")
        {
            document.getElement(lngID).value = this.special[type]['marker'].getLatLng().lng();
        }
        else
        {
            var lng = this.fromBogenmass(this.special[type]['marker'].getLatLng().lng());
            document.getElement(lngID[0]).value = lng[0];
            document.getElement(lngID[1]).value = lng[1];
            document.getElement(lngID[2]).value = lng[2];
        
        }

        document.getElement(zoomID).value = this.map.getZoom();
    }

    this.fromBogenmass = function(wert)
    {
        var erg = new Array();

        erg[0] = Math.floor(wert);
        wert -= erg[0];
        wert *= 60;
        erg[1] = Math.floor(wert);
        wert -= erg[1];
        wert *= 60;
        erg[2] = Math.floor(wert);
        wert -= erg[2];
        wert *= 1000;
        erg[2] += Number(Math.floor(wert) / 1000);
        return erg;
    }

}

function gVisualization(canvasID, title)
{
    this.title = title;
    this.canvasID = canvasID;
    this.canvas = document.getElement(canvasID);
    this.columns = new Array();
    this.data = new Array();

    this.load = function()
    {
        google.load("visualization", "1", {"callback" : this.apiLoaded.scopeBind(this)});
    }

    this.apiLoaded = function()
    {
        alert('hallo');
    }

    this.addColumn(title, type)
    {
        var ar = new Array();
        ar['title'] = title;
        ar['type'] = type;
        this.columns = ar;
    }
}

function cCountdowns(textStopped, textNull)
{
    this.ids = new Array();
    this.objs = new Array();
    this.timers = new Array();

    this.textNull = textNull;
    this.textStopped = textStopped;

    this.set = function(seconds, id)
    {
        if (!in_array(id, this.ids))
        {
            this.ids.push(id);
            this.objs[id] = document.getElement(id);
            if (this.objs[id] == null)
            {
                this.unset(id);
                alert("Countdown-Area not found: " + id);
                return;
            }
        }

        this.timers[id] = seconds;
    }

    this.unset = function(id)
    {
        this.ids = array_erase(id, this.ids);
        if (this.objs[id] != null)
        {
            this.objs[id].innerHTML = this.textStopped;
            this.objs[id] = null;
        }
        this.timers[id] = 0;
    }

    this.run = function()
    {
        for (var i = 0; i < this.ids.length; i++)
        {
            var id = this.ids[i];

            if (this.objs[id] == null)
                continue;

            if (this.timers[id] > 0)
            {
                if (--this.timers[id] > 0)        
                {
                    lSeconds = this.timers[id]%60;          
                    lMinutes = Math.floor(this.timers[id] / 60);
                    lHours = Math.floor(lMinutes / 60);
                    lMinutes%=60;
                    lMinutes= ((lMinutes<10)? "0" : "" ) +  (lMinutes);
                    lSeconds =((lSeconds<10)?"0":"") +  (lSeconds);
                    this.objs[id].innerHTML = lHours + ":" + lMinutes + ":" + lSeconds;
                }
                else
                {
                    this.objs[id].innerHTML = this.textNull;
                }
            }
        }
    }

    setInterval(this.run.scopeBind(this), 1000);
}

function cTooltip(tooltip_id, position)
{
    this.id = tooltip_id;
    this.tooltip = null;
    this.position = position;
    
    this.opened = false;
    this.mouseoverIt = false;

    this.mouseAction = function(mouseoverIt)
    {
        this.mouseoverIt = mouseoverIt;
    }

    this.create = function()
    {
        this.tooltip = new cElement(tooltip_id, 'div');
        this.tooltip.opacity(0);
        this.tooltip.obj.onmouseover = this.mouseAction.scopeBind(this, [true]);
        this.tooltip.obj.onmouseout = this.mouseAction.scopeBind(this, [false]);
    }


    this.open = function(element)
    {
        if (this.tooltip == null)
            this.create();

        if (typeof(element) == "string")
            element = new cElement(element);

        this.tooltip.appendToParent(element.obj);
        var elementPos = element.getRelativePosition(this.position);
        this.tooltip.setPosition(elementPos[0], elementPos[1], 100, 'absolute');
        this.tooltip.overlay(this.tooltip_id);
        this.opened = true;
    }   

    this.close = function()
    {
        if (this.tooltip == null)
            this.create();

        this.tooltip.hideBlend();
        this.opened = false;
    }

    this.append = function(element)
    {
        if (this.tooltip == null)
            this.create();

        this.tooltip.obj.innerHTML = '';
        this.tooltip.obj.appendChild(element);
    }

}

function cAutocomplete(fieldId, script, borderFocus, waitForKeyPressed)
{
    this.field = new cElement(fieldId);
    this.script = script;

    this.borderFocus = false;
    if (typeof(borderFocus) != "undefined")
    {
        this.borderFocus = borderFocus;
    }

    this.waitForKeyPressed = 800;

    if (typeof(waitForKeyPressed) != "undefined")
        this.waitForKeyPressed = waitForKeyPressed;

    this.tooltip = new cTooltip('autocomplete_tooltip', 'left,below');
    this.timer = null;
    this.marked = 0;
    this.ajax = new cAJAX();
    this.selected = false;

    this.data = null;
    this.rows = null;

    this.onkeyup = function(ev)
    {
        if (this.timer != null)
        {
            window.clearTimeout(this.timer);
            this.timer = null;
        }

        switch (parseFloat(ev.keyCode))
        {
            case 38: //Pfeil OBEN
                if (this.tooltip.opened)
                    this.choose(null, -1);
                else
                    this.start(1);
                return true;
            case 40: //Pfeil UNTEN
                if (this.tooltip.opened)
                    this.choose(null, 1);
                else 
                    this.start();
                return true;
            case 13: //Return
                if (this.tooltip.opened)
                    this.select(this.marked);
                return true;
            case 27: //ESC
                if (this.data != null)
                    this.field.obj.value = this.data[0]; 
                this.tooltip.close();
                return true;
            default:
                this.timer = window.setTimeout(this.start.scopeBind(this), this.waitForKeyPressed);
        }
    }

    this.onfocus = function()
    {
        if (this.borderFocus)
            this.field.obj.style.borderColor = this.borderFocus;
    }    

    this.onblur = function()
    {
        if (this.tooltip.mouseoverIt)
            return true;

        if (this.borderFocus)
            this.field.obj.style.borderColor = '';

        if (!this.selected && this.data != null)
            this.field.obj.value = this.data[0];

        this.tooltip.close();
    }

    this.field.obj.onkeyup = this.onkeyup.scope(this);
    this.field.obj.onfocus = this.onfocus.scopeBind(this);
    this.field.obj.onblur = this.onblur.scopeBind(this);

    this.start = function()
    {
        if (this.timer != null)
        {
            window.clearTimeout(this.timer);
            this.timer = null;
        }

        this.tooltip.create();

        if (this.field.obj.value.length > 0)
        {
            var params = new Array();
            params[this.field.obj.id] = this.field.obj.value;
             
            this.ajax.execute(this.script, params, this.onreadystate.scopeBind(this));
        }
        else
            this.tooltip.close();
    }

    this.onreadystate = function()
    {
        if (this.ajax.isReady())
        {
            this.data = new Array();
            this.rows = new Array();
            this.data[0] = this.field.obj.value;
            this.marked = 0;
            this.selected = false;

            var rootNode = this.ajax.documentElement();
            if (!rootNode)
                return;

            var rowNodes = rootNode.getElementsByTagName("row");
            var table = document.createElement('div');
            table.className = 'autocomplete_table' ;

            for (var i = 0, key = 1; i < rowNodes.length; i++, key++)
            {
                var rowNode = rowNodes[i];
                this.data[key] = rowNode.getAttribute('value');
                
                var tr = document.createElement('div');
                tr.className = 'autocomplete_unmarked';
                tr.onclick = this.select.scopeBind(this, [key]);
                tr.onmouseover = this.choose.scopeBind(this, [key]);
                tr.style.cursor = 'pointer';

                var td = document.createElement('span');
                td.className = 'autocomplete_value';
                td.style.cssFloat = 'left';
                td.style.styleFloat = 'left';
                td.appendChild(document.createTextNode(this.data[key]));
                tr.appendChild(td);

                var counts = rowNode.getAttribute('count');
                if (counts)
                {
                    td = document.createElement('span');
                    td.className = 'autocomplete_count';
                    td.style.cssFloat = 'left';
                    td.style.styleFloat = 'left';
                    td.style.display = 'block';
                    td.appendChild(document.createTextNode(counts));
                    tr.appendChild(td);
                }

                td = document.createElement('div');
                td.style.clear = 'left';
                td.style.fontSize = '0pt';
                td.style.height = '0px';
                tr.appendChild(td);

                this.rows[i] = tr;
                table.appendChild(tr);
            }

            if (this.data.length > 1)
            {
                tr = document.createElement('div');
                tr.style.clear = 'left';
                table.appendChild(tr);
                this.tooltip.append(table);
                this.tooltip.open(this.field);
            }
            else
            {
                this.tooltip.close();
            }
        }
    }

    this.select = function(key)
    {
        this.selected = true;
        this.field.obj.value = this.data[key];
        this.field.obj.focus();
        this.tooltip.close(); 
    }

    this.choose = function(next, direction)
    {
        if (next == null)
        {
            next = Number(this.marked) + Number(direction);         
            var length = this.data.length - 1;
            if (next < 0)
                next = length;
            else if (next > length)
                next = 0;
        }

        this.marked = next;
        this.field.obj.value = this.data[next];

        next--;
        for (var i = 0; i < this.rows.length; i++)
        {
            if (next > -1 && next == i)
                this.rows[i].className = 'autocomplete_marked';
            else
                this.rows[i].className = 'autocomplete_unmarked';
        }
    }

}
