var subs;

function toggleMenu(status, sub) {
    if (status == 'show') {
        window.clearTimeout($(sub).data('timeout'));
        if ($(sub).data('initialized') === true) {
            $(sub).prevAll('a:first').addClass('hovered');
            $(subs).not($(sub)).each(function() {
                toggleMenu('hide', $(this));
            });
            $(sub).animate({
                'height': $(sub).data('o_height'),
                'opacity': 1
            }, 240);
        } else {
            $(subs).each(function() {
                $(this).data('o_height', $(this).outerHeight() + 1);
                $(this).data('initialized', true);
                $(this).height(0);
            });
            toggleMenu('show', sub);
        }
    } else {
        $(sub).prevAll('a:first').removeClass('hovered');
        $(sub).stop(true).animate({
            'height': 0,
            'opacity': 0
        }, 180);
    }
}

var latlng = [51.220903, 7.660523];
var map, gdir, mrk, toadress = "Hueckstraße 16, 58511 Lüdenscheid";

function openInfoBox(address) {
    if (typeof address == 'undefined' || address == '') {
        address = '<strong>Hotset</strong><br />' + 
        '<small>Heizpatronen und Zubehör GmbH</small><br />' +
        'Hueckstraße 16<br />' + 
        'D-58511 Lüdenscheid<br />';
    }
    mrk.openInfoWindow(
        '<div class="map_inner_w">' + address + '</div>'
    );
}

function setDirections(fromAddress, locale) {
    gdir.loadFromWaypoints([fromAddress, toadress],
    { "locale": locale.substr(0,2) });
    
    return false;
}

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(gdir.getStatus().code + " Ein unbekannter Fehler ist aufgetreten.");
    }
}

function loadMap(id, language, direction) {
    if (GBrowserIsCompatible()) {
        var con = document.getElementById(id);
        var adr = '';
        if ($(con).find('span').length) {
            adr = $(con).find('span:first').html();
            if ($(con).find('span:first').attr('title')!='') {
                latlng = $(con).find('span:first').attr('title').split(',');
            }
        }
        map = new GMap2(con);
        
        map.addControl(new GMapTypeControl());
    	map.addControl(new GSmallMapControl());
    	map.addControl(new GScaleControl());
        
        if (direction === true) {
            gdir = new GDirections(map, document.getElementById("directions"));
            GEvent.addListener(gdir, "load", onGDirectionsLoad);
            GEvent.addListener(gdir, "error", handleErrors);
            toadress = new GLatLng(latlng[0],latlng[1]);
            if (adr != '') {
                setDirections(adr, language);
            } else {
                setDirections("A45 Lüdenscheid", language);
            }
        } else {
            var pnt = new GLatLng(latlng[0], latlng[1]);
            mrk = new GMarker(pnt);
            map.addOverlay(mrk);
            
            map.setCenter(pnt, 16, G_HYBRID_MAP);
            GEvent.addListener(mrk, 'click', function() {
                openInfoBox(adr);
            });
            
            $(window).load(function() {
                map.panDirection(0,1);
                openInfoBox(adr);
            });
        }
    }
}

function toggleBubble(c, t) {
    b = $(c).find('div.h-content:first');
    var top_align = ($(c).hasClass('al-bottom') || $(c).hasClass('al-right-bottom'));
    if (t == 'show') {
        if (!$(b).hasClass('h-opened')) {
            $(c).parent().find('.h-opened').not($(b)).each(function() {
                $(this).hide().removeClass('h-opened');
            });
            
            $(b).css({
                'opacity' : 0,
                'marginBottom' : (!top_align ? -15 : 0),
                'marginTop' : (!top_align ? 0 : -10)
            }).show().addClass('h-opened').animate({
                'opacity' : 1,
                'marginBottom' : 0,
                'marginTop' : 0
            }, 240);
        }
    } else {
        $(b).animate({
            'opacity' : 0,
            'marginBottom' : (!top_align ? -15 : 0),
            'marginTop' : (!top_align ? 0 : -10)
        }, 180, 'easein', function() { $(this).removeClass('h-opened').hide(); });
    }
}

function initHistory(h) {
    $(h).find('div.el').each(function(i){
        $(this).hoverIntent(
            function() { toggleBubble($(this), 'show'); },
            function() { toggleBubble($(this), 'hide'); }
        );
        if (i==0) {
            toggleBubble($(this), 'show');
        }
    });
}

jQuery().ready(function() {
    if ($('#topmsg').length) {
        $('#topmsg').css('opacity', 0.9);
        window.setTimeout(function() {
            $('#topmsg').css('overflow', 'hidden').animate({
                'opacity' : 0,
                'height' : 0
            }, 500);
        }, 6400);
    }
    
    if ($('#gmap').length) {
        loadMap('gmap', language, ($('#gmap').hasClass('directions') ? true : false));
        var input = $('#dir_form').find('input[type=text]:first')
        $('#dir_form').submit(function() {
            var from = $(input).val();
            setDirections(from, language);
            return false;
        });
    }
    
    if($('#history-title').length) {
        initHistory($('#history-title'));
    }
    
    subs = $('#menu').find('div.sub');
    $('#menu ul#main-menu li:first').siblings('li').andSelf().each(function() {
        var sub = $(this).find('div.sub');
        if ($(sub).length) {
            $(sub).css({
                'opacity': 0,
                'overflow': 'hidden'
            }).hide();
            
            /* Correct Position of right-outer Submenus */
            var pos = $(sub).parent().offset().left - $(sub).parents('.container:first').offset().left;
            if (pos + $(sub).width() > $(sub).parents('.container:first').width()) {
                $(sub).css({
                    'left': 'auto',
                    'right': '0px'
                });
            }
                    
            $(this).hoverIntent({
                over: function() { 
                    toggleMenu('show', sub); 
                },
                out: function() { 
                    $(sub).data('timeout', window.setTimeout(function() {
                        toggleMenu('hide', sub);
                    }, 1000)); 
                },
                timeout: 0,
                interval: 68
            });
        }
    });
    $('a[rel=external]').attr('target', '_blank');
});