(function($) { 
	$.fn.animBg = function(command,options) {
	    // JS animated bg images don't look good in IE6:
	    if ($.browser.msie && $.browser.version.substr(0,1)<7) {
	        return this;
        }
		if(command && typeof command ==='string'){
			clearInterval($(this).data('anim'));
			return this;
		}
		var $this = $(this),
		o = {'interval':100},
		options = (typeof command === 'object' && typeof options === 'undefined')?command:options,
		o = jQuery.extend({}, o, options), anim;
		if(!o.step && !o.steps){return this;}
		anim = setInterval(function() { 
			var bgpos = parseInt( $this.css('background-position') );
			if(isNaN(bgpos)) {
			    // IE returns 'undefinded' for $this.css('background-position')
			    bgpos = parseInt( $this.css('background-position-x') );
			}
			$this.css('background-position',(-(o.step*o.steps)>=(bgpos-o.step)?0:bgpos-o.step)+'px 0');
		}, o.interval);
		$this.data('anim',anim);
		return this; 
	}
})(jQuery);

var ZoomMap = function(map) {
    var zoomOutCSS = {
        width: map.css('width'),
        height: map.css('height'),
        top: map.css('top'),
        left: map.css('left')
	};
	this.zoomOut = function(callBack) {
	    map.animate(zoomOutCSS, 'slow', function() {
	        if(typeof callBack == 'function') {
	            callBack();
	        }
	    });
	}
	this.zoomIn = function(css, callBack) {
		map.animate(css, 'slow', callBack);
	}
	map.bind({
        mousewheel: function(e) {
    	    map.clearQueue();
            var width = parseInt(map.css('width'));
            var height = parseInt(map.css('height'));
            var top = parseInt(map.css('top'));
            var left = parseInt(map.css('left'));
            var stepWidth = parseInt(width/10);
            if (e.wheelDelta < 0) {
                stepWidth *= -1;
            }
            var stepHeight = parseInt(stepWidth*height/width);
            var zoomCSS = {
                width: width+stepWidth+'px',
                height: height+stepHeight+'px',
                top: top-parseInt(stepHeight/2)+'px',
                left: left-parseInt(stepWidth/2)+'px'
        	};
            map.animate(zoomCSS, 'fast');
        }
    }).draggable({cursor: 'pointer'});
}

var LocationPoints = function(map, locationsMap, locationsContainer, pointCallBack) {
    var mapZoomed = false;
    var dataLoaded = false;
    var point = $('<div class="map_point"/>').bind({
        mouseenter: function(e) {
            var location = $(this).data('location').clone().appendTo($(this));
            var cssMap = {
                top: (-1)*location.height()+'px',
                left: parseInt($(this).width()/2)+'px'
            };
            if ($(this).offset().top - locationsMap.offset().top < locationsMap.outerHeight()/2) {
                cssMap.top = parseInt($(this).height()/2)+'px';
            }
            if ($(this).offset().left - locationsMap.offset().left > locationsMap.outerWidth()/2) {
                cssMap.left = (-1)*(location.width()+parseInt($(this).width()/2))+'px';
            }
            location.css(cssMap).fadeIn('fast');
        },
        mouseleave: function(e) {
            $(this).find('.location').fadeOut('fast', function() {
                $(this).remove();
            });
        },
        click: function(e) {
            var point = $(this);
            locationsContainer.find('.location').hide('fast');
            point.data('location').show('fast');
            e.stopPropagation();
        },
        mousedown: function(e) {
            e.stopPropagation();
        }
    });
    var drawPoints = function() {
        locationsContainer.find('.location').each(function() {
            var top = (90-parseFloat($(this).attr('data-latitude')))/180*100;
            var left = (180+parseFloat($(this).attr('data-longitude')))/360*100;
            var clonedPoint = point.clone(true).css({
                top: top+'%',
                left: left+'%'
            }).data('location', $(this)).appendTo(map);
	        if(typeof pointCallBack == 'function') {
	            pointCallBack(clonedPoint);
	        }
        });
        mapZoomed = false;
        dataLoaded = false;
    }
    this.mapCallBack = function() {
        mapZoomed = true;
        if(dataLoaded) {
            drawPoints();
        }
    }
    this.dataCallBack = function() {
        dataLoaded = true;
        if(mapZoomed) {
            drawPoints();
        }
    }
}

