var prev_al = false;
var prev_el = false;
var autoplay = false;
var moogaloop = false;

// landscape: ratio < 1
function scaleSize(max_w, max_h, cur_w, cur_h) {
	var img_ratio = cur_h / cur_w;
	var box_ratio = max_h / max_w;
	if(img_ratio <= box_ratio && cur_w > max_w) {
		cur_w = max_w;
		cur_h = cur_w * img_ratio;
	} else if(img_ratio > box_ratio && cur_h > max_h) {
		cur_h = max_h;
		cur_w = cur_h / img_ratio;
	}
	return [cur_w, cur_h];
}


// 4. LOAD PHOTO
function loadPhoto(mediumKey) {
	$('mediaContainer').fade('hide');
	$('mediaContainer').empty();

	var myImage = Asset.image(mediumKey, {
		onLoad: function() {
			// empty here to to resolved back & forth bug
			// this is not ideal either... need abort thingy (does not exist!)
			$('mediaContainer').empty();

			$('mediaContainer').grab(myImage);
			var newSize = scaleSize(1020, 500, this.getSize()['x'], this.getSize()['y']);
			this.setProperties({width: newSize[0], height: newSize[1]});
			if(newSize[1] < 500)
				this.setStyle('margin-top', ((500-newSize[1])/2).round());

			$('mediaContainer').fade('in');
		}
	});
}


function nextMedium() {
	if(prev_el.getNext()) {
		prev_el.getNext().fireEvent('mouseenter');
		prev_el.getNext().fireEvent('click');
	} else {
		prev_el.getParent().getFirst().fireEvent('mouseenter');
		prev_el.getParent().getFirst().fireEvent('click');
	}
}

function prevMedium() {
	if(prev_el.getPrevious()) {
		prev_el.getPrevious().fireEvent('mouseenter');
		prev_el.getPrevious().fireEvent('click');
	} else {
		prev_el.getParent().getLast().fireEvent('mouseenter');
		prev_el.getParent().getLast().fireEvent('click');
	}
}


function vimeo_player_loaded() {
	if (!Browser.ie){
		$('mediaContainer').fade('in'); // IE BUG
	}

	if(autoplay)
		Swiff.remote($('moogaloop_swf_id'), 'api_play');
	if(!autoplay)
		autoplay = true;
	Swiff.remote($('moogaloop_swf_id'), 'api_addEventListener', 'onFinish', 'vimeo_on_finish');
}

function vimeo_on_finish() {
	nextMedium();
}

// 4. LOAD VIDEO
function loadVideo(mediumKey) {
	if (!Browser.ie){
		$('mediaContainer').fade('hide'); // IE BUG
	}
	var swf_id = 'moogaloop_swf_id';
	moogaloop = new Swiff('http://vimeo.com/moogaloop.swf', {
		id: swf_id,
		container: 'mediaContainer',
		width: 800,
		height: 450,
		vars: {
			clip_id: mediumKey,
			fp_version: 10,
			show_title: 0,
			show_byline: 0,
			show_portrait: 0,
			js_api: 1, // required in order to use the Javascript API
			js_onLoad: 'vimeo_player_loaded', // moogaloop will call this JS function when it's done loading (optional)
			/*color: 'ffffff',*/
			js_swf_id: 'moogaloop' // this will be passed into all event methods so you can keep track of multiple moogaloops (optional)
		},
		params: {
			bgcolor: '#000000',
			allowscriptaccess: 'always',
			allowfullscreen: 'true'
		}
	});
	if (!Browser.ie){
		$(swf_id).setStyle('margin-top', 50);
	}
}

// 3. LOAD MEDIUM
function loadMedium(mediumKey, filename) {
	if(filename == 'videos')
		loadVideo(mediumKey);
	if(filename == 'photos')
		loadPhoto(mediumKey);
}

// 2b. EXTENT MEDIA NAVIGATION, fades and set hover-color 
function extentNavigation(container) {
	clearTimeout(timer);
	var timer = false;
	container.getChildren().each(function(el) {
		var title = el.retrieve('title');
		el.addEvent('click', function() {
			$('tag').store('vid_title', title);
			$('tag').set('html', title);
			if(prev_el) prev_el.setStyle('color', '');
			prev_el = el;
			el.setStyle('color', '#00ADEF');
		});
		el.addEvent('mouseenter', function() {
			$('tag').set('html', title);
			$('tag').tween('color', '#00ADEF');
			clearTimeout(timer);
			timer = (function(){ $('tag').tween('color', '#111A19');timer = false; }).delay(1000);
		});
		el.addEvent('mouseleave', function() {
			$('tag').set('html', $('tag').retrieve('vid_title', '&nbsp;'));
		});
	});
	container.getFirst().fireEvent('mouseenter', null, 0);
	container.getFirst().fireEvent('click', null, 0);
}

// 2a. BUILT MEDIA NAVIGATION
// !! REQUIRES #navigation
function builtNavigation(media, filename) {
	// do not autoplay when loading new album
	// autoplay = false;
	var bullet = '&#9679;'
	var container = $('navigation');
	container.empty();
	media.each(function(medium){
		var anchor = new Element('a', {
			html: bullet,
		    events: {
				click: function(){
					loadMedium(medium.key, filename);
				}
			}
		});
		anchor.store('title', medium.title)
		container.grab(anchor);
	});
	extentNavigation(container);
}


