/* General Scripts freshlabs.de	Author: Tim Isenheim */

var siteURL = "http://www.freshlabs.de";


/* onload functions */

onLoadFunctions = new Array();

function appendOnLoad(funct){
  onLoadFunctions[onLoadFunctions.length] = funct;
}

function runOnLoad(){
  for(i in onLoadFunctions)
    eval(onLoadFunctions[i]);
}

// 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;            
    }
}

/* ================ */
/* 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;
}

/* External Links */


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);  
}

/* ----------------------------------
 * fixFormLabels - make labels clickable in IE and Safari
 * ----------------------------------
 */

function fixFormLabels(){
	// IE and Safari only
	var isIE, 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();
			};
		}
	}
}

/* ----------------------------------
 * Ajaxify Portfolio Projects
 * ----------------------------------
 */
var AjaxProject = {
	projectNode : Object,
	
	init : function(link){
		this.projectNode = link.parentNode.parentNode.parentNode;
 		Event.observe(link, "click", function(){
 			var myAjax = new Ajax.Request( siteURL + '/wp-content/themes/freshlabs/projectitem-ajax.php', 
 										 { method: 'get', 
 										   parameters: "id=" + this.id,
 										   onLoading: AjaxProject.showLoadingMessage(this.parentNode.parentNode.parentNode),
 										   onSuccess: AjaxProject.showProject
 										  } );
 		});
	},
	
	showLoadingMessage:function(node){
		this.projectNode = node;
		this.projectNode.innerHTML = "";
		img = document.createElement('img');
		img.id = "loadingimage";
		img.src = siteURL + '/wp-content/themes/freshlabs/images/ajax-loader.gif';
		this.projectNode.appendChild(img);
		
	},
	
	showProject : function(originalRequest){
		node = $('loadingimage').parentNode;
		node.style.display = "none";
		node.innerHTML = originalRequest.responseText;
		new Effect.SlideDown(node, {duration: 0.5});
	}
};

function initAjaxProjects(){
	var k=0;
	var pars;
	var els = $('content').getElementsByTagName('div');
	for(var i=0; i<els.length; i++){
		if(els[i].className.indexOf("details-link") >= 0){
	 		els[i].childNodes[0].id = els[i].className.substr(13,10);
	 		els[i].childNodes[0].href = 'javascript:void(0)';
	 		new AjaxProject.init(els[i].childNodes[0]);

	 		k++;
		}
	}
}


//appendOnLoad('initAjaxProjects()');
appendOnLoad('fixFormLabels()');
appendOnLoad('prepareExternalLinks()');

/*-------*/