/* 
 *	Some general applicable javascripts
 *
 *	See for information:
 *	https://devwikis.stepstone.com/OnlineWiki/general%20javascript%20lib.js%20explained.ashx
 *
 *	$Revision: 1.101 $
 *	$Date: 2009/04/08 14:21:49 $
 */
var debug = true; // show debug message; setting this to false saves some mem
var ShowAlerts = false; // show alert box when 'console' is not available.
var ErrorMessages = []; // new Array()
var alerts = ''; // alerts output
var ExpandTextareas = false; // make textareas expand when typing

if(typeof ROOT != 'string'){
	var ROOT = "/channels/_default/";	// Ticket 9436 : root of the current site
}

var resourcesFolder = ROOT + 'resources/'; // set folder for css and images
var doCheckPopupBlocker = false;
var env; // holds browser env info
var showScreenInfo = false; // dump screen size and scroll info
var dosetRoundedCorners = false; // default is off
var supportedbrowser = true;
var supportedscreen = true;
var prototypeAvailable = false;
var ConsoleAvailable = false;
var isIE6 = false;

// Set site minimals
var minW = "1176";
var minH = "1500";

if (!OldBrowserMsg) {
    var OldBrowserMsg = "WARNING: The browser that you are using (__browser__ __version__) doesn't support some features of this website.<br />Some elements of this site may not be displayed correctly. <a href=\"http://www.google.com/search?q=download+web+browser\">Using a different browser is highly recommended</a>.";
}


/**
 * Test if prototype library function $ exists
 */
function PrototypeTest(){
    if (typeof(Prototype) == "undefined") {
        return false;
    }
    prototypeAvailable = true;
    log('Prototype Version: ' + Prototype.Version);
}

function ConsoleTest(){
	if (typeof(window.console) == "undefined") {
        return false;
    }
    ConsoleAvailable = true;
    log('Console available');
}

function isobject(o){
    return (typeof o != 'object') ? true : false;
}

/**
 * Dreamweaver findObj
 * @param {Object} theObj
 * @param {Object} theDoc
 */
function findObj(theObj, theDoc){
    var p, i, foundObj;
    
    if (!theDoc) 
        theDoc = document;
    if ((p = theObj.indexOf("?")) > 0 && parent.frames.length) {
        theDoc = parent.frames[theObj.substring(p + 1)].document;
        theObj = theObj.substring(0, p);
    }
    if (!(foundObj = theDoc[theObj]) && theDoc.all) 
        foundObj = theDoc.all[theObj];
    for (i = 0; !foundObj && i < theDoc.forms.length; i++) 
        foundObj = theDoc.forms[i][theObj];
    for (i = 0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++) 
        foundObj = findObj(theObj, theDoc.layers[i].document);
    if (!foundObj && document.getElementById) 
        foundObj = document.getElementById(theObj);
    
    return foundObj;
}

/**
 * Simple load handler
 * @param {Object} func
 */
