/* ------------------------------------------------------------------------------------------------------------------
 roberthilbe.com Basic Javascripts
 Author:   Robert Hilbe
 Version:  26 December 2006
--------------------------------------------------------------------------------------------------------------------- */

// prepareInputs: select default text in input fields onfocus ------------------------------------------------------- //

function prepareInputs() {
	if (!document.getElementsByTagName) return false;
	var inputs = document.getElementsByTagName('input');
	
	for (var i = 0; input = inputs[i]; i++) {
		if (input.type == 'text') {
			input.defaultValue = input.value;
			input.onfocus = function() {
				if (this.value == this.defaultValue)
					this.select();
			}
			input.onblur = function() {
				if (this.value == '')
					this.value = this.defaultValue;
			}
		}
	}
}

// slideElement: Slides an Element by (x) and (y), (inc) defines Speed ---------------------------------------------- //

// from http://adactio.com

function slideElement(elementId, x, y, inc) {
	if (!document.getElementById) return false;
	if (!document.getElementById(elementId)) return false;
	
	var element = document.getElementById(elementId);
	if (element.sliding) clearTimeout(element.sliding);
	
	if (!element.xpos)
		element.xpos = 0;
	if (!element.ypos)
		element.ypos = 0;
	
	if (element.xpos == x && element.ypos == y) return true;
	
	if (element.xpos > x) {
		var dist = Math.ceil((element.xpos-x)/inc);
		element.xpos = element.xpos - dist;
	}
	if (element.xpos < x) {
		var dist = Math.ceil((x-element.xpos)/inc);
		element.xpos = element.xpos + dist;
	}
	if (element.ypos > y) {
		var dist = Math.ceil((element.ypos-y)/inc);
		element.ypos = element.ypos - dist;
	}
	if (element.ypos < y) {
		var dist = Math.ceil((y-element.ypos)/inc);
		element.ypos = element.ypos + dist;
	}
	element.style.left = element.xpos+'px';
	element.style.top = element.ypos+'px';
	element.sliding = setTimeout('slideElement("'+elementId+'",'+x+','+y+','+inc+')',10);
}

// googleSearchHighlight: Highlights Searched Words ----------------------------------------------------------------- //

/*
from http://www.kryogenix.org/code/browser/searchhi/
define .searchword in CSS
*/

function highlightWord(node, word) {
	if (node.hasChildNodes) {
		var hi_cn;
		for (hi_cn = 0; hi_cn < node.childNodes.length; hi_cn++) {
			highlightWord(node.childNodes[hi_cn], word);
		}
	}
	if (node.nodeType == 3) {
		tempNodeVal = node.nodeValue.toLowerCase();
		tempWordVal = word.toLowerCase();
		if (tempNodeVal.indexOf(tempWordVal) != -1) {
			pn = node.parentNode;
			if (pn.className != 'searchword') {
				nv = node.nodeValue;
				ni = tempNodeVal.indexOf(tempWordVal);
				before = document.createTextNode(nv.substr(0,ni));
				docWordVal = nv.substr(ni,word.length);
				after = document.createTextNode(nv.substr(ni+word.length));
				hiwordtext = document.createTextNode(docWordVal);
				hiword = document.createElement('span');
				hiword.className = 'searchword';
				hiword.appendChild(hiwordtext);
				pn.insertBefore(before,node);
				pn.insertBefore(hiword,node);
				pn.insertBefore(after,node);
				pn.removeChild(node);
			}
		}
	}
}

function googleSearchHighlight() {
	if (!document.createElement) return;
	ref = document.referrer;
	if (ref.indexOf('?') == -1) return;
	qs = ref.substr(ref.indexOf('?')+1);
	qsa = qs.split('&');
	for (i=0;i<qsa.length;i++) {
		qsip = qsa[i].split('=');
		if (qsip.length == 1) continue;
		if (qsip[0] == 'q' || qsip[0] == 'p') {
			words = unescape(qsip[1].replace(/\+/g,' ')).split(/\s+/);
			for (w = 0; w < words.length; w++) {
				highlightWord(document.getElementsByTagName('body')[0], words[w]);
			}
		}
	}
}

// Fadomatic: Fads Elements in or out ------------------------------------------------------------------------------- //

// from http://chimpen.com/fadomatic/

Fadomatic.INTERVAL_MILLIS = 50; // fade interval in milliseconds (make this larger if you experience performance issues)