var LocationsMenu = function(locationResults, ajaxSuffix, placeholder) {
    this.loadResults = function(url, callBack) {
        locationResults.hide('fast');
        locationResults.load(url+ajaxSuffix, function(){
            if(locationResults.height()) {
                placeholder.hide('fast');
            } else {
                placeholder.show('fast');
            }
            locationResults.show('fast');
	        if(typeof callBack == 'function') {
	            callBack();
	        }
        });
    }
    this.selectLink = function(link, callBack) {
        this.loadResults(link.attr('href'), callBack);
        link.closest('ul').find('ul').hide('fast');
        link.siblings('ul').show('fast');
    }
}

var initLocations = function() {
    var map = $('#zoom_map');
    var hoverMap = $('#hover_map');
    var locationsMap = $('#locations_map');
    var locationsContainer = $('#location_result');
    var locationsPlaceholder = $('#location_result_placeholder')
    var zoomMap = new ZoomMap(map);
    var menu = new LocationsMenu(
        locationsContainer,
        '&template=06_locations_ajax.html&syndicat:view=pre',
        locationsPlaceholder
    );
    var removeMapPoints = function() {
        $('#zoom_map .map_point').fadeOut('fast', function() {
            $(this).remove();
        });
    }
    var pointCallBack = function(point) {
        point.click(function(){
            locationsPlaceholder.hide('fast');
        });
        point.fadeIn('fast').animBg({'step':15,'steps':15,'interval':100});
    }
    map.click(function() {
        removeMapPoints();
        zoomMap.zoomOut(function() {
	        hoverMap.css('visibility', 'visible');
	        map.fadeOut('fast');
        });
    });
    $('#hover_map a, #location_menu a').click(function() {
        $(this).blur();
        removeMapPoints();
        var points = new LocationPoints(map, locationsMap, locationsContainer, pointCallBack);
        var menuItem = $('#'+$(this).attr('id').replace('map','menu'));
        var mapItem = $('#'+$(this).attr('id').replace('menu','map'));
        var zoomData = $.parseJSON(mapItem.attr('data-zoom'));
        menu.selectLink(menuItem, points.dataCallBack);
        map.fadeIn('fast', function() {
    	    hoverMap.css('visibility', 'hidden');
            zoomMap.zoomIn(zoomData, points.mapCallBack); 
        });
        return false;
    });
}

var fluid = {

    Kwicks : function(){
        var animating = false;
        $("#timeline .history_entry")
            .bind("mouseenter", function(e) {
                if (animating) return false;
                animating == true;
                $("#kwick .kwick").not(this).animate({ "width": 80 }, 200);
                $(this).animate({ "width": 150 }, 200, function() {
                    animating = false;
                });
            });
        $("#timeline .history_entry").bind("mouseleave", function(e) {
            $(this).animate({ "width": 80 }, 200);
        });
        
        
    }
}

function displayContent(url, id) {
    //$('#'+id).empty().html('<img src="project/media/lightbox/images/loading.gif" />');
    $.get(url, function(data) {
        $('#'+id).html(data);
    });
}

function displayImage(img) {
    showDialog('image_layer', function() {
        $('#image_layer_content').html('<img  src="'+img+'" />');
    });
}

$('#timeline_btn_prev').bind("mouseover", function(e) {
            $('#timeline').animate({scrollLeft: $('#timeline').scrollLeft()-200});
            e.stopPropagation();
});

function showDialog(id, cb) {
    width = (id == 'image_layer') ? 716 : 694;
    dialogClass = (id == 'image_layer') ? 'image_dialog' : '';
    if($('#'+id).length == 0) {
            $('body').append('<div id="'+id+'"></div>');
            var options = {
                autoOpen: false,
                modal: true,
                resize: false,
                width: width,
                title: false,
                draggable: false,
                stack: true,
                closeText: '',
                dialogClass: dialogClass,
                height: 'auto',
                open: function(){closedialog=1;$(document).bind('click', function(){if(closedialog){$('#'+id).dialog('close');}closedialog=1;});},
                focus: function(){closedialog = 0;},
                close: function(){$(document).unbind('click');},
                position: ['center',175]
            }
            if($.browser.msie && $.browser.version=='6.0') {
                // IE6 does not work well with modal in this case:
                options.modal = false;
            }
            $('#'+id).dialog(options);
        } else {
            $('#'+id+'_content').html('');
            //$('#'+id).dialog('open');
        }
        dialog = $('#'+id).dialog('open');
        closedialog = 0;
        var htmlContent = '';
        jQuery.post('index.php', {"layer:id": id, template: '99_layer.html'}, function(data) {
            htmlContent = data;
            if($.browser.msie && $.browser.version=='6.0') {
            // IE6 does not work well with modal in this case:
            //htmlContent = '<div id="'+id+'_content"></div>';
            }
            $('#'+id).html(htmlContent);
            if(typeof cb == 'function') {
                cb();
            }
        });
//        var htmlContent = '<div class="close_label"><a href="#" onClick="$(\'#'+id+'\').dialog(\'close\');return false;">schliessen <img src="project/media/images/layer_close.gif" /></a></div>'
//            +'<div id="'+id+'_content"></div>';
        
}

