/*
 *  Author:    Daniel Gratzl <dag@dagsystems.de>
 */
var slideBoxWidth = 0;
var profileImagePositions = new Array();


/**
 * Handles the slidebox arrow navigation
 *  
 * @returns
 */
function slider() {
	var isRunning;
	var speed = 10;
	var distance = 10;
	
	return {
		forward : function(){
			var newPos = $('#slide-box').scrollLeft()+distance;
			$('#slide-box').scrollLeft(newPos);
			isRunning = setTimeout('slide.forward();', speed);
		},
		backward : function(){
			var newPos = $('#slide-box').scrollLeft()-distance;
			$('#slide-box').scrollLeft(newPos);
			isRunning = setTimeout('slide.backward();', speed);
		},
		stop : function (){
			if (isRunning) clearTimeout(isRunning);
		}
	}
}


/**
 * Creates the slidebox arrow navigation
 *  
 * @returns void
 */
var createSlideNavigation = function() {
	$('#content').append(
		$('<div id="slide-previous" class="slide-navigator"></div>')
	).append(
		$('<div id="slide-next" class="slide-navigator"></div>')
	);
}


/**
 * 
 * @return void
 */
var filterProjects = function() {
	var id = $('li.mosaic').attr('id');
	
	if(id != undefined && id != 'work' && id != 'publications' && id != 'home') {
		$('li.mosaic img').not('.'+id)
			.each(function(index, e){
				$(e).css('opacity', 0.3).next('span').remove();
				
				$(e).closest('a').click(function(e){
					e.preventDefault();
				}).css('cursor', 'default');
			});
	}
}


/**
 * Resizes the moisic to its content width
 *  
 * @returns void
 */
var resizeMosaic = function() {
    var maxWidth = 0;
    var width = 0;

    $('li.mosaic > div').each(function(index){
        position = $(this).position();
        width = $(this).width() + position.left;

        if(width > maxWidth) {
            maxWidth = width;
        }
    });

    $('li.mosaic').width(maxWidth);
}


$(window).load(
    function() {
        resizeMosaic();        

        $('#slide-box ul').children().each(function(index) {
            slideBoxWidth += $(this).outerWidth();
        });
        
        $('#slide-box ul').width(slideBoxWidth + 1); // +1 pixel fix for firefox?

        // on not touchenabled device and if the slidebox width is wider than the content       
        if($('html').hasClass('no-touch') && $('#slide-box').width() < slideBoxWidth) {
            createSlideNavigation();    
        }

        $('#slide-box.profileimages img').each(function(index, element) {
        	var imgId = $(element).attr('id');
        	imgId = imgId.substr(imgId.indexOf('-') + 1);
        	profileImagePositions[imgId] = $(element).offset().left - $('#content').offset().left - $('#profile-navigation').width();
        });	
    }
);


/**
 * Setup the Container position
 * 
 * @returns void
 */
var setupDom = function() {
	filterProjects();
	
	/*
	 * vertical alignment of the content
	 */	
    $('#vertical-spacer').css({
        'margin-bottom': 0 - (($('#content').height()) / 2)  - $('header').height()
    });
}


setupDom();

var slide = new slider();

/*
 * handle slide arrow next button
 */
$('#slide-next').live('mousedown', function(e) {
	slide.forward();
}).live('mouseup', function(e){
	slide.stop();
});


/*
 * handle slide arrow previous button
 */
$('#slide-previous').live('mousedown', function(e) {
	slide.backward();
}).live('mouseup', function(e){
	slide.stop();
});


/*
 * Detail description
 */
$('#detail-description.folded').live('click', function(e){
	$(this).removeClass('folded').addClass('unfolded')
		.children('p').fadeOut();
	var height = $('#detail-description-overlay').height();
	$('#detail-description-overlay').height(0)
		.show()
		.animate({'height' : height});
});

function foldDescription(overlay, description) {
	$(overlay).fadeOut(function(){
		$(description).removeClass('unfolded').addClass('folded')
		.children('p').fadeIn();
	});
}

