var thebody = false;
var player = false;
var lang = false;

var DEF_VAL = false;
var isSafari = ((parseInt(navigator.productSub)>=20020000) && (navigator.vendor.indexOf('Apple Computer')!=-1));

var camfresh = thefresh = camtime = false;

function addEvent(obj, evType, fn, useCapture) {
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		//alert("Handler could not be attached");
	}
}

function removeEvent(obj, evType, fn, useCapture) {
	if (obj.removeEventListener) {
		obj.removeEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.detachEvent) {
		var r = obj.detachEvent("on"+evType, fn);
		return r;
	} else {
		//alert("Handler could not be removed");
	}
}

function replaceSearchField()
{
	if (!document.getElementById)
		return;
	var searchForm = document.getElementById('sq');
	var searchField = document.getElementById('query');
	var searchLabel = searchForm.getElementsByTagName('label')[0];
	var searchButton = searchForm.getElementsByTagName('input')[1];
	if (isSafari) {
		searchField.setAttribute('type', 'search');
		searchField.setAttribute('autosave', 'de.fh-rosenheim.solar-decathlon.suche');
		searchField.setAttribute('results', '5');
		searchField.setAttribute('placeholder', DEF_VAL);
		searchLabel.style.display = 'none';
		searchField.setAttribute('class', 'saf');
		searchButton.style.display = 'none';
	}else{
		searchField.style.color = '#777';
		addEvent(searchField, 'focus', focusSearch, false);
		addEvent(searchField, 'blur',	blurSearch, false);
		if (searchField.value=='') searchField.value = DEF_VAL;
	}
	if(searchForm.className == 's') searchField.focus();
}

function focusSearch() {
	if (this.value==DEF_VAL) {
		this.value = '';
		this.setAttribute('class', 'focus');
	}
}

function blurSearch() {
	if (this.value=='') {
		this.value = DEF_VAL;
		this.removeAttribute('class', 'focus');
	}
}

