/*
 * freshlabs journal universal JavaScript
 * modified: 19/10/2006
 */
 
var siteURL = "http://www.freshlabs.de/journal";


/*
 * onload event function
 * ABC Boot Loader Simon: http://simon.incutio.com/archive/2004/05/26/addLoadEvent
 */

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

/*
 * Collapsibles
 */
var Collapsible = Class.create();

Collapsible.prototype = {
	handle : Object,
	trigger : Object,
	container : Object,
	
	initialize : function(h,c){
		this.handle = $(h);
		this.container = $(c);
		
		// attach trigger to handle
		var t = document.createElement('a');
		t.href = 'javascript:void(0)';
		t.className = 'clp-trigger';
		t.appendChild(document.createTextNode('Hide'));
		t.onclick = this.toggle;
		this.handle.appendChild(t);
		this.trigger = t;
	},
	
	toggle : function(){
		el = this.parentNode.nextSibling.nextSibling;
		if(hasClass(el, 'collapsed')){ 
			el.className = 'clp-container uncollapsed';
			this.innerHTML = "Hide";
			new Effect.ScrollTo(this);
		}
		else
		if(el.className == 'clp-container uncollapsed'){
			el.className = 'clp-container collapsed';
			this.innerHTML = "Show";
		}
	}
}


var Collapsibles = {
	
	init : function(){
		this.boxes = document.getElementsByClassName('clp-box');
		for(i=0; i<this.boxes.length; i++){
			var handle;
			var target;
			$A(this.boxes[i].childNodes).each(function(child){
				if(child.className != undefined && child.className == 'clp-handle')
					handle = child;
				else if(child.className != undefined && child.className.indexOf('clp-container') != -1)
					target = child;
			});
			clp = new Collapsible(handle, target);
		};
		return this;
	}
}

// ## LoadingMessage
// ## Version: 0.6
// ## Author: Tim Isenheim - http://blog.freshlabs.de 

var LoadingMessage = {
	imageURL : siteURL + '/wp-content/scripts/ajax-loader.gif',
	waitImg : null,
	containerId : "loading-message",
	loadTextId : "loading-text",
	waitImgId : "loading-image",
	waitImgWidth : 16,
	waitImgHeight : 16,
	
	init : function(){
		this.waitImg = document.createElement('img');
		this.waitImg.setAttribute('src', this.imageURL);
		this.waitImg.setAttribute('height', this.waitImgHeight);
		this.waitImg.setAttribute('width', this.waitImgWidth);
		this.waitImg.setAttribute('alt','loading...');
		this.waitImg.id = this.waitImgId;
		this.waitImg.style.border = '0';
		this.waitImg.style.backgroundColor = 'transparent';
		this.waitImg.style.margin = '0';
		this.waitImg.style.padding = '0';
	},
	
	append : function(where){
		var parent = $(where);
		var loadbox;
		if(!$(this.containerId)){
			loadbox = document.createElement('div');
			var loadtext = document.createElement('div')
			loadbox.id = this.containerId;
			loadtext.id = this.loadTextId;
			txt = document.createTextNode(" loading");
			loadtext.appendChild(this.waitImg);
			loadtext.appendChild(txt);
			loadbox.appendChild(loadtext);
		}
		else loadbox = $(this.containerId);
		loadbox.style.display = "none";
		new Effect.Appear(loadbox, { to: 0.7, queue: 'end' });
		parent.appendChild(loadbox);
	},
	
	remove : function(){
		new Effect.Fade(this.containerId, {duration: 0.25, queue: 'end' });
		//removeElementById(this.containerId);
	}
} // .LoadingMessage ---------------------


/* ----------------------------------
 * PNG FIX
 * ----------------------------------
 */ 

if (navigator.platform == "Win32" && navigator.appName == "Microsoft Internet Explorer" && window.attachEvent) {
/*window.attachEvent("onload", alphaBackgrounds);*/
}