function addLoadEvent(func){
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function(){
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

/**
 *	aliases for addLoadEvent
 */
addloadevent = addLoadEvent;
RegisterOnLoad = addLoadEvent;
addLoadListener = addLoadEvent;

/**
 *	ULTRA-SIMPLE EVENT ADDING
 *	Quirksmode.org
 */
function addEventSimple(obj, evt, fn){
    if (obj.addEventListener) 
        obj.addEventListener(evt, fn, false);
    else 
        if (obj.attachEvent) 
            obj.attachEvent('on' + evt, fn);
}

function removeEventSimple(obj, evt, fn){
    if (obj.removeEventListener) 
        obj.removeEventListener(evt, fn, false);
    else 
        if (obj.detachEvent) 
            obj.detachEvent('on' + evt, fn);
}

// add Array.push if needed (ie5)
if (!Array.prototype.push) {
    Array.prototype.push = function(item){
        this[this.length] = item;
        return this.length;
    }
}

// The shift() and unshift() methods. (ie5)
if (!Array.prototype.shift) { // if this method does not exist..
    Array.prototype.shift = function(){
        firstElement = this[0];
        this.reverse();
        this.length = Math.max(this.length - 1, 0);
        this.reverse();
        return firstElement;
    }
}

if (!Array.prototype.unshift) { // if this method does not exist..	
    Array.prototype.unshift = function(){
        this.reverse();
        for (var i = arguments.length - 1; i >= 0; i--) {
            this[this.length] = arguments[i]
        }
        this.reverse();
        return this.length
    }
}

/**
 * Trim spaces from a string
 * http://www.nicknettleton.com/zine/javascript/trim-a-string-in-javascript
 */
String.prototype.trim = function(){
    return this.replace(/^\s+|\s+$/g, '');
}


/**
 * Get Elements by classname
 * @param {Object} classname
 * @param {Object} node
 */
function getElementsByClassName(classname, node){
    if (!node) 
        node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for (var i = 0, j = els.length; i < j; i++) 
        if (re.test(els[i].className)) 
            a.push(els[i]);
    return a;
}

/**
 *	Adds divs in side a container that can be positioned and styled using css.
 *	These divs will be positioned in the top left, top right, bottom left and bottom right corner of the block element.
 *	This of course requires the styles to be defined.
 */
function CreateRoundedCorners(className, containerId){
    dump("CreateRoundedCorners");
	className = (className != null) ? className : "rounded";
    containerId = (containerId != null) ? containerId : "container"; // PageContent only add the rounded corners to the elements in this container with the assigned classname
    var allcorners = '<div class="topleft"><!-- tl --></div><div class="topright"><!-- tr --></div><div class="bottomleft"><!-- bl --></div><div class="bottomright"><!-- br --></div>';
    var topcorners = '<div class="topleft"><!-- tl --></div><div class="topright"><!-- tr --></div>';
    var bottomcorners = '<div class="bottomleft"><!-- bl --></div><div class="bottomright"><!-- br --></div>';
    var corners = allcorners;
    var els = getElementsByClassName(className, document.getElementById(containerId));
    for (var i = 0, j = els.length; i < j; i++) {
        dump('Adding Rounded Corners to ' + els[i].id);
        //els[i].innerHTML = els[i].innerHTML + corners;
        if(typeof Element != undefined) Element.insert(els[i], corners);
    }
}

function SetRoundedCorners(){
    CreateRoundedCorners();
}

/**
 *	Holds browser and display information
 **/
env = {

    // returned variables
    
    sw: 0, // screen.width
    sH: 0, // screen.height
    aW: 0, // screen.availWidth
    aH: 0, // screen.availHeight
    cD: 0, // screen.colorDepth
    pW: 0, // pageWidth
    pH: 0, // pageHeight
    wW: 0, // windowWidth
    wH: 0, // windowHeight
    sX: 0, // xScroll
    sY: 0, // yScroll
    sU: 0, // screen usage percentage
    uW: 0, // screen usage width
    uH: 0, // screen usage height
    init: function(){
        env.sW = screen.width;
        env.sH = screen.height;
        env.aW = screen.availWidth;
        env.aH = screen.availHeight;
        env.cD = screen.colorDepth;
        if (debug) 
            log("Screen size: " + env.sW + "px x " + env.sH + "px");
        if (debug) 
            log("Screen available size: " + env.aW + "px x " + env.aH + "px");
        if (debug) 
            log("Screen colordepth: " + env.cD + "bit");
        // returns array: pageWidth,pageHeight,windowWidth,windowHeight
        arrPageSizes = env.getPageSize();
        env.pW = arrPageSizes[0];
        env.pH = arrPageSizes[1];
        env.wW = arrPageSizes[2];
        env.wH = arrPageSizes[3];
        if (debug) 
            log("Page size: " + env.pW + "px x " + env.pH + "px");
        if (debug) 
            log("Window size: " + env.wW + "px x " + env.wH + "px");
        // returns array: xScroll,yScroll
        var arrPageScroll = env.getPageScroll();
        env.sX = arrPageScroll[0];
        env.sY = arrPageScroll[1];
        if (debug) 
            log("Scrolling: " + env.sX + " x " + env.sY);
        // screensize,windowsize,PercentageTotal,PercentageWidth,PercentageHeight
        arrScreenUsage = env.getScreenUsage();
        env.sU = arrScreenUsage[2];
        env.uW = arrScreenUsage[3];
        env.uH = arrScreenUsage[4];
        if (debug) 
            log("Total Screen Usage: " + env.sU + "% / Width: " + env.uW + "% / Height: " + env.uH + "%");
        
    },
    // on resize function
    calculatePageSize: function(output){
        var arrPageSizes = env.getPageSize();
        env.pW = arrPageSizes[0];
        env.pH = arrPageSizes[1];
        env.wW = arrPageSizes[2];
        env.wH = arrPageSizes[3];
        if (debug) 
            dump("Page size: " + env.pW + "px x " + env.pH + "px");
        if (debug) 
            dump("Window size: " + env.wW + "px x " + env.wH + "px");
        
    },
    // on resize function
    calculatePageScroll: function(output){
        var arrPageScroll = env.getPageScroll();
        env.sX = arrPageScroll[0];
        env.sY = arrPageScroll[1];
        if (debug) 
            dump("Scrolling: " + env.sX + " x " + env.sY);
    },
    
    calculateScreenUsage: function(){
        // screensize,windowsize,PercentageTotal,PercentageWidth,PercentageHeight
        arrScreenUsage = env.getScreenUsage();
        env.sU = arrScreenUsage[2];
        env.uW = arrScreenUsage[3];
        env.uH = arrScreenUsage[4];
        if (debug) 
            dump("Total Screen Usage: " + env.sU + "% / Width: " + env.uW + "% / Height: " + env.uH + "%");
    },
    
    // Quirksmode.org
    getPageSize: function(){
        var xScroll, yScroll;
        if (window.innerHeight && window.scrollMaxY) {
            xScroll = window.innerWidth + window.scrollMaxX;
            yScroll = window.innerHeight + window.scrollMaxY;
        }
        else 
            if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
                xScroll = document.body.scrollWidth;
                yScroll = document.body.scrollHeight;
            }
            else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
                xScroll = document.body.offsetWidth;
                yScroll = document.body.offsetHeight;
            }
        var windowWidth, windowHeight;
        if (self.innerHeight) { // all except Explorer
            if (document.documentElement.clientWidth) {
                windowWidth = document.documentElement.clientWidth;
            }
            else {
                windowWidth = self.innerWidth;
            }
            windowHeight = self.innerHeight;
        }
        else 
            if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
                windowWidth = document.documentElement.clientWidth;
                windowHeight = document.documentElement.clientHeight;
            }
            else 
                if (document.body) { // other Explorers
                    windowWidth = document.body.clientWidth;
                    windowHeight = document.body.clientHeight;
                }
        // for small pages with total height less then height of the viewport
        if (yScroll < windowHeight) {
            pageHeight = windowHeight;
        }
        else {
            pageHeight = yScroll;
        }
        // for small pages with total width less then width of the viewport
        if (xScroll < windowWidth) {
            pageWidth = xScroll;
        }
        else {
            pageWidth = windowWidth;
        }
        arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
        return arrayPageSize;
    },
    
    // Quirksmode.org
    getPageScroll: function(){
        var xScroll, yScroll;
        if (self.pageYOffset) {
            yScroll = self.pageYOffset;
            xScroll = self.pageXOffset;
        }
        else 
            if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
                yScroll = document.documentElement.scrollTop;
                xScroll = document.documentElement.scrollLeft;
            }
            else 
                if (document.body) {// all other Explorers
                    yScroll = document.body.scrollTop;
                    xScroll = document.body.scrollLeft;
                }
        arrayPageScroll = new Array(xScroll, yScroll);
        return arrayPageScroll;
    },
    
    getScreenUsage: function(){
        var screensize, windowsize, PercentageTotal, PercentageWidth, PercentageHeight;
        screensize = env.sW * env.sH;
        windowsize = env.wW * env.wH;
        PercentageTotal = Math.ceil((windowsize / screensize) * 100);
        PercentageWidth = Math.ceil((env.wW / env.sW) * 100);
        PercentageHeight = (Math.ceil(env.wH / env.sH) * 100);
        arrayScreenUsage = new Array(screensize, windowsize, PercentageTotal, PercentageWidth, PercentageHeight);
        return arrayScreenUsage;
    }
}