// creates a fader
function Fadomatic (element, rate, initialOpacity, minOpacity, maxOpacity) {
	this._element = element;
	this._intervalId = null;
	this._rate = rate;
	this._isFadeOut = true;
	this._minOpacity = 0;
	this._maxOpacity = 99;
	this._opacity = 99;

	if (typeof minOpacity != 'undefined') {
		if (minOpacity < 0) {
			this._minOpacity = 0;
		} else if (minOpacity > 99) {
			this._minOpacity = 99;
		} else {
			this._minOpacity = minOpacity;
		}
	}

	if (typeof maxOpacity != 'undefined') {
		if (maxOpacity < 0) {
			this._maxOpacity = 0;
		} else if (maxOpacity > 99) {
			this._maxOpacity = 99;
		} else {
			this._maxOpacity = maxOpacity;
		}

		if (this._maxOpacity < this._minOpacity) {
			this._maxOpacity = this._minOpacity;
		}
	}

	if (typeof initialOpacity != 'undefined') {
		if (initialOpacity > this._maxOpacity) {
			this._opacity = this._maxOpacity;
		} else if (initialOpacity < this._minOpacity) {
			this._opacity = this._minOpacity;
		} else {
			this._opacity = initialOpacity;
		}
	}
	
	if(typeof element.style.opacity != 'undefined') {
		this._updateOpacity = this._updateOpacityW3c;
	} else if(typeof element.style.filter != 'undefined') {
		var existingFilters="";
		if (element.style.filter) {
			existingFilters = element.style.filter+" ";
		}
		element.style.filter = existingFilters+"alpha(opacity="+this._opacity+")";
		this._updateOpacity = this._updateOpacityMSIE;
	} else {
		this._updateOpacity = this._updateVisibility;
	}
	this._updateOpacity();
}

// starts fading out
Fadomatic.prototype.fadeOut = function () {
	this._isFadeOut = true;
	this._beginFade();
}

// starts fading in
Fadomatic.prototype.fadeIn = function () {
	this._isFadeOut = false;
	this._beginFade();
}

// sets opacity to max
Fadomatic.prototype.makeVisible = function () {
	this.haltFade();
	this._opacity = this._maxOpacity;
	this._updateOpacity();
}

// sets opacity to min
Fadomatic.prototype.makeTransparent = function () {
	this.haltFade();
	this._opacity = 0;
	this._updateOpacity();
}

Fadomatic.prototype.haltFade = function () {
	clearInterval(this._intervalId);
}

Fadomatic.prototype.resumeFade = function () {
	this._beginFade();
}

Fadomatic.prototype._beginFade = function () {
	this.haltFade();
	var objref = this;
	this._intervalId = setInterval(function() { objref._tickFade(); },Fadomatic.INTERVAL_MILLIS);
}

Fadomatic.prototype._tickFade = function () {
	if (this._isFadeOut) {
		this._opacity -= this._rate;
		if (this._opacity < this._minOpacity) {
			this._opacity = this._minOpacity;
			this.haltFade();
		}
	} else {
		this._opacity += this._rate;
		if (this._opacity > this._maxOpacity ) {
			this._opacity = this._maxOpacity;
			this.haltFade();
		}
	}
	this._updateOpacity();
}

Fadomatic.prototype._updateVisibility = function () {
	if (this._opacity > 0) {
		this._element.style.visibility = 'visible';
	} else {
		this._element.style.visibility = 'hidden';
	}
}

Fadomatic.prototype._updateOpacityW3c = function () {
	this._element.style.opacity = this._opacity/100;
	this._updateVisibility();
}

Fadomatic.prototype._updateOpacityMSIE = function () {
	this._element.filters.alpha.opacity = this._opacity;
	this._updateVisibility();
}

Fadomatic.prototype._updateOpacity = null;

// keyboard shortcuts: use the same shortcuts as accesskeys ---------------------------------------------------------- //

if(document.captureEvents) {
    
    // non IE (NS 4, NS 6+, Mozilla 0.9+)
    if(Event.KEYUP) {
    	document.captureEvents(Event.KEYUP);
    }
}

// when a key is pressed, run the alertkey function
document.onkeyup = alertkey;

// process the event