function showUnsubscribeForm() {
    showDialog('download_cart_layer', function() {
        jQuery.get('newsletter_unsubscribe.php', function(data) {
            $('#download_cart_layer_content').html(data);
            initPlaceHolders();
        });
    });
}

function showDownloadsCart(mode) {
        showDialog('download_cart_layer', function() {
            getDownloadsCartContent(mode);
        });
	//contentNode = document.getElementById("overlayContainerContent");
	//contentNode.innerHTML = '<div style="width:100%; text-align:center; margin:auto; margin-bottom:50px;"><img src="project/media/images/loading.gif" border="0" /></div>';
	
}

function showDownloadCartForm() {
    showDialog('download_cart_layer', function() {
        displayContent('index.php?pageID=cartform&template=11_cart_form_single.html', 'download_cart_layer_content');
    });
}

function addItemToDownloadsCart(item) {
    jQuery.getJSON('downloadCartService.php', {action: 'add', item: item}, function(data) {
        for(var i = 0; i < data.length; i++) {
            $('#'+data[i]['id']).html(data[i]['value']);
        }
    });
}

function removeItemFromDownloadsCart(item, mode) {
    jQuery.getJSON('downloadCartService.php', {action: 'remove', item: item, mode: mode}, function(data) {
        for(var i = 0; i < data.length; i++) {
            $('#'+data[i]['id']).html(data[i]['value']);
        }
    });
}

function getDownloadsCartContent(mode) {
    jQuery.getJSON('downloadCartService.php', {action: 'get', mode: mode}, function(data) {
        for(var i = 0; i < data.length; i++) {
            $('#'+data[i]['id']).html(data[i]['value']);
        }
    });
}

function updateDownloadsCart(item, num, mode) {
    jQuery.getJSON('downloadCartService.php', {action: 'update', item: item, num: num, mode: mode}, function(data) {
        for(var i = 0; i < data.length; i++) {
            $('#'+data[i]['id']).html(data[i]['value']);
        }
    });
}

function submitCartForm() {
    jQuery.post('index.php?pageID=cartform&template=11_cart_form_single.html',
                $('form#cartform').serializeArray(),
         function(data){
             $('#download_cart_layer_content').html(data);
         });
}


/* History timeline */