/**
 * Calculate the height of an iframe's content
 * Auto-resize an ifame depending on it's content
 * Add this to the onload handler of the iframe tag
 * Only works when iframe source is on the same domain!
 * @param {Object} el The iframe to check
 */
function calcHeight(el,minHeight,minWidth){

	var f,c,minHeight,minWidth,fHeight,fWidth,newHeight,newWidth;	
	var name = 'calcHeight';
	var extraHeight = 50;
	var extraWidth = 50;
	
	var setHeight = true;
	var setWidth = true;
	
    minHeight = typeof(minHeight) != 'undefined' ? minHeight : 600;
    minWidth = typeof(minWidth) != 'undefined' ? minWidth : 700;
    
    newHeight = minHeight;
	newWidth = minWidth;
	fHeight = minHeight;
	fWidth = minWidth;
	
    f = document.getElementById(el);
	
	if (typeof f == 'undefined' || f.tagName.toLowerCase() != 'iframe') {
		log(name + ' : invalid target element');
		return false;
	}
	
	// find the main content element to set the as well to make the iframe fit nicely
	c = (document.getElementById("Content")) ? document.getElementById("Content") : document.getElementById("content");
	
	if(c == null){
		// try to find the "jobcontent" container, fail back to "container"
		c = (document.getElementById("jobcontent")) ? document.getElementById("jobcontent") : document.getElementById("container");
	}
	
	//log(name + ' : ' + f.id + ' / tagName: ' + f.tagName);
    
	// set bigger iframe size for jobs with classname "joblayout960"
	// uses prototype to get the current classname
	if (typeof $$ != 'undefined') {
	
		// look for DE
		if($('stepstone-de-v5') != null){
			//setWidth = false;
		}
		
		if ($$("body")[0].hasClassName("popup") && $$("body")[0].hasClassName("job")) {
			
			log(name + ' : iframe style.height set to ' + f.style.height);
			
			setWidth = false;
			
			// set width to use 99.5% of window for scrollbars
			f.style.width = "99.5%";
			f.setAttribute('width','99.5%');
			
			$$("body")[0].addClassName("iframe");
			
		}
		
		if ($$("body")[0].hasClassName("joblayout960")) {
			log(name + ' : joblayout960');
			minHeight = 1000; // bigger because of the 960 width
			minWidth = 960;
			newHeight = minHeight;
			newWidth = minWidth;
		}
		
	}else{
		log(name + ' : no prototype');
	}	

	// fallbacks for iframe height check
	if(setHeight){
		f.style.height = fHeight + "px";
		f.style.minHeight = fHeight + "px";
		f.setAttribute('height',fHeight);
		log(name + ' : iframe style.height set to ' + f.style.height);
	}
	
	if(setWidth){
		f.style.width = fWidth + "px";
		f.setAttribute('width',fWidth);
		log(name + ' : iframe style.width set to ' + f.style.width);
	}

	try{    
		//reset the iframe border
		f.setAttribute("frameBorder","0");
		
		//sets frameborder for IE
		try	{
			f.frameBorder = 0;
		} catch (e) {
			//continue
		}	
		
		// FireFox exception
        var getFFVersion = navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1]
        var FFextraHeight = parseFloat(getFFVersion) >= 0.1 ? 32 : 0 //extra height in px to add to iframe in FireFox 1.0+ browsers
        
		// calc height of the iframe
		//try{			
			
        	if (f.contentDocument && f.contentDocument.body.scrollHeight) {
                log(name + ' : ns6 syntax trying body.scrollHeight');
                newHeight = f.contentDocument.body.scrollHeight + extraHeight;
                newWidth = f.contentDocument.body.scrollWidth + extraWidth;
                    
            } else if (f.contentDocument && f.contentDocument.documentElement.offsetHeight) {
                log(name + ' : ns6 syntax trying documentElement.offsetHeight');
                newHeight = f.contentDocument.documentElement.offsetHeight + extraHeight;
                newWidth = f.contentDocument.documentElement.offsetWidth + extraWidth;
                
            } else if (f.contentDocument && f.contentDocument.body.offsetHeight) {
            	log(name + ' : ns6 syntax trying body.offsetHeight');
            	newHeight = f.contentDocument.body.offsetHeight + FFextraHeight + extraHeight;
                newWidth = f.contentDocument.body.offsetWidth + extraWidth;
                
            } else if (f.Document && f.Document.body.scrollHeight) { //ie5+ syntax                   
                log(name + ' : ie5+ syntax trying body.scrollHeight');
                newHeight = f.Document.body.scrollHeight + extraHeight;
                newWidth = f.Document.body.scrollWidth;
                
            } else {
                log(name + " error: problem getting the frame body dimensions");
            }

			
		//}catch(e){			
		//	return false;
		//}	        

        // set new width and heighy only if it's higher or equal the min width & height
		log(name + ' : fHeight: ' + newHeight + ' minHeight: ' + minHeight + ' / fWidth: ' + newWidth + ' minWidth: ' + minWidth);
		
		fHeight = (parseInt(newHeight) >= parseInt(minHeight)) ? newHeight : minHeight;
		fWidth = (parseInt(newWidth) >= parseInt(minWidth)) ? newWidth : minWidth;
		
		log(name + ' : fHeight: ' + fHeight + ' / fWidth: ' + fWidth);
		
		if(setHeight){
			f.style.height = fHeight + "px";
			f.style.minHeight = fHeight + "px";		
			f.setAttribute('height',fHeight);
			log(name + ' : iframe height set to ' + fHeight);
		}
		
		if(setWidth){
			f.style.width = fWidth + "px";
			f.setAttribute('width',fWidth);
			log(name + ' : iframe width set to ' + fWidth);
		}		
		
		// set the minHeight of #Content
		if (c != null && typeof c == 'object') {
			c.style.minHeight = fHeight + "px";
			log(name + ' : c.style ok');
		}
		
		return true;   
		
	}catch(err){
		
		log(name + ' : error : ' + err.description);
		
		if(err.description == 'undefined'){
			f.style.height = minHeight + "px"; // set height to a "save" height		
			log(name + ' set height to ' + minHeight + 'px');
		}
			
		return false;
		
	}

}