function alertkey(e) {
    
	if(!e) {
		if(window.event) e = window.event;
		else return;
	}
    
    // check, if focus is on input element and stop if so
    
	if(document.all) target = e.srcElement;
	else target = e.target;
	if(target.tagName == 'TEXTAREA' || target.tagName == 'INPUT' || e.ctrlKey || e.altKey || e.shiftKey) return;
    
    if(typeof(e.which) == 'number') {
        
        //NS 4, NS 6+, Mozilla 0.9+, Opera
        e = e.which;
        
    } else if(typeof(e.keyCode) == 'number') {
        
        //IE, NS 6+, Mozilla 0.9+
        e = e.keyCode;
        
    } else if(typeof(e.charCode) == 'number') {
        
        //also NS 6+, Mozilla 0.9+
        e = e.charCode;
        
    } else return;
 		
	// h: Homepage
	if (e == 72) location.href = "/";

	// l: Log
	if (e == 76) location.href = "/log/";

	// p: Portfolio
	if (e == 80) location.href = "/portfolio/";

	// f: Fotos
	if (e == 70) location.href = "/fotos/";

	// u: Ueber mich
	if (e == 85) location.href = "/uebermich/";

	// i: Links
	if (e == 73) location.href = "/links/";
	
	// s: Suche
	if (e == 83) {
		if (document.getElementById('livesearch')) {
			document.getElementById('livesearch').focus();
			setTimeout("document.getElementById('livesearch').value=''",50);
			setTimeout("document.getElementById('livesearch').value='Suchbegriff eingeben'",50);
			setTimeout("document.getElementById('livesearch').select();",50);
		}
	}
	
	/* arrows: Atriclenav
	if (document.getElementById('articlenav')) {
		
		// left arrow
		if (e == 37) {
			if (document.getElementById('articlenav').childNodes[1].className == 'previous') {
				location.href = document.getElementById('articlenav').childNodes[1].childNodes[1].attributes[0].nodeValue;
			}
		}
		
		// right arrow
		else if (e == 39) {
			if (document.getElementById('articlenav').childNodes.length > 3 && document.getElementById('articlenav').childNodes[3].className == 'next') {
				location.href = document.getElementById('articlenav').childNodes[3].childNodes[1].attributes[0].nodeValue;
			} else if (document.getElementById('articlenav').childNodes[1].childNodes[1].className == 'next') {
				location.href = document.getElementById('articlenav').childNodes[1].childNodes[1].attributes[0].nodeValue;
			}
		}
	}
*/
}

// live search ------------------------------------------------------------------------------------------------------ //

/*
from http://www.wilshireone.com

+----------------------------------------------------------------------+
| Copyright (c) 2004 Bitflux GmbH                                      |
+----------------------------------------------------------------------+
| Licensed under the Apache License, Version 2.0 (the "License");      |
| you may not use this file except in compliance with the License.     |
| You may obtain a copy of the License at                              |
| http://www.apache.org/licenses/LICENSE-2.0                           |
| Unless required by applicable law or agreed to in writing, software  |
| distributed under the License is distributed on an "AS IS" BASIS,    |
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or      |
| implied. See the License for the specific language governing         |
| permissions and limitations under the License.                       |
+----------------------------------------------------------------------+
| Author: Bitflux GmbH <devel@bitflux.ch>                              |
+----------------------------------------------------------------------+
*/

