/* Das ist das bewegliche Menü */
var name = "#main_menu";
var menuYloc = null;
// Diese Variable sperrt das dynamische Scrollen, wenn ein Menüpunkt gewählt wird
var isAllowed = false;

// Stellt sicher, dass sich das Menü beim normalen scrollen automatisch mitbewegt
$(document).ready(function(){
    // Wenn Menü existiert
    if($(name).length != 0) {
        menuYloc = parseInt($(name).css("top").substring(0,$(name).css("top").indexOf("px")));
        $(window).scroll(function () {
        
            // Wenn kein Link geklickt wurde
            if(isAllowed == true) {
                var offset = menuYloc+$(document).scrollTop()+"px";
                // Damit das Menü nicht ganz nach oben scrollt
                if(menuYloc+$(document).scrollTop() < 74) {
                    offset = "74px";
                }
                // Damit der Lift ganz unten ordentlich abschließt
                if(menuYloc+$(document).scrollTop() > 5149) {
                    offset = "5673px";
                }
                $(name).animate({top:offset},{duration:600,queue:false});
            }
        });
    }
});

/* Wird beim Klicken auf einen Link im Menü ausgeführt */
function scrollthisTo(post) {
    if(isAllowed == true) {
    
        isAllowed = false;
        
        if(post == 'top') {
            var offset = $('#header').offset();
            // Lift runterfahren
            $('#main_menu').animate({top:74+'px'},700);
            // Gleichzeitig alles scrollen (ganz nach oben)
            $.scrollTo( 0, 700, {axis:'y', onAfter:function() {
                // Danach Dynamisches Scrollen wieder erlauben
                isAllowed = true;
                checkState();
            }});
        }
        // Ganz unten
        else if(post == 8) {
            var offset = $('#post-'+post).offset();
            offset.top = offset.top + 8;
            // Lift runterfahren
            $('#main_menu').animate({top:offset.top+'px'},700);
            // Gleichzeitig alles scrollen (ganz nach unten)
            $.scrollTo( '100%', 700, {axis:'y', onAfter:function() {
                // Danach Dynamisches Scrollen wieder erlauben
                isAllowed = true;
                checkState();
            }});
        }
        else {
            var offset = $('#post-'+post).offset();
            // Lift runterfahren
            $('#main_menu').animate({top:offset.top+'px'},700);
            // Gleichzeitig alles scrollen
            //$.scrollTo( '#post-'+post, 5000, {easing:'elasout'} );
            $.scrollTo( '#post-'+post, 700, {axis:'y', onAfter:function() {
                // Danach Dynamisches Scrollen wieder erlauben
                isAllowed = true;
                checkState();
            }});
        }
    }
}

/* Mathematische Funktion für einen easing-Effekt */
jQuery(function( $ ){
	$.easing.elasout = function(x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	};
});


/* Startprozedur */
var currentSong = 1;
    
$(document).ready(function(){
$(window).load(function() {

    /* Das Flash wird sichtbar (unsichtbar) 1px auf 1px dargestellt, damit der Preload stattfindet */
    var pos0 = (($(window).scrollTop()) - 800);
    $('#flashcontent embed').css('top',pos0);
    /* Getränkekarte richtig positionieren */
    window.setTimeout(function() {
        $('#flashcontent embed').css('top','0');
        $('#flashcontent embed').css('width','690px');
        $('#flashcontent embed').css('height','1000px');
    }, 2000);

    /* Form Elemente zurücksetzen */
    $('#sb_name').val("");
    $('#sb_message').val("");
    $('#sb_message').val("");
    $('.your-name input').val("");
    $('.your-message textarea').val("");
    $('.your-email input').val("");
    
    /* Flashbook Detection */
    var flash = flash_detection(7, 99);
    if(!flash[0] || flash[0] < flash[1]) {
        // Wenn kein Flash installiert ist, wird das Flashbook ausgeblendet und die alternative Galerie eingeblendet
        $('#flashcontent_alternativ').show();
        $('#flashcontent').hide();
        $('#post-14 .entry').hide();
    }
    
    /* Wenn man eingeloggt ist, wird im Kontakt-Formular automatisch der Name/Email eingesetzt */
    if($('#secret_user_meta').length > 0) {
        var user_name = $('#secret_user_meta .user_name').html();
        var user_email = $('#secret_user_meta .user_email').html();
        $('.your-name input').val(user_name);
        $('.your-email input').val(user_email);
    }
    
    /* Gallery Iframe zurücksetzen */
    $('gallery_iframe').attr('src', 'http://www.skybar-vilshofen.de/?page_id=126');
    
    /* Musik starten, je nachdem was für ein Cookie gesetzt wird */
    var value = $.readCookie('skybar_music');
    if( value ) {
        if(value == 'song_1') { playMusic1(); currentSong = 1; }
        if(value == 'song_2') { playMusic2(); currentSong = 2; }
        if(value == 'song_3') { playMusic3(); currentSong = 3; }
        if(value == 'song_0') { currentSong = 1; stopMusic(''); }
    }
    else {
        // Keine Musik gewählt
        currentSong = 1;
        // Traffic starten
        //stopMusic('');
        /* Musik wird über MoveLift dann gestartet */
    }


    /* Mit Hilfe eines Cookies wird sichergestellt, dass
    nicht jedes mal das komplette Intro abgespielt wird */

    // wenn Intro-Cookie gefunden wird
    var value = $.readCookie('skybar_intro');
    if( value ) {
        //alert( 'Cookie bereits vorhanden.' );
        moveLift(1000);

        showMusicControl();
                
    }
    else {
        //alert('Cookie NICHT vorhanden.');
        
        setCookie('intro');
        
        /* Startprozedur */
        $.scrollTo( 0, 0, {axis:'y', onAfter:function() {
            window.setTimeout(function() {
                moveLift(4000);
                
                showMusicControl();
                
            }, 1000);
        }});
    }
}); 
});