// synonimes
calcheight = calcHeight;
CalcHeight = calcHeight;

/**
 *	Check popupblocker
 *	Sets a session cookie with the result of the check
 *	Status: experimental
 */
function checkPopupBlocker(){
    
	var name = "checkPopupBlocker";
	var msg = name + " " + new Date();
	
	// check for an existing cookie
	if (typeof Cookies.popUpsBlocked == 'string') {
        cookie = Cookies.popUpsBlocked;
        var popUpsBlocked = cookie;
        msg += " : popUpsBlocked:" + popUpsBlocked;
        log(msg);
        return true;
    }
	
	// no cookie? test if we can open popups
    if (typeof Cookies.popUpsBlocked == 'undefined') {
        
    	var mine = window.open('', '', 'width=1,height=1,left=-1000px,top=-1000px,scrollbars=no');
    	msg += " : no Cookies.popUpsBlocked: mine:" + typeof mine;
        
        if (mine) {
            var popUpsBlocked = false;
            // close the window if it exists
           	msg += " : closing mine";
           	mine.close();
        }else {
            var popUpsBlocked = true;
        }
        
        msg += " : popUpsBlocked:" + popUpsBlocked;
        
        // check if we already did a check
        if (typeof Cookies.cookiecheck == 'string') {
        	msg += " : setting Cookies.cookiecheck";
        	Cookies.create('popUpsBlocked', popUpsBlocked);
        }
        
    }else{
    	msg += ";Cookies.popUpsBlocked:" + Cookies.popUpsBlocked;
    }	
    
    // we have checked the feature, don't do it again
    if (typeof Cookies.cookiecheck == 'undefined') {
    	msg += " : setting Cookies.cookiecheck";
    	Cookies.create('cookiecheck', true);
    }
    
    log(msg);
    
    return true;
   
}