function xmlhttpPost(strURL, what, callback) {
	var xmlHttpReq = false;
	var self = this;
	if (window.XMLHttpRequest) {
		self.xmlHttpReq = new XMLHttpRequest();
	}
	else if (window.ActiveXObject) {
		self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	self.xmlHttpReq.open('POST', strURL, true);
	self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	self.xmlHttpReq.onreadystatechange = function() {
		if (self.xmlHttpReq.readyState == 4) {
			if(!callback) updatepage(self.xmlHttpReq.responseText);
		}
	}
	self.xmlHttpReq.send(what);
}

function addPlayer() {
	document.getElementById('audiohelp').className = 'hidden';
	var theendiv = document.getElementsByTagName('div')[2];
	theendiv.appendChild(player);
}

function updatepage(str) {
	if(!player) {
		player = document.createElement('embed');
		player.id = 'txt2speech';
		player.src = str;
		player.setAttribute('loop', 'false');
		player.setAttribute('autostart', 'true');
		player.setAttribute('controls', 'console');
		setTimeout('addPlayer();', 1500);
	}
}

function getquerystring() {
	var file = 'solar-start-en3';
	var thetxtfield1 = document.getElementsByTagName('h3')[2];
	var thetxtfield1str = thetxtfield1.getElementsByTagName('em')[0].firstChild.nodeValue;
	thetxtfield1str += ' Projekt Solar Decathlon, ' + thetxtfield1.getElementsByTagName('span')[0].firstChild.nodeValue;
	var thetxtfield = document.getElementsByTagName('blockquote')[2];
	var txt = thetxtfield1str + '. ' + thetxtfield.firstChild.nodeValue;
	var qstr = 'file=' + escape(file) + '&txt=' + escape(txt);
	return qstr;
}

function externalLinks() {
	var links = thebody.getElementsByTagName('a');
	var linknum = links.length;
	switch(lang) {
		case 'de':
			var pdflangstr = 'Laden Sie ';
			break;
		case 'es':
			var pdflangstr = 'Descargar ';
			break;
		case 'en':
			var pdflangstr = 'Download ';
			break;
	}
	for(var i = 0; i <linknum; i++) {
		var thelink = links[i];
		if(thelink.rel && thelink.rel == 'nofollow') {
			thelink.target = '_blank';
		}
		if(thelink.href && thelink.href.substr(-4) == '.pdf') {
			//thelink.title = 'Adobe Reader Document';
			var pdflink = document.createElement('a');
			var pdflinkspan = document.createElement('span');
			var pdflinkstr = document.createTextNode(pdflangstr + 'Adobe Acrobat Reader');
			pdflink.rel = thelink.href;
			pdflink.className = 'pdf';
			pdflink.href = 'http://get.adobe.com/reader/';
			pdflink.target = '_blank';
			pdflinkspan.appendChild(pdflinkstr);
			pdflink.appendChild(pdflinkspan);
			thelink.parentNode.appendChild(pdflink);
		}
	}
}

function handleMenu() {
	sel = false;
	if(sel = document.getElementById('pm')) {
		var xseli = sel.getElementsByTagName('strong');
		if(xseli.length > 0) var seli = xseli[0];
		else return;
		var selp = seli.parentNode.parentNode;
		do {
			if(selp.tagName) {
				if(selp.tagName.toLowerCase() == 'ul' && selp.className.toLowerCase() == 'h') {
					selp.className = '';
				}
				if(selp.tagName.toLowerCase() == 'li') {
					selp.className = 's';
				}
			}
			selp = selp.parentNode;
		} while (selp);
		var selc = seli.parentNode.getElementsByTagName('ul');
		if(selc.length > 0) selc[0].className = '';
	}
}

function isIE() {
	return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

function txt2speech() {
	var thedivs = document.getElementsByTagName('div');
	if(!thedivs[2]) return false;
	var theendiv = thedivs[2];
	var thelink = document.createElement('a');
	thelink.id = 'audiohelp';
	var thelinkstr = document.createTextNode('get this text read to you');
	thelink.appendChild(thelinkstr);
	theendiv.appendChild(thelink);
	thelink.onclick = function() {
		xmlhttpPost('/api/txt2speech.api.php', getquerystring(), false);
	}
}

var allimgs = false;
var allimgtags = [];
var selimg = false;
var thegallery = false;
var imgnum = 0;

function imgView(elm, gmode) {
	if(!elm) return false;
	if(elm.tagName != 'img') {
		if(elm.tagName == 'a' && selimg) {
			var theimgid = parseInt(selimg.rel);
			var theimg = (elm.className == 'prev' ? allimgtags[theimgid-1] : allimgtags[theimgid+1]);
			return imgView(theimg, true);
		}
		if(elm.tagName == 'p') elm = elm.parentNode.getElementsByTagName('img')[0];
		if(elm.tagName == 'em') elm = elm.parentNode.parentNode.getElementsByTagName('img')[0];
	}else{
		thegallery.className = '';
	}
	if(elm.parentNode.className == 'f') elm = elm.parentNode.parentNode.getElementsByTagName('img')[0];
	if(selimg && selimg == elm) {
		selimg.parentNode.parentNode.className = '';
		selimg = false;
		return false;
	}
	if(selimg) {
		selimg.parentNode.parentNode.className = (selimg.parentNode.parentNode.className == 'h s' ? 'h' : '');
	}
	selimg = elm;
	var selli = selimg.parentNode.parentNode;
	if(!selli.rel) {
		selli.rel = selimg.getAttribute('longdesc');
		var timgp = document.createElement('p');
		var timgpdesc = document.createElement('em');
		timgpdesc.appendChild(document.createTextNode(selimg.alt));
		timgp.appendChild(timgpdesc);
		timgp.className = 'f';
		var timg = document.createElement('img');
		timg.src = selli.rel;
		if(selimg.rel > 0) {
			var prevLink = document.createElement('a');
			switch(lang) {
				case 'de':
					var prevstr = 'vorheriges';
					break;
				case 'es':
					var prevstr = 'previo';
					break;
				case 'en':
					var prevstr = 'prev';
					break;
			}
			prevLink.appendChild(document.createTextNode(prevstr));
			prevLink.className = 'prev';
			timgp.appendChild(prevLink);
		}
		if(selimg.rel < imgnum-1) {
			var nextLink = document.createElement('a');
			switch(lang) {
				case 'de':
					var nextstr = 'nächstes';
					break;
				case 'es':
					var nextstr = 'próximo';
					break;
				case 'en':
					var nextstr = 'next';
					break;
			}
			nextLink.appendChild(document.createTextNode(nextstr));
			nextLink.className = 'next';
			timgp.appendChild(nextLink);
		}

		timgp.appendChild(timg);
		selli.appendChild(timgp);
	}else{
		var timgp = selli.getElementsByTagName('p')[2];
	}
	selli.className = (selli.className && selli.className == 'h' ? 'h s' : 's');

	return false;
}

function makeGallery() {
	if(thegallery = document.getElementById('g')) {
		thegallery.onclick = function(e) {
			imgView(e.target);
		}
		allimgs = thegallery.getElementsByTagName('img');
		imgnum = allimgs.length;
		for(i = 0; i < imgnum; i++) {
			allimgtags[i] = allimgs[i];
			allimgs[i].style.opacity = .8;
			allimgs[i].rel = i;
			if(allimgs[i].offsetHeight > allimgs[i].offsetWidth) allimgs[i].parentNode.parentNode.className = 'h';
			var oImage = new Image;
			oImage.src = allimgs[i].getAttribute('longdesc');
			oImage.rel = i;
			oImage.onload = function() {
				allimgs[this.rel].style.opacity = 1;
			}
		}
	}
}

/*
function webCam() {
	if(theimg = document.getElementById('cam')) {
		if(!camfresh) {
			if(!(thefresh = document.getElementById('fresh'))) return false;
			thefresh.onchange = function() {
				window.clearTimeout(camtime);
				webCam();
			}
		}
		theimg.onclick = function() {
			theimg.className = theimg.className == 'f' ? '' : 'f';
		}
		camfresh = thefresh.value;
		theimg.src = '/medien/webcam/latest.png?' + new Date();
		camtime = window.setTimeout('webCam()', camfresh*1000);
	}
}
*/

var selcam = false;

function switchCam(what) {
	switch(what) {
		case 'back': camurl = 'http://82.144.4.126:5003/mjpg/video.mjpg'; break;
//		case 'split': camurl = 'http://82.144.4.126:5003/mjpg/video.mjpg'; break;
		default: camurl = 'http://82.144.4.126:5004/mjpg/video.mjpg';
	}
	var theimg = document.getElementById('camstream');
	theimg.src = camurl;
}
function webCam() {
	if(theimg = document.getElementById('camstream')) {
		var camcontainer = theimg.parentNode;
		switch(lang) {
			case 'de':
				var frontcamstr = 'Eingangsbereich';
				var backcamstr = 'Veranda';
//				var splitviewstr = 'Beide Kameras';
				break;
			case 'es':
				var frontcamstr = 'Entrada';
				var backcamstr = 'Veranda';
//				var splitviewstr = 'Todas las cámaras';
				break;
			case 'en':
				var frontcamstr = 'Entry area';
				var backcamstr = 'Deck view';
//				var splitviewstr = 'Split view';
				break;
		}
		var camswitch = document.createElement('a');
		camswitch.appendChild(document.createTextNode(frontcamstr));
		var camswitch2 = document.createElement('a');
		camswitch2.appendChild(document.createTextNode(backcamstr));
//		var camswitch3 = document.createElement('a');
//		camswitch3.appendChild(document.createTextNode(splitviewstr));
		camcontainer.appendChild(camswitch);
		camcontainer.appendChild(camswitch2);
//		camcontainer.appendChild(camswitch3);
		camswitch.onclick = function() {
			if(selcam) selcam.className = '';
			this.className = 's';
			selcam = this;
			switchCam('front');
		}
		camswitch2.onclick = function() {
			if(selcam) selcam.className = '';
			this.className = 's';
			selcam = this;
			switchCam('back');
		}
/*
		camswitch3.onclick = function() {
			if(selcam) selcam.className = '';
			this.className = 's';
			selcam = this;
			switchCam('split');
		}
*/
		switchCam('front');
		selcam = camswitch;
		selcam.className = 's';
	}
}

function addSocial() {
	var sul = document.createElement('ul');
	sul.id = 'si';
	var platforms = new Array(
		'Digg',
		'flickr',
		'reddit',
		'YouTube',
		'del.icio.us',
		'twitter',
		'facebook'
		);
	var platformicons = new Array(
		'digg',
		'flickr',
		'reddit',
		'youtube',
		'delicious',
		'twitter',
		'facebook'
		);
	var platformunames = new Array(
		'SolarDecathlon',
		'SolarDecathlon',
		'SolarDecathlon',
		'SolarDecathlon2010',
		'solar.decathlon',
		'SolarDecathlon',
		'Solar Decathlon'
		);
	var platformlinks = new Array(
		'http://digg.com/users/SolarDecathlon',
		'http://www.flickr.com/photos/solar-decathlon/',
		'http://www.reddit.com/user/SolarDecathlon/',
		'http://www.youtube.com/SolarDecathlon2010',
		'http://delicious.com/solar.decathlon',
		'http://twitter.com/SolarDecathlon',
		'http://www.facebook.com/solar.decathlon'
		);
	for(i = 0; i < platforms.length; i++) {
		var asli = document.createElement('li');
		asli.className = platformicons[i];
		var aslink = document.createElement('a');
		var aslinksp = document.createElement('span');
		switch(lang) {
			case 'de':
				if(platforms[i] == 'twitter') {
					platformunames[i] += 'D';
					platformlinks[i] += 'D';
				}
				aslinksp.appendChild(document.createTextNode('besuchen Sie ' + platformunames[i] + ' auf ' + platforms[i]));
				break;
			case 'es':
				if(platforms[i] == 'twitter') {
					platformunames[i] += 'E';
					platformlinks[i] += 'E';
				}
				aslinksp.appendChild(document.createTextNode('visita ' + platformunames[i] + ' en ' + platforms[i]));
				break;
			case 'en':
				aslinksp.appendChild(document.createTextNode('see ' + platformunames[i] + ' on ' + platforms[i]));
				break;
		}
		aslink.href = platformlinks[i];
		aslink.rel = 'nofollow';
		aslink.target = '_blank';
		aslink.appendChild(aslinksp);
		asli.appendChild(aslink);
		sul.appendChild(asli);
	}
	thebody.appendChild(sul);
}

function init() {
	thebody = document.getElementsByTagName('body')[0];
	var thehtml = document.getElementsByTagName('html')[0];
	lang = thehtml.getAttribute('lang');
	if(!lang) lang = thehtml.getAttribute('xml:lang');
	switch(lang) {
		case 'de':
			DEF_VAL = 'Suche auf der Seite...';
			break;
		case 'es':
			DEF_VAL = 'Búsqueda en la página...';
			break;
		case 'en':
			DEF_VAL = 'Search on this site...';
			break;
	}
	replaceSearchField();
	handleMenu();
	externalLinks();
	makeGallery();
	addSocial();
	webCam();
//	txt2speech();
}

addEvent(window, 'load', init, false);
