/*
 * Main DAH-Site-Setup
 *
 * author:  Christoph Schuessler (cs@hirnstrom.de)
 *
 */


////////////////////////////////////////////////////////////////////////////////
//
// firebug console output
// @param text String the debug message
// @param type String the message type [error | info | warn] (optional)
//
////////////////////////////////////////////////////////////////////////////////
function debug(text,type) {
    if (window.console && window.console.log) {
        if(type === 'error' && window.console.error) {
            window.console.error(text);
        }
        else if(type === 'info' && window.console.info) {
            window.console.info(text);
        }
        else if(type === 'warn' && window.console.warn) {
            window.console.warn(text);
        }
        else {
            window.console.log(text);
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
//
// Place iframe behind selected element to overlap windowed elements
// like select boxes or ActiveX-controls in IE6
//
////////////////////////////////////////////////////////////////////////////////
jQuery.fn.activeXOverlap = function() { 

    $(this).each(function(i){
        var h   = $(this).outerHeight();
        var w   = $(this).outerWidth();
        var iframe  = '<!--[if IE 6]>' +
                      '<iframe src="javascript:false;" style="height:' + 
                      h + 
                      'px; width:' + 
                      w + 
                      'px" class="selectOverlap">' + 
                      '</iframe>' +
                      '<![endif]-->'  ;
        $(this).prepend(iframe);
    });
};

////////////////////////////////////////////////////////////////////////////////
//
// son of suckerfish dropdown (original code see:
// http://htmldog.com/articles/suckerfish/dropdowns/)
//
////////////////////////////////////////////////////////////////////////////////
jQuery.fn.sfHover = function() {
    
    // the list to enhance
    var list = $(this);
    list.each(function(i){
        
        //add classes for ie on hover
        $(this).children('li').hover(
            function() {
                //list.find('li').removeClass('hover');
                $(this).addClass('hover');
            },
            function() {
                list.find('li').removeClass('hover');
            }
        );

        
        //first level menu items should stay highlighted when moving to flyout menu
        $(this).find('li .menu').hover(
            function() {
                var tab = $(this).prev('a');
		//FIXME: for some reason, drupal places a div around some submenus
		if (tab.length == 0)
		{
			tab = $(this).parent().prev('a');
		}
                tab.addClass('hover');
            },
            function() {
                var tab = $(this).prev('a');
		//FIXME: for some reason, drupal places a div around some submenus
		if (tab.length == 0)
		{
			tab = $(this).parent().prev('a');
		}
                tab.removeClass('hover');
            }
        );
    });
};

jQuery.fn.sfDropdown = function() {
    
    // the list to enhance
    var dd = $(this);
    
    dd.each(function(i){
        dd = $(this);
        
        //add classes for ie on hover
        $(this).find('.tl').hover(
            function() {
                dd.addClass('hover');
            },
            function() {
                dd.removeClass('hover');
            }
        );
        
        //first level menu items should stay highlighted when moving to flyout menu
        $(this).find('ul').hover(
            function() {
                 dd.addClass('hover');
            },
            function() {
                dd.removeClass('hover');
             }
         );
    });
};         

////////////////////////////////////////////////////////////////////////////////
//
// teaser stage animation
//
// @param arr Array the image links
// @param speed Int the transistion speed
// @param interval Int the interval between transitions 
//
////////////////////////////////////////////////////////////////////////////////
jQuery.fn.teaserStageAnim = function(arr,speed,interval) { 
        
    $(this).each(function(){
        
        // vars
        var el = $(this);
        var len = arr.length;
        var c = 0; // current index
        var n = 1; // new index (start at 1 because first image gets set seperately)
        
        //set first image to stage
        el.attr('src', visuals[0]); 
        
        // once all elements have loaded
        $(window).bind('load', function() {
        
            // periodically call stage visuals function
            window.setInterval(
                function () {
                
        
                    // get current array index from storage
                    if( $.data(el, 'counter') !== undefined) {
                        c = $.data(el, 'counter');
                        
                        // limit to array length
                        if($.data(el, 'counter') < (len - 1)) {
                            n = $.data(el, 'counter') + 1;
                        }
                        else {
                            
                            n = 0;
                        }
                    }
                    
                    // update counter storage
                    $.data(el, 'counter', n); 
                       
                    // display new visual with fade-to-new-image transition
                    var temp = $('<img id="visual-overlay" alt="" />');
                    el.after(temp);
                    temp.attr('src', visuals[(c)]);
                    el.attr('src', visuals[n]);

                    //once image has loaded
                    el.unbind(); // fix memory leak
                    el.bind('load', function() {
                        
                        //fade overlay
                        temp.fadeTo(speed, 0, function(){
                            temp.remove();
                        });
                    });
                },
            interval);
        });
    });
};



////////////////////////////////////////////////////////////////////////////////
//
// jQuery.extend
// reset():  reset forms, like javascript reset(), but for jQuery objects
// unwrap(): opposite of wrap() 
//
////////////////////////////////////////////////////////////////////////////////
jQuery.fn.extend({
    reset: function() {
        return this.each(function() {
            $(this).is('form') && this.reset();
        })
    },
    unwrap: function() {
        return this.parent(':not(body)').each(function() {
            $(this).replaceWith( this.childNodes );
        })
    }
});


////////////////////////////////////////////////////////////////////////////////
//
// domready
//
////////////////////////////////////////////////////////////////////////////////
var searcher;
jQuery(function() {

    // Stage Visuals
    //--------------------------------------------------------------------------  
    var stage = $('#visual');
    var interval = 4000; //speed of slideshow loop
    var speed = 3000; //speed of fading transition
    if(stage.length > 0) {
        stage.teaserStageAnim(visuals,speed,interval);
    }

    // Setup of Son of Suckerfish Dropdown Menu
    //--------------------------------------------------------------------------
    
    $('#nav-h #block-menu_block-2 .content .menu-name-menu-dah-h').children('ul').sfHover();
    $('#nav-h #block-menu_block-2 .content .menu-name-menu-dah-h ul li ul').activeXOverlap();
	$('#nav-h #block-menu_block-5 .content .menu-name-menu-dah-h-eng').children('ul').sfHover();
    $('#nav-h #block-menu_block-5 .content .menu-name-menu-dah-h-eng ul li ul').activeXOverlap();
    $('.nav-dropdown').sfDropdown();
    
    // misc ui improvements
    //--------------------------------------------------------------------------

    /* wrapped input elements need focus style for their wrapper */
    $('.input-wrap input').focus( 
        function(){
            $(this).parent().addClass('focus');
        }
    );
    $('.input-wrap input').blur( 
        function(){
            $(this).parent().removeClass('focus');
        }
    );
    
    /* buttons need hover-support in ie */
    $('input.submit').hover( 
        function() {
            $(this).addClass('hover');
        },
        function() {
            $(this).removeClass('hover');
        }
    );
    
    /* fading image links */
    $('a.img').hover(
        function() {
            $(this).find('img').fadeTo('fast',0.8);
        },
        function() {
            $(this).find('img').fadeTo('fast',1);
        }
    );
    
    /* set address selection to equal height as map area */
    $('#addresses .scroll').height($('#addresses .map-col').outerHeight(true) - $('#addresses .rbox').outerHeight(true) + $('#addresses .scroll').height());
    
    
    // table zebra striping
    //--------------------------------------------------------------------------
    $('table.zebra tr:odd').addClass('odd');
     
 	// truncate float box content 
 		    // if there are more than n links in float box list, show only the  
 		    // n first links and add "more"-link whcich slides down the rest 
 		    //-------------------------------------------------------------------------- 
 	var trunclength = 3;  
 	$('.float-box-m .float-box-content').children('ul.menu').each( 
 	function(){ 
              
 	    // if there are more than n links in a list 
        if ($(this).children('li:gt(' + trunclength + ')').length > 0) { 
               
			// select n-1 items and wrap them in a hidden div 
			var items = $(this).children('li:gt(' + (trunclength -1) + ')'); 
			var more = $('<div class="trunc-more"/>'); 
			var showmore =  $('<li><a href="#">' + Drupal.t('Mehr') + '&hellip;</a></li>'); 
			$(this).children('li').eq(trunclength).after(more); 
			more.append(items).hide().after(showmore); 
                
               // append more-link and behaviour 
	            showmore.find('a').click(function(){ 
					more.slideDown('fast'); 
					showmore.remove(); 
					return false; 
	            }); 
            } 
	    } 
    ); 
    
    // Links as submit buttons
    //--------------------------------------------------------------------------
    $('.b-submit').click(function(e){
        $(this).parents('form').submit();
        e.preventDefault();
    });
    
    
    // Selects as submit buttons
    //--------------------------------------------------------------------------
    $('.change-submit').change(function(){
        $(this).parents('form').submit();
    });

  // Print buttons 
 	//-------------------------------------------------------------------------- 
 	$('.action-print').click(function(e){ 
 	  window.print(); 
 	  e.preventDefault(); 
 	});     
    
    // Accordion
    //--------------------------------------------------------------------------
    var acc = $('.acc');
    
    if(acc.length > 0) {
		if (document.location.hash.substring(1))
		{
			var anchor = document.location.hash.substring(1);
			var element = $('#' + anchor).nextAll('.acc-toggler');
			acc.accordion({
				header:     '.acc-toggler',
				autoHeight: false,
				active: '.' + anchor
			});
			
		}
		else
		{
			acc.accordion({
				header:     '.acc-toggler',
				autoHeight: false

			});
		}
		
        
		
		
    }
    
    // Gallery
    //--------------------------------------------------------------------------
    var gallery = $('.gallery');
    /* Commented out due to bug in line             progress:   '.load'
    if(gallery.length > 0) {
        $('.gallery a').overlay({ 
            target: '#gallery-overlay', 
            expose: '#304454',
            close:  '.close-warn',
            onBeforeLoad: function(){
                this.getOverlay().appendTo('body');
            }
        }).gallery({ 
            speed:      800,
            autohide:   false,
            opacity:    1,
            template:   '<strong>${title}</strong> <span class="dimmed smaller fr">Bild ${index} von ${total}</span>',
            info:       '.caption',
            next:       '.imgr',
            prev:       '.imgl',
            progress:   '.load'
        });
    }
    
    var singleImage = $('.text-img');
    
    if(singleImage.length > 0) {
        $('.text-img a.single-image').overlay({ 
            target: '#single-image-overlay', 
            expose: '#304454',
            close:  '.close-warn',
            onBeforeLoad: function(){
                this.getOverlay().appendTo('body');
            }
        }).gallery({ 
            speed:      800,
            autohide:   false,
            opacity:    1,
            template:   '<strong>${title}</strong>',
            info:       '.caption',
            progress:   '.load'
        });
    }
    */
    /*
    // Datepicker
    //--------------------------------------------------------------------------
    var dateinput = $('.dateinput');
    if(dateinput.length > 0) {
    
        // create additional option element
        var eventOptionHelper = $('<option value="user-defined"></option>');
        
        dateinput.datepicker({
            dateFormat: 'd.m.yy',
            minDate:    0,
            nextText:   'NÃ¤chster Monat',
            prevText:   'Vorheriger Monat',
            dayNamesMin: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'],
            dayNames:   ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'],
            monthNames: ['Januar','Februar','MÃ¤rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
            onSelect:   function(dateText, inst) {
                
                // convert dates to Date object
                var from    = $('#event-from').val().split('.');
                from = new Date(from[2],from[1] -1,from[0]);
                var to      = $('#event-to').val().split('.');
                to = new Date(to[2],to[1] -1,to[0]);
                
                // prevent picking a toDate older than fromDate and vice versa
                $('#event-to').datepicker('option','minDate',from);
                $('#event-from').datepicker('option','maxDate',to);
                
                // add option to select element displaying current selected date range
                var value   = $('#event-from').val() + ' - ' + $('#event-to').val();
                eventOptionHelper.text(value);
                $('#event-timeframe').prepend(eventOptionHelper);
                
                // make sure the new option is preselected
                $('#event-timeframe:selected').removeAttr('selected');
                eventOptionHelper.attr('selected', 'selected');
            }
            
        });
    }
    */

    // Comment Reply Forms toggle
    //--------------------------------------------------------------------------
    $('.comment-reply-form-wrap a.button').toggle(
        function(){
		if (!$(this).hasClass('login'))
		{
			w21GetForm($(this))
		}
            $(this).toggleClass('b-plus').toggleClass('b-minus');
            $(this).parent().next('.target').slideDown('fast');
        },
        function(){
            var b = $(this);
            $(this).parent().next('.target').slideUp('fast', function() {
                b.toggleClass('b-plus').toggleClass('b-minus');
            });
        }
    );
    
    
    // Extended Forms toggle
    //--------------------------------------------------------------------------
    $('.extended').hide();
    $('.ex-toggler a.button').toggle(
        function(){
            //open extended search and change button
            $(this).toggleClass('b-plus').toggleClass('b-minus');
            $(this).parents('fieldset').next('fieldset.extended').fadeIn('fast');
        },
        function(){
            //close extended search and change button back
            $(this).toggleClass('b-plus').toggleClass('b-minus');
            $(this).parents('fieldset').next('fieldset.extended').fadeOut('fast', function(){
                
                // reset form
                if ($.browser.msie) {
                    $(this).parents('form').reset();
                }
                else {
                    /* NOT WORKING IN IE
                    // reset only elements in extended search upon closing extended search
                    // we need to enclose only the extended part of the form in a new form to reset it, the unwrap it again
                    */
                    $(this).wrap('<form></form>').parent().reset().children().unwrap();
                }
            });
            
        }
    );
	
	
	$('.extended').hide();
    $('.search-ex-toggler a.button').toggle(
        function(){
            //open extended search and change button
            $(this).toggleClass('b-plus').toggleClass('b-minus');
            $(this).parent('div').next('div.extended').fadeIn('fast');
        },
        function(){
	  
            //close extended search and change button b
            $(this).toggleClass('b-plus').toggleClass('b-minus');
            $(this).parent('div').next('div.extended').fadeOut('fast', function(){
                

            });
            
        }
    );
    
    
    // Get IE to handle change event on radio buttons right
    //--------------------------------------------------------------------------
    $(function () {
        if ($.browser.msie) {
            $(':radio,:checkbox').click(function () {
                this.blur();
                this.focus();
            });
        }
    });
    
    
    // Toggle radio selection dependent form elements
    //--------------------------------------------------------------------------
    // hide all dependent elements if their triggers are not checked
    $('.dependent').prev('.row').find(':radio.dependent-trigger-off:checked').parents('.row').next('.dependent').hide();
    
    // show / hide dependent element according to user selection
    $(':radio.dependent-trigger-on').change(function(){
        $(this).parents('.row').next('.dependent').slideDown('fast');
    });
    $(':radio.dependent-trigger-off').change(function(){
        $(this).parents('.row').next('.dependent').slideUp('fast');
    });
    
    
    // hide all subselections if their triggers are not checked
    //--------------------------------------------------------------------------
    $('.subselect-trigger:not(:checked)').each(function(){
        
        // hide on load
        $(this).nextAll('.subselection').eq(0).hide();
        
        // remove special class
        $(this).closest('.has-trigger').removeClass('has-subselection');
        
    });
	

    
    
    // Toggle radio selection dependent subselections
    //
    // Subselections are hidden extra form elements. When their trigger is
    // clicked, they are shown with an animation, any other open subselection in
    // the same radio group gets hidden
    //
    // HTML-Structure:
    // <div class="row">                     
    //   <div class="has-trigger has-subselection">
    //     <input type="radio" name="foo" id="foo-1" class="subselect-trigger" />
    //     <div class="subselection">foo</div>
    //   </div>
    //   <div class="has-trigger">
    //     <input type="radio" name="foo" id="foo-2" class="subselect-trigger" />
    //   </div>
    // </div>
    //
    //--------------------------------------------------------------------------
       
    // add event listener to all buttons in group
    // (no other way to check for unchecking of a radio button)
    $(':radio.subselect-trigger').each(function(){
        
        //whenever a radio button changes
        $(this).change(function(){
            
            // close all open subselections in the same radio button group
            $(this).closest('.row').find('.subselection').slideUp('fast', function() {
            
                // and remove the special class
                $(this).closest('.has-trigger').removeClass('has-subselection');
            });
            
            // then open the subuselection of the currently checked radio button (if has subselection)
            $(this).nextAll('.subselection').eq(0).slideDown('fast').closest('.has-trigger').addClass('has-subselection');
        });
    });
	
	    // add event listener to all buttons in group
    
	if ($('#edit-submitted-zahlungsmethode-zahlung-2').is(':checked'))
	{
		$('#edit-submitted-zahlungsmethode-zahlung-2-wrapper label').addClass('has-subselection');
		$('#webform-component-zahlungsmethode--einzug').slideDown('fast');
	}
	// (no other way to check for unchecking of a radio button)
	$('#edit-submitted-zahlungsmethode-zahlung-1').change(function(){
		
			if (!$(this).is(':checked'))
			{
				$('#edit-submitted-zahlungsmethode-zahlung-2-wrapper label').addClass('has-subselection');
				$('#webform-component-zahlungsmethode--einzug').slideDown('fast');
			}
			else
			{
				$('#webform-component-zahlungsmethode--einzug').slideUp('fast', function() {
					$('#edit-submitted-zahlungsmethode-zahlung-2-wrapper label').removeClass('has-subselection');
				});
			}
	});
			
    $('#edit-submitted-zahlungsmethode-zahlung-2').change(function(){
			if ($(this).is(':checked'))
			{
				$('#edit-submitted-zahlungsmethode-zahlung-2-wrapper label').addClass('has-subselection');
				$('#webform-component-zahlungsmethode--einzug').slideDown('fast');
			}
			else
			{
				 $('#webform-component-zahlungsmethode--einzug').slideUp('fast', function() {
					$('#edit-submitted-zahlungsmethode-zahlung-2-wrapper label').removeClass('has-subselection');
				});
			}
    });
	
	if ($('#edit-submitted-ubernachtung-hotel-2').is(':checked') && $('#webform-component-ubernachtung--hoteloptionen input').length > 1)
	{
		$('#edit-submitted-ubernachtung-hotel-2-wrapper label').addClass('has-subselection');
		$('#webform-component-ubernachtung--hoteloptionen').slideDown('fast');
	}

	$('#edit-submitted-ubernachtung-hotel-1').change(function(){
		
			if ($('#webform-component-ubernachtung--hoteloptionen input').length > 1)
			{
				if (!$(this).is(':checked') && $('#webform-component-ubernachtung--hoteloptionen input').length > 1)
				{
					$('#edit-submitted-ubernachtung-hotel-2-wrapper label').addClass('has-subselection');
					$('#webform-component-ubernachtung--hoteloptionen').slideDown('fast');
				}
				else 
				{
					$('#webform-component-ubernachtung--hoteloptionen').slideUp('fast', function() {
						$('#edit-submitted-ubernachtung-hotel-2-wrapper label').removeClass('has-subselection');
					});
				}
			}
	});
			
    $('#edit-submitted-ubernachtung-hotel-2').change(function(){
			if ($('#webform-component-ubernachtung--hoteloptionen input').length > 1)
			{
				if ($(this).is(':checked'))
				{
					$('#edit-submitted-ubernachtung-hotel-2-wrapper label').addClass('has-subselection');
					$('#webform-component-ubernachtung--hoteloptionen').slideDown('fast');
				}
				else
				{
					 $('#webform-component-ubernachtung--hoteloptionen').slideUp('fast', function() {
						$('#edit-submitted-ubernachtung-hotel-2-wrapper label').removeClass('has-subselection');
					});
				}
			}
    });
	 
	if ($('#edit-submitted-teilnehmerdaten-private-2').is(':checked'))
	{
		$('#webform-component-teilnehmerdaten--firma').slideDown('fast');
	}
	// (no other way to check for unchecking of a radio button)
	$('#edit-submitted-teilnehmerdaten-private-1').click(function(){
		
			if ($(this).is(':checked'))
			{
				$('#webform-component-teilnehmerdaten--firma').slideUp('fast');
			}
	});
	$('#edit-submitted-teilnehmerdaten-private-2').click(function(){
		
			if ($(this).is(':checked'))
			{
				$('#webform-component-teilnehmerdaten--firma').slideDown('fast');
			}
	});
	
	
	
	
	
	if ($('#edit-submitted-unterstutzung-vor-ort-substitution-orga-1').is(':checked'))
	{
		$('#edit-submitted-unterstutzung-vor-ort-substitution-orga-1-wrapper').addClass('has-subselection');
		$('#webform-component-unterstutzung-vor-ort--substitution').slideDown('fast');
	}
	// (no other way to check for unchecking of a radio button)
	$('#edit-submitted-unterstutzung-vor-ort-substitution-orga-1').change(function(){
		
			if ($(this).is(':checked'))
			{
				$('#edit-submitted-unterstutzung-vor-ort-substitution-orga-1-wrapper').addClass('has-subselection');
				$('#webform-component-unterstutzung-vor-ort--substitution').slideDown('fast');
			}
			else
			{
				$('#webform-component-unterstutzung-vor-ort--substitution').slideUp('fast', function() {
					$('#edit-submitted-unterstutzung-vor-ort-substitution-orga-1-wrapper').removeClass('has-subselection');
				});
			}
	});

	if ($('#edit-submitted-unterstutzung-vor-ort-aerztliche-unterstuetzung-1').is(':checked'))
	{
		$('#edit-submitted-unterstutzung-vor-ort-aerztliche-unterstuetzung-1-wrapper').addClass('has-subselection');
		$('#webform-component-unterstutzung-vor-ort--arzt').slideDown('fast');
	}
	// (no other way to check for unchecking of a radio button)
	$('#edit-submitted-unterstutzung-vor-ort-aerztliche-unterstuetzung-1').change(function(){
		
			if ($(this).is(':checked'))
			{
				$('#edit-submitted-unterstutzung-vor-ort-aerztliche-unterstuetzung-1-wrapper').addClass('has-subselection');
				$('#webform-component-unterstutzung-vor-ort--arzt').slideDown('fast');
			}
			else
			{
					$('#webform-component-unterstutzung-vor-ort--arzt').slideUp('fast', function() {
					$('#edit-submitted-unterstutzung-vor-ort-aerztliche-unterstuetzung-1-wrapper').removeClass('has-subselection');
				});
			}
	});
	
	if ($('#edit-submitted-unterstutzung-vor-ort-kinder-1').is(':checked'))
	{
		$('#edit-submitted-unterstutzung-vor-ort-kinder-1-wrapper').addClass('has-subselection');
		$('#webform-component-unterstutzung-vor-ort--kinderset').slideDown('fast');
	}
	// (no other way to check for unchecking of a radio button)
	$('#edit-submitted-unterstutzung-vor-ort-kinder-1').change(function(){
		
			if ($(this).is(':checked'))
			{
				$('#edit-submitted-unterstutzung-vor-ort-kinder-1-wrapper').addClass('has-subselection');
				$('#webform-component-unterstutzung-vor-ort--kinderset').slideDown('fast');
			}
			else
			{
				$('#webform-component-unterstutzung-vor-ort--kinderset').slideUp('fast', function() {
					$('#edit-submitted-unterstutzung-vor-ort-kinder-1-wrapper').removeClass('has-subselection');
				});
			}
	});
	
    
    // Toggle checkbox selection dependent subselections
    //
    // Subselections are hidden extra form elements. They can be toggled via a 
    // checkbox
    //--------------------------------------------------------------------------
    $(':checkbox.subselect-trigger').each(function(){
        
        //whenever a radio button changes
        $(this).change(function(){
            
            // if the checkbox is checked
            if($(this).is(':checked')) {
                // open the subuselection of the currently checked checkbox
                $(this).nextAll('.subselection').eq(0).slideDown('fast').closest('.has-trigger').addClass('has-subselection');
            }
            else {
                // close the subuselection of the currently checked checkbox
                $(this).nextAll('.subselection').eq(0).slideUp('fast', function() {
            
                    // and remove the special class
                    $(this).closest('.has-trigger').removeClass('has-subselection');
                });
            }
        });
    });
    
    /*
    // open popup overlays
    //--------------------------------------------------------------------------
    $('a.popup').overlay({
		//target: '#agb',
        expose: '#304454',
        close:  '.close-popup',
        onBeforeLoad: function(){
            alert('popup');
            //fix ie7 placement bug
            this.getOverlay().appendTo('body');
        }
    });*/


    $('a.popup').click(function() {
		$('#agb').fadeIn();
		$('#agb').css("position", "absolute");
		
		$('#agb').css("top", ( $(window).height() - $('#agb').height() ) / 2+$(window).scrollTop() + "px");
		$('#agb').css("left", "270px");
		$('#agb').fadeIn();
		return false;
	});
	
	if($('#messages-popup').length)
	{
		$('#messages-popup').fadeIn();
		$('#messages-popup').css("position", "absolute");
		
		$('#messages-popup').css("top", ( $(window).height() - $('#messages-popup').height() ) / 2+$(window).scrollTop() + "px");
		$('#messages-popup').css("left", "270px");
		$('#messages-popup').fadeIn();
		$('.close-popup').click(function() {
			$('#messages-popup').fadeOut();
		});
	}
	
	 $('#socialmediarss').click(function() 
	{
		//alert('hmm');
		$('#rssoverlay').fadeIn();
		$('#rssoverlay').css("position", "absolute");
		
		$('#rssoverlay').css("top", ( $(window).height() - $('#rssoverlay').height() ) / 2+$(window).scrollTop() + "px");
		$('#rssoverlay').css("left", "270px");
		$('#rssoverlay').fadeIn();
		$('#rssoverlay .close-popup').click(function() {
			$('#rssoverlay').fadeOut();
		});
		return false;
	});
	
	
	$('.close-popup').click(function() {
		$('#agb').fadeOut();
	});
	
    // lang select setup
    //--------------------------------------------------------------------------
	
    $(".lang-subselect").tooltip({
    
        // tooltip options
        position:   ['bottom','center'],
        relative:   true,
        offset:     [10, -1],
        // effect:     'fade',
        tip:        '.lang-select'
    });
	// $(".lang-subselect").tooltip('.lang-select'); 

    
    // calendar setup
    //--------------------------------------------------------------------------
   
    // w21ToolTip();
    //w21MapReady();
   //w21LoginPopup ();
    w21FAQAccordionFix();
    w21GoogleAjaxInit();

	
    $("a[@href^='http']:not([@href^='http://dah.werk21system.de/']:not([@href^='http://www.aidshilfe.de/'])").attr('target','_blank'); 
    //$('.hidden_tab_menu').hide();
   // $('.float-box-content .menu').accordion({ header: '.tab_parent', active: false });
	$('.alphabet li').each(function (index, Element) {
	var code = $(Element).children().text().charCodeAt(0);
	if (code >= 48 && code <= 57)
	{
		$(Element).hide();
	}
	
	});
	w21_type_filter_links();
	if ($('#views-exposed-form-eventlist-page-1 #edit-date-filter-min-day, #views-exposed-form-eventlist-page-3 #edit-date-filter-min-day').length)
	{
		$('#edit-date-filter-min-day').val(1);

		var dd = new Date($('#edit-date-filter-max-year').val(), $('#edit-date-filter-max-month').val(), 0);		
		$('#edit-date-filter-max-day').val(dd.getDate());
	}
		$('#edit-date-filter-max-year, #edit-date-filter-max-month').change(function() {
		
			var dd = new Date($('#edit-date-filter-max-year').val(), $('#edit-date-filter-max-month').val(), 0);		
			$('#edit-date-filter-max-day').val(dd.getDate());
		});
	$('#views-exposed-form-Meldungen-page-1, #views-exposed-form-Meldungen-page-2').submit(function()
	{
		if ($('#edit-date-filter-max-year').val() && $('#edit-date-filter-max-month').val())
		{
			var dd = new Date($('#edit-date-filter-max-year').val(), $('#edit-date-filter-max-month').val(), 0);		
			$('#edit-date-filter-max-day').val(dd.getDate());
		}
		if ($('#edit-date-filter-min-year').val() && $('#edit-date-filter-min-month').val())
		{
			$('#edit-date-filter-max-year').val($('#edit-date-filter-min-year').val());
			$('#edit-date-filter-max-month').val($('#edit-date-filter-min-month').val());
		}
		else if ($('#edit-date-filter-min-year').val() && !$('#edit-date-filter-min-month').val())
		{
			$('#edit-date-filter-max-year').val($('#edit-date-filter-min-year').val());
			$('#edit-date-filter-min-month').val(1);
			$('#edit-date-filter-max-month').val(12);
		}
		else if (!$('#edit-date-filter-min-year').val() && $('#edit-date-filter-min-month').val())
		{
			$('#edit-date-filter-min-year').val($('#edit-date-filter-min-year option:last').attr('value'));
			$('#edit-date-filter-max-month').val($('#edit-date-filter-min-month').val());
			$('#edit-date-filter-max-year').val($('#edit-date-filter-min-year').val());

		}
	});
	
	$('.lang-en-UK abbr').each(function () {
		$(this).replaceWith($(this).find('a').html());
		
	}
	);
	
	$('.body-text table tr:nth-child(odd)').addClass('odd');
	
});


/* The good old W21 google ajax */
var searchers = new Array();
function w21GoogleAjaxInit()
{
	if (typeof(w21SearchSites) == "undefined")
	{
		return;
	}
	for (var i = 0; i < w21SearchSites.length; i++)
	{
		searchers[i] = new google.search.WebSearch();
		searchers[i].setSiteRestriction(w21SearchSites[i][1]);
		searchers[i].setSearchCompleteCallback(null, w21SearchComplete, [i]);
		searchers[i].setResultSetSize(google.search.Search.LARGE_RESULTSET);
		searchers[i].execute(w21SearchTerm);
	}
}

function w21SearchComplete(id)
{ // Check whether we got results
	if (searchers[id].results && searchers[id].results.length > 0) {
		var contentDiv = $('#search_results');

		// Loop through our results, printing them to the page.
		if (!($('#searcher-' + id).length))
		{
			var append = '<h2 class="section-header acc-toggler ui-state-default"  >';
			append = append + '&nbsp;<span class="title">' + w21SearchSites[id][0] + '</span>';
			append = append +  '<span class="dimmed">&nbsp;' + w21SearchSites[id][1] + '</span>';
			append = append + '</h2>';


			append = append + '<ul class="listing acc-entry" style="display: none" id="searcher-' + id + '">';

			//append = append + 
			append = append + "</ul>"; 
			contentDiv.append(append);
			w21RenderGoogleResults(id);
		}
		else
		{
			$('#searcher-' + id).html('');
			w21RenderGoogleResults(id);
		}
		w21SearchAccordionFix();
		w21AddPaging(id)
	}
}

function w21RenderGoogleResults(id)
{
	
	var append= "";
	var results = searchers[id].results;
	for (var i = 0; i < results.length; i++) 
	{

		searchers[id].createResultHtml(results[i]);
 
		var node = results[i].html.cloneNode(true);

		var li = document.createElement('li');
		li.appendChild(node);
		document.getElementById('searcher-' + id).appendChild(li);
		//container.appendChild(node)
		//$('#searcher-' + id).apend('<li></li>').append($(node));
		//var title = results[i][title];
		//append = append + "<li>" + results[i][html] + "</li>";
	}


	// now, see if we have a cursor, and if so, create the 
	// cursor control
	var pager = '';
	if (searchers[id].cursor) {
		pager = '<li><ul class=" center pagination">';
		for (var i = 0; i< searchers[id].cursor.pages.length; i++) {
			if (i == searchers[id].cursor.currentPageIndex) {
				pager = pager + '&nbsp;<li ><strong><a href="#" class="pager-' + id + '" id="page-' + id + '-' + i + '">' + searchers[id].cursor.pages[i].label + "</a></strong></li>";
			}
			else
			{
				pager = pager + '&nbsp;<li><a class="pager-' + id + '" id="page-' + id + '-' + i + '">' + searchers[id].cursor.pages[i].label + "</a></li>";
			}
		}
		var attrib  = searchers[id].getAttribution();
		if (attrib)
		{
			append = append + $(attrib);
		}
		attrib  = GSearch.getBranding();
		if (attrib)
		{
			append = append + (attrib.innerHTML);
		}
		pager = pager + '</ul></li>';
	}
	append = append + pager;
	
	$('#searcher-' + id).append(append);
	
}

function w21AddPaging(id)
{
	$('.pager-' + id).click(function () {
		var page =  $(this).attr('id').split('-');
		page = page[2];
		searchers[id].gotoPage(page);
	});
}

function w21SearchAccordionFix()
{
	var acc = $('.acc2');
	if(acc.length > 0) {
		acc.accordion({
		header:     '.acc-toggler',
		autoHeight: false
		});
	}
	$('h2').click(function() {
	$('h2').addClass("ui-state-default").removeClass('ui-state-active'); 
	$(this).removeClass('ui-state-default').addClass('ui-state-active');;

	});
}

/* Kommentar formulare können nur einmal pro Seite existieren. Daher kopieren wir.
*/
function w21GetForm(obj)
{
	
	var url = obj.attr('href');
	var id = url.substr(url.lastIndexOf('/')+1);
	// schon erstellte -> re-use
	if ($('#comment-form-box-div-' + id).length > 0)
	{
		return;
	}
	
	var div = $('#comment-form').parent().parent().clone();
	div.attr('id', 'comment-form-box-div-' + id);
	form = div.children('.content').children('#comment-form');
	div.find('[id]').attr('id',  
		function () {
			return this.id + '-' + id;
		} 
	);
	form.attr('action', url);
	form.find('[name=form_token]').attr('value', $('#token-' + id).html());

	$('#reply-' + id).append(div); 
}

var map;
var geocoder;




// Set up the address page and its google map.
function w21MapReady()
{
	// do we nned a map at all?
	if ($('#map').length == 0)
	{
		return;
	}
	
	// Rounded Corners for the google map
	function RoundedCornersLeft() {
	}
	RoundedCornersLeft.prototype = new GControl();
	RoundedCornersLeft.prototype.initialize = function(map) {
		var container = document.createElement("div");
		var left = document.createElement("img");
		left.src="/sites/all/themes/dah/assets/img/w21/map-l.png"
		container.appendChild(left);
		map.getContainer().appendChild(container);
		return container;
	}

	RoundedCornersLeft.prototype.getDefaultPosition = function() {
		return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 12));
	}

	function RoundedCornersTop() {
	}
		RoundedCornersTop.prototype = new GControl();
		RoundedCornersTop.prototype.initialize = function(map) {
		var container = document.createElement("div");
		var top = document.createElement("img");
		top.src="/sites/all/themes/dah/assets/img/w21/map-t.png"
		container.appendChild(top);
		map.getContainer().appendChild(container);
		return container;
	}

	RoundedCornersTop.prototype.getDefaultPosition = function() {
		return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, -1));
	}
	
	function RoundedCornersRight() {
	}
		RoundedCornersRight.prototype = new GControl();
		RoundedCornersRight.prototype.initialize = function(map) {
		var container = document.createElement("div");
		var right = document.createElement("img");
		right.src="/sites/all/themes/dah/assets/img/w21/map-r.png"
		container.appendChild(right);
		map.getContainer().appendChild(container);
		return container;
	}

	RoundedCornersRight.prototype.getDefaultPosition = function() {
		return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 12));
	}
		
	function RoundedCornersBottom() {
	}
		RoundedCornersBottom.prototype = new GControl();
		RoundedCornersBottom.prototype.initialize = function(map) {
		var container = document.createElement("div");
		var bottom = document.createElement("img");
		bottom.src="/sites/all/themes/dah/assets/img/w21/map-b.png"
		container.appendChild(bottom);
		map.getContainer().appendChild(container);
		return container;
	}

	RoundedCornersBottom.prototype.getDefaultPosition = function() {
		return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(0, -5));
	}
		


	map = new GMap2(document.getElementById('map'));
	geocoder = new GClientGeocoder();
	/* set auto-submit for exposed filter adressen */
	$('#edit-submit-adressen').addClass('hidden_submit ');
	
	// If an address is clicke, mark it as selected, show its vcard and move the map
	$('.addresses a').click(function ()
	{
		$('.selected').removeClass('selected');
		$(this).addClass('selected');
		var raw_id = ($(this).attr('id'));
		var id = raw_id.substr(raw_id.lastIndexOf('-')+1);
		$('.map-head').html($('#div-' + id).html());
		var address = $('#address-' + id).html();
		var lat = $('#lat-' + id).html();
		var long = $('#long-' + id).html();
		var point = new GLatLng(lat, long);
		
		/*
		geocoder = new GClientGeocoder();
		geocoder.getLatLng(address , function (point)
		{
			map.setCenter(point, 15);
			var marker = new GMarker(point);
			map.addOverlay(marker);
			marker.openInfoWindowHtml($('.map-head').html());
		}); 	
		*/
		map.setCenter(point, 15);
		var marker = new GMarker(point);
		map.addOverlay(marker);
		marker.openInfoWindowHtml($('.map-head').html());
		return false;
	});
	   
	// Initially, we show DAH itself or - if its not in the list - the first entry
	var map = new GMap2(document.getElementById('map'));
	// round the map corners
	map.addControl(new RoundedCornersLeft());
	map.addControl(new RoundedCornersTop());
	map.addControl(new RoundedCornersRight());
	map.addControl(new RoundedCornersBottom());

	var address_sel = $('#address-91');
	var id = 91;
	if (address_sel.length == 0)
	{
		var raw_id = $('.hidden_vcard').attr('id');
		id = raw_id.substr(raw_id.lastIndexOf('-')+1);
	}
	address = $('#address-' + id).html();
	var ilat = $('#lat-' + id).html();
	var ilong = $('#long-' + id).html();
	var ipoint = new GLatLng(ilat, ilong);
	$('#a-' + id).addClass('selected');
	$('.map-head').html($('#div-' + id).html());

		map.setCenter(ipoint, 15);
		var marker = new GMarker(ipoint);
		map.addOverlay(marker);
		marker.openInfoWindowHtml($('.map-head').html());
		
	
	
}

