$(document).ready(function(){
    
    //dynmaische Inhalte laden wenn #! in URL...
    if(document.location.hash != ''){
        if(document.location.hash.indexOf('!/article') > 0){
            prepareArticleAnimation(document.location.hash);
        }else{
            prepareReferenceAnimation();
        }
    }
    
    //...oder sich die URL mit #! ändert
    $(window).bind('hashchange', function() {        
        if(document.location.hash.indexOf('!/article') > 0){
            prepareArticleAnimation(document.location.hash);
        }else{
            prepareReferenceAnimation();
        }
	});
    
    //Referenzen-Links hashbangen
    $('ul.references a').click(function(){
        $('ul.references a.active').removeClass('active');
        $(this).addClass('active');
        
        var refId = $(this).attr('id').split('-');
        var href = $(this).attr('href').split('/');
        
        document.location.hash = '!/'+refId[1]+'/'+href[1];
        
        if($.browser.msie && parseInt($.browser.version) <= 7){
            prepareReferenceAnimation();
        }
        
        return false;
    });
    
    //Newsartikel-Links hashbangen
    $('ul.news a').click(function(){
        $('ul.news a.active').removeClass('active');
        $(this).addClass('active');
        
        //var refId = $(this).attr('id').split('-');
        var href = $(this).attr('href').split('/');
		
        //falls der Kategoriefilter gesetzt wurde
		if(href[1] == 'select_category'){
			document.location.hash = '!/'+href[3]+'/'+href[4];
		}else{
			document.location.hash = '!/'+href[1]+'/'+href[2];
		}
        
        if($.browser.msie && parseInt($.browser.version) <= 7){
            prepareArticleAnimation();
        }
        
        return false;
    });
    
    $('#notification .close').live('click', function(){
       $(this).closest('#notification').slideUp(function(){
            $(this).remove();
        });
       return false;
    });
    
    filterReferences('*');
    
});

function prepareArticleAnimation(href){
    if(href.indexOf('!') < 0){
        return false;
    }
    
    $('body').append('<div id="loading"/>');
    $('#loading').fadeIn();
    
    var parts = document.location.hash.split("/");
    
    $.get('aktuelles/'+parts[1]+'/'+parts[2], function(data){
        
        var contentHtml = $(data).find('#content').html();        
        $('#content').html(contentHtml);
        
        $('#loading').fadeOut(function(){
           $(this).remove(); 
        });
    });
    
}

function getLatestReference(position, showLoadingScreen){
    
	if(showLoadingScreen){
		$('body').append('<div id="loading"/>');
		$('#loading').fadeIn();
	}
    
    $.getJSON('/?type=99&tx_rlreferenceoverview_pi1[action]=jsonGetLatestReferences&tx_rlreferenceoverview_pi1[controller]=Page', function(data){
        
        if(data.length > 0){
            switch(position){
                case 0:{
                    showReference($(data).eq(0), true, 'first');
                    break;
                }
                case 110:{
                    showReference($(data).eq(1), true, 'second');
                    break;
                }
                case 220:{
                    showReference($(data).eq(2), true, 'third');
                    break;
                }
            }
        }else{
            printAjaxError();
        }
        
    });
}

function prepareReferenceAnimation(){
    if(document.location.hash.indexOf('!') < 0){
        return false;
    }
    $('body').append('<div id="loading"/>');
    $('#loading').fadeIn();
    var parts = document.location.hash.split("/");
    
    $.getJSON('/?type=99&tx_rlreferenceoverview_pi1[action]=jsonGetReference&tx_rlreferenceoverview_pi1[controller]=Page&uid='+parts[1], function(data){
        
        if(data.length > 0){
            
            if($('#notification').length > 0){
                $('#notification').slideUp(function(){
                    $(this).remove();
                });
            }
            
            showReference(data, false, 0);
            
        }else{
            printAjaxError();
        }
    });
    
    $('body').ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
        printAjaxError();
    });
}

function printAjaxError(){
    $('#loading').fadeOut(function(){
        $(this).remove(); 
    });
    
    var message = '<div id="notification" class="message clearfix">';
    message += 'Leider ist beim Laden der Seite ein Fehler aufgetreten. Bitte versuchen Sie es erneut.';
    message += '<a href="#" class="close" title="Meldung schließen">Schließen</a>';
    message += '</div>';
    
    $('body').prepend(message).find('#notification').slideDown();
}

function showReference(ref, isLatest, latestDescriptionClassIndex){

    var img = $('<img/>').attr('src', ref[0].bgImage);
    
    img.load(function(){
		
        var topOffset = ($("body").scrollTop());
		
		$('#loading').fadeOut(function(){
           $(this).remove(); 
        });
        
        var bg = 'background:url('+ref[0].bgImage+') center top no-repeat;';
		
		var top = 990 - topOffset;
		var topPlusOffset = 990 + topOffset;
		
        var newContainerHtml = '<div id="bg_container" style="'+bg+' top:'+topPlusOffset+'px">';
        newContainerHtml += '<img class="blank" src="fileadmin/templates/www.re-lounge.com/media/blank.gif" alt="">';
        newContainerHtml += '<img id="blende" src="fileadmin/templates/www.re-lounge.com/media/blende.png" alt="">';
        newContainerHtml += '</div>';
        
        if(!isLatest){
            var contentHtml = '<h2>'+ref[0].contentHeader+'</h2>';
            contentHtml += '<p class="bodytext">'+ref[0].contentBody+'</p>';
            contentHtml += '<div class="additional">';
            contentHtml += ref[0].contentAdditionalImage ? '<img src="'+ref[0].contentAdditionalImage+'" alt="'+ref[0].title+'"/>' : '';
            contentHtml += '<p>'+ref[0].contentAdditional+'</p>';    
            contentHtml += '</div>';
        }
        else if(isLatest){
            $('#stage .description').removeClass('second').removeClass('third').addClass(latestDescriptionClassIndex);
            $('#stage .description .date').text(ref[0].date);
            $('#stage .description a').replaceWith('<a href="'+ref[0].url+'">'+ref[0].title+'</a>');
			//$('#stage .description a').replaceWith('<a href="referenzen/#!/'+ref[0].uid+'/">'+ref[0].title+'</a>');
        }
        
        $('#bg_container').attr('id', 'bg_container_helper').after(newContainerHtml)
        $('#bg_container_helper').addClass('animate').css('top', topOffset+'px').animate({
            top: "-"+top
        }, 1000, function(){
            $(this).remove();
        });
        
        $('#bg_container').addClass('animate').animate({
            top: topOffset
        }, 1000, function(){
            $(this).removeClass('animate').css('top', 0);
            
            if(!isLatest){
                $('#content').html(contentHtml);
            }
            
        });
        
    });
    
}

function filterArticles(selector){
    
    if(selector == 'Alle Artikel'){
        selector = '';
    }else{
        selector = '.'+selector;
    }
        
    $('ul.news').fadeOut(function(){
        $(this).find('li').hide();
        $(this).find('li'+selector).show();
        $(this).delay(200).fadeIn();
    });
}

function filterReferences(selector){
    //console.info("filter mit "+selector);
    $('ul.references').isotope({
        filter: selector,
        layoutMode : 'fitRows',
        animationEngine: 'jquery',
        animationOptions: {
            duration: 750,
            easing: 'swing',
            queue: true
        },
        hiddenStyle:{
            opacity : 0,
            scale : 0.5
        }
    });
    
	return false;
}