// Musik
function playMusic3() {
playMusic('.music_container', 'aHR0cDovL3d3dy5za3liYXItdmlsc2hvZmVuLmRlL3dwLWNvbnRlbnQvdGhlbWVzL2RlZmF1bHQvbXAzcy9iZWF0MS5tcDM', 'yes', 30, 0);
setCookie('song_3');
}
function playMusic2() {
playMusic('.music_container', 'aHR0cDovL3d3dy5za3liYXItdmlsc2hvZmVuLmRlL3dwLWNvbnRlbnQvdGhlbWVzL2RlZmF1bHQvbXAzcy9iZWF0Mi5tcDM', 'yes', 25, 0);
setCookie('song_2');
}
function playMusic1() {
playMusic('.music_container', 'aHR0cDovL3d3dy5za3liYXItdmlsc2hvZmVuLmRlL3dwLWNvbnRlbnQvdGhlbWVzL2RlZmF1bHQvbXAzcy9iZWF0My5tcDM', 'yes', 40, 0);
setCookie('song_1');
}

function playCurrent() {
    eval("playMusic"+currentSong+"();");
}
function playNext() {
    // Zum nächsten Song schalten (3 stehen zur Auswahl)
    if(currentSong < 3) {
        currentSong = currentSong + 1;
    }
    else {
        currentSong = 1;
    }
    eval("playMusic"+currentSong+"();");
}
function playMusic(location, song, loop, volume, traffic) {
    $(location).html('<object width="1" height="1" type="application/x-shockwave-flash" name="audioplayer_1" style="outline: medium none;" data="http://www.skybar-vilshofen.de/wp-content/plugins/audio-player/assets/player.swf?ver=2.0.4.1" id="audioplayer_1"><param name="bgcolor" value="#FFFFFF"><param name="wmode" value="transparent"><param name="menu" value="false"><param name="flashvars" value="animation=no&amp;encode=yes&amp;initialvolume='+volume+'&amp;remaining=no&amp;noinfo=yes&amp;buffer=5&amp;checkpolicy=no&amp;rtl=no&amp;bg=000000&amp;text=000000&amp;leftbg=000000&amp;lefticon=000000&amp;volslider=000000&amp;voltrack=000000&amp;rightbg=000000&amp;rightbghover=000000&amp;righticon=000000&amp;righticonhover=000000&amp;track=000000&amp;loader=000000&amp;border=000000&amp;tracker=000000&amp;skip=000000&amp;autostart=yes&amp;loop='+loop+'&amp;soundFile='+song+'&amp;playerID=audioplayer_1"><p>&nbsp;</p></object>');
    // Verkehr abschalten
    if(traffic == 0) {
        $('.traffic_container').html('');
    }
    /* Play verbergen, Stop und Next anzeigen */
    if(location == '.music_container') {
        $('.music_control a:nth-child(3)').hide();
        $('.music_control a:nth-child(3)').prev().show();
        $('.music_control a:nth-child(3)').prev().prev().show();
        $('.music_control a:nth-child(3)').next().show();
        $('.music_control a:nth-child(3)').next().next().hide();
    }
}
function stopMusic(location) {
    $(location).html('');
    setCookie('song_0');
    // Verkehr anschalten
    playMusic('.traffic_container', 'aHR0cDovL3d3dy5za3liYXItdmlsc2hvZmVuLmRlL3dwLWNvbnRlbnQvdGhlbWVzL2RlZmF1bHQvbXAzcy90cmFmZmljLm1wMw', 'yes', 10, 1);
    
    /* Play anzeigen, Rest verbergen */
    if(location == '.music_container') {
        $('.music_control a:nth-child(1)').hide();
        $('.music_control a:nth-child(1)').next().hide();
        $('.music_control a:nth-child(1)').next().next().show();
        $('.music_control a:nth-child(1)').next().next().next().hide();
        $('.music_control a:nth-child(1)').next().next().next().next().show();
    }
}
/* Bei Links mit target="_blank" Musik stoppen */
$(document).ready(function(){
    $("a[target='_blank']").click(function(){
        $('.music_control').children(":first").click();
        $('.traffic_container').html('');
    });
});