/**
 *	COOKIES
 *	http://www.quirksmode.org/quirksmode.js
 */
var Cookies = {
    init: function(){
        var allCookies = document.cookie.split('; ');
        for (var i = 0; i < allCookies.length; i++) {
            var cookiePair = allCookies[i].split('=');
            this[cookiePair[0]] = cookiePair[1];
        }
    },
    create: function(name, value, days){
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else 
            var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
        this[name] = value;
    },
    erase: function(name){
        this.create(name, '', -1);
        this[name] = undefined;
    }
};

/*
 * Example:
 *
 // INITIALISE PREFERENCES (needs cookies)
 var Preferences = {
 init: function () {
 if (!Cookies.sitePrefs) return;
 sitePrefs = Cookies.sitePrefs.split(',,');
 for (var i=0;i<sitePrefs.length;i++) {
 var oneSitePref = sitePrefs[i].split(':');
 this[oneSitePref[0]] = oneSitePref[1];
 }
 }
 };
 Preferences.init();
 *
 */
// Cookie functions
function setCookie(name, value, expiredays){
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = name + "=" + escape(value) +
    ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

function toggleCookie(name, expiredays, undefValue){
    if (getCookie(name) == "") 
        setCookie(name, undefValue, expiredays);
    else 
        if (getCookie(name) == 1) 
            setCookie(name, 0, expiredays);
        else 
            setCookie(name, 1, expiredays);
    
}

function getCookie(name){
    if (document.cookie.length > 0) {
        start = document.cookie.indexOf(name + "=");
        if (start != -1) {
            start = start + name.length + 1;
            end = document.cookie.indexOf(";", start);
            if (end == -1) 
                end = document.cookie.length;
            return unescape(document.cookie.substring(start, end));
        }
    }
    return "";
}


/**
 * Create a browser popup window
 *
 * @param {String} url
 * @param {String} name
 * @param {String} w
 * @param {String} h
 * @param {String} scroll
 * @param {String} menubar
 */
function PopUp(url, name, w, h, scroll, menubar){
    var Window = null;
    LeftPosition = (screen.width) ? (screen.width - w) / 2 : 0;
    TopPosition = (screen.height) ? (screen.height - h) / 2 : 0;
    if(menubar == null){
		menubar = 0;
	}
	settings = 'height=' + h + ',width=' + w + ',top=' + TopPosition + ',left=' + LeftPosition + ',scrollbars=' + scroll+',resizable=1,menubar=' + menubar;
	Window = window.open(url, "_blank", settings);
    
}


/**
 * Outputs an email address where .'s are obscured with 'dot' and @'s with 'at'
 * @param {String} e
 */
function address(e){
    e = e.replace(/ dot /g, ".");
    e = e.replace(/ at /g, "@");
    document.write(e);
}

/**
 * Very simple nospam measure
 * @param {String} u user
 * @param {String} d domain
 * @param {String} t tld
 */
function noSpam(u, d, t){
    l = "mailto:" + u + "@" + d + "." + t;
    window.location = l;
}

/**
 * Addition to nospam measures
 * @param {String} a address
 * @param {String} s subject
 * @param {boolean} t track
 */
function send(a, s, t){
    var url;
    url = "mailto:" + a;
    //url = "mailto:test@stepstone.be";
    if (s) {
        url += '?subject=' + s;
    }
    if (t) {
        date = new Date;
        if (debug) 
            dump(url + ' is clicked on ' + date.toString());
        // place ajax call here
    }
    //dump('l:' + url.toString());
    window.location = url.toString();
}

// aliases for send function
sendmail = send;
mail = send;

/**
 * open an url
 * @param {String} u url
 * @param {String} t target
 */
function url(u, t){
    var u;
    // log this
    if (t == '_blank') {
        window.open = u;
    }
    else {
        window.location = u;
    }
}

goto = url;

/**
 * Set display none of obj
 * @param {Object} obj
 */
function hide(obj){
    el = findObj(obj);
    if (debug) 
        log('found: ' + el.id);
    el.style.display = 'none';
}

/**
 * Debug log wrapper
 * Uses console.log if available, otherwise alerts the log messages
 * Use when building functions
 * @param {String} msg
 */
function log(msg){
    if (ErrorMessages && typeof ErrorMessages == 'object') {
        ErrorMessages.push(msg);
    }
}

/**
 * Show gathered messages in one alert
 * Use this to output intermediate log messages in the code on execution
 * @param {String} msg
 */
function dump(msg){
    if (msg != null && msg.length > 0) {
        //old_alerts = alerts;
        alerts = msg;
    }
    else {
        for (var i = 0; i < ErrorMessages.length; i++) {
            alerts += ErrorMessages[i] + '\r\n';
        }
    }
    if (debug) {
        // use console if available? Works in FireFox firebug, Safari 3
        if (window.console && console.log) {
            console.log(alerts);
        }
        else {
            // opera alternative
            if (window.opera && opera.postError) {
                opera.postError(alerts);
            }
            else {
                // only alert if requested
                if (window.alert && ShowAlerts) {
                    alert(alerts);
                }
            }
        }
    }
}

/**
 *
 */
var FormHelpers = {
    init: function(){
        if (ExpandTextareas) {
            addLoadEvent(this.ExpandTextareas);
        }
    },
    // looks for textareas and tries to make them grow on text input
    ExpandTextareas: function(){
        var ts;
        ts = document.getElementsByTagName('textarea');
        //log("Found " + textareas.length + " textareas");		
        for (var i = 0; i < ts.length; i++) {
            //log(textareas[i].id + " is a " + typeof textareas[i]);			
            t = ts[i];
            log('Expanding:' + ts[i].id);
            ts[i].className += ' expand';
            ts[i].originalHeight = ts[i].offsetHeight;
            
            ts[i].onkeyup = function(){
                if (this.scrollHeight - Math.round(this.originalHeight / 30) > this.originalHeight) {
                    this.style.height = this.scrollHeight + 'px';
                }
            }
        }
    },
    validateEmail: function(strEmail){
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,16})+$/.test(strEmail)) {
            return true;
        }
        else {
            return false;
        }
    },
    Trim: function(s){
        while (s.substring(0, 1) == ' ') {
            s = s.substring(1, s.length);
        }
        return s;
    },
    /**
     *	On change select menu handler
     */
    GoSelect: function(obj){
        //dump('obj: ' + obj);
        if (typeof obj != 'undefined' && window) {
            //dump('selected: ' + obj.options[obj.selectedIndex].value);
            window.location = obj.options[obj.selectedIndex].value;
        }
    }
};


