/* 
  This program is free software. It comes without any warranty, to
  the extent permitted by applicable law. You can redistribute it
  and/or modify it under the terms of the Do What The Fuck You Want
  To Public License, Version 2, as published by Sam Hocevar. See
  http://sam.zoy.org/wtfpl/COPYING for more details.
*/

/* I'm sorry I never got around to beautifying the code, but I was
 * simply more focused on encoding and subbing my films.
 */

function empty(){}


HTMLElement.prototype.set_opacity = function(val) {
	this.style.opacity = val
	this.style.filter = 'alpha(opacity=' + val*100 + ')'
}

HTMLElement.prototype.fade = function(fade_in, increase, speed, afterfunc) {
	if (increase == undefined || increase == -1)
		var increase = 5
	if (speed = undefined || speed == -1)
		var speed = 50
	if (afterfunc == undefined)
		var afterfunc = empty
	
	this.style.display = 'block'
	if (fade_in) {
		this.fade_opacity = 0
		this.set_opacity(0)
	}
	else {
		this.fade_opacity = 100
		this.set_opacity(1)
	}
	this.fade_increase = increase
	this.fade_afterfunc = afterfunc
	this.fade_in = fade_in
	this.fade_interval = setInterval(this.fade_run, speed, this)
}

HTMLElement.prototype.fade_in = function(increase, speed, afterfunc) {
	this.fade(true, increase, speed, afterfunc)
}

HTMLElement.prototype.fade_out = function(increase, speed, afterfunc) {
	this.fade(false, increase, speed, afterfunc)
}

HTMLElement.prototype.fade_run = function(obj) {
	var end
	if (obj.fade_in) {
		obj.fade_opacity += obj.fade_increase
		end = obj.fade_opacity >= 100
	}
	else {
		obj.fade_opacity -= obj.fade_increase
		end = obj.fade_opacity <= 0
	}
	if (!end)
		obj.set_opacity(obj.fade_opacity/100)
	else
		obj.fade_end()
}

HTMLElement.prototype.fade_end = function() {
	clearInterval(this.fade_interval)
	if (this.fade_in)
		this.set_opacity(1)
	else {
		this.set_opacity(0)
		this.style.display = 'none'
	}
	delete this.fade_interval
	delete this.fade_opacity
	delete this.fade_increase
	delete this.fade_in
	var func = this.fade_afterfunc
	delete this.fade_afterfunc
	func()
}


function get_window_size() {
	if (window.innerWidth) {
		w = window.innerWidth
		h = window.innerHeight
	}
	else if (document.body.clientWidth) {
		w = document.body.clientWidth
		h = document.body.clientHeight
	}
}

function update_csssvg() {
	get_window_size()
	
	try {
		// More logical resize
		if (h < w * 0.45)
			svg.setAttribute('preserveAspectRatio', 'xMidYMid slice')
		else
			svg.setAttribute('preserveAspectRatio', 'xMidYMid meet')
    } catch (error) {}
    // Just for looks
    text_box.style.minHeight = h - 101 + 'px'
    text_content.style.minHeight = h - 215 - menu_height + 'px'
}

function in_list(obj, lst) {
	for (var x in lst) {
		if (lst[x] == obj)
			return x
	}
	
	return -1
}

function set_title_based_on_page(num) {
	if (pages_titles[num])
		document.title = root_title + ' :: ' + pages_titles[num]
}





function pagescroll_start() {
	if (page_scrolling)
		return false
	
	var newelem = pages_elems[new_num]
	var oldelem = pages_elems[old_num]
	
	newelem.style.position = 'absolute'
	newelem.style.top = '6px'
	newelem.style.marginLeft = '525px'
	newelem.className = 'focus'
	
	if (newelem.scrollHeight > oldelem.scrollHeight) {
		newelem.style.position = ''
		newelem.style.marginLeft = '525px'
		oldelem.style.position = 'absolute'
		oldelem.style.top = '6px'
	}
	
	page_moved = 0
	
	increase = 10
	page_change_increase = 400
	
	page_scrolling = true
	pagescroll()
}