function alphaBackgrounds(){
	var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
	var itsAllGood = (rslt != null && Number(rslt[1]) >= 5.5);
	for (i=0; i < document.all.length; i++){
		var bg = document.all[i].currentStyle.backgroundImage;
		if (itsAllGood && bg){
			if (bg.match(/\.png/i) != null){
			var mypng = bg.substring(5,bg.length-2);
			document.all[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+mypng+"', sizingMethod=&#39;scale&#39;)";
			document.all[i].style.backgroundImage = "url(&#39;http://www.freshlabs.de/inc/images/transparent.gif&#39;)";
			}
		}
	}
}
	
/* ----------------------------------
 * fixFormLabels - make labels clickable in IE and Safari
 * ----------------------------------
 */

function fixFormLabels(){
	// IE and Safari only
	var isIE = false;
	var isSafari = false;
	var labels;
	
	// User agent filtering
	if(document.all){ isIE = true; }
	if (navigator.userAgent.indexOf("Safari") > 0){ isSafari = true;}
	
	if(isIE || isSafari){
		labels = document.getElementsByTagName("label");
		for(i=0; i<labels.length; i++){
			labels[i].onclick = function(){ 
				var target = document.getElementById(this.getAttribute('for'));
				// Checkboxes or radio button labels
				if(target.type == 'checkbox' || target.type == 'radio')
					target.checked = target.checked == false ? true : false;
				else
				// Textareas and input fields
				if(target.type.indexOf('text') >= 0)
					target.focus();
			};
		}
	}
}


// replace Image
function replaceImage(id, src){
  var img = document.getElementById(id);
  var i = img.cloneNode(true);
  i.setAttribute("src", src);
  var parent = img.parentNode;
  parent.replaceChild(i, img);
  return false;
}

// swap Array items

function swap(array,i,j){
	var tmp = array[i];
	array[i] = array[i+1];
	array[i+1] = tmp;
}


/*------------------------------------------------*/
/*                              Ajaxcontainer     */
/* dropdown container with Ajax-loaded content    */
/*------------------------------------------------*/


function loadAjaxContentXML(url,params){
	var myAjax = new Ajax.Request(url,	{method: 'get', parameters: params, onComplete: showAjaxResponse});
}

function showAjaxResponse(originalRequest){
	$('result').value = originalRequest.responseText;
}


function loadAjaxContentHTML(target,url,params)
{	
	var contentAjax = new Ajax.Updater(target, url, {method: 'get', parameters: params});
	return contentAjax;
}


// ( event listener )
// by Scott Andrew - http://scottandrew.com
// -------------------------------------------------
function addEvent(obj, evType, fn)
	{
	if (obj.addEventListener)
		{
		obj.addEventListener(evType, fn, false); 
		return true;
		}
	else if (obj.attachEvent)
		{
		var r = obj.attachEvent('on'+evType, fn);
		return r;
		}
	else
		{
		return false;
		}
	}


// event listeners eventually to replace the one above
function addEventToObject(obj, evt, func)
	{
	var oldhandler = obj[evt];
	if (typeof obj[evt] != 'function')
		{
		obj[evt] = func;
		}
	else
		{
		obj[evt] = function()
			{
			oldhandler();
			func();
			}
		}
	}
	
// get form/label associations function by beetle -- http://www.peterbailey.com
// details at http://www.codingforums.com/showthread.php?t=14672
		
function addLabelProperties(f){
    //    Collect all label elements in form, init vars
    if ( typeof f.getElementsByTagName == 'undefined' ) return;
    var labels = f.getElementsByTagName( "label" ),
        label,
        elem,
        i = j = 0;

    //    Loop through labels retrieved
    while ( label = labels[i++] )
    {            
        //    For Opera 6
        if ( typeof label.htmlFor == 'undefined' ) return;
        
        //    Retrieve element
        elem = f.elements[label.htmlFor];

        if ( typeof elem == 'undefined' )
        {    //    No element found for label
            alert( "No element found for label: " + label.htmlFor );
        }
        else if ( typeof elem.label != 'undefined' )
        {    //    label property already added
            continue;
        }
        else if ( typeof elem.length != 'undefined' && elem.length > 1 && elem.nodeName != 'SELECT' )
        {    //    For checkbox arrays and radio-button groups
            for ( j = 0; j < elem.length; j++ )
            {
                elem.item( j ).label = label;                    
            }
        }
        //    Regular label
        elem.label = label;            
    }
}


/*--------------------------- */
/* removeElementById()        */
/* Author: Tim Isenheim       */
/* -------------------------- */

function removeElementById(theId){

	var deleted = false;
	
	if(document.getElementById(theId)){
		// acquire parent node
		var parent = document.getElementById(theId).parentNode;
		var children = parent.childNodes;
		
		// browse child nodes until id-item is found
		for(var i=0; i<children.length;i++){
		  if(children[i].id == theId){
				deleted = parent.removeChild(children[i]);  // remove it
			}
		}
	}
	return deleted;
}


/*--------------------------- */
/* build_radioList()          */
/* Author: Tim Isenheim       */
/* -------------------------- */

function build_radioList(options, id){
	rad = document.createElement("div");
	if(id!=null) rad.setAttribute("id", id);
	var i=0;
	do{
		var opt = document.createElement("input");
		opt.setAttribute("value", options[i+1]);
		opt.setAttribute("type", "radio");
		opt.setAttribute("name", "taglink[]");
		var label = document.createElement("label");
		label.setAttribute("for", "taglink"+i);
		label.appendChild(document.createTextNode(options[i]));
		label.appendChild(opt);
		label.appendChild(document.createElement("br"));
		rad.appendChild(label);
		i+=2;
	}while(i<options.length);
	return rad;
}
	
	
/* --------------------------- */
/* Cookie Functions            */
/* --------------------------- */

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}
	
	
// -------------------------------------------------
// ( smooth scrolling between internal links )
// http://www.sitepoint.com/article/scroll-smoothly-javascript
// -------------------------------------------------
// set vars
var ss_INTERVAL;
var ss_STEPS = 15;

