var root, opened_hov, timer;
static_sub = null;
window.addEvent('domready', function() {
    if ($('static_sub')) {
        static_sub = new Fx.Tween($('static_sub'), { duration: 350, link: 'ignore' });
        if (acLink != null) {
            $(acLink).addEvent('mouseover', function() {
                if (opened_hov != null) {
                    opened_hov.hideSub();
                }
                static_sub.start('opacity', 1);
            });
        }
    }
    if (hov_links.length > 0) {
        hov_links.each(function(l) {
            var li_0 = l[0];
            var li_1 = l[1];
            var ul = $(li_1);
            
            ul.tw = new Fx.Tween(ul, { duration: 350, link: 'cancel', onStart: function() { 
                    if (static_sub) {
                        static_sub.start('opacity', 0);
                    }
                    if (opened_hov != ul) {
                        try {
                            opened_hov.hideSub();
                        } catch(e) {}
                    }
                } 
            });
            ul.tw.set('opacity', 0);
            
            ul.hideSub = function() {
                if (static_sub) {
                    static_sub.start('opacity', 1);
                }
                opened_hov = null;
                ul.setStyle('z-index', 33);
                ul.tw.start('opacity', 0);
            }
            $(li_0).addEvent('mouseover', function() {
                
                ul.setStyle('z-index', 1000);
                ul.tw.start('opacity', 1);
                opened_hov = ul;
                try {
                    $clear(timer);
                } catch(e) {}
            });
            $(li_0).addEvent('mouseout', function() {
                timer = ul.hideSub.delay(3000);
            });
        });
    }
    
    if ($('track_toggler')) {
        var w = $('tracks').getFirst().getStyle('width').toInt();
        $('track_toggler').addEvent('click', function() {
            $('tracks').tween('width',($('tracks').getSize().x > 0 ? 0 : 319));
            $(this).getParent().toggleClass('act');
        });
    }
    
    $$('a').each(function(link) {
        if (link.getProperty('rel') == 'external')
        {
            link.setProperty('target', '_blank');
        }
    });
});

var t, b, opac, sw;
var newsStat = 0;

function getNews(dir, max, min, excl) {
    if (newsStat + (dir * 5) >= min && newsStat + (dir * 5) < max) {
        newsStat = newsStat + (dir * 5);
    }
    
    if (newsStat >= (max - 5)) {
        $('tog2').setStyle('visibility', 'hidden');
    } else {
        $('tog2').setStyle('visibility', 'visible');
    }
    if (newsStat <= min) {
        $('tog1').setStyle('visibility', 'hidden');
    } else {
        $('tog1').setStyle('visibility', 'visible');
    }
    
    $('more_news_con').getFirst().setStyle('visibility', 'hidden');
    $('more_news_con').addClass('loading');
    var req = new Request({
        url: root + 'news/getnews/' + newsStat + '/' + excl,
        onComplete: function(requestHTML) {
            $('more_news_con').removeClass('loading');
            $('more_news_con').set('html', requestHTML);
        }
    });
    req.send();
}

function headerFade(images) {
    t = $('layer2');
    b = $('layer1');
    var fadeHeader = function() { t.fade('toggle'); }
    var num = 2;

    t.set(
        'tween', 
        { 
            duration: 2800,
            onComplete: function() {
                opac = t.getStyle('opacity').toInt();
                if (opac > 0)
                {
                    sw = b;
                }
                else
                {
                    sw = t;
                }
                num = ( num < (images.length - 1) ? (num + 1) : 0 );
                sw.setStyle('background-image', 'url(' + images[num] + ')');
                var preloadImg = new Asset.images([images[num]], { 
                    onComplete: function() { 
                        fadeHeader.delay(5800); 
                    } 
                });
            }
        }
    );
    fadeHeader.delay(3000);
    //fadeHeader.periodical(6400);
}

function initHistory() {
    var hover_item;
    var active = $('active_ev');
    var default_image = root + 'img/content/history/default.jpg';
    $$('.event a').each(
        function(hs) {
            var par = hs.getParent();
            var hi = new Fx.Morph(
                hs, 
                {
                    duration: 'short', 
                    transition: Fx.Transitions.Back.easeOut
                }
            );
            hs.orig = hs.getStyle('padding-bottom').toInt();
            hs.margin = hs.getStyle('margin-top').toInt();

            hs.year = par.getFirst('.invisible').getFirst('span').get('html');
            hs.cont = par.getFirst('.invisible').getFirst('div').get('html');
            var im = par.getFirst('.invisible').getFirst('img') ? par.getFirst('.invisible').getFirst('img') : false;
            hs.image = (im ? im.getProperty('src') : default_image);
            hs.image_link = (im ? im.getProperty('src') : default_image);
            hs.image_link = hs.image_link.replace(/\.[^\.]*$/,'_big$&');
            
            hs.addEvent('mouseenter',function(){

                hover_item = hi;

                hi.start({
                    'padding-bottom': (hs.orig + 4),
                    'margin-top': (hs.margin - 4)
                });
            });

            hs.addEvent('mouseleave',function(){
                hover_item = null;
                hi.start({
                    'padding-bottom': (hs.orig),
                    'margin-top': hs.margin
                });
            });

            hs.addEvent('click',function(){
                active.removeClass('act');
                par.addClass('act');
                active = par;
                //$('h_con').set('html', hs.getParent().getFirst().get('html'));
                $('cur_year').set('html', hs.year);
                $('cur_text').set('html', hs.cont);
                $('cur_image').setProperty('src', hs.image);
                $('cur_image').getParent().setProperty('href', hs.image_link);
            });

        }
    );
}

var map;
var gdir;
var geocoder = null;
var addressMarker;

function correctSize() {
    //alert($('directions').getSize().y.toInt());
    if ($('directions').getSize().y.toInt() > 248) {
        $('map').setStyle('height', ($('directions').getSize().y.toInt() - 14) + 'px');
    } else {
        $('map').setStyle('height', '290px');
    }
    map.checkResize();
}

function setDirections(fromAddress, toAddress, locale) {
    gdir.load("from: " + fromAddress + " to: " + toAddress,
    { "locale": locale });
}

function onGDirectionsLoad() { 
    //
}

function handleErrors() {
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
    {
    alert("Zu der eingegebenen Adresse konnten keine geographischen Daten gefunden werden. Möglicherweise haben Sie eine relativ neue oder falsche Adresse eingegeben.\nError code: " + gdir.getStatus().code);
    }
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
    {
    alert("Die Geocoding-Anfrage konnte nicht erfolgreich ausgeführt werden. Eine genaue Ursache ist nicht bekannt.\n Error code: " + gdir.getStatus().code);
    }
    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
    {
    alert("Der HTTP q Parameter fehlt oder hat keinen Wert. Möglicherweise wurde ein leeres Adressfeld übermittelt.\n Error code: " + gdir.getStatus().code);

    //   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
    //     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
    }
    else if (gdir.getStatus().code == G_GEO_BAD_KEY)
    {
    alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
    }
    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
    {
    alert("Die Anfrage konnte nicht vollständig verarbeitet werden.\n Error code: " + gdir.getStatus().code);
    }
    else 
    {
    alert("Ein unbekannter Fehler ist aufgetreten.");
    }
}

function loadMap(lng) {
    if (GBrowserIsCompatible()) {      
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());

        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
        GEvent.addListener(gdir, "addoverlay", correctSize);

        setDirections("A45 Lüdenscheid", "Königsberger Straße 23 - 33, 58511 Lüdenscheid", lng);
    }
}