// Alle 3 Minuten neuen Cookie setzen
$(document).ready(function(){
    window.setInterval("setCookie('intro')",100000);
});
/* Hilfsfunktion, um Cookies zu setzen */
function setCookie(value) {
    if(value == 'los') {
        /* Alten ggf. löschen */
        var del = $.delCookie('skybar_los');
        /* Neuen Cookie erstellen */
        var cookie = $.setCookie( 'skybar_los', 'Rubbellos', {
          duration : (1/2), // In Tagen, also 12 Stunden
          path : '',
          domain : '',
          secure : false
        });
    }
    if(value == 'intro') {
        /* Alten ggf. löschen */
        var del = $.delCookie('skybar_intro');
        /* Neuen Cookie erstellen */
        var cookie = $.setCookie( 'skybar_intro', 'Startprozedur', {
          duration : (1/144), // In Tagen, also 10 Minuten
          path : '',
          domain : '',
          secure : false
        });
    }
    if(value == 'song_0' || value == 'song_1' || value == 'song_2' || value == 'song_3') {
        /* Alten ggf. löschen */
        var del = $.delCookie('skybar_music');
        /* Neuen Cookie erstellen */
        var cookie = $.setCookie( 'skybar_music', value, {
          duration : 365, // In Tagen, also 3 Minuten
          path : '',
          domain : '',
          secure : false
        });
    }
}


function moveLift(duration) {
    /* Aktuelle Scrollposition ermitteln */
    var pos = $(window).scrollTop();
    // Wenn man ganz oben ist
    if(pos < 74) {
        pos = 74;
    }
    // Wenn man ganz unten ist
    if(pos > 5149) {
        pos = 5673;
    }
    /* Lift reset */
    if(pos > 2500) {
        $('#main_menu').animate({ "top": pos-($(window).height()) }, 0000);
    }
    if(pos <= 2500) {
        $('#main_menu').animate({ "top": pos+($(window).height()) }, 0000);
    }
    $("#main_menu").show();
    /* Lift hinfahren */
    $('#main_menu').animate({
        "top": pos
    }, duration, function(){
            isAllowed = true;
            checkState();
            var value = $.readCookie('skybar_music');
            if( value ) { }
            else {
                // Musik starten (beim ersten Mal, wenn Lift oben ist, wenn kein Cookie gesetzt wurde
                $('.music_control a:nth-child(3)').click();
            }
      });
}


/* Hauptmenü aktiv state */
$(document).ready(function(){
    // Wenn geklickt wird
    $('#main_menu ul li').click(function() {
        // Alles inaktiv setzen
        $('#main_menu ul li').removeClass('active');
        // Aktuellen aktiv setzen
        $(this).addClass('active');
    });
});