function w21LoginPopup()
{	
	return;
	var loginForm = $('#login');
	if (loginForm.length != 0)
	{
		var menuItem = $('.menu-mlid-2553');
		menuItem.empty();
		menuItem.append($('#login'));
	}
}		


function w21FAQAccordionFix()
{
	$('.question').click(function() {
		$('.question').addClass("ui-state-default");
		$(this).removeClass('ui-state-default');
	});
}

Drupal.behaviors.calendarBehavior = function (context) {
	 w21ToolTip();
	//make_calendar_ajaxy();
	    // Selects as submit buttons
	    //--------------------------------------------------------------------------
	    $('.change-submit').change(function(){
		$(this).parents('form').submit();
	});

};



/**
Make the prev/next links use AJAX. Slightly altered from http://drupal.org/node/339279 #45
*/
function make_calendar_ajaxy() {
      if(Drupal.settings.views.ajax_path){
        var $name = "event_calendar";
        var $display_id = "calendar_block_1";        
         
      	//Let's fix those nav links
  		  //First, let's scope this so we don't mess with other calendars
  		  jqscope = '.view-id-'+$name+'.view-display-id-'+$display_id;
  		  varscope = 'view-id-'+$name+'_view-display-id-'+$display_id;		  
  		  //Now, get the parent container to stuff the results in
  		  var parent = $(jqscope).parent()[0];
  		  //First, we need to know where we are right now... see if we've got our date settings
  		  vars = Drupal.settings;
  		  current = 'current_calendar_view'+varscope;
  		  previous = 'previous_calendar_view'+varscope;
  		  next = 'next_calendar_view'+varscope;
  		  if(!vars[current]) {
  		  	vars[current] = new Date();
  		  	vars[previous] = new Date();
  		  	vars[next] = new Date();
  		  	//Luckily, javascript is smart enough to deal with year wrapping... 
  		  	//2010-13 = 2011-02 (remember it's zero-based)
  		  	vars[previous].setMonth(vars[previous].getMonth() - 1);
  		  	vars[next].setMonth(vars[next].getMonth() + 1);		
  		  }
  		  //Disable whatever's there already
  		  $('.month-prev, .month-next').each( function() {
  		  	$(this).attr("href", "javascript:void(0)");
  		  });
  		  //Setup the links
  		  $('.month-prev').click( function() {
			  alert('current');
  		  	$.ajax({
  		  		url: '/views/ajax', //Drupal.settings.views.ajax_path,
  		  		data: {
  		  			'js': 1,
  		  			'view_name': $name,
  		  			'view_display_id': $display_id,
  		  			//Yeah, javascript sucks for having 0-based months
  		  			'view_args': vars[previous].getFullYear()+"-"+(vars[previous].getMonth()+1)
  		  		},
  		  		dataType: 'json',
  		  		success: function (data, status, request) {
					  
  		  					parent.innerHTML = data.display;
  		  					//Make sure our variables track with what's displayed
  		  					vars[current].setMonth(vars[next].getMonth() - 1);
  		  					vars[previous].setMonth(vars[previous].getMonth() - 1);
  		  					vars[next].setMonth(vars[next].getMonth() - 1);
  		  					//Make the newly inserted calendar ajaxy again
  		  					//make_calendar_ajaxy();
						 w21ToolTip();
	    // Selects as submit buttons
	    //--------------------------------------------------------------------------
	   /* $('.change-submit').change(function(){
		$(this).parents('form').submit();
	});*/
  		  				}
  		  	});
  		  });
  		  $('.month-next').click( function() {
  		  	$.ajax({
  		  		url: '/views/ajax',
  		  		data: {
  		  			'js': 1,
  		  			'view_name': $name,
  		  			'view_display_id': $display_id,
  		  			'view_args': vars[next].getFullYear()+"-"+(vars[next].getMonth()+1)
  		  		},
  		  		dataType: 'json',
  		  		success: function (data, status, request) {
  		  					parent.innerHTML = data.display;
  		  					//Make sure our variables track with what's displayed
  		  					vars[current].setMonth(vars[current].getMonth() + 1);
  		  					vars[previous].setMonth(vars[previous].getMonth() + 1);
  		  					vars[next].setMonth(vars[next].getMonth() + 1);
  		  					//Make the newly inserted calendar ajaxy again
  		  					make_calendar_ajaxy();
						 w21ToolTip();
	    // Selects as submit buttons
	    //--------------------------------------------------------------------------
	    $('.change-submit').change(function(){
		$(this).parents('form').submit();
	});
  		  				}
  		  	});
  		  });
      }
}
	
