/*-- IE6nomore --*/

    $.IE6nomore = function(){
        if(!$('#ie6nomore').length)
            return;
        $('#ie6nomore').css({
            'left': 0,
            'top': 0,
            'bottom': 0,
            'right': 0,
            'position': 'absolute',
            'z-index': 9999
        });
    };

/*-- Spam protection --*/

    function getAdr(prefix, postfix, text){
        document.write('<a href="mailto:' + prefix + '@' + postfix + '">' + (text ? text.replace(/&quot;/g, '"').replace(/%EMAIL%/, prefix + '@' + postfix) : prefix + '@' + postfix) + '</a>');
    }

/*-- Cookies --*/

    $.cookie = function(name, value, options){
        if (typeof value != 'undefined'){
            options = options || {};
            if (value === null){
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)){
                var date;
                if (typeof options.expires == 'number'){
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                }
                else
                    date = options.expires;
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        }
        else{
            var cookieValue = null;
            if (document.cookie && document.cookie != ''){
                var cookies = document.cookie.split(';');
                $(cookies).each(function(){
                    var cookie = $.trim(this);
                    if (cookie.substring(0, name.length + 1) == (name + '=')){
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        return;
                    }
                });
            }
            return cookieValue;
        }
    };

/*-- Get url vars --*/

    $.getUrlVars = function(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        $(hashes).each(function(){
            hash = this.split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        });
        return vars;
    };

/*-- Hide or show grid -- */

    $.initGrid = function(){
        if($.getUrlVars()['grid'] == 1)
            $.cookie('grid', 'show', { path: '/', expires: 7 });
        if($.getUrlVars()['grid'] == 0)
            $.cookie('grid', '', { path: '/', expires: 7 });
        if($.cookie('grid') == 'show')
            $('body').addClass('showgrid');
    };

/* Border radius */

    (function($){
        $.fn.borderRadius = function(radius){
            return this.each(function(e){
                $(this).css({
                    '-moz-border-radius': radius,
                    '-webkit-border-radius': radius,
                    'border-radius': radius
                });
            });
        };
    })(jQuery);

/*-- Iframe popup --*/

    (function($){
        $.fn.IframePopup = function(options){
            if(!$(this).length)
                return;

            // Settings
            var IP_Settings = {
                margin: 20, // Margin from the iframe popup
                width: 700, // Default popup width
                height: 500, // Default popup height
                borderradius: '10px'  // Popup border-radius
            };
            var IP_Settings = $.extend(IP_Settings, options);

            // Create iframe popup
            createIframePopup();
            // Open iframe popup
            $(this).click(function(){
                // Hide scrollbar and fadein overlay
                $('body, html').css('overflow', 'hidden');
                $(ip_overlay).fadeTo('slow', 0.8);
                // Set tabindex="-1" to content
                $('a, input, textarea, select, button').not('.close').each(function(){
                    $(this).addClass('tabindex').attr('tabindex', '-1');
                });
                // Get popup size from rel attribut
                var popupHeight = this.rel.split(',')[1];
                var popupWidth = this.rel.split(',')[0];
                if(popupWidth == null || popupHeight == null){
                    popupWidth = IP_Settings.width;
                    popupHeight = IP_Settings.height;
                }
                // Set popup size
                var NormalCSS = {
                    'bottom': 'auto',
                    'height': popupHeight+'px',
                    'left': '50%',
                    'margin-left' : Math.floor(-(popupWidth)/2)+'px',
                    'margin-top': Math.floor(-(popupHeight)/2)+'px',
                    'max-height': popupHeight+'px',
                    'top': '50%',
                    'width' : popupWidth+'px'
                };
                var FlexibleCSS = {
                    'bottom': IP_Settings.margin+'px',
                    'height': 'auto',
                    'margin-top': 0,
                    'top': IP_Settings.margin+'px'
                };
                // Normal iframe popup size
                $(ip_popup).css(NormalCSS).borderRadius(IP_Settings.borderradius).show();
                // Flexible iframe popup size
                $(window).resize(function(){
                    ($(this).height() <= ($(ip_popup).outerHeight()+2*IP_Settings.margin)) ? $(ip_popup).css(FlexibleCSS) : $(ip_popup).css(NormalCSS);
                });
                ($(window).height() <= ($(ip_popup).outerHeight()+2*IP_Settings.margin)) ? $(ip_popup).css(FlexibleCSS) : $(ip_popup).css(NormalCSS);
                // Insert iframe title
                $(ip_title).html(this.title);
                // Insert iframe content
                $(ip_popup).addClass('ip_loading');
                $(ip_iframe).attr('src', this); 
                // Preloader
                $(ip_iframe).css('visibility', 'hidden');
                $(ip_iframe).load(function(){
                    $(ip_popup).removeClass('ip_loading');
                    $(ip_iframe).css('visibility', 'visible');
                });
                $(document).bind('keydown', keyDown);
                return false;
            });

            // Close popup
            function closeIframePopup(){
                $('body').css('overflow', bodyOverflow);
                $('html').css('overflow', htmlOverflow);
                $(ip_popup).hide();
                $(ip_overlay).fadeOut('slow');
                $(window).unbind('resize');
                // Remove tabindex="-1"
                $('.tabindex').each(function(){
                    $(this).removeClass('tabindex').removeAttr('tabindex');
                });
            }

            // Keyboard events
            function keyDown(event){
                var code = event.keyCode;
                return ($.inArray(code, [27,88,67]) >= 0) ? closeIframePopup() : true;
            }

            // Create iframe popup
            function createIframePopup(){
                $('body').append(
                    ip_overlay = $('<div>').attr({ 'class': 'ip_overlay' }).hide().click(closeIframePopup),
                    ip_popup = $('<div class>').attr({ 'class': 'ip_popup' }).append(
                        ip_close = $('<a>').attr({ 'class': 'close', href: '#', title: close+' [ESC]' }).text(close).click(closeIframePopup),
                        ip_title = $('<h2>').attr({ 'class': 'title' }),
                        $('<div>').attr({ 'class': 'ip_content' }).append(
                            ip_iframe = $('<iframe>').attr({ 'src': '', 'frameborder': '0' })
                        )
                    ).hide()
                );
                $([
                    bodyOverflow = $('body').css('overflow'),
                    htmlOverflow = $('html').css('overflow')
                ])
            }
        };
    })(jQuery);