// Active state dynamisch bestimmen
function checkState() {
    if(isAllowed == true) {
        var main_menu = $('#main_menu').offset();
        var menu_1 = $('#post-18').offset();
        var menu_2 = $('#post-14').offset();
        var menu_3 = $('#post-16').offset();
        var menu_4 = $('#post-12').offset();
        var menu_5 = $('#post-10').offset();
        var menu_6 = $('#post-8').offset();
        if( main_menu != null &&
            menu_1 != null &&
            menu_2 != null &&
            menu_3 != null &&
            menu_4 != null &&
            menu_5 != null &&
            menu_6 != null) {
            // Alles inaktiv setzen
            $('#main_menu ul li').removeClass('active');
            if(((-1) * (menu_1.top - main_menu.top)) < 1100 && ((-1) * (menu_1.top - main_menu.top)) > 0) {
                /* alert('Ich befinde mich im Menü 1'+(menu_1.top - main_menu.top)); */
                // Aktuellen aktiv setzen
                $('#main_menu ul li:nth-child(1)').addClass('active');
                /* Stockwerksanzeige */
                $('#main_menu #currentLevel').html('5');
            }
            if(((-1) * (menu_2.top - main_menu.top)) < 1100 && ((-1) * (menu_2.top - main_menu.top)) > 0) {
                /* alert('Ich befinde mich im Menü 2'+(menu_2.top - main_menu.top)); */
                // Aktuellen aktiv setzen
                $('#main_menu ul li:nth-child(2)').addClass('active');
                /* Stockwerksanzeige */
                $('#main_menu #currentLevel').html('4');
            }
            if(((-1) * (menu_3.top - main_menu.top)) < 1100 && ((-1) * (menu_3.top - main_menu.top)) > 0) {
                /* alert('Ich befinde mich im Menü 3'+(menu_3.top - main_menu.top)); */
                // Aktuellen aktiv setzen
                $('#main_menu ul li:nth-child(3)').addClass('active');
                /* Stockwerksanzeige */
                $('#main_menu #currentLevel').html('3');
            }
            if(((-1) * (menu_4.top - main_menu.top)) < 1100 && ((-1) * (menu_4.top - main_menu.top)) > 0) {
                /* alert('Ich befinde mich im Menü 4'+(menu_4.top - main_menu.top)); */
                // Aktuellen aktiv setzen
                $('#main_menu ul li:nth-child(4)').addClass('active');
                /* Stockwerksanzeige */
                $('#main_menu #currentLevel').html('2');
            }
            if(((-1) * (menu_5.top - main_menu.top)) < 1100 && ((-1) * (menu_5.top - main_menu.top)) > 0) {
                /* alert('Ich befinde mich im Menü 5'+(menu_5.top - main_menu.top)); */
                // Aktuellen aktiv setzen
                $('#main_menu ul li:nth-child(5)').addClass('active');
                /* Stockwerksanzeige */
                $('#main_menu #currentLevel').html('1');
            }
            if(((-1) * (menu_6.top - main_menu.top)) < 1100 && ((-1) * (menu_6.top - main_menu.top)) > 0) {
                /* alert('Ich befinde mich im Menü 6'+(menu_6.top - main_menu.top)); */
                // Aktuellen aktiv setzen
                $('#main_menu ul li:nth-child(6)').addClass('active');
                /* Stockwerksanzeige */
                $('#main_menu #currentLevel').html('G');
            }
        }
    }
}
$(document).ready(function(){
    window.setInterval("checkState()",1000);
});



/* Rubbellos wird genau dann aktiviert, wenn noch kein Cookie gesetzt wurde */
$().ready(function() {

    var value = $.readCookie('skybar_los');
    
    if(value) {
        // wenn Rubbel-Cookie gefunden wird, passiert nichts
        //alert( 'Cookie bereits vorhanden.' );
    }
    else {
        // wenn nicht, wird Rubbeln gestartet (nach kurzer Verzögerung)
        //alert('Cookie NICHT vorhanden.');
        window.setTimeout(function() {
            $("#rubbellos img").jScratchcard({
                opacity: 0.35,
                color: '#2984E6',
                stepx: 25,
                stepy: 19,
                mousedown: true
            });
        }, 2000);
    }   
    // Rubbellos einblenden (nach kurzer Verzögerung)
    window.setTimeout(function() {
        $("#rubbellos #code").css("visibility","visible");
        $("#rubbellos img").css("visibility","visible");
    }, 3000);
    
});
/* Wenn gerubbelt wird, wird der Cookie gesetzt */
$().ready(function() {
    window.setTimeout(function() {
        $('#rubbellos .internalName__sc').mousedown(function() {
            setCookie('los');
        });
    }, 4000);
});





/* Flash Detection */
function flash_detection(required, max)
{
    var required_version = required;
    var max_version = max;
    var available_version = 0;

    if(typeof(navigator.plugins["Shockwave Flash"]) == "object")
    {
        var description = navigator.plugins["Shockwave Flash"].description;
        available_version = description.substr(16, (description.indexOf(".", 16) - 16));
    }
     else if(typeof(ActiveXObject) == "function")
    {
        for(var i = 2; i < (max_version + 1); i ++)
        {
            try
            {
                if(typeof(new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i)) == "object")
                {
                    available_version = i;
                }
           }
           catch(error)
           {
           }
        }
    }
    return [available_version, required_version];
}
/* Nur Musik anzeigen, wenn Flash vorhanden */
function showMusicControl() {
    var flash = flash_detection(7, 99);
    if(!flash[0] || flash[0] < flash[1]) { }
    else {
        $('.music_control').show();
    }
}