var liveSearchReq = false;
var t = null;
var liveSearchLast = "";
var isIE = false;
// on !IE we only have to initialize it once
if (window.XMLHttpRequest) {
	liveSearchReq = new XMLHttpRequest();
	newMastheadReq = new XMLHttpRequest();
}
function liveSearchInit() {

	// Turns off autocomplete on the input element
	var searchInput = document.getElementById('livesearch');
	if( searchInput == null ) return;
	searchInput.setAttribute('autocomplete', 'off');

	if (navigator.userAgent.indexOf("Safari") > 0) {
		document.getElementById('livesearch').addEventListener("keydown",liveSearchKeyPress,false);
	} else if (navigator.product == "Gecko") {
		document.getElementById('livesearch').addEventListener("keypress",liveSearchKeyPress,false);
	} else {
		document.getElementById('livesearch').attachEvent('onkeydown',liveSearchKeyPress);
		isIE = true;
	}
}
function liveSearchKeyPress(event) {
	if (event.keyCode == 40 )
	//KEY DOWN
	{
		highlight = document.getElementById("LSHighlight");
		if (!highlight) {
			try {
			highlight = document.getElementById("LSRes").firstChild;
			} catch (exception) { }
		} else {
			highlight.removeAttribute("id");
			highlight = highlight.nextSibling;
		}
		if (highlight) {
			highlight.setAttribute("id","LSHighlight");
		}
		if (!isIE) { event.preventDefault(); }
	}
	//KEY UP
	else if (event.keyCode == 38 ) {
		highlight = document.getElementById("LSHighlight");
		if (!highlight) {
			try {
			highlight = document.getElementById("LSRes").lastChild;
			} catch (exception) {}
		}
		else {
			highlight.removeAttribute("id");
			highlight = highlight.previousSibling;
		}
		if (highlight) {
				highlight.setAttribute("id","LSHighlight");
		}
		if (!isIE) { event.preventDefault(); }
	}
	//ESC
	else if (event.keyCode == 27) {
		highlight = document.getElementById("LSHighlight");
		if (highlight) {
			highlight.removeAttribute("id");
		}
		document.getElementById("LSResult").style.display = "none";
		document.forms.searchform.q.value = '';
	}
	//ENTER
	else if (event.keyCode == 13) {
		liveSearchSubmit();
	}

}
function closeLiveSearch() {
	highlight = document.getElementById("LSHighlight");
	if (highlight) {
		highlight.removeAttribute("id");
	}
	document.getElementById("LSResult").style.display = "none";
	document.forms.searchform.q.value = '';
}
function liveSearchStart() {
	if (t) { window.clearTimeout(t); }
	t = window.setTimeout("liveSearchDoSearch()",200);
}
function liveSearchDoSearch() {
	if (liveSearchLast != document.forms.searchform.q.value) {
	if (liveSearchReq && liveSearchReq.readyState < 4) {
		liveSearchReq.abort();
	}
	if ( searchTrimAll(document.forms.searchform.q.value) == "") {
		document.getElementById("LSResult").style.display = "none";
		highlight = document.getElementById("LSHighlight");
		if (highlight) {
			highlight.removeAttribute("id");
		}
		return false;
	}
	if (window.XMLHttpRequest) {
	// branch for IE/Windows ActiveX version
	} else if (window.ActiveXObject) {
		liveSearchReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	// Show loading with css, RH 06-01-12
	document.getElementById('livesearch').className = 'loading';
	liveSearchReq.onreadystatechange= liveSearchProcessReqChange;
	liveSearchReq.open("GET", "?ls=" + document.forms.searchform.q.value);
	liveSearchLast = document.forms.searchform.q.value;
	liveSearchReq.send(null);
	}
}
function liveSearchProcessReqChange() {
	if (liveSearchReq.readyState == 4) {
		var res = document.getElementById("LSResult");
		res.style.display = "block";
		res.firstChild.innerHTML = '<div id="LSHeader"><div style="float:right;"><a href="#" title="[Esc]" onclick="closeLiveSearch(); return false">Resultate schliessen</a></div><br /></div>'+liveSearchReq.responseText;
		
		// Hide loading with css, RH 06-01-12
		document.getElementById('livesearch').className = '';
	}
}
function liveSearchSubmit() {
	var highlight = document.getElementById("LSHighlight");
	if (highlight && highlight.firstChild) {
		window.location = highlight.firstChild.getAttribute("href");
		return false;
	} else {
		var searchInput = document.getElementById('searchform');
	  searchInput.submit();
		return false;
	}
}

function liveSearchByContext(thelink,theText) {
var searchTerm = theText;
	if (liveSearchLast != searchTerm) {
	if (liveSearchReq && liveSearchReq.readyState < 4) {
		liveSearchReq.abort();
	}

	if (window.XMLHttpRequest) {
	// branch for IE/Windows ActiveX version
	} else if (window.ActiveXObject) {
		liveSearchReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	liveSearchReq.onreadystatechange=function() {
	if (liveSearchReq.readyState == 4) {
		var newDiv = document.createElement('div');
		newDiv.id = 'liveLinkRes';
		newDiv.style.display = 'none';
		newDiv.innerHTML = '<div id="liveLinkHead"><div style="float:left;">&nbsp;</div><div style="float:right;"><a href="#" title="Close results" onclick="closeLiveLink(); return false">[x]</a></div><br /></div>'+liveSearchReq.responseText;//;
		newDiv.style.display = 'block';

		myRes=document.getElementById(theText+"-livelink");
		myRes.appendChild(newDiv);
		myBlank=document.createTextNode("");
		myRes.insertBefore(myBlank,newDiv);
	}
 }
	liveSearchReq.open("GET", "?ls=" + searchTerm);
	liveSearchLast = searchTerm;
	liveSearchReq.send(null);
	} else {
		closeLiveLink();
	}
}

function searchTrimAll(sString) {
	while (sString.substring(0,1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ') {
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function closeLiveLink() {
	liveSearchLast = "";
	highlight = document.getElementById("LSHighlight");
	if (highlight) {
		highlight.removeAttribute("id");
	}
	document.getElementById("liveLinkRes").style.display = "none";
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

// onloadStarter: kicks on functions -------------------------------------------------------------------------------- //

function onloadStarter() {
	liveSearchInit();
	prepareInputs();
	googleSearchHighlight();
	
	// check for foto and fade in
	if (document.getElementById('foto')) {
		var foto = document.getElementById('foto');
		fader = new Fadomatic(foto, 3, 0);
		fader.fadeIn();
	}
}

window.onload = onloadStarter;