// 1. LOAD ALBUM, get information to built bullets
function loadAlbum(id, filename) {
	var url = location.href.match(/^.*\//) + filename + '.json';
	var request = new Request.JSON({
		url: url,
		method: 'get',
		onSuccess: function(albums) {
			builtNavigation(albums[id].media, filename);
		}
	}).send();
}



// 0b. FOOTER fix hover-background-color, onclick loadalbum()
// !! REQUIRES #videoAlbums div a, #photoAlbums div a
function extentPanel(){
	$$('#videoAlbums div a, #photoAlbums div a').each(function(al) {
		al.addEvent('click', function() {
			if(prev_al) prev_al.setStyles({color: '', 'background-color': ''});
			prev_al = al;
			al.setStyles({color: '#FFFFFF', 'background-color': '#000000'});
		});
	});
	$$('#videoAlbums div a').each(function(al, i) {
		al.addEvent('click', function() {
			loadAlbum(i, 'videos');
		});
	});
	$$('#photoAlbums div a').each(function(al, i) {
		al.addEvent('click', function() {
			loadAlbum(i, 'photos');
		});
	});
}


// 0a. FOOTER mouseover slide events
// !! REQUIRES #panel, #footer
var footertimer = false;
function builtPanel(){
	var height = $('panel').getSize()['y'];
	//var timer = false;
	$('footer').addEvent('mouseleave', function() {
		clearTimeout(footertimer);
		footertimer = (function(){ $('footer').tween('bottom', -height); }).delay(125);
	});
	$('footer').addEvent('mouseenter', function() {
		clearTimeout(footertimer);
		footertimer = (function(){ $('footer').tween('bottom', 0); }).delay(50);
	});
}




// 0e. INITIALIZE and KEY Events
// !!  REQUIRES div#albums div div a
window.addEvent('domready', function() {
	builtPanel();
	extentPanel();

	window.addEvent('keydown', function(event) {
		if(!prev_al) {
	    	if (event.key == 'right' || event.key == 'left' || event.key == 'down' || event.key == 'up') {
	    		document.getElement('#albums div div a').fireEvent('click');
				footertimer = (function(){ $('footer').fireEvent('mouseleave', null, 0); }).delay(500);
			}
	    }
    	else if (event.key == 'right')
    		nextMedium();
    	else if (event.key == 'left')
    		prevMedium();

    	else if (event.key == 'down') {
			footertimer = (function(){
				$('footer').fireEvent('mouseenter', null, 0);
				footertimer = (function(){
					$('footer').fireEvent('mouseleave', null, 0);
				}).delay(1750);
			}).delay(0)

			if(prev_al.getParent().getNext()) {
				prev_al.getParent().getNext().getFirst().fireEvent('click');
			} else {
				if(prev_al.getParent().getParent().getNext()) {
					prev_al.getParent().getParent().getNext().getFirst().getFirst().fireEvent('click');
				} else {
					prev_al.getParent().getParent().getPrevious().getFirst().getFirst().fireEvent('click');
				}
			}
		}
		else if (event.key == 'up') {
			footertimer = (function(){
				$('footer').fireEvent('mouseenter', null, 0);
				footertimer = (function(){
					$('footer').fireEvent('mouseleave', null, 0);
				}).delay(1750);
			}).delay(0)

			if(prev_al.getParent().getPrevious()) {
				prev_al.getParent().getPrevious().getFirst().fireEvent('click');
			} else {
				if(prev_al.getParent().getParent().getNext()) {
					prev_al.getParent().getParent().getNext().getLast().getFirst().fireEvent('click');
				} else {
					prev_al.getParent().getParent().getPrevious().getLast().getFirst().fireEvent('click');
				}
			}
		}
	});

});


	//  PROCESS VIDEOS DATA
	/*function processVideos(videos) {
		var bullet = '&#9679;'
		var container = $(navigation);

		videos.each(function(video){
			alert(video.id);
			var anchor = new Element('a', {
				html: bullet,
			    events: {
					click: function(){
						loadVideo(video.id);
					}
				}
			});
			anchor.store('title', video.title)
			container.grab(anchor);
		});
		builtNavigation();
	}*/

	//  RETRIEVE VIDEOS
	/*var url = 'http://vimeo.com/api/v2/user3491195/videos.json';
	var request = new Request.JSONP({
		url: url,
		onSuccess: function(videos) {
			processVideos(videos);
		}
	}).send();*/







	//  PROCESS ALBUMS DATA
/*	function processAlbums(albums) {
		var container = $(videoAlbums);

		albums.each(function(album) {

			var div = new Element('div');
			var anchor = new Element('a', {
				html: album.title,
			    events: {
					click: function(){
						//loadVideo(video.id);
					}
				}
			});
			anchor.store('title', album.title);
			
			div.grab(anchor);
			container.grab(div);
		});
		builtPanel();
	}

	//  RETRIEVE ALBUMS
	var url = 'http://vimeo.com/api/v2/user3491195/albums.json';
	var request = new Request.JSONP({
		url: url,
		onSuccess: function(albums) {
			processAlbums(albums);
		}
	}).send();*/















/*jQuery(function($) {
    var slide = false;
    var height = $('#footer_content').height();
    $('#footer_button').click(function() {
        var docHeight = $(document).height();
        var windowHeight = $(window).height();
        var scrollPos = docHeight - windowHeight + height;
        $('#footer_content').animate({ height: "toggle"}, 1000);
        if(slide == false) {
            if($.browser.opera) { //Fix opera double scroll bug by targeting only HTML.
                $('html').animate({scrollTop: scrollPos+'px'}, 1000);
            } else {
                $('html, body').animate({scrollTop: scrollPos+'px'}, 1000);
            }
                            slide = true;
        } else {
                            slide = false;
                    }
    });
});*/
