///////////////////////////////////////
//
// firebug console output
//
//////////////////////////////////////
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);
        }
    }
}

///////////////////////////////////////
//
// twitter integration
// (modified from http://twitter.com/javascripts/blogger.js)
//
//////////////////////////////////////
function twitterSpy() {
    if($("#twitter_update_list li.visible").length > 1) {
        $('#twitter_update_list li.visible:first').fadeOut('slow');
        $('#twitter_update_list li.visible:first').removeClass('visible');
    }
    else {
        $('#twitter_update_list li.visible:first').fadeOut('slow', function() {
            $('#twitter_update_list li').addClass('visible');
            $('#twitter_update_list li').show();
        });
    }
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'gerade eben';
  } else if(delta < 120) {
    return 'vor ca. \'ner minute';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' Minuten her';
  } else if(delta < (120*60)) {
    return 'vor ca. 1 Stunde';
  } else if(delta < (24*60*60)) {
    return 'vor ca. ' + (parseInt(delta / 3600)).toString() + ' Stunden';
  } else if(delta < (48*60*60)) {
    return 'vor einem Tag';
  } else {
    return (parseInt(delta / 86400)).toString() + ' Tage her';
  }
}

function twitterCallback2(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
    statusHTML.push('<li class="visible"><span>'+status+'</span> <a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li>');
  }
  $('#twitter_update_list').html(statusHTML.join(''));
  setInterval(twitterSpy,4000);
}


///////////////////////////////////////
//
// toggle default field value
//
//////////////////////////////////////
jQuery.fn.toggleDefaultValue = function() {
    $(this).each(function(i){
        
        // the default value
        var val = $(this).val();
        if(val) {
            
            // strore it in elements data storage
            $(this).data('default',val);
            
            // prevent value caching in ff (non-xhtml-compliant) 
            $(this).attr('autocomplete','off');
            
            // add focus and blur behaviour
            $(this).focus(function(){
                if($(this).val() === $(this).data('default')) {
                    $(this).val('');
                }
            });
            $(this).blur(function(){
                if($(this).val() === '') {
                    $(this).val($(this).data('default'));
                }
            });
        }
    });
};


///////////////////////////////////////
//
// clear default field values on form submit
//
//////////////////////////////////////
jQuery.fn.clearDefaultValues = function() {
    
    $(this).each(function(i){
        
        // if a form has been passed
        if($(this).is('form')) {
            // and has been submited
            $(this).submit(function(e){
            
                //check each input field
                fields = $(this).find(':input');
                fields.each(function(i){

                    if($(this).data('default') === $(this).val()) {
                        $(this).val('');
                    }
                });
            
            
            });
        }
    });
};

///////////////////////////////////////
//
// flash player overlay
//
//////////////////////////////////////
jQuery.fn.openFlashPlayer = function(playlist,title) {
    $(this).each(function(i){
        
        // vars
        var player = $('#flv-player-overlay');
        var insert =    '<object type="application/x-shockwave-flash" width="1035" height="700" data="' + baseurl + 'assets/videos/news/news-player.swf">' +
                            '<param name="movie" value="' + baseurl + 'assets/videos/news/news-player.swf" />' +
                            '<param name="wMode" value="transparent" />' +
                            '<param name="scale" value="exactfit" />' +
                            '<param name="FlashVars" value="playlistURL=' + baseurl + 'assets/videos/news/' + playlist + '" />' +
                        '</object>';
        
        // user clicks anchor
        $(this).click( function(){
            
            // adjust overlay to doc height
            player.css('height',$(document).height());
            
            // add close action
            player.find('#player-close a').click(function(){
                player.fadeOut('slow');
                player.find('object').remove();
            });
            
            player.find('#player-title').text(title);
            
            // and fade it in
            player.fadeIn('slow', function(){
                // insert flash player
                player.find('#play').html(insert);
            });
        });
    });
};