Drupal.behaviors.mapBehavior = function (context) {
	w21MapReady();
};

Drupal.behaviors.w21EventList = function (context) {

  // Datepicker
    //--------------------------------------------------------------------------
   /* var dateinput = $('.dateinput');
    if(dateinput.length > 0) {
    
        // create additional option element
        var eventOptionHelper = $('<option value="user-defined"></option>');
        
        dateinput.datepicker({
            dateFormat: 'd.m.yy',
            minDate:    0,
            nextText:   'NÃ¤chster Monat',
            prevText:   'Vorheriger Monat',
            dayNamesMin: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'],
            dayNames:   ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'],
            monthNames: ['Januar','Februar','MÃ¤rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
            onSelect:   function(dateText, inst) {
               //alert($('#date_filter[min]').length);
                // convert dates to Date object
                var from    = $('#edit-date-filter-min').val().split('.');
                from = new Date(from[2],from[1] -1,from[0]);
                var to      = $('#edit-date-filter-max').val().split('.');
                to = new Date(to[2],to[1] -1,to[0]);
                
                // prevent picking a toDate older than fromDate and vice versa
                $('#edit-date-filter-max').datepicker('option','minDate',from);
                $('#edit-date-filter-min').datepicker('option','maxDate',to);
                 
                // add option to select element displaying current selected date range
                var value   = $('#edit-date-filter-min').val() + ' - ' + $('#edit-date-filter-max').val();
                eventOptionHelper.text(value);
		
                $('#event-timeframe').prepend(eventOptionHelper);
                
                // make sure the new option is preselected
                $('#event-timeframe:selected').removeAttr('selected');
                eventOptionHelper.attr('selected', 'selected');
            }
            
        });
    }
	*/
    $('#event-timeframe').change(function () {
		if ($('#event-timeframe').val() != 0)
		{
			var values = $('#event-timeframe').val().split('-');
			
			var min = values[0].split('|');
			var max = values[1].split('|');
			$('#edit-date-filter-min-year').val(parseInt(min[1]));
			$('#edit-date-filter-min-month').val(parseInt(min[0]));
			$('#edit-date-filter-max-year').val(parseInt(max[1]));
			$('#edit-date-filter-max-month').val(parseInt(max[0]));
		}
	});
	
	
	$('#edit-date-filter-min-wrapper select, #edit-date-filter-max-wrapper select').change(function() {$('#event-timeframe').val(0);});
	/*
	$('#views-exposed-form-eventlist-page-1').submit( function () {
		if ($('#edit-date-filter-min').val().split('.').length == 3)
		{
			var from = $('#edit-date-filter-min').val().split('.');
			from = from[2] + '-' + from[1] + '-' + from[0];
			$('#edit-date-filter-min').val(from);
		}
		if ($('#edit-date-filter-max').val().split('.').length == 3)
		{
			var to = $('#edit-date-filter-max').val().split('.');
			to = to[2] + '-' + to[1] + '-' + to[0];
			$('#edit-date-filter-max').val(to);
		}
	}
	
	);*/
	 
    
}
	
