$(document).ready(function() {
	$('.scrollable').scrollable({ vertical: true, mousewheel: true });
	
	$("#players img").reflect({height: 0.5, opacity: 0.6});
			
	var currentPosition = 0;
    var slideWidth = 860;
    var slides = $('.slide');
    var numberOfSlides = slides.length;

    // Remove scrollbar in JS
    $('#slidesContainer').css('overflow', 'hidden');

    // Wrap all .slides with #slideInner div
    slides.wrapAll('<div id="slideInner"></div>').css({
        'float' : 'left',
        'width' : slideWidth
    });

    // Set #slideInner width equal to total width of all slides
    $('#slideInner').css('width', slideWidth * numberOfSlides);

    // Insert controls in the DOM
    $('#slideshow').prepend('<span class="control" id="leftControl">Clicking moves left</span>').append('<span class="control" id="rightControl">Clicking moves right</span>');

    // Hide left arrow control on first load
    manageControls(currentPosition);

    // Create event listeners for .controls clicks
    $('.control').bind('click', function(){
        // Determine new position
        currentPosition = ($(this).attr('id')=='rightControl') ? currentPosition+1 : currentPosition-1;
        // Hide / show controls
        manageControls(currentPosition);
        // Move slideInner using margin-left
        $('#slideInner').animate({
            'marginLeft' : slideWidth*(-currentPosition)
        });
    });

    // manageControls: Hides and Shows controls depending on currentPosition
    function manageControls(position){
        // Hide left arrow if position is first slide
        if(position==0){ $('#leftControl').hide() } else{ $('#leftControl').show() }
        // Hide right arrow if position is last slide
        if(position==numberOfSlides-1){ $('#rightControl').hide() } else{ $('#rightControl').show() }
    }    
	
	$("#triggers img[rel]").overlay({effect: 'apple'});
	$("tr[rel]").overlay({effect: 'apple'});
	
	// setup tooltip for a single DIV element
	$("#tooltiptable span.upled").tooltip({
		// each trashcan image works as a trigger
		// tip: '#tooltip',
		// custom positioning
		position: 'center right',
		// move tooltip a little bit to the right
		offset: [-35, -35],
		// there is no delay when the mouse is moved away from the trigger
		delay: 0,
		opacity: 0.8
	});
	
	$('.menue').buildMenu({
		template:'yourMenuVoiceTemplate',
		additionalData:'',
		menuSelector:'.menuContainer',
		menuWidth:150,
		openOnRight:false,
		containment:'window',
		iconPath:'ico/',
		hasImages:true,
		fadeInTime:100,
		fadeOutTime:200,
		menuTop:0,
		menuLeft:0,
		submenuTop:0,
		submenuLeft:4,
		opacity:1,
		shadow:false,
		shadowColor:'black',
		shadowOpacity:.2,
		openOnClick:true,
		closeOnMouseOut:false,
		closeAfter:500,
		minZindex:'auto',
		hoverIntent:0, //if you use jquery.hoverIntent.js set this to time in milliseconds; 0= false;
		submenuHoverIntent:0 //if you use jquery.hoverIntent.js set this to time in milliseconds; 0= false;
	});
			
	$('#signupForm').submit(function(e) {
		// If a previous submit is in progress:
		if($('#submit').hasClass('active')) return false;
		
		// Adding the active class to the button. Will show the preloader gif:
		$('#submit').addClass('active');
		
		// Removing the current error tooltips
		$('.errorTip').remove();
		
		// Issuing a POST ajax request to submit.php (the action attribute of the form):
		$.post($('#signupForm').attr('action'),$('#signupForm').serialize()+'&fromAjax=1',function(response){
			if(!response.status) {
				// Some kind of input error occured
				
				// Looping through all the input text boxes,
				// and checking whether they produced an error
				$('input[type!=submit]').each(function() {
					var elem = $(this);
					var id = elem.attr('id');
					
					if(response[id])
						showTooltip(elem,response[id]);
				});
			} else 
				location.replace(response.redirectURL);
			
			$('#submit').removeClass('active');
		},'json');
		
		e.preventDefault();
	});
	
	var loader = $('#loader');
	var pollcontainer = $('#pollcontainer');
	loader.fadeIn();
	
	//Load the poll form
	$.get('poll.php', '', function(data, status) {
		pollcontainer.html(data);
		animateResults(pollcontainer);
		pollcontainer.find('#viewresult').click(function() {
			//if user wants to see result
			loader.fadeIn();
			$.get('poll.php', 'result=1', function(data,status) {
				pollcontainer.fadeOut(1000, function() {
					$(this).html(data);
					animateResults(this);
				});
				loader.fadeOut();
			});
			//prevent default behavior
			return false;
		}).end()
		.find('#pollform').submit(function() {
			var selected_val=$(this).find('input[name=poll]:checked').val();
			if (selected_val!='') {
				//post data only if a value is selected
				loader.fadeIn();
				$.post('poll.php', $(this).serialize(), function(data, status) {
					$('#formcontainer').fadeOut(100, function() {
						$(this).html(data);
						animateResults(this);
						loader.fadeOut();
					});
				});
			}
			//prevent form default behavior
		return false;
		});
		loader.fadeOut();
	});
	
	$("a[rel=group]").fancybox({
		'transitionIn'  : 'none',
		'transitionOut' : 'none',
		'titlePosition' : 'over',
		'titleFormat'   : function(title, currentArray, currentIndex, currentOpts) {
			return '<span id="fancybox-title-over">Bild ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
		}
	});

	function animateResults(data) {
		$(data).find('.bar').hide().end().fadeIn('slow', function() { 
			$(this).find('.bar').each(function() {
				var bar_width=$(this).css('width');
				$(this).css('width', '0').animate({ width: bar_width }, 1000);
			});
		});
	}
});

// Helper function that creates an error tooltip:
function showTooltip(elem,txt) {
	// elem is the text box, txt is the error text
	$('<div class=\"errorTip\">').html(txt).appendTo(elem.closest('.formRow'));
}