/* Shoutbox */
$(document).ready(function(){
    $(".scrollShoutboxDown").mousedown(function(){
        downInterval = setInterval("scrollShoutboxDown()", 20);
    });
    $(".scrollShoutboxUp").mousedown(function(){
        upInterval = setInterval("scrollShoutboxUp()", 20);
    });
});
function scrollShoutboxTop() {
    $('#sb_messages').scrollTo( 0, 1000, {axis:'y'});
}
function scrollShoutboxUp() {
    $('#sb_messages').scrollTo( '-=20px', 5, {axis:'y'});
    $(".scrollShoutboxUp").mouseup(function(){
        clearInterval(upInterval);
    });
}
function scrollShoutboxDown() {
    $('#sb_messages').scrollTo( '+=20px', 5, {axis:'y'});
    $(".scrollShoutboxDown").mouseup(function(){
        clearInterval(downInterval);
    });
}




/* Spotlight */
$(document).ready(function(){
	$('#wpcf7-f1-p8-o1').bind('focusin', function(){
		$(this).spotlight({
            opacity: .5,				//spotlight opacity
            speed: 400,					//animateion speed
            color: '#000',				//spotlight colour
            animate: true,				//enable animation (if false 'speed' and 'easing' are irrelevant)
            exitEvent:'mouseover'
        });
	});
	$('#shoutbox').bind('focusin', function(){
		$(this).spotlight({
            opacity: .5,				//spotlight opacity
            speed: 400,					//animateion speed
            color: '#000',				//spotlight colour
            animate: true,				//enable animation (if false 'speed' and 'easing' are irrelevant)
            exitEvent:'mouseover'
        });
	});
});


/* Wenn IE erkannt, wird für den IFrame das xhtml non-valide Tag "allowtransparency" gesetzt */
$(document).ready(function(){
if ($.browser.msie) {
    //alert("this is IE!");
    $('#gallery_iframe').attr("allowtransparency","true");
}
});


/* Submit Forms mit Enter bestätigen */
$(document).ready(function(){
$(function(){
    /* In der Shoutbox */
    $('#input_area input').keydown(function(e){
        if (e.keyCode == 13) {
            $('#sb_addmessage').click();
            return false;
        }
    });
    /* In dem Kontaktformular */
    $('.wpcf7-form input').keydown(function(e){
        if (e.keyCode == 13) {
            $('.wpcf7-form .submit input').click();
            return false;
        }
    });
});
});






/* Image Slider */
$(document).ready(function(){
	/* This code is executed after the DOM has been completely loaded */
	var totWidth=0;
	var positions = new Array();

	$('#slides .slide').each(function(i){
		/* Loop through all the slides and store their accumulative widths in totWidth */
		positions[i]= totWidth;
		totWidth += $(this).width();

		/* The positions array contains each slide's commulutative offset from the left part of the container */
		if(!$(this).width())
		{
			alert("Please, fill in width & height for all your images!");
			return false;
		}
	});

	$('#slides').width(totWidth);
	/* Change the cotnainer div's width to the exact width of all the slides combined */
	$('#slide-menu ul li a').click(function(e){
		/* On a thumbnail click */
		$('li.menuItem').removeClass('act').addClass('inact');
		$(this).parent().addClass('act');

		var pos = $(this).parent().prevAll('.menuItem').length;

		$('#slides').stop().animate({marginLeft:-positions[pos]+'px'},500);
		/* Start the sliding animation */

		e.preventDefault();
		/* Prevent the default action of the link */
	});

	$('#slide-menu ul li.menuItem:first').addClass('act').siblings().addClass('inact');
	/* On page load, mark the first thumbnail as active */
    
	/*****
	 *
	 *	Auto Slideshow
	 *
	 ****/
	var current=1;
	function autoAdvance()
	{
		if(current==-1) return false;
		
		$('#slide-menu ul li a').eq(current%$('#slide-menu ul li a').length).trigger('click',[true]);	// [true] will be passed as the keepScroll parameter of the click function on line 28
		current++;
	}
	// The number of seconds that the slider will auto-advance in:
	var changeEvery = 10;
	//var itvl = setInterval(function(){autoAdvance()},changeEvery*1000);
	/* End of customizations */
});




/* Bei allen Links darf kein Text selektiert werden */
$(function(){
	$.extend($.fn.disableTextSelect = function() {
		return this.each(function(){
			if($.browser.mozilla){//Firefox
				$(this).css('MozUserSelect','none');
			}else if($.browser.msie){//IE
				$(this).bind('selectstart',function(){return false;});
			}else{//Opera, etc.
				$(this).mousedown(function(){return false;});
			}
		});
	});
	$('a').disableTextSelect();//No text selection on elements with a class of 'noSelect'
});