///////////////////////////////////////
//
// domready...
//
//////////////////////////////////////
$(document).ready(function () {
       
    // nav-main animations
    //--------------------------------------------------------------------------
    
    // hide unselected elements on startup
    $('#nav-main a:not(.selected)').parent('li').css({
        opacity:    0,
        marginTop:  '0px'
    });
    $('#nav-main li').removeClass('no-js');
    
    // hover behaviour
    $('#nav-main a:not(.selected)').hover(
        function() {
            $(this).parent('li').stop().animate({
                opacity:    1,
                marginTop:  '10px'
            },200).addClass('no-filter');
        },
        function() {
            $(this).parent('li').removeClass('no-filter').stop().animate({
                opacity:    0,
                marginTop:  '0px'
            },200, function() { $(this).removeClass('no-filter'); });
        }
    );
    
    
    // nav-formate animations
    //--------------------------------------------------------------------------
    
    // hide unselected elements on startup
    $('.nav-format-items').css({
        opacity:    0
    }).removeClass('no-js');
    
    $('.nav-format-items li').css({
        marginLeft:    '-220px'
    });
    
    // hover behaviour
    $('.nav-format-items a').hover(
        function() {
            $(this).stop().animate({
                opacity:    0.5
            },200);
        },
        function() {
            $(this).stop().animate({
                opacity:    1
            },200);
        }
    );
    // hover on format boxes
    $('.nav-format-items').hover(
        function() {
            
            // the animation speed
            var speed = 120;
            
            // fade out logo
            $(this).animate({
                opacity:    1
            }, speed);
            
            // iterate over all menu items
            var el = $(this).find('li');
            for(var i=0; i <= el.length; i++) {
            
                
                var pause = (speed / el.length) * i ; // pause before showing next element
                
                // return elements to left side and pause
                el.eq(i).animate({
                    marginLeft:    '-220px'
                },pause);
                
                // slide in from the left
                el.eq(i).animate({
                    marginLeft:    '0px',
                    opacity:        1
                },speed);
            }
        },
        function() {
            var speed = 120; // the animation speed
            
            // fade in logo
            $(this).animate({
                opacity:    0
            }, speed);
            
            // slide out all elements
            $(this).find('li').stop().animate({
                marginLeft:    '220px',
                opacity:        0
            },speed);
        }
    );
    
    // table tooltips
    //--------------------------------------------------------------------------
    $('.tooltip').hide();
    $('.trigger').hover(
        function(){
            $(this).addClass('over');
            $(this).siblings().css('opacity',0.3);
            $(this).find('.tooltip').eq(0).show().mouseover(function(){ $(this).hide(); });
            
        },
        function(){
            $(this).removeClass('over');
            $(this).siblings().css('opacity',1);
            $(this).find('.tooltip').eq(0).hide();
            
        }
    );
    
    // toggle default values in forms
    //--------------------------------------------------------------------------
    $('.has-default-value').toggleDefaultValue();
    
    
    // clear form default values on submit
    //--------------------------------------------------------------------------
    $('form').clearDefaultValues();
    
    
    // player overlay
    //--------------------------------------------------------------------------
    $('#nav-news .nav-2 a').openFlashPlayer('news.xml','Neuigkeiten');
    $('#t-session').openFlashPlayer('session.xml','Session');
    $('#t-thema').openFlashPlayer('thema.xml','Thema');
    $('#t-games').openFlashPlayer('games.xml','Games');
    $('#t-gaeste').openFlashPlayer('gaeste.xml','Gäste');
    $('#t-festival').openFlashPlayer('festivals.xml','Festival');
    $('#t-musicids').openFlashPlayer('musicids.xml','Musicids');
    
    
    // flowplayer setup
    //--------------------------------------------------------------------------
    if(typeof flowplayer==='function') {
    
        flowplayer("a.flowplayer", {src: baseurl + "assets/flash/flowplayer-3.1.1.swf", wmode: 'opaque'}, { 
            clip:  { 
                autoPlay: false/*, 
                autoBuffering: true*/ 
            },
            plugins: {
                controls: {
                    url: 'flowplayer.controls-3.1.1.swf',
                    playlist: false,
                    scrubber: true,
                    time: false,
                    mute: false,
                    bufferColor: '#666666',
                    progressGradient: 'medium',
                    borderRadius: '0px',
                    volumeSliderGradient: 'none',
                    backgroundColor: '#000000',
                    volumeSliderColor: '#666666',
                    tooltipTextColor: '#ffffff',
                    buttonColor: '#666666',
                    tooltipColor: '#666666',
                    sliderColor: '#000000',
                    bufferGradient: 'none',
                    backgroundGradient: 'none',
                    sliderGradient: 'none',
                    buttonOverColor: '#999999',
                    height: 20,
                    
                    tooltips: { 
                        buttons: true, 
                        fullscreen: 'Im Vollbildmodus abspielen!' 
                    } 
                } 
            }
        });
    }
});