function ss_fixAllLinks()
	{
	// grab all the links
	var allLinks = document.getElementsByTagName('a');
	
	// loop through all the links
	for (var i=0; i<allLinks.length; i++)
		{
		var lnk = allLinks[i];
		
		// check to see if there's a hash, and if the current url completely matches the one in the link
		if ((lnk.href && lnk.href.indexOf('#') != -1) && ( (lnk.pathname == location.pathname) || ('/'+lnk.pathname == location.pathname) ) && (lnk.search == location.search))
			{
			addEvent(lnk, 'click', smoothScroll);
			}
		}
	}

function smoothScroll(e)
	{
	var target;
	// checks with event model to use
	if (window.event)
		{
		// ie
		target = window.event.srcElement;
		}
	else if (e)
		{
		// other
		target = e.target;
		}
	else return;
	
	// strip off the hash
	var anchor = target.hash.substr(1);
	// grab all the anchors on the page
	var destinationLink = document.getElementById(anchor);
	// if none found, exit
	if (!destinationLink) return true;
	
	// find position of destination link
	var destx = destinationLink.offsetLeft; 
	var desty = destinationLink.offsetTop;
	var thisNode = destinationLink;
	// loop up through offsetParent until we hit the document body, as IE requires
	while (thisNode.offsetParent && (thisNode.offsetParent != document.body))
		{
		thisNode = thisNode.offsetParent;
		destx += thisNode.offsetLeft;
		desty += thisNode.offsetTop;
		}
	
	// clear the interval timer (why here?)
	clearInterval(ss_INTERVAL);
	
	// get current y-position
	var cypos = ss_getCurrentYPos();
	
	// calculate the step sizes
	var ss_stepsize = parseInt((desty-cypos)/ss_STEPS);
	
	// run the scroll
	ss_INTERVAL = setInterval('ss_scrollWindow('+ss_stepsize+','+desty+',"'+anchor+'")',10);
	
	// stop the browser handling the event as normal and opening the link
	// kills the bubble
	if (window.event)
		{
		window.event.cancelBubble = true;
		window.event.returnValue = false;
		}
	if (e && e.preventDefault && e.stopPropagation)
		{
		// hmmm, safari gets inside here, but then fails to stop the event, and so a 'jump' rather than a 'scroll' takes place. I can't figure it out...
		e.preventDefault();
		e.stopPropagation();
		}
	return true;
	}