function pagescroll() {
	var tmp_increase = increase + 15
	if (page_moved + tmp_increase < page_change_increase)
		increase = tmp_increase
	else
		increase -= 25
	mv = page_moved + increase
	if (mv < PAGE_WIDTH) {
		page_moved = mv
		text_content.style.left = -mv + 'px'
		setTimeout("pagescroll()", 50)
	}
	else
		pagescroll_end()
}

function pagescroll_end() {
	var newelem = pages_elems[new_num]
	var oldelem = pages_elems[old_num]
	
	current_page = pages_refs[new_num]
	set_title_based_on_page(new_num)
	
	text_content.removeAttribute('style')
	newelem.removeAttribute('style')
	oldelem.removeAttribute('style')
	oldelem.className = 'hidden'
	
	text_content.style.left = '0'
	newelem.style.left = '0'
	oldelem.style.left = '0'
	
	pages_menu_elems[old_num].className = ''
	pages_menu_elems[new_num].className = 'focus'
	
	page_scrolling = false
}






function cinema_start(num, subs_lang) {
	if (video_playing) {
		if (num != video_playing) {
			video_playing = num
			cininf.fade_out(10, -1, function() {cinema_set_description(); cininf.fade_in(10)})
			cinema_play()
		}
		return
	}
		
	if (subs_lang) {
		var ok = false
		for (var x in subtitles) {
			if (subtitles[x][0] == num) {
				ok = true
				subtitles[x][1].resume()
				break
			}
		}
		if (!ok)
			subtitles.push([num, new subtitle(cinvid, 'vid/niels-natur'+num+'-'+subs_lang+'.srt', cinelm)])
	}
	video_playing = num
	cinema_set_description()
	cinelm.fade_in(7, -1, cinema_start_continue)
}

function cinema_set_description() {
	cininf.innerHTML = root_title + ' ' + video_playing
}

function cinema_start_continue() {
	cininf.fade_in(10)
	cinelm_close.fade_in(10)
	
	text_wrapper.style.display = 'none'
	bgflow.style.display = 'none'
	
	cinema_play()
}

function cinema_play() {
	var url = 'vid/niels-natur' + video_playing + '-small.ogv'
	
	if (cinvid.currentTime != undefined) {
		cinvid.src = url
		cinvid.play()
	}
	else {
		add_cortado(url)
	}
}

function cinema_end() {
	text_wrapper.style.display = ''
	bgflow.style.display = ''
	
	if (cinvid.currentTime != undefined) {
		cinvid.pause()
	}
	else {
		remove_cortado()
	}
	for (var x in subtitles) {
		if (subtitles[x][0] == video_playing) {
			subtitles[x][1].stop()
			break
		}
	}
	video_playing = 0
	
	cininf.fade_out(7)
	cinelm_close.fade_out()
	cinelm.fade_out(-1, -1, function(){})
}




function do_action(href) {
	var action, x
	action = href.substr(href.indexOf('#')+1)
	if (!page_scrolling && action != current_page && in_list(action, pages_refs) != -1) {
		// It is a hidden page (to be shown)
		
		var name, elem, menu_elem, parent
		for (x in pages_refs) {
			name = pages_refs[x]
			elem = pages_elems[x]
			menu_elem = pages_menu_elems[x]
			if (name == action) {
				// Put element after other elements
				parent = elem.parentNode
				parent.removeChild(elem)
				parent.appendChild(elem)
				
				new_num = x
			}
			else if (name == current_page) {
				old_num = x
			}
		}
		
		pagescroll_start()
	}
	else if (action.indexOf('play') == 0) {
		var play = action.substr(4)
		var dot = play.indexOf('.')
		var subs
		if (dot != -1) {
			subs = play.substr(dot+1)
			play = play.substr(0, dot)
		}
		else
			subs = false
		play = play*1
		if (play) {
			do_action(pages_refs[1])
			cinema_start(play, subs)
		}
	}
}

function remove_cortado(url) {
	cinvid.removeChild(cinapp)
	delete cinapp
}

