var selectedVideo = '';

var arrowover = function(){
	$(this).css("opacity","1");
}
var arrowout = function(){
	$(this).css("opacity","0.5");
}

var checkArrowVisibility = function(id) {
	if (id == 0) {
		$('.prev-video img').css('visibility', 'hidden');
		$('.prev-video').css('cursor', 'default');
		$('.next-video img').css('visibility', 'visible');
		$('.next-video').css('cursor', 'pointer');
	} else if (id == (parseInt(videoitemscount)-1)) {
		$('.next-video img').css('visibility', 'hidden');
		$('.next-video').css('cursor', 'default');
		$('.prev-video img').css('visibility', 'visible');
		$('.prev-video').css('cursor', 'pointer');
	} else {
		$('.next-video img').css('visibility', 'visible');
		$('.next-video').css('cursor', 'pointer');
		$('.prev-video img').css('visibility', 'visible');
		$('.prev-video').css('cursor', 'pointer');
	}
}

$(document).ready(function() {
	var thumbWidth = 140;
	var thumbSpacer = 8;
	// div with hidden overflow
	var scrollWindow = $('#slideshow-box');
	// scrolling div
	var scrollDiv = $('#slideshow-countdown');
	var divWidth = (thumbWidth + thumbSpacer) * videoitemscount;
	var scrollWindowWidth = $(window).width() - scrollWindow.position().left;
	var scrollWindowCenter = scrollWindow.position().left + (scrollWindowWidth / 2);
	var windowPos = scrollWindow.css('left').split('px')[0];
	var mouseX = null;
	var selectedVideoCaption = '';
	
	$('.prev-video img').css('opacity', '0.5');
	$('.next-video img').css('opacity', '0.5');
	
	// setting definitive widths
	scrollDiv.css('width', divWidth);
	if (navigator.appName != 'Microsoft Internet Explorer') {
		scrollWindow.css('width', scrollWindowWidth);
	}
	
	var html = '';
	for (var i = 0; i < videoitemscount; i++) {
		var splittedUrl = videoitems[i]['uri'].split('v=');
		var description = videoitems[i]['desc'];
		html += '<div class="videoBox">'
		html += '<div id="fancyvideo-' + i + '" class="imgFrame">';
		html += '<img src="http://img.youtube.com/vi/' + splittedUrl[1] + '/1.jpg" alt="Video" width="' + thumbWidth + '" /></div>';
		html += '</div>\n';
	}
	scrollDiv.html(html);
	
	// functions
	
	/*
	 * delta calculation based on distance from scrollWindow center
	 */
	beginScrollThumbs = function() {
		var delta = 0;
		if (mouseX) {
			delta = (mouseX / scrollWindowWidth);
			// incrementing scrolling speed
			delta *= -15;
			delta *= delta *= delta;
		}
		// creating non scrolling area
		if (delta > 60) {
			delta -= 60;
		} else if (delta < -60) {
			delta += 60;
		}
		// scrolling
		if (delta != 0) {
			scrollThumbsWithDelta(delta);
		}
		scrollThread = setTimeout("beginScrollThumbs()", 100);
	}
	
	
	/*
	 * move the scrolling div inside boundaries
	 */
	scrollThumbsWithDelta = function(delta) {
		var offset = scrollDiv.position().left;
		if (offset+delta >= 0) {
			delta = 0;
			offset = 0;
		} else if (offset+delta < -(divWidth-windowPos)) {
			delta = 0;
			offset = -(divWidth-windowPos);
		}
		var value = Math.ceil(offset + delta);
		scrollDiv.css({'left': value + 'px'});
	}
	
	// listeners
	scrollDiv.bind('mouseleave', function(){
        clearTimeout( scrollThread );
    });
    
	scrollDiv.bind('mouseenter', function(){
		if (scrollDiv.width() > ($(window).width() - windowPos)) {
			beginScrollThumbs();
		}
    });

	// show video by id
	showVideo = function (id) {
		$('img.selected').removeClass('selected');
		$('#fancyvideo-' + id + ' img').addClass('selected');
		$('.prev-video').attr('id', 'video-' + (id));
		$('.next-video').attr('id', 'video-' + (parseInt(id)+2));
		var splittedUrl = videoitems[id]['uri'].split('v=')[1];
		$('#captiontext').html(videoitems[id]['desc']);
		$('#videonumber').html('Video ' + (parseInt(id)+1) + '/' + videoitemscount);
		html  = '<object width="490" height="300">';
		html += '<param name="movie" value="http://www.youtube.com/v/' + splittedUrl + '"></param>';
		html += '<param name="allowFullScreen" value="true"></param>';
		html += '<param name="allowscriptaccess" value="always"></param>';
		html += '<param name="bgcolor" value="#000000"></param>';
		html += '<embed src="http://www.youtube.com/v/' + splittedUrl + '&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" bgcolor="#000000" width="490" height="300"></embed>';
		html += '</object>';
		$('#videobox').html(html);
		selectedVideo = id;
    	checkArrowVisibility(id);
	}
	
	// listeners
	
	// show caption
	$('.imgFrame').bind('mouseenter', function() {
		var id = $(this).attr('id').split('-')[1];
		$('#caption').html(videoitems[id]['desc']);
	});
	
	// hide caption
	$('.imgFrame').bind('mouseleave', function() {
		$('#caption').html('&nbsp;');
	});
	
	// click on a video
	$('.imgFrame').click(function() {
		var id = $(this).attr('id').split('-')[1];
		showVideo(id);
	});
	
    $().mousemove(function(e){
        mouseX = e.pageX - scrollWindowCenter;
    });
    
    function previousVideo(id) {
    	if (id != 'video-0') {
			var numId = parseInt(id.split('-')[1]);
			if (divWidth > scrollWindowWidth) {
				var movement = -(thumbWidth + thumbSpacer) * (numId - 1);
				if (movement < $(window).width()-windowPos-divWidth) {
					scrollDiv.animate({'left': $(window).width()-windowPos-divWidth}, 1000, 'swing');
				} else {
					scrollDiv.animate({'left': movement + 'px'}, 1000, 'swing');
				}
			}
			showVideo(numId-1);
		}
    	checkArrowVisibility(numId-1);
    }
    
    function nextVideo(id) {
    	if (id != 'video-' + (parseInt(videoitemscount)+1)) {
			var numId = parseInt(id.split('-')[1]);
			if (divWidth > scrollWindowWidth) {
				var movement = -(thumbWidth + thumbSpacer) * (numId - 1);
				if (movement < $(window).width()-windowPos-divWidth) {
					scrollDiv.animate({'left': $(window).width()-windowPos-divWidth}, 1000, 'swing');
				} else {
					scrollDiv.animate({'left': movement + 'px'}, 1000, 'swing');
				}
			}
			showVideo(numId-1);
		}
    	checkArrowVisibility(numId-1);
    }
    
    $('.prev-video').click(function() {
		var id = $(this).attr('id');
		if (id!="video-0"){
			previousVideo(id);
		}
    });
	
	$('.next-video').click(function() {
		var id = $(this).attr('id');
		if ("video-"+(videoitemscount+1)!=id){
			nextVideo(id);
		}
	});
	
	$(window).resize(function() {
		scrollWindowWidth = $(window).width() - scrollWindow.position().left;
		scrollWindowCenter = scrollWindow.position().left + (scrollWindowWidth / 2);
		scrollWindow.css('width', scrollWindowWidth);
		if (scrollDiv.width() < ($(window).width() - windowPos)) {
			scrollDiv.css({'left': '0px'});
		}
	});
	
	$(window).keydown(function(event) {
    	if (event.keyCode == 37) {
    		// left
    		previousVideo('video-' + (parseInt(selectedVideo)));
    	} else if (event.keyCode == 39) {
    		// right
    		nextVideo('video-' + (parseInt(selectedVideo)+2));
    	}
    });
	
	$('.prev-video img').bind('mouseleave', arrowout);
	$('.prev-video img').bind('mouseenter', arrowover);
	$('.next-video img').bind('mouseleave', arrowout);
	$('.next-video img').bind('mouseenter', arrowover);
	
	// showing initial video
	showVideo(0);
	$('.prev-video img').css('visibility', 'hidden');
	$('.prev-video').css('cursor', 'default');
});

init = function () {}