function w21ToolTip() {
	if ($(".cal-trigger").length == 0) {
		return;
	}
	
			
	$(".cal-trigger").tooltip({
    
        // tooltip options
  //      position:   'top center',
   //     relative:   true,
          offset:     [20, 0],
//        effect:     'fade',
        events: { 
            def: 'click'
        },
        
		 
		 
		 	
		
        // load events into tooltip 
        onBeforeShow: function() {
			$('.cal-tooltip').empty();
			$('.cal-tooltip').hide();
            // the current tip
            var tip = (this.getTip());
			
            /*
            tip.append( '<div class="cal-tooltip-head">' +
                        '   <span class="date">' + dateStr + '</span>' +
                        '   <span class="close">' +
                        '       <a href="#" class="button b-img b-control-s close" title="' + calClose + '">' + calClose + '</a>' +
                        '   </span>' +
                        '</div>' +
                        '<div class="cal-tooltip-body">' +
                        '   <div class="load scroll" />' +
                        '</div>');
            */
			//alert(this.getTrigger().parent().html());
			var newtip = this.getTrigger().parent().find('.date-details').html();
			//alert(newtip);
			//alert(this.getTrigger().parent().html());
			tip.append($(newtip));
		
            // add event listener to close tip
            tip.find('.close').click(function(e){
                e.preventDefault();
                tip.empty();
                tip.hide();
            });

       
            // remotely load events for selected date
	    /*
            $.getJSON('cal-events-example.json',data,
                function(responseData,textStatus){
                
                    //if call was succesfull
                    if(textStatus == 'success' || textStatus == 'notmodified') {
                    
                        //remove loading graphic once call has completed
                        tip.find('.load').removeClass('load');
                        
                        //create and append list with return values to scroll area
                        var list =  $('<ul />').appendTo(tip.find('.scroll'));
                        
                        // iterate through JSON array
                        $.each(responseData.events, function(i,event){
                            
                            //insert list items
                            list.append('<li><a href="' + event.url + '"><span class="title">' + event.title + '</span><br /><span class="mute smaller">' + event.location + '</span></a></li>');
                        });
                    }
                    // if call was not successfull, hide tip
                    else {
                        debug(textStatus);
                        tip.hide();
                    } 
                    
                }
            );
			*/

        },
        onHide: function() {
            this.getTip().empty();
        }
    }).click(function(e){
        //prevent browser from following links
        e.preventDefault();
    });
	

	 
			
			$(".cal-trigger").each(function() {

				
				for (method in $(this).data("events").mouseover )
				{
					var event_handler = $(this).data("events").mouseover[method];
					$(this).click(event_handler);
				}
				$(this).click(event_handler);
			});
			$(".cal-trigger").unbind('mouseover');
			$(".cal-trigger").unbind('mouseout');
			$(".cal-tooltip").unbind('mouseenter');
			$(".cal-tooltip").unbind('mouseleave');
			
			$(".cal-trigger").click(function(){
					$(".cal-tooltip").unbind('mouseenter');
					$(".cal-tooltip").unbind('mouseleave');
			});
			/*$(".cal-trigger").mouseover(function (event) {
				
			});*/
			/*$(".cal-trigger").click($(this).mouseover());*/
    
	

}