function add_cortado(url) {
	cinapp = document.createElement('applet')
	cinapp.setAttribute('code', 'com.fluendo.player.Cortado.class')
	cinapp.setAttribute('archive', 'http://theora.org/cortado.jar')
	cinapp.width = '640'
	cinapp.height = '360'
	
	namval = {
	    'url': url,
	    'local': 'false',
	    'duration': '',
	    'bufferSize': '200',
	    'autoPlay': 'true',
	    'statusHeight': '16'
	}
	
	for (x in namval) {
		elem = document.createElement('param')
		elem.setAttribute('name', x)
		elem.setAttribute('value', namval[x])
		if (x == 'url')
			cinapp_url = elem
		cinapp.appendChild(elem)
	}
	
	cinvid.appendChild(cinapp)
}


window.onload = function() {
	// Get elements
	bgflow = document.getElementById('bgflow')
	text_wrapper = document.getElementById('text_wrapper')
	text_box = document.getElementById('text_box')
	text_menu = document.getElementById('text_menu')
	text_content = document.getElementById('text_content')
	
	
	PAGE_WIDTH = 525
	HALF_PAGE = Math.round(PAGE_WIDTH / 2) + 10 // With a little extra
	
	// Set default values (also for debugging)
	w = -1
	h = -1
	old_num = -1
	new_num = -1
	page_scrolling = false
	video_playing = 0
	
	// Get menu height if menu exists
	try {
		menu_height = text_menu.offsetHeight
	} catch(err) {
		menu_height = 0
	}
	
	// Get root element of background SVG
	try {
		svg = bgflow.getSVGDocument().rootElement
	} catch (error) {}
	
	root_title = document.title
	
	var elems, elem, x, y, name, urlhash, hash_in_list, elem_num, menu_elem
	var elems2, elem2
	urlhash = window.location.hash.substr(1)
	
	pages_refs = new Array()
	pages_elems = new Array()
	pages_menu_elems = new Array()
	pages_titles = new Array()
	
	elems = text_menu.childNodes
	for (x in elems) {
		elem = elems[x]
		if (elem.nodeName && elem.nodeName.toLowerCase() == 'li') {
			pages_menu_elems.push(elem)
			elem = elem.childNodes[0]
			pages_titles.push(elem.innerHTML)
			pages_refs.push(elem.href.substr(elem.href.indexOf('#')+1))
		}
	}
	
	hash_in_list = in_list(urlhash, pages_refs)
	if (hash_in_list != -1) {
		current_page = urlhash
		elem_num = hash_in_list
	}
	else {
		current_page = pages_refs[0]
		elem_num = 0
	}
	
	// Hide non-current pages
	for (x in pages_refs) {
		name = pages_refs[x]
		elem = document.getElementById('content_' + name)
		menu_elem = pages_menu_elems[x]
		pages_elems.push(elem)
		if (name == current_page) {
			elem.className = 'focus'
			menu_elem.className = 'focus'
		}
		else {
			elem.className = 'hidden'
			menu_elem.className = ''
		}
	}
	
	set_title_based_on_page(elem_num)
	
	// Set up alternate handling of '#' links and prepare video shots
	elems = document.getElementsByTagName('a')
	for (x in elems) {
		elem = elems[x]
		if (elem.href != undefined && elem.href.indexOf('#') != -1)
			elem.onclick = function() {do_action(this.href)}
	}
	
	// Prepare page for viewing video
	cinelm = document.createElement('div')
	cinelm.id = 'cinema'
	
	cinelm_close = document.createElement('div')
	cinelm_close.id = 'cinema-close'
	cinelm_close.onclick = function() {cinema_end()}
	cinelm.appendChild(cinelm_close)
	
	cinvid = document.createElement('video')
	cinvid.id = 'cinema-film'
	cinvid.width = '640'
	cinvid.height = '360'
	cinvid.setAttribute('controls', 'controls')
	cinvid.addEventListener('ended', function() {cinema_end()}, true)
	
	cinelm.appendChild(cinvid)
	
	cininf = document.createElement('div')
	cininf.id = 'cinema-info'
	cinelm.appendChild(cininf)

	document.body.appendChild(cinelm)
	
	// Prepare for loading of subtitles
	subtitles = new Array()
	
	// Do whatever the hash tells you to do
	do_action(urlhash)
	
	// Prepare to update css and svg (and do it)
	window.onresize = function() {update_csssvg()}
	update_csssvg()
}