$('#detail-description.unfolded').live('click', function(e){
	foldDescription('#detail-description-overlay', this);
});


/*
 * Detail description overlay 
 */
$('#detail-description-overlay').click(function(e) {
	foldDescription(this, '#detail-description');
});


/*
 *  Profile Navigation
 */
$('#profile-navigation li a').click(function(e){
	e.preventDefault();
	var id = $(this).attr('id');
	id = id.substr(id.indexOf('-') + 1);

	var description = $('#profileimage-'+id).attr('alt');
	$('#detail-description').html(description);
	$('#detail-description-overlay p:first').html(description);

	if(description == '') {
		$('#detail-description').hide();
	} else {
		$('#detail-description').show();
	}
	
	$('#detail-description-overlay').fadeOut();
	
	$('#slide-box').scrollLeft(profileImagePositions[id]);
});


/*
 * show and hide arrow navigation
 */
$('#slide-box').mouseenter(function(){
	$('.slide-navigator').show();
}).mouseleave(function(e){
	if(! $(e.relatedTarget).hasClass('slide-navigator')) {
		$('.slide-navigator').hide();
	}
	
});


/*
 * handle click on mosaic
 */
$('.thumb-mosaic a').click(function(){
    var image = 'image_' + $(this).find('input').val();
    var newPosition = ($('#'+image).offset().left - $('#content').offset().left);
    $('#slide-box').scrollLeft(newPosition);
});


// only on not touch devices
if($('html').hasClass('no-touch')) {    
	$('#slide-box:not(.slide-box-mosaic)').dragscrollable();
	
	$('#slide-box').mousewheel(function(event, delta){
        this.scrollLeft -= Math.round(delta * 15);
        
        if (event.preventDefault) {
        	//disable default wheel action of scrolling page
        	event.preventDefault();
        } else {
        	return false;
        }
    }).css({
        'overflow' : 'hidden',
        'cursor' : '-moz-grab'
    });
	/*
	 * enables scrolling via middle mouse button and mousewheel
	 */
    /*
	$('#slide-box').mousedown(function(event){
    	if(! $(this).hasClass('slide-box-mosaic')) {
	        $(this).data('down', true)
	            .data('x', event.clientX)
	            .data('scrollX', this.scrollLeft);
	        alert($(this).data('scrollX') + $(this).data('x') - event.clientX);
	        return false;
    	}
    }).mouseup(function(event){
        $(this).data('down', false);
    }).mousemove(function(event){
    	//if(! $(this).hasClass('slide-box-mosaic')) {
	        var newPosition = $(this).data('scrollX') + $(this).data('x') - event.clientX;
	        //console.log(newPosition);
	        if ($(this).data('down') == true){
	            this.scrollLeft = newPosition;
	        }
        //}
    }).mousewheel(function(event, delta){
        this.scrollLeft -= Math.round(delta * 15);
        
        if (event.preventDefault) {
        	//disable default wheel action of scrolling page
        	event.preventDefault();
        } else {
        	return false;
        }
    }).css({
        'overflow' : 'hidden',
        'cursor' : '-moz-grab'
    });
*/
    /*
     * stop sliding if mouse leaves the window
     * TODO: necessary?
     */
    $(window).mouseout(function(){
        if ($('#slide-box').data('down') == true) {
            try {
                $('#slide-box').data('down', false);
            } catch(e) {}
        }
    });

    /*
     * show titles on mosaic tiles 
     */
    $('li.mosaic div a, li.mosaic div span').hover(
        function(event) {
            $(this).children('span.overlay').show();
        }, function(event) {
            $(this).children('span.overlay').hide();
        }
    );
} else { // only on touch devices
    /*
     * Swipe handlers.
     */
    var swipeStatus = function(event, direction, distance) {
        if (direction == 'right') {
            $(this).scrollLeft($(this).scrollLeft() - distance);
        } else if (direction == 'left') {
            $(this).scrollLeft($(this).scrollLeft() + distance);    
        }
    }

    /*
     * Enable swiping...
     */
    $("#slide-box").swipe({
        swipe: swipeStatus,
        allowPageScroll:"auto"
    });
}