function w21_type_filter_links()
{
	var type_array = new Array();
	var count_array = new Array();
	$('.type-div').each(
		function() {
			var info = $(this).text().split('|');
			if (!type_array[info[0]])
			{
				type_array[info[0]] = info[1];
				count_array[info[0]] = 0;
			}
			count_array[info[0]]++;
		}
	);
	if (type_array.length > 1)
	{
		var links = "";
		for (key in type_array)
		{
			links += ('<a id="filterlink-' + key + '" class="filterlink filterlink-inactive" title="' + Drupal.t('Nach dieser Materialart Filtern') + '"href="#" onclick="shop_filter(' + key + '); return false;">' + type_array[key] + '(' + count_array[key] + ')</a>; ');
			
		}
		$('#filter-links').html(links);
	}
}

function shop_filter(type)
{
	var elem = $('#filterlink-' + type );
	if (elem.hasClass('filterlink-active'))
	{
		elem.removeClass('filterlink-active');
		elem.addClass('filterlink-inactive');
	}
	else
	{
		elem.addClass('filterlink-active');
		elem.removeClass('filterlink-inactive');
	}
	
	var shown = 0;
	$('.filterlink-inactive').each(function () {
		var id = $(this).attr('id').split('-');
		id = id[1];
		$('.type-' + id).slideUp();
	});
	$('.filterlink-active').each(function () {
		var id = $(this).attr('id').split('-');
		id = id[1];
		shown += $('.type-' + id).slideDown().length;
		
	});
	if ($('.filterlink-active').length == 0)
	{
		$('.product').slideDown();
		$('#extra_count').html('');
	}
	else
	{
		if (shown == 1)
		{
			$('#extra_count').html(' (' + Drupal.t('Eines wird angezeigt') + ')');
		}
		else
		{
			$('#extra_count').html(' (' + shown + ' ' + Drupal.t('werden angezeigt') + ')');
		}
	}
	
}