var TimeLine = function() {
    function shrinkEntry(node) {
        //if(!node.hasClass('active')) {
            $('#timeline_items').data('toggle_node', true);
            node.children('h2').css('border-color', '#bcbcbc');
            node.children('h2').css('color', '#676767');
            node.children('.history_teaser').first().css('display', 'none');
            node.animate({"width": "128px"}, function() {
                $('#timeline_items').data('toggle_node', false);
        
            });
        //}
    }

    function toggleHistoryEntry(node) {
        if(!node.hasClass('active')) {
    
            removeActiveState();
            $('#timeline_items').data('toggle_node', true);
            node.children('h2').css('border-color', '#fb7f6e');
            node.children('h2').css('color', '#464646');
            node.children('.history_teaser').first().css('display', '');
            node.animate({"width": "213px"}, 700, function() {
                $('#timeline_items').data('toggle_node', false);
                $(this).addClass('active');
            });
        }
    }

    function removeActiveState() {
        $('.history_entry').each(function(){
            if($(this).hasClass('active')) {
                $(this).removeClass('active');
                shrinkEntry($(this));
            }
        });
    }
    
    function scrollLeft() {
        if($('#timeline_btn_next').data('mousedown') == true) {
            var scrollWidth = Math.abs($('#timeline_items').position().left - 130) <= Math.abs(timlineItemsWidth() - $('#timeline').width()) ? -1*Math.abs($('#timeline_items').position().left - 130) : -1*Math.abs(timlineItemsWidth() - $('#timeline').width());
                $('#timeline_items').animate({'left': scrollWidth});
                updateTimelineButtons();
//                setTimeout('scrollLeft()', 10);
            
        }
    }
    window.scrollLeft = scrollLeft;

    function scrollRight() {
        if($('#timeline_btn_prev').data('mousedown') == true) {
            var scrollWidth = $('#timeline_items').position().left + 130 <= 0 ? $('#timeline_items').position().left + 130 : 0;
            $('#timeline_items').animate({'left': scrollWidth});
            updateTimelineButtons();
        }
    }
    window.scrollRight = scrollRight;

    function timlineItemsWidth() {
        var width = 0;
        $('.history_entry').each(function(){
            width += $(this).width();
        });
        return width;
    }

    function updateTimelineButtons() {
        //Links
        if($('#timeline_items').position().left < 0) {
            $('#timeline_btn_prev').addClass('active_icon');
        }else {
            $('#timeline_btn_prev').removeClass('active_icon');
        }

        //Rechts
        if(Math.abs($('#timeline_items').position().left - 5) < Math.abs(timlineItemsWidth() - $('#timeline').width())) {
            $('#timeline_btn_next').addClass('active_icon');
        }
        else {
            $('#timeline_btn_next').removeClass('active_icon');
        }
    }
    
    this.initialize = function() {
        //$('#timeline_items').css('width', $('#timeline_items').children('.history_entry').length * 116 + 64 );
        $('#timeline_items').data('toggle_node', false);

        $('.history_entry').each(function() {
            $(this).mouseenter(function(e) {
            //    toggleHistoryEntry($(this));
            });
            $(this).mouseleave(function(e) {
            //    shrinkEntry($(this));
            });
            $(this).click(function(e) {
                toggleHistoryEntry($(this));
            });
            $(this).resize(function(e) {
            });
        });

        $('#timeline_btn_next').mousedown(function(e) {
            $(this).data('mousedown', true);
            scrollLeft();
            //newLeft = (Math.abs($('#timeline_items').position().left - 95) > $('#timeline_items').width() - $('#timeline').width() ) ?  -1 * ($('#timeline_items').width() - $('#timeline').width()) : $('#timeline_items').position().left - 95;
            //$('#timeline_items').animate({'left': newLeft+"px"});
        });

        $('#timeline_btn_next').mouseup(function(e) {
            $(this).data('mousedown', false);
            updateTimelineButtons();
        });

        $('#timeline_btn_next').mouseleave(function(e) {
            $(this).data('mousedown', false);
            updateTimelineButtons();
        });

        $('#timeline_btn_prev').mouseup(function(e) {
            $(this).data('mousedown', false);
            updateTimelineButtons();
        });

        $('#timeline_btn_prev').mouseleave(function(e) {
            $(this).data('mousedown', false);
            updateTimelineButtons();
        });

        $('#timeline_btn_prev').mousedown(function(e) {
            $(this).data('mousedown', true);
            scrollRight();
            //newLeft = ($('#timeline_items').position().left + 95 > 0) ? 0 : $('#timeline_items').position().left + 95;
            //$('#timeline_items').animate({'left': newLeft+"px"});
        });

        updateTimelineButtons();
    }
}

var initPersonGallery = function() {
    $('.person a.person').click(function() {
        var that = $(this);
        showDialog('person_layer', function() {
            $('#person_layer_content').load(that.attr('href'));
        });
        return false;
        
    });
}

var initGallery = function() {
    $('.gallery a.gallery_image').click(function() {
        displayImage($(this).attr('href'));
        return false;
    });
}

function slideSwitch() {
    var $active = $('#slideshow img.active');

    if ( $active.length == 0 ) $active = $('#slideshow img:last');

    var $next =  $active.next().length ? $active.next()
        : $('#slideshow img:first');

    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 2000, function() {
            $active.removeClass('active last-active');
        });
}

var initSlideShow = function() {
    if($('#slideshow').length == 1) {
        // nur einmal wechseln:
        setTimeout('slideSwitch()', 4000);
        //setInterval('slideSwitch()', 4000 );
    }
}