/* moved pngfixes to separate file pngfix.js because it's only used in IE6 */


/**
 * Browser Detection
 * http://www.quirksmode.org/js/detect.html
 *
 * Checks also for the required version to make the site work
 * Uses a structure with current browsers
 * Outputs the OldBrowserMsg if necessary
 *
 */
var BrowserDetect = {
    init: function(theMsg){
        this.msg = theMsg;
        this.browser = this.searchString(this.dataBrowser) || "unknown";
        this.version = this.searchVersion(navigator.userAgent) ||
        this.searchVersion(navigator.appVersion) ||
        "unknown";
        this.userAgent = this.browser + ' ' + this.version;
        this.OS = this.searchString(this.dataOS) || "unknown";
        this.check = this.checkBrowser(this.dataBrowser);
        this.checkVersion();
    },
    searchString: function(data){
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1) 
                    return data[i].identity;
            }
            else 
                if (dataProp) 
                    return data[i].identity;
        }
    },
    checkBrowser: function(data){
        for (var i = 0; i < data.length; i++) {
            required = data[i].required;
            // stop if we found our browser in data
            if (this.browser == data[i].identity) {
                // check if we have a required version for this browser
                if (this.browser == data[i].identity && required) {
                    //log("Check: " + this.browser + ' ' + this.version + " >= " + data[i].identity + ' ' + required);
                    // check if the current version is higher or equal to the required version
                    if (this.version >= data[i].required) {
                        return true;
                    }
                    else {
                        return false;
                    }
                }
                else {
                    // we didn't set a minimum version, so return ok
                    return true;
                }
            }
        }
    },
    searchVersion: function(dataString){
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) 
            return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    checkVersion: function(targetBrowser, minVersion){
        if (this.msg == null || this.msg.length == 0) 
            return false;
        // note: this will not check sub versions
        //log('Good browser? ' + this.check);
        var Msg = this.msg.replace("__browser__", this.browser).replace("__version__", this.version);
        // note that we only target known browsers with issues here...
        if (!this.check) {
            supportedbrowser = false;
            this.resetCSS();
            document.write('<div id="goldbar">' + Msg + ' <a href="#" onclick="javascript:hide(\'goldbar\');">X</a></div>');
        }
    },
    resetCSS: function(){
        document.write('<link rel="stylesheet" type="text/css" href="' + resourcesFolder + 'css/reset.css" />');
    },
    dataBrowser: [{
        string: navigator.userAgent,
        subString: "Chrome",
        identity: "Chrome"
    }, {
        string: navigator.userAgent,
        subString: "OmniWeb",
        versionSearch: "OmniWeb/",
        identity: "OmniWeb"
    }, {
        string: navigator.vendor,
        subString: "Apple",
        identity: "Safari",
        required: "3" // Set required version for the site to work correctly
    }, {
        prop: window.opera,
        identity: "Opera",
        required: "8"
    }, {
        string: navigator.vendor,
        subString: "iCab",
        identity: "iCab"
    }, {
        string: navigator.vendor,
        subString: "KDE",
        identity: "Konqueror"
    }, {
        string: navigator.userAgent,
        subString: "Firefox",
        identity: "Firefox",
        required: "2" // Set required version for the site to work correctly
    }, {
        string: navigator.vendor,
        subString: "Camino",
        identity: "Camino"
    }, { // for newer Netscapes (6+)
        string: navigator.userAgent,
        subString: "Netscape",
        identity: "Netscape"
    }, {
        string: navigator.userAgent,
        subString: "MSIE",
        identity: "Explorer",
        versionSearch: "MSIE",
        required: "6.0" // Set required version for the site to work correctly
    }, {
        string: navigator.userAgent,
        subString: "Gecko",
        identity: "Mozilla",
        versionSearch: "rv"
    }, { // for older Netscapes (4-)
        string: navigator.userAgent,
        subString: "Mozilla",
        identity: "Netscape",
        versionSearch: "Mozilla"
    }],
    dataOS: [{
        string: navigator.userAgent,
        subString: "iphone",
        identity: "iphone"
    }, {
        string: navigator.userAgent,
        subString: "ipod",
        identity: "ipod"
    }, {
        string: navigator.platform,
        subString: "WinCE",
        identity: "Windows Mobile"
    }, {
        string: navigator.platform,
        subString: "palm",
        identity: "palm"
    }, {
        string: navigator.platform,
        subString: "Win",
        identity: "Windows"
    }, {
        string: navigator.platform,
        subString: "Mac",
        identity: "Mac"
    }, {
        string: navigator.platform,
        subString: "Linux",
        identity: "Linux"
    }, {
        string: navigator.userAgent,
        subString: "symbian",
        identity: "symbian"
    }, {
        string: navigator.userAgent,
        subString: "android",
        identity: "android"
    }]

};

