var latlng = [51.211551,7.667148];
var map, gdir, mrk, directed = false;
var loaded = [], imgs = [], cur = 0, loading = false, slideshow = false;

function correctMapSize() {
    map.panBy(new GSize(0,100));
}

function openInfoBox() {
    mrk.openInfoWindow(
        '<div class="map_inner_w">' + 
        '<strong>WEMA GmbH</strong><br />' + 
        'Kalver Stra&szlig;e 28<br />' + 
        'D-58515 Lüdenscheid<br /></div>'
    );
    correctMapSize();
}

function setDirections(fromAddress, toAddress, loc) {
    if (directed === false) {
        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "addoverlay", onGDirectionsLoaded);
        GEvent.addListener(gdir, "error", handleErrors);
        
        mrk.hide();
        mrk.closeInfoWindow();
        
        var inst = $('#instant-contact');
        $(inst).clone(true).addClass('box-bg ptb mt1').appendTo($('#first-col'));
        $(inst).remove();
        $('#directions').parent().removeClass('span-6').addClass('pad-6');
        
        directed = true;
    }
    gdir.load("from: " + fromAddress + " to: " + toAddress, {
        'locale' : loc
    });
    
    return false;
}

function onGDirectionsLoaded() {
    correctMapSize();
    map.zoomOut();
}

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 renderMap() {
    if (GBrowserIsCompatible()) {
        var con = document.getElementById('map');
        map = new GMap2(con);
        var pnt = new GLatLng(latlng[0], latlng[1]);
        mrk = new GMarker(pnt);

        map.addOverlay(mrk);
        map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,54)));
    	map.addControl(new GSmallMapControl(), new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(10,54)));
    	//map.addControl(new GScaleControl());

        map.setCenter(pnt, 16, G_HYBRID_MAP);
        GEvent.addListener(mrk, 'click', function() {
            openInfoBox();
        });
        
        $(window).load(function() {
            map.panDirection(0,1);
            openInfoBox();
        });
    }
}

function fireBackground(href) {
    $('.header .activeslide').addClass('prevslide').removeClass('activeslide');
    $('.header .nextslide').hide().css('backgroundImage', 'url('+href+')').removeClass('nextslide').addClass('activeslide').fadeIn(1200);
    $('.header .prevslide').removeClass('prevslide').addClass('nextslide');
}

function loadImage(index) {
    var img = imgs[index];
    if (jQuery.inArray(img, loaded) < 0) {
        loading = true;
        $.cacheImage(img, {
            load : function (e) {
                loaded.push(img);
                fireBackground(imgs[index]);
                loading = false;
            }
        });
    } else {
        fireBackground(imgs[index]);
    }
}

function initHeaderSlideshow() {
    $('.header #images a').each(function(i, o) {
        imgs.push($(this).attr('href'));
        $(this).click(function() {
            loadImage(i);
            $(this).parents('ul:first').find('a.active').removeClass('active').end().end().addClass('active');
            return false;
        });
    });
    
    loaded.push(imgs[cur]);
    
    slideshow = window.setInterval(function() {
        cur = (cur + 1) < $('.header #images a').length ? cur + 1 : 0;
        loadImage(cur);
    }, 8000);
}

function orangeBarPos(bar) {
    var browserwidth = $(window).width();
    browserwidth = Math.ceil((browserwidth - $('#header .container:first').width()) / 2);
    
    $(bar).css({
        'display': 'block',
        'width': (browserwidth),
        'right': - (browserwidth)
    });
}

jQuery().ready(function() {
    $('body').removeClass('no-js').addClass('js-enabled');
    $('a').each(function() {
        $(this).bind('click', function() {
            if (this.blur) {this.blur();}
        });
        if ($(this).attr('rel') == 'external') {
            $(this).attr('target', '_blank');
        }
        if ($(this).attr('rel') == 'fancy') {
            $(this).attr('title', '').find('img').attr('alt', '');
        }
    });

    $("head").append("<link>");
    var css = $("head").children(":last");
    css.attr({
        rel:  "stylesheet",
        type: "text/css",
        href: webroot + "css/hacks.css"
    });
    
    $('#lang li:not(.active) a').hover(
        function() { $(this).find('img').animate({ 'opacity' : 1 }, 320); },
        function() { $(this).find('img').animate({ 'opacity' : 0.65 }, 240); }
    ).find('img').css('opacity', 0.65);
    $('#lang li.active a').css('cursor', 'default').click(function() { return false; });
    
    if ($('#orange-bar').length) {
        $('body').css({
            'overflowX': 'hidden',
            'overflowY': 'visible'
        });
        
        orangeBarPos($('#orange-bar'));
        $(window).bind("resize", function(){
            orangeBarPos($('#orange-bar'));
        });
    }
    
    if ($('#map').length) {
        renderMap();
        $('#header-bg').css({
            'background' : '#000',
            'zIndex' : 3,
            'height': $('#header').outerHeight() + 18,
            'opacity' : 0.5
        });
    }
    
    if ($('.products .container:not(.fail)').length) {
        $('.products .container').each(function() {
            $(this).data('bg', $(this).css('backgroundImage'));
            $(this).hover(
                function() { 
                    $(this).stop().animate({
                        'backgroundColor' : '#000000'
                    }, 300);
                },
                function() {
                    $(this).stop().animate({
                        'backgroundColor' : '#333333'
                    }, 360, 'swing');
                }
            );
        });
        
        $('.products .container h3 a').hover(
            function() { $(this).stop(true).animate({ 'color' : '#fff' }, 420); },
            function() { $(this).animate({ 'color' : '#f58a00' }, 300); }
        );
    }
    
    if ($('#history-wrap').length) {
        $('#history ul li a').click(function() {
            var target = $('#history-wrap ' + $(this).attr('href'));
            if ($(target).length && !$(target).hasClass('activeslide')) {
                $(target).addClass('nextslide');
                $('#history ul .active').removeClass('active');
                $(this).parent().addClass('active');
                
                $('#history-wrap .arrow:first').animate({
                    'left': $(this).position().left + 2
                }, 460, 'swing');
                
                $('#history-wrap .activeslide').css('display', 'block').addClass('prevslide').removeClass('activeslide');
                $('#history-wrap .nextslide').css('display', 'block').hide().removeClass('nextslide').addClass('activeslide').delay(200).fadeIn(500);
                $('#history-wrap .prevslide').fadeOut(250).removeClass('prevslide');
            }
            return false;
        });
    }
    
    if ($('.header #images a').length) {
        initHeaderSlideshow();
    }
});