var initPlaceHolders = function() {
    var placeHoldersSelector = '.newsletter_email, .newsletter_name';
    $(placeHoldersSelector).each(function() {
        var str = 'placeholder';
        if(!(str in document.createElement('input'))) {
            var placeholder = $(this).attr(str);
            $(this).addClass(str)
                .val(placeholder)
                .focus(function() {
                    if($(this).val() == placeholder) {
                        $(this).val('');
                        $(this).removeClass(str);
                    }
            }).blur(function() {
                if($(this).val() == '') {
                    $(this).addClass(str);
                    $(this).val(placeholder);
                }
            });
        }
    });
}

var validateEmail = function(field) {
    var emailRegexp = /^[^@]+@[^@]+$/;
    if (!field.val() || !emailRegexp.test(field.val())) {
        field.addClass('errFormField').change(function(){
            $(this).removeClass('errFormField')
        }).focus();
        return false;
    }
    return true;
}

var initNewsletterForm = function() {
    /*
    $('.newsletter_form').submit(function() {
        return validateEmail($('.newsletter_email'));
    });
    */
}

function submitNewsletterForm() {
    jQuery.get('newsletter_ajax.php', $('#newsletter_form').serializeArray(), function(data) {
        $('#newsletter_form_content').replaceWith(data);
        return false;
    });
}

function submitUnsubscribeForm() {
    jQuery.getJSON('newsletter_unsubscribe.php', {email: $('#email_unsubscribe').val(), newsletter_form_sent: '1'}, function(data) {
        if(data[0] == true) {
            $('#unsubscribe_form_content').html(data[1]);
        }
        else {
            $('#unsubscribe_status').html(data[1]);
        }
        return false;
    });
}

var initTablePager = function() {
    $('#kennzahlen a').live('click', function() {
        $($(this).attr('href')).detach().prependTo('#kennzahlen');
        if(window.location.hash.length > 1) {
            window.location.hash = $(this).attr('href');
            window.location.hash = '';
        }
        return false;
    });
}

function slideSwitchFlashstage() {
    var $active = $('#slideshowFlashstage img.active');
    if ( $active.length == 0 ) $active = $('#slideshowFlashstage img:last');

    var $next =  $active.next().length ? $active.next() : $('#slideshowFlashstage img:first');
    $active.addClass('last-active');
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 2000, function() {
             $active.removeClass('active last-active');
    });
    setTimeout('slideSwitchFlashstage()', 4000);
}

function slideSwitchFlash() {
    var $active = $('.flashstage.active');
    if ( $active.length == 0 ) $active = $('.flashstage:last');

    var $next =  $active.next().length ? $active.next() : $('.flashstage:first');
    $active.addClass('last-active').hide();
    $next.show()
        .addClass('active')
        //.animate({opacity: 1.0}, 2000, function() {
             $active.removeClass('active last-active');
//    });
    document.getElementById($next.children().first().attr('id')).Rewind();
    document.getElementById($next.children().first().attr('id')).Play();
//    console.log($next.children().first().attr('id'));
//    $next.children().first().Rewind();
    setTimeout('slideSwitchFlash()', 10000);
}
          
var initSlideShowFlashstage = function() {
    if(!swfobject.hasFlashPlayerVersion('9')) {
    //if($('#flashStage_1').find('object').length == 0) {
        // nur einmal wechseln:
        setTimeout('slideSwitchFlashstage()', 4000);
        //setInterval('slideSwitch()', 4000 );
    }
    else if($('#flashStage_1').length == 1){
        $('#slideshowFlashstage').detach();
        //setTimeout('slideSwitchFlash()', 10000);
    }
}

function slideSwitch() {
    var $active = $('#slideshow img.active');

    if ( $active.length == 0 ) $active = $('#slideshow img:last');

    var $next =  $active.next().length ? $active.next()
        : $('#slideshow img:first');

    $active.addClass('last-active');

    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 2000, function() {
            $active.removeClass('active last-active');
        });
}

var initSlideShow = function() {
    if($('#slideshow').length == 1) {
        // nur einmal wechseln: 
        	//setTimeout('slideSwitch()', 4000);
        // alle 4 sekunden wechseln:
        	setInterval('slideSwitch()', 3000 );
    }
}

$(document).ready(function() {
    initLocations();
    initGallery();
    initPersonGallery();
    if ($('#timeline').length == 1) {
        var timeLine = new TimeLine();
        timeLine.initialize();
    }
    initSlideShow();
    initSlideShowFlashstage();
    initPlaceHolders();
    initTablePager();
//    initNewsletterForm();
});