/**
 * Returns the height of an element
 * @param {Object} id
 */
function checkHeight(id){
    //log('checking height of ' + id);	
    var el = findObj(id);
    if (!el) {
        return false;
    }
    //log('found :' + el.id + ' is ' + el.offsetHeight + 'px high' );
    return el.offsetHeight;
}

/**
 * Move the element the dif number of px to the top
 * @param {Object} el
 * @param {Integer} dif
 */
function moveToTop(el, dif){
    dif += 5;
    el.style.top = '-' + dif / 1.75 + 'px';
    //el.style.zIndex = '99';
}

/**
 * Remove element from the dom
 * @param {Object} el
 */
function removeElement(el){
    d = findObj(el);
    d.parentNode.removeChild(document.getElementById(el));
}

/**
 * Create Photo element when necessary
 */
function createPhoto(){
    photo = document.createElement('div');
    photo.setAttribute("id", "Photo");
    thebox = findObj('DynamicBox');
    if (debug) 
        log('thebox:' + thebox.id);
    if (typeof thebox != 'undefined') {
        thebox.appendChild(photo);
    }
}

//DOM ready watcher - scripting by brothercake -- http://www.brothercake.com/
function domFunction(f, a){
    var n = 0;
    var t = setInterval(function(){
        var c = true;
        n++;
        if (typeof document.getElementsByTagName != 'undefined' && (document.getElementsByTagName('body')[0] != null || document.body != null)) {
            c = false;
            if (typeof a == 'object') {
                for (var i in a) {
                    if ((a[i] == 'id' && document.getElementById(i) == null) ||
                    (a[i] == 'tag' && document.getElementsByTagName(i).length < 1)) {
                        c = true;
                        break;
                    }
                }
            }
            if (!c) {
                f();
                clearInterval(t);
            }
        }
        if (n >= 60) {
            clearInterval(t);
        }
    }, 250);
};