/*-- Create onchange select --*/

    (function($){
        $.fn.createOnchangeSelect = function(options){
            var settings = $.extend({
                'label': false,
                'group': false,
                'id': 'selection'
            }, options);

            return this.each(function(){
                var el = this;
                if(!$('li a', el).length)
                    return;
                if(settings.group){
                    // Create form and select
                    $(el).append(
                        form = $('<form>').attr('action', '').append(
                            select = $('<select>').attr({
                                'id': settings.id,
                                'name': settings.id
                            }).addClass($(this).attr('class'))
                        )
                    );
                    // Create optgroup
                    $(settings.group, el).each(function(){
                        $(select).append(
                            optgroup = $('<optgroup>').attr('label', $(this).text())
                        );
                        // Fill select with options
                        $.fn.createOnchangeSelect.fillSelect($(this).next('ul'), optgroup);
                    });
                }
                else{
                    $('ul, ol', el).each(function(){
                        // Create form and select
                        $(this).after(
                            form = $('<form>').attr('action', '').append(
                                select = $('<select>').attr({
                                    'id': settings.id,
                                    'name': settings.id
                                }).addClass($(this).attr('class'))
                            )
                        );
                        // Fill select with options
                        $.fn.createOnchangeSelect.fillSelect(el, select);
                    });
                }
                // Onchange
                $(select).change(function(){
                    location.href=this.value;
                });
                // Create label
                if(settings.label){
                    $(form).prepend(
                        label = $('<label>').attr('for', settings.id).text($(settings.label).text())
                    );
                }
                // Remove non javascript html code
                $('ul, ol, '+settings.group, el).remove();
                $(settings.label).remove();
            });
        }

        // Fill select with options
        $.fn.createOnchangeSelect.fillSelect = function(el, select){
            $('li a', el).each(function(){
                $(select).append(
                    option = $('<option>').val(this.href).text($(this).text())
                );
                if($(this).hasClass('active'))
                    $(option).attr('selected', 'selected');
            });
        }
    })(jQuery);

/*-- Google Maps --*/

    (function($){
        $.fn.GoogleMaps = function(options){
            // Settings
            var settings = $.extend({
                'id': false,
                'mapdata': false,
                'zoom': 17,
                'min_zoom': 4,
                'max_zoom': 18,
                'map_control': false,
                'hide_description': false,
                'hide_company_name': false
            }, options);

            return this.each(function(){
                var el = this;
                if(!$(el).length || !settings.id || !settings.mapdata)
                    return;
                // Show Map -> hide without javascript
                $(el).show();
                // Remove static map
                $('img', el).remove();
                // Default latlng
                var location = {
                    company_name: settings.mapdata[0].company_name,
                    street: settings.mapdata[0].street,
                    postal_code: settings.mapdata[0].postal_code,
                    city: settings.mapdata[0].city,
                    country: settings.mapdata[0].country,
                    latitude: settings.mapdata[0].latitude,
                    longitude: settings.mapdata[0].longitude
                };
                var address = '';
                if(location.street && location.postal_code && location.city && location.country)
                    address = location.street + ', ' + location.postal_code + ' ' + location.city + ', ' + location.country;
                if(location.latitude && location.longitude){
                    var latlng = new google.maps.LatLng(location.latitude, location.longitude);
                    // Initialize map
                    $.fn.GoogleMaps.init(el, settings, latlng);
                }
                else if(address){
                    // Geocode: convert address to latlng
                    var geocoder = new google.maps.Geocoder();
                    geocoder.geocode({ 'address': address }, function(results, status){
                        if(status == google.maps.GeocoderStatus.OK){
                            var latlng = results[0].geometry.location;
                            // Initialize map
                            $.fn.GoogleMaps.init(el, settings, latlng);
                        }
                    });
                }
            });
        }

        $.fn.GoogleMaps.init = function(el, settings, latlng){
            // Map options
            var MapOptions = {
                zoom: settings.zoom,
                center: latlng,
                scrollwheel: false,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                mapTypeControl: settings.map_control,
                mapTypeControlOptions:{
                    style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
                },
                navigationControl: true,
                navigationControlOptions:{
                    style: google.maps.NavigationControlStyle.SMALL
                }
            };
            // Initialize map
            var map = new google.maps.Map(document.getElementById($(el).attr('id')), MapOptions),
                infowindow = new google.maps.InfoWindow(),
                cords = new Array(),
                markers = new Array();
            // min/max zoom
            google.maps.event.addListener(map, 'zoom_changed', function() {
                if (this.getZoom() < settings.min_zoom) this.setZoom(settings.min_zoom);
                if (this.getZoom() > settings.max_zoom) this.setZoom(settings.max_zoom);
            });
            // Directions panel
            $.fn.GoogleMaps.directions(map, settings, markers, cords, infowindow);
            // Set Markers
            $(settings.mapdata).each(function(){
                var location = {
                    company_name: this.company_name,
                    street: this.street,
                    postal_code: this.postal_code,
                    city: this.city,
                    country: this.country,
                    phone: this.phone,
                    fax: this.fax
                };
                var address = '';
                if(location.street && location.postal_code && location.city && location.country)
                    address = location.street + ', ' + location.postal_code + ' ' + location.city + ', ' + location.country;
                if(this.latitude && this.longitude){
                    latlng = new google.maps.LatLng(this.latitude, this.longitude);
                    cords.push(latlng);
                    markers.push($.fn.GoogleMaps.marker(map, settings, latlng, location, infowindow));
                    $.fn.GoogleMaps.update(map, settings, markers);
                }
                // Geocode: convert address to latlng
                else if(address){
                    var geocoder = new google.maps.Geocoder();
                    geocoder.geocode({ 'address': address }, function(results, status){
                        if(status == google.maps.GeocoderStatus.OK){
                            latlng = results[0].geometry.location;
                            cords.push(latlng);
                            markers.push($.fn.GoogleMaps.marker(map, settings, latlng, location, infowindow));
                            $.fn.GoogleMaps.update(map, settings, markers);
                        }
                    });
                }
            });
        }

        $.fn.GoogleMaps.marker = function(map, settings, latlng, location, infowindow){
            // Create infowindow
            var description = '<div class="google description">';
            if(location.company_name && settings.hide_company_name){
                description += '<h2>' + location.company_name + '</h2>';
            }
            description += '<div class="google address">';
            description += '<p>' + location.street + '<br />' + location.postal_code + ' ' + location.city + '<br />' + location.country + '</p>';
            if(location.phone || location.fax)
                description += '<p>';
            if(location.phone)
                description += phone + ' ' + location.phone + '<br />';
            if(location.fax)
                description += fax + ' ' + location.fax + '<br />';
            if(location.phone || location.fax)
                description += '</p>';
            description += '</div>';
            description += '</div>';
            // Set marker
            var marker = new google.maps.Marker({
                position: latlng, 
                map: map,
                title: marker_title,
                description: description,
                clickable: (settings.hide_description)? true : false
            });
            // Set infowindow to marker
            if(settings.hide_description){
                if(description){
                    google.maps.event.addListener(marker, 'click', function(){
                        infowindow.setContent(this.description);
                        infowindow.open(map, this);
                    });
                    if(settings.mapdata.length == 1)
                        google.maps.event.trigger(marker, 'click');
                }
            }
            return marker;
        }

        $.fn.GoogleMaps.update = function(map, settings, markers){
            // Update map
            if($(markers).length > 1){
                // Show all markers on the map
                var bounds = new google.maps.LatLngBounds();
                $(markers).each(function(){
                    bounds.extend(this.getPosition());
                });
                map.fitBounds(bounds);
            }
        }

        // Hide all markers
        $.fn.GoogleMaps.hideAllMarkers = function(map, markers, infowindow){
            $(markers).each(function(){
                this.setVisible(false);
            });
            infowindow.close(map);
        }

        $.fn.GoogleMaps.directions = function(map, settings, markers, cords, infowindow){
            var direction = '#direction_' + settings.id;
            if(!$(direction).length)
                return;
            // Show DIV -> hide without javascript
            $(direction).show();
            // Initialize directions panel
            var directionsService = new google.maps.DirectionsService();
            var directions = new google.maps.DirectionsRenderer({
                map: map,
                panel: document.getElementById('panel_' + settings.id)
            });
            $('form', direction).submit(function(){
                $('#content').scrollTop(0);
                if($('#saddr_' + settings.id).val().length){
                    // Print directions result
                    var panel = '#panel_' + settings.id;
                    $(panel).show();
                    $('.print a', panel).click(function(){
                        window.print();
                        return false; 
                    });
                    // Directions result             
                    var destination_value = $(cords)[$('#daddr_' + settings.id).val()];
                    var request = {
                        origin: $('#saddr_' + settings.id).val(),
                        destination: (destination_value ? destination_value : $(cords)[0]),
                        travelMode: google.maps.DirectionsTravelMode.DRIVING
                    };
                    directionsService.route(request, function(result, status){
                        if(status == google.maps.DirectionsStatus.OK){
                            directions.setDirections(result);
                            $.fn.GoogleMaps.update(map, settings, markers);
                            $.fn.GoogleMaps.hideAllMarkers(map, markers, infowindow);
                        }
                    });
                }
                return false;
            });
        }
    })(jQuery);

/*-- Add bookmark links --*/

    (function($){
        $.fn.bookmark = function(options){
            // Settings
            var settings = $.extend({
                'appendTo': false
            }, options);

            if($.browser.opera || $.browser.msie || $.browser.mozilla){
                return this.each(function(){
                    var el = this;
                    // Create boommark link
                    var bookmarkLink = $('<a>').attr({
                        'href': el.href,
                        'title': 'Lesezeichen hinzufügen'
                    }).addClass('bookmark click').text('Lesezeichen hinzufügen');
                    // Add bookmark link
                    if(settings.appendTo){
                        $(settings.appendTo).show();
                        $(el).parent().next(settings.appendTo).append(bookmarkLink);
                    }
                    else
                        $(el).after(bookmarkLink);
                    // Click bookmark link
                    $(bookmarkLink).click(function(){
                        var el = this;
                        var bookmarkUrl = el.href;
                        var bookmarkTitle = el.title;
                        if(window.sidebar)
                            window.sidebar.addPanel(bookmarkTitle, bookmarkUrl, ''); // For Mozilla Firefox Bookmark
                        else if(window.external || document.all)
                            window.external.AddFavorite(bookmarkUrl, bookmarkTitle); // For IE Favorite
                        else if(window.opera)
                            $(el).attr('rel', 'sidebar'); // For Opera Browsers
                        return false;
                    });
                });
            }
            else if(settings.addTo){
                $(settings.addTo).remove();
            }
        }
    })(jQuery);

/*-- Scroll menu -- */

    function scroll_menu(){
        var container = '#article',
            menu = '#subnav';
        if(!$(menu).length)
            return;

        var menuPosition = $(menu).offset().top,
            maxOffset = $(container).outerHeight(true) - $(menu).outerHeight(true);

        $(window).scroll(function(){
            if(menuPosition >= $(window).scrollTop()){
                $(menu).stop().animate({ 'top':0 }, 'fast');
            }

            if(maxOffset >= (($(window).scrollTop() - menuPosition) + 20) && menuPosition <= $(window).scrollTop()){
                $(menu).stop().animate({'top': ($(window).scrollTop() - menuPosition) + 20}, 'fast');
            }
        });
    }

/*-- DOM -- */

    $(function(){
        // IE6nomore
        $.IE6nomore();
        // News
        $('#news_selection').createOnchangeSelect({ 'label': '#news_selection h3' });
        $('#news_selection').css({
            'position': 'absolute',
            'right': 20,
            'top': 15
        });
        // Infolists
        $('.selection').createOnchangeSelect({ 'group': '.group' });
        // Iframe popup
        $('.popup').IframePopup();
        // Grid
        $.initGrid();
        // Menu
        scroll_menu();
        // Links
        $('.link').bookmark({ 'appendTo': '.bookmark' });
    });