function w21_ie6_popup()
{
	$.getJSON('/ie6', function(data) {
		if (data.message)
		{
			var text = data.message;
			var info_html = '<div class="popup-overlay hide" id="ie6-popup">';
			info_html = info_html + '<a class="button b-img b-control-s close-warn close-popup fr" title="' + Drupal.t('Schließen') + '">' + Drupal.t('Schließen') + '</a>';
			info_html = info_html + '<h3 class="icon-heading">';
			info_html = info_html + '<img alt="' + Drupal.t('Information') + '" class="fl" src="/sites/all/themes/dah/assets/img/icon/info.png" /> <em>' + Drupal.t('Information') + '</em></h3>';
			info_html = info_html + '<div >';
			info_html = info_html + '<p>';
			info_html = info_html + text;
			info_html = info_html + '</p></div>';
			info_html = info_html + '<div class="centered-wrap">';
			info_html = info_html + '<div class="centered">';
			info_html = info_html + '<a class="button b-text b-action b-close close-popup"><span>' + Drupal.t('Schließen') + '</span></a>';
			info_html = info_html + '</div>';
			info_html = info_html + '</div>';
			info_html = info_html + '</div>';
			
			var info_area = $(info_html);
			$('.message_area').append(info_area);
			info_area.fadeIn();
			info_area.css("position", "absolute");
			
			info_area.css("top", ( $(window).height() - info_area.height() ) / 2+$(window).scrollTop() + "px");
			info_area.css("left", "270px");
			info_area.fadeIn();
			$('.close-popup').click(function() {
				info_area.fadeOut();
			});
		}
	
	});

}

function w21_ie6_text()
{
	$.getJSON('/ie6', function(data) {
		if (data.message)
		{
			var text = data.message;
			
			var info_area = $('<div class="error">' + text + '</div>');
			$('.message_area').append(info_area);
			
		}
	
	});
}


Drupal.behaviors.ie6Behavior = function (context) {
	
	
	if (isMSIE6)
	{
		if ($('#col-0').length)
		{
			w21_ie6_popup()
		}
		else
		{
			w21_ie6_text();
		}
	}


};