// Environment tests
addLoadEvent(ConsoleTest);
addLoadEvent(PrototypeTest);


// detect current browser and output warning message if necessary
BrowserDetect.init(OldBrowserMsg);
if (debug) log('\n\nBrowser: ' + BrowserDetect.userAgent + ' / supported: ' + supportedbrowser);

// start form helper methods
FormHelpers.init();

// start cookies
Cookies.init();

// check popup blocker
if(doCheckPopupBlocker){
	checkPopupBlocker();
}

// Check environment on page load
addLoadEvent(env.init);

// Routines for explorer
if ((BrowserDetect.browser.toLowerCase() == "explorer") && (BrowserDetect.version < 7)) {
    var isIE6 = true;
}

/*
 * set rounded corners / create the divs when the dom is loaded
 * "Footer" vs "footer"
 */ 
if (dosetRoundedCorners) {	
	var rounding = new domFunction(function(){
		if (!document.getElementById('footer')) return false;
		CreateRoundedCorners();
    }, {
        'footer': 'id' // execute the function when this element is loaded
    });
}

/* randomise script
 * Author: Elle Meredith <elle at designbyelle dot com dot au>
 * Version: 2009 Jan 20
 *
 * This script is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation.
 *
 * http://designbyelle.com.au/
 *
 * Randomises the children of an unordered list container.
 * Then, whether it is displayed or not is controlled with CSS
*/
function randomiseList(element) {
	if (!document.getElementById || !document.getElementsByTagName) return false;
	if (!document.getElementById(element)) return false;
 		var elem = document.getElementById(element);
 		var quotes = elem.getElementsByTagName("li");
 		var quote_count = quotes.length;
 		var random_num = Math.floor ((Math.random() * quote_count));
 	for (var i=0; i<quote_count; i++) {
 		if (quotes[i] == quotes[random_num]) {
 			addClass(quotes[i], "selected");
 		} else {
 			addClass(quotes[i], "hide");
 		}
 	}
}

function addClass(element,value) {
	if (!element.className) {
		element.className = value;
	} else {
		newClassName = element.className;
		newClassName+= " ";
		newClassName+= value;
		element.className = newClassName;
	}
} 

// adserver script function fallback
if (typeof OA_show != 'function') {
    function OA_show(){
        dump("Dummy OA_show : was not defined");
    }
}

// update screen & page dimensions
if (showScreenInfo) {
    addEventSimple(window, "resize", env.calculatePageSize);
    addEventSimple(window, "resize", env.calculateScreenUsage);
    addEventSimple(window, "scroll", env.calculatePageScroll);
}

// Error logging and feedback
addLoadEvent(dump);


/* Added for the german pricelist */
function PriceListToggle(sec) {
	var t = $(sec);
	if(t == null) return false;
	if(t.style.display == 'none') {
		t.style.display = '';
		$(sec+'-Link').style.backgroundPosition = 'left -8px';
		t.focus();
	}
	else {
		t.style.display = 'none';
		$(sec+'-Link').style.backgroundPosition = 'left 3px';		
	}
}

function alignFrontContentBoxes() {
	var frontContent = $$('div.columnContent');
	
	if(frontContent == null) return false;
		var fC1 = frontContent[0];
		var fC2 = frontContent[1];
		
		if(fC1.getHeight() > fC2.getHeight()) {
			fC2.style.height = fC1.getHeight()+'px';
		} else {
			fC1.style.height = fC2.getHeight()+'px';
		}
}