function ss_scrollWindow(scramount, dest, anchor)
	{
	var wascypos = ss_getCurrentYPos();
	var isAbove = (wascypos < dest);
	window.scrollTo(0,wascypos + scramount);
	var iscypos = ss_getCurrentYPos();
	var isAboveNow = (iscypos < dest);
	// if finished cancel timer and jump anchor so url is correct
	if ((isAbove != isAboveNow) || (wascypos == iscypos))
		{
		window.scrollTo(0,dest);
		clearInterval(ss_INTERVAL);
		location.hash = anchor;
		}
	}

function ss_getCurrentYPos()
	{
	// ie5 and ie5.5
	if (document.body && document.body.scrollTop)
	return document.body.scrollTop;
	// ie6
	if (document.documentElement && document.documentElement.scrollTop)
	return document.documentElement.scrollTop;
	// netscape etc
	if (window.pageYOffset)
	return window.pageYOffset;
	return 0;
	}
	
/* another method */
function scrollIntoView (node) {
  var h = self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0;
  var offset = self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
  var pos = absolutePosition(node);
  if (pos.y + node.scrollHeight > h + offset) {
    if (node.scrollHeight > h) {
      window.scrollTo(0, pos.y);
    } else {
      window.scrollTo(0, pos.y + node.scrollHeight - h);
    }
  }
}

/**
 * Retrieves the absolute position of an element on the screen
 */
function absolutePosition(el) {
  var sLeft = 0, sTop = 0;
  var isDiv = /^div$/i.test(el.tagName);
  if (isDiv && el.scrollLeft) {
    sLeft = el.scrollLeft;
  }
  if (isDiv && el.scrollTop) {
    sTop = el.scrollTop;
  }
  var r = { x: el.offsetLeft - sLeft, y: el.offsetTop - sTop };
  if (el.offsetParent) {
    var tmp = absolutePosition(el.offsetParent);
    r.x += tmp.x;
    r.y += tmp.y;
  }
  return r;
};

/**
 * Returns true if an element has a specified class name
 */
function hasClass(node, className) {
  if (node.className == className) {
    return true;
  }
  var reg = new RegExp('(^| )'+ className +'($| )')
  if (reg.test(node.className)) {
    return true;
  }
  return false;
}

/*------------------------------------------------*/
/*                           Comment Validation   */
/*------------------------------------------------*/


function validateCommentForm(){
	var isReader = true;
	
	//elements to validate, and their regex
	var vEles = {
		'author' : '',
		'email' : '[^@]+@[^\.]+\.[a-zA-Z]',
		'comment' : ''
		};
		
	//check contact form is there
	var commentForm = document.getElementById('commentform');
	if(commentForm != null)
	{
	  
		//button detection handler
		document.getElementById('submit').onfocus = function() { isReader = false; };
		document.getElementById('submit').onmousedown = function() { isReader = false; };
		
		//form onsubmit handler
		commentForm.onsubmit = function()
		{
			var isValid = true;
			var results = document.getElementById('comment-results');
				
			//process the form for graphical browsers
			if(!isReader)			
			{

				for(var j in vEles)
				{
					
					this.regex = new RegExp(vEles[j],'');
					if(!this.regex.test(this[j].value)){
					//	this[j].value = '';
						this[j].style.backgroundColor = "#cc0000";
						this[j].style.color = "#fff";
						results.className = 'error';
						results.innerHTML += 'Please complete the required field: ' + this[j].id + '<br />';
						isValid = false;
					}
					
					//else if field is empty, add message to label
					
					else if(this[j].value == ''){
						this[j].style.backgroundColor = "#cc0000";
						this[j].style.color = "#fff";
						results.className = 'error';
						results.innerHTML += 'Please complete the required field: ' + this[j].id + '<br />';
						isValid = false;
					}
					
				} // end for

			} //end if is reader
			
			return isValid;
		};	// end function onsubmit
	} // end if form != null
}


/*-----------------------------------------------*/
/* 	  				External Links & Window functions */
/*-----------------------------------------------*/

function prepareExternalLinks() {

	if (!document.getElementsByTagName) return false;
	// catch all links on a page
	var hrefs = document.getElementsByTagName("a");

	for (var i=0; i<hrefs.length; i++) {
	  if (hrefs[i].getAttribute("rel") != null){
			if (hrefs[i].getAttribute("rel").indexOf("external") == -1) continue;
	
			hrefs[i].onclick = function() {
				window.open(this.href);
				return false;
			}
			// make links accessible for keyboard
			hrefs[i].onkeypress = hrefs[i].onclick;
    }
	}
}

function popupWindows() {
    if(!document.getElementsByTagName) {
         return;
    }
    var scrW = screen.availWidth;
    var scrH = screen.availHeight;
    var anchors = document.getElementsByTagName("a");
    for (var i = 0; i < anchors.length; i++) {
         var anchor = anchors[i];
         var linkDest = anchor.getAttribute("href");
         var relIndex = anchor.getAttribute("rel");
         if(relIndex != null){
	         var relSplit = relIndex.split("|");
	         var windowAttributes = "";
	         if(relSplit[0] == "popup") {
	              if (relSplit[1] > scrW) {
	                 pW = scrW - 10;
	              }
	              else {
	                 pW = relSplit[1];
	              }
	              if (relSplit[2] > scrH) {
	                 pH = scrH - 40;
	              }
	              else {
	                 pH = relSplit[2];
	              }
	              scrX = (scrW - pW - 10) * .5;
	              scrY = (scrH - pH - 30) * .5;
	              var windowAttributes = "width=" + pW + ",height=" + pH + ",left=" + scrX + ",top=" + scrY + ",screenX=" + scrX + ",screenY=" + scrY;
	              windowAttributes += ",location=" + relSplit[4] + ",resizable=" + relSplit[4] + ",scrollbars=" + relSplit[4];
	              anchor.setAttribute("href", "javascript:popupWin('" + linkDest + "','" + windowAttributes + "')");
	         }
	      }
    }
}

function popupWin(link,attribs) {
    var popupWin = null;
    popupWin = window.open(link,'winPopup',attribs);  
}


/*------------------------------------------------*/
/*                                Style Switching */
/*------------------------------------------------*/

function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

function loadStyleCookie(){
  var cookie = readCookie("freshlabs-journal");
  var title = cookie ? cookie : getPreferredStyleSheet();
  setActiveStyleSheet(title);
}
/*
addEvent(window,'load', loadStyleCookie);


addEvent(window,'unload', function(e) {
  var title = getActiveStyleSheet();
  createCookie("freshlabs-journal", title, 365);}
	);
*/

/*
function randomImg() {
	var thePics = new Array()

	thePics[1] = "header1.jpg"
	thePics[2] = "header2.jpg"
	
	var rn = Math.floor(Math.random() * thePics.length)
	if (rn == 0) {
	  rn = 1
	}
	document.write("<img src=\"/photos/hp/"+thePics[rn]+"\" width=\"194\" height=\"146\" border=\"0\" />")
}
*/



