jQuery(function($) {
    

    var centerLatitude = 48.4419;
    var centerLongitude = 7.1419;
    var startZoom = 4;
    var point = new Array();
    var marker = new Array();
    var link = new Array();
    var my_cat = $("#kategorie").val();
    var my_land = $("#land").val();
    var markerArray = daten;
    var markerArray_hidden = new Array();
    var info = new Array();
    var map;

    $(document).ready(function(){

        
        
        //$("#kategorien").prependTo('.kategorien');
        //$('.subcolumns').hide();

        $('<div class="contentLoading" style="display: none;"><img src="fileadmin/images/icons/ajax-loader.gif" alt="Loading data, please wait..."></div>').appendTo('div.galerie');
        $('<div class="contentLoading" style="display: none;"><img src="fileadmin/images/icons/ajax-loader.gif" alt="Loading data, please wait..."></div>').insertBefore('div.details');
        $('.news-list-container').addClass('noscroll');
        $('.news-list-item').addClass('disactive');

        
        
        //$('.tx-ekgeo-pi1 .teaser').append($('.news-list-container'));
        var teaser = $('.news-list .news-list-container').html();
        $('.tx-ekgeo-pi1 .teaser').html('<span class="info">i</span><span class="up"> << </span><div class="news-list-container">' + teaser + '</div><span class="down"> >> </span>');
        $('.news-list').hide();

        $(".up").click(function(){
            var pos = $('.tx-ekgeo-pi1 .teaser .news-list-container').offset();
            var pos_new = pos.top - 272 + 70;
            //$('.tx-ekgeo-pi1 .teaser .news-list-container').css('top', pos_new);
            position_teaser(pos_new);
        });
        
        $(".down").click(function(){
            var pos = $('.tx-ekgeo-pi1 .teaser .news-list-container').offset();
            var pos_new = pos.top - 272 - 70;
            //$('.tx-ekgeo-pi1 .teaser .news-list-container').css('top', pos_new);
            position_teaser(pos_new);
            
        });

        $(".news-list-item").live('click', function(){
            var my_id = this.id;
            var id = my_id.substr(8,my_id.length);

            map_markers_remove();
            map_marker_update(id);
            set_details(id);

            if($('#map_canvas').is(':visible') == false){
                $('#map_canvas').show();
            }

            return false;
        });

        





        $('.goto_top').click(function(){
            $('.news-list-item').addClass('disactive');
            gallery_hide();
            $('.news-list-container').scrollTo(
            {
                left: '0',
                top:'-=150'
            },
            1000
            );
        });
        $('.goto_bottom').mousedown(function(){
            $('.news-list-item').addClass('disactive');
            gallery_hide();
            $('.news-list-container').scrollTo(
            {
                left: '0',
                top:'+=150'
            },
            1000
            );
            
        });
        

    })

    /*
     *  TODO: if detail view....
     *
     *
    function slide_up(){
        if($(".details").is(":hidden")){

        }else{
            $(".details").slideUp();
        }
    }
    */

   

    









    
    /*
     *  Name:           set_details(id)
     *  Beschreibung:   1. Effekt bevor Detailansicht angezeigt wird: Ladezeichen
     *                  2. Detailansicht statt Listenansicht
     *                  3. Navigation: vor/zurück Details andere Projekte
     *  Paramenter:
     *                  id      z.B. p16
     *                  url     URL der Detailseite/Single-Ansicht
     *
     **/
    function set_details(id) {
        $('.details').hide();
        $('#gallery-adv').hide();
        $('#thumbs-adv').hide();

        //var url = $("h3#"+id).find('a:first').attr('href');
        var url = $(".teaser #projekt_"+id).find('a:first').attr('href');
        //id = id.substr(1,id.length);
        //gallery_hide(id);
        $.ajax({
            //erweitere aufzurufenden Link
            //url: url.replace(/\.html/, "/ajax.html"),
            url: url,
            success: function(html) {
                // Neu in neuem div
                set_cat_info('hide');
                set_teaser_act(id);
                set_details_act(id,html);
                set_gallery_act(id,html);
                set_marker(id,html);
                //
                //Adresszeile aktualisieren
                //location.hash = "ek_p" + id;
                //location.hash = url.replace(/\.html/, "");
            }
        });
    }
    function set_marker(id,html){
        if(marker[id]){
            map.panTo(marker[id].getLatLng());
            marker[id].openInfoWindowHtml('<div class="map_image">' + get_first_image(id,html) +'</div><div class="map_title"><h1>'+ get_title(id) + '</h1></div>',{ maxWidth: 50});
        }
    }
    function get_title(id){
        var title = 'Projekt';
        $.each(markerArray, function(index, value) {
            if(value){
                if(value[0] == id){
                    title = value[1];
                }
            }
        });
        return title;
    }
    function set_teaser_act(id){
        $('.news-list-item').removeClass('act');
        $('.news-list-item').addClass('disactive');

        $('.teaser #projekt_' + id).removeClass('disactive');
        $('.teaser #projekt_' + id).addClass('act');
    }
    function set_details_act(id,html){
        var title = $('.title', html).html();
        var subheader = $(".subheader", html).html();
        var text = $(".news-single-content", html).html();
        $('.right .details')
        .removeClass()
        .addClass('details')
        .addClass('id' + id)
        .html(title)
        .append('<div>' + text + '</div>')
        .append('<div>' + subheader + '</div>')
        .show();
        $('.right span.fwd').remove();
        $('.right').append(get_fwd_html(id));
        $('.left span.prev').remove();
        $('.left').append(get_prev_html(id));

        $(".fwd .act").click(function(){
            set_details(get_fwd_id(id));
        });
        $(".prev .act").click(function(){
            set_details(get_prev_id(id));
        });
    }

    // TODO: find next / prev visible!
    function get_fwd_html(id){
        var e = '<span class="fwd"><a class="inact"> >> </a></span>';
        if($('.teaser #projekt_' + id + '~ .visible').length){
            e = '<span class="fwd"><a class="act"> >> </a></span>';
        }
        return e;
    }
    function get_fwd_id(id){
        var next_id;
        var next_id_nr;
        if($('.teaser #projekt_' + id + '~ .visible').length){
            next_id = $('.teaser #projekt_' + id + '~ :visible').eq(0).attr("id");
            next_id_nr = next_id.substr(8,next_id.length);
        }
        return next_id_nr;
    }
    
    function get_prev_html(id){
        var e = '<span class="prev"><a class="inact"> << </a></span>';
        if($('.teaser #projekt_' + id).prevAll('.visible').length > 0){
            e = '<span class="prev"><a class="act"> << </a></span>';
        }
        return e;
    }
    function get_prev_id(id){
        var prev_id;
        var prev_id_nr;
        if($('.teaser #projekt_' + id).prevAll('.visible').length > 0){
            prev_id = $('.teaser #projekt_' + id).prevAll('.visible').eq(0).attr("id");
            prev_id_nr = prev_id.substr(8,prev_id.length);
        }
        return prev_id_nr;
    }
    
    function get_first_image(id,html){
        var image = $('.thumb:first-child',html).html();
        return image;
    }
    function set_gallery_act(id,html) {
        //$('#gallery-adv').remove();
        //$('#thumbs-adv').remove();
        $('.gallery').remove();
        var galerie = $('.gallery_div',html).html();
        var loading = '<div class="contentLoading" style="display: none;"><img src="fileadmin/images/icons/ajax-loader.gif" alt="Loading data, please wait..."></div>';
        $('.left').prepend('<div class="gallery">' + galerie + loading + '</div>');
        gallery_show();
    }
    function gallery_show(){
        var onMouseOutOpacity = 0.67;
        $('#thumbs-adv ul.thumbs li').css(
            'opacity',
            onMouseOutOpacity
            )
        .hover(
            function () {
                $(this).not('.selected').fadeTo(
                    'fast',
                    1.0
                    );
            },
            function () {
                $(this).not('.selected').fadeTo(
                    'fast',
                    onMouseOutOpacity
                    );
            }
            );
        // Initialize Advanced Galleriffic Gallery
        var galleryAdv = $('#gallery-adv').galleriffic('#thumbs-adv', {
            delay:                  2000,
            numThumbs:              12,
            preloadAhead:           10,
            enableTopPager:         true,
            enableBottomPager:      true,
            imageContainerSel:      '#slideshow-adv',
            controlsContainerSel:   '#controls-adv',
            captionContainerSel:    '#caption-adv',
            loadingContainerSel:    '#loading-adv',
            renderSSControls:       true,
            renderNavControls:      true,
            playLinkText:           'Play Slideshow',
            pauseLinkText:          'Pause Slideshow',
            prevLinkText:           '&lsaquo; Previous Photo',
            nextLinkText:           'Next Photo &rsaquo;',
            nextPageLinkText:       'Next &rsaquo;',
            prevPageLinkText:       '&lsaquo; Prev',
            enableHistory:          true,
            autoStart:              false,
            onChange:               function(prevIndex, nextIndex) {
                $('#thumbs-adv ul.thumbs').children()
                .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
                .eq(nextIndex).fadeTo('fast', 1.0);
            },
            onTransitionOut:        function(callback) {
                $('#slideshow-adv, #caption-adv').fadeOut('fast', callback);
            },
            onTransitionIn:         function() {
                $('#slideshow-adv, #caption-adv').fadeIn('fast');
            },
            onPageTransitionOut:    function(callback) {
                $('#thumbs-adv ul.thumbs').fadeOut('fast', callback);
            },
            onPageTransitionIn:     function() {
                $('#thumbs-adv ul.thumbs').fadeIn('fast');
            }
        });

        // Initialize Minimal Galleriffic Gallery
        var galleryMin = $('#gallery-min').galleriffic('#thumbs-min', {
            imageContainerSel:      '#slideshow-min',
            controlsContainerSel:   '#controls-min'
        });
        $('#thumbs-adv ul.thumbs li a').each(function(){
            var anchor = $(this).attr("href");
            var newURL = window.location.protocol + "//" + window.location.host + "" + window.location.pathname;
            this.href = this.href.replace(this.href,newURL+anchor);

        });
    }
        
    




        
    


    

    
    







    
    /* Show first element after document load */
    function get_details_first(){
        var id_first = false;
        var my_id_name = 'projekt_';
        var my_id_first = $('.teaser div ul').find(":first.visible").attr('id');
        if(my_id_first){
            id_first = my_id_first.substr(my_id_name.length,my_id_first.length);
        }
        
        return id_first;
        
    }

    /*
     *  Name:           markerArray_clear
     *  Beschreibung:   entfernt alle Daten aus dem array in markerArray
     **/
    function markerArray_clear() {
        markerArray = new Array();
    }

    /*
     *  Name:           markerArray_refill()
     *  Beschreibung:   Füllt markerArray mit allen verfügbaren Daten
     *
     *  Problem:        id Datensatz der Fremdsprache in data-array
     *                  != id project-Datensatz in list view!
     *  Lösung:         Korrektur der id noetig:
     *                  wenn  id != 'ursprung-id' // z.B. id=53 und urspr.-id=10
     *                  --> ersetze id durch 'ursprung-id'
     *                  daten[i][0]     ursprung-id
     *                  i               id evtl fremdsprache
     *
     **/
    function markerArray_refill() {
        $.each(daten, function(index, value) {
            if(value){
                $.each(daten[index][6], function(indexCat, valueCat) {
                    //markerArray.push(daten[index]);
                    /*
                    * korrektur der id!
                    * setzen der ursprung-id */
                    if(index != daten[index][0]){
                        markerArray[daten[index][0]] = daten[index]; // id-korrektur..
                        markerArray.splice(index, 1); // loesche fremdspr-id-datensatz

                    }else{
                        markerArray[index] = daten[index]; // keine korrektur, einfach setzen
                    }
                });
            }
        });
    }



    /*  Name:           markerArray_reduce
     *  Beschreibung:   lässt im markerArray nur die Daten der Kategorie cat
     *
     *  geht alle Daten in markerArray durch
     *  geht alle Kategorien in daten durch
     *  so bald Kategorie mit my_cat übereinstimmt:
     *  --> wird daten in temp_markerArray hinzugefügt
     *
     *  zum Schluss: markerArray = temp_markerArray
     *
     *  Sonstiges:      markerArray[i]      Datensatz mit allen Infos
     *                  markerArray[i][6]   Array mit Kategorien
     *
     **/
    function markerArray_reduce(category) {
        var temp_markerArray_visible = new Array();
        var temp_markerArray_hidden = new Array();

        if(category > 0){
            $.each(markerArray, function(index, value) {
                if(value){
                    $.each(markerArray[index][5], function(indexCat, valueCat) {
                        //markerArray.push(daten[index]);
                        if(markerArray[index][6][indexCat] == category){
                            temp_markerArray_visible.push(markerArray[index]);
                        }else{
                            temp_markerArray_hidden.push(markerArray[index]);
                        }
                    });
                }
            });
            markerArray = temp_markerArray_visible;
            markerArray_hidden = temp_markerArray_hidden;
        }
    }

    
    /*
     *
     *  DETAIL VIEW: Gallery
     *
     *
     **/
    function gallery_hide() {
        $("#gallery-adv").remove();
        $("#thumbs-adv").remove();
    }
    
    








    /*
     *  ****************    Right   ************
     *  *
     *  *   Dropdown: Land, Kategorie
     *  *   Map
     *  *
     *  ****************************************
     **/
    function init() {
        if (GBrowserIsCompatible()) {
            markerArray_clear();
            markerArray_refill();

            //map = new google.maps.Map2(document.getElementById("map_canvas"));
            map = new GMap2(document.getElementById("map_canvas"));

            map.setCenter(
                new GLatLng(
                    centerLatitude,
                    centerLongitude
                    ),
                startZoom
                );
            map.setUIToDefault();
            map.enableDragging();

            map_markers_update();
            set_cat_markerArray(my_land,my_cat);
        }
    }
    /*
     *  Markers set/update
     *
     **/
    function map_markers_update(){
        $.each(markerArray, function(index, value) {
            if(value){
                map_marker_update(index);
            }
        });
    }
    function map_marker_update(id){
        point[id] = new GLatLng(markerArray[id][2],markerArray[id][3]);
        marker[id] = new GMarker(point[id]);
        info[id] = markerArray[id][1];

        add_click(id);
        add_mouseover(id);
        map.addOverlay(marker[id]);
    }
    /*
     *  Name:           map_markers_remove
     *  Beschreibung:   Entfernt alle Marker von der Karte
     *
     **/
    function map_markers_remove(){
        map.clearOverlays();

        point = new Array();
        info = new Array();
    }

    
    
    /*
     *  Marker Events
     *
     **/
    /*
     *  id:     z.B. p16
     *  url:    URL der Detailseite/Single-Ansicht
     *
     **/
    function add_click(id){
        GEvent.addListener(marker[id],"click",
            function() {
                map.panTo(marker[id].getLatLng());
                set_details(markerArray[id][0]);
            }
        );
    }
    /*
     *  id:     z.B. p16
     *  url:    URL der Detailseite/Single-Ansicht
     *
     **/
    function add_mouseover(id){
        GEvent.addListener(
            marker[id],
            "mouseover",
            function() {
                marker[id].openInfoWindowHtml(
                    info[id],
                    {
                        maxWidth: 50
                    }
                    )
            }
        );
    }


    /*
     *  Name:           projects_list_show
     *  Beschreibung:   show elements
     *
     **/
    function set_teaser_list(){
        $.each(markerArray_hidden, function(index, value) {
            if(value){
                $(".teaser .news-list-container #projekt_" + markerArray_hidden[index][0]).removeClass('visible');
                $(".teaser .news-list-container #projekt_" + markerArray_hidden[index][0]).addClass('hidden');
            }
        });
        $.each(markerArray, function(index, value) {
            if(value){
                $(".teaser .news-list-container #projekt_" + markerArray[index][0]).removeClass('hidden');
                $(".teaser .news-list-container #projekt_" + markerArray[index][0]).addClass('visible');
            } else {
                $(".teaser .news-list-container #projekt_" + markerArray[index][0]).removeClass('visible');
                $(".teaser .news-list-container #projekt_" + markerArray[index][0]).addClass('hidden');
            }
        });

        

        

    }



    /*
     *  KATEGORIE
     *
    **/
    
    /* Kategorie Menu */
    $(".kategorien ul li a").click(function(){
        var prefix = 'kategorie_';
        var id = this.name.substr(prefix.length,this.name.length);

        set_cat(id);

        return false;
    });
    /* Kategorie Details Übersicht */
    $('.kategorie-details div').click(function(){
        var prefix = 'kategorie_';
        var id = this.className.substr(prefix.length,this.className.length);

        set_cat(id);

        return false;
    });

    
    function set_cat(id){
        position_teaser('5px');
        
        set_cat_info('hide');
        set_cat_class('.kategorien','kategorie_',id); // class-name, id
        set_cat_markerArray("",id); // update markerArray + markers on the map

        set_teaser_list();

        map_markers_remove();
        map_markers_update();

        set_details(get_details_first());

        if($('#map_canvas').is(':visible') == false){
            $('#map_canvas').show();
        }

        $(".news-list-item").click(function(){
            var my_id = this.id;
            var id = my_id.substr(8,my_id.length);

            set_details(id);
            return false;

        });
    }
    function position_teaser(px){
        $('.tx-ekgeo-pi1 .teaser .news-list-container').css('top', px);
    }
    
    function set_cat_info(status){
        if(status == 'hide'){
            $(".kategorie-details").hide();
        }
    }
    function set_cat_class(className,namePrefix,id){
        $(className).find('a').removeClass('act');
        $(className).find('a[name=' + namePrefix + id + ']').addClass('act');
    }
    function set_cat_markerArray(land,cat){
        markerArray_clear();
        markerArray_refill();


        if(land){
            my_land = land;
        }
        if(cat){
            my_cat = cat;
        }
        markerArray_reduce(my_land);
        markerArray_reduce(my_cat);
    }
    
    
    
    
    /*
     *  LAND
     *
    **/
    $(".land ul li a").click(function(){
        var prefix = 'land_';
        var id = this.name.substr(prefix.length,this.name.length);

        set_cat_class('.land','land_',id);
        
        set_cat_markerArray(id,"");

        // LIST VIEW
        //$('.teaser .news-list-container ul li').remove();
        set_teaser_list();
        set_details(get_details_first());

        $(".news-list-item").click(function(){
            var my_id = this.id;
            var id = my_id.substr(8,my_id.length);

            set_details(id);
            return false;

        });

        return false;
    });








    /*
    *   LOAD
    **/
    $().ajaxSend(function(r,s){
        $(".contentLoading").show();
    });

    $().ajaxStop(function(r,s){
        $(".contentLoading").fadeOut("fast");
    });

    //function globalAjaxCursorChange(){
    $("html").bind("ajaxSend", function(){
        $(this).addClass('busy');
    }).bind("ajaxComplete", function(){
        $(this).removeClass('busy');
    });
    //}

    window.onload = init;
    window.onunload = GUnload;
//google.setOnLoadCallback(init);

});
