/*
   Behaviour v1.1 by Ben Nolan, June 2005. Based largely on the work
   of Simon Willison (see comments by Simon below).

   License:
   	This file is entirely BSD licensed.

   More information:
   	http://ripcord.co.nz/behaviour/
*/

Behaviour = {
	list : new Array,

	register : function(sheet){
		Behaviour.list.push(sheet);
	},

	start : function(){
		Behaviour.addLoadEvent(function(){
			Behaviour.apply();
		});
	},

	apply : function(){
		for (h=0;sheet=Behaviour.list[h];h++){
			for (selector in sheet){
				list = document.getElementsBySelector(selector);

				if (!list){
					continue;
				}

				for (i=0;element=list[i];i++){
					sheet[selector](element);
				}
			}
		}
	},

	addLoadEvent : function(func){
		var oldonload = window.onload;

		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				oldonload();
				func();
			}
		}
	}
}

// using onload="main" to prevent IE from freeing the script - Alwin Blok - 2007-04-05
//Behaviour.start();

// The following code is Copyright (C) Simon Willison 2004.

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}
document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
				// added && element - Alwin Blok 2007-03-29
      if (tagName && element && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) { //"
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }

    if (!currentContext[0]){
    	return;
    }

    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}


/********
*
*   DHL behaviours
*
********/

// assumes default best/worst ratings : 0-5
styleRating = function(elem){
	var pct = parseFloat(elem.innerHTML)*20
	elem.style.width = (pct +'%')
	elem.style.fontSize = '5px'
	elem.style.height='0px'
	elem.style.paddingTop='20px'
}

new_TabbedPanel = function(elem){
	new TabbedPanel(elem)
}

setupImageViewer = function(elem){
  var tp = new TabbedPanel(elem)
	var ls = new LinkStepper(elem)
	tp.onselect = function(evt){ls.position = evt.index}
	var as = elem.parentNode.getElementsByTagName('A');
	for(var i=0; i<as.length; i++){
		if(as[i].className == 'next'){
			as[i].onclick = function(){ls.next()}
			as[i].href = 'javascript:void(0);'
		}
		if(as[i].className == 'prev'){
			as[i].onclick = function(){ls.prev()}
			as[i].href = 'javascript:void(0);'
		}
	}
}

setupRatingControl = function(elem){
	// .. select span.value
	var span = elem.parentNode.parentNode.parentNode.getElementsByTagName('SPAN')[0];
	elem.onclick = function(){span.innerHTML = elem.value;styleRating(span)}
}

Behaviour.register({
	//"div#tab ul#mortgage_menu" : new_TabbedPanel,
	//"ul.employees" : new_TabbedPanel
})


function main(){
	var mortgage_menu = document.getElementById('mortgage_menu');
	if (mortgage_menu){
		new TabbedPanel(mortgage_menu, {'activeClass' : 'blad_selected', 'inactiveClass' : 'blad', 'activeLinkClass' : 'selected', 'inactiveLinkClass' : ''});
	}

	var employees_menu = document.getElementById('employees');
	if (employees_menu){
		new TabbedPanel(employees_menu, {'activeClass' : 'employee_selected', 'inactiveClass' : 'employee', 'activeLinkClass' : 'selected', 'inactiveLinkClass' : ''});
	}
	//Behaviour.apply();
}


/*
   Behaviour v1.1 by Ben Nolan, June 2005. Based largely on the work
   of Simon Willison (see comments by Simon below).

   License:
   	This file is entirely BSD licensed.

   More information:
   	http://ripcord.co.nz/behaviour/
*/

Behaviour = {
	list : new Array,

	register : function(sheet){
		Behaviour.list.push(sheet);
	},

	start : function(){
		Behaviour.addLoadEvent(function(){
			Behaviour.apply();
		});
	},

	apply : function(){
		for (h=0;sheet=Behaviour.list[h];h++){
			for (selector in sheet){
				list = document.getElementsBySelector(selector);

				if (!list){
					continue;
				}

				for (i=0;element=list[i];i++){
					sheet[selector](element);
				}
			}
		}
	},

	addLoadEvent : function(func){
		var oldonload = window.onload;

		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				oldonload();
				func();
			}
		}
	}
}

// using onload="main" to prevent IE from freeing the script - Alwin Blok - 2007-04-05
//Behaviour.start();

// The following code is Copyright (C) Simon Willison 2004.

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}
document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
				// added && element - Alwin Blok 2007-03-29
      if (tagName && element && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) { //"
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }

    if (!currentContext[0]){
    	return;
    }

    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}


/********
*
*   DHL behaviours
*
********/

// assumes default best/worst ratings : 0-5
styleRating = function(elem){
	var pct = parseFloat(elem.innerHTML)*20
	elem.style.width = (pct +'%')
	elem.style.fontSize = '5px'
	elem.style.height='0px'
	elem.style.paddingTop='20px'
}

new_TabbedPanel = function(elem){
	new TabbedPanel(elem)
}

setupImageViewer = function(elem){
  var tp = new TabbedPanel(elem)
	var ls = new LinkStepper(elem)
	tp.onselect = function(evt){ls.position = evt.index}
	var as = elem.parentNode.getElementsByTagName('A');
	for(var i=0; i<as.length; i++){
		if(as[i].className == 'next'){
			as[i].onclick = function(){ls.next()}
			as[i].href = 'javascript:void(0);'
		}
		if(as[i].className == 'prev'){
			as[i].onclick = function(){ls.prev()}
			as[i].href = 'javascript:void(0);'
		}
	}
}

setupRatingControl = function(elem){
	// .. select span.value
	var span = elem.parentNode.parentNode.parentNode.getElementsByTagName('SPAN')[0];
	elem.onclick = function(){span.innerHTML = elem.value;styleRating(span)}
}

Behaviour.register({
	//"div#tab ul#mortgage_menu" : new_TabbedPanel,
	//"ul.employees" : new_TabbedPanel
})


function main(){
	var mortgage_menu = document.getElementById('mortgage_menu');
	if (mortgage_menu){
		new TabbedPanel(mortgage_menu, {'activeClass' : 'blad_selected', 'inactiveClass' : 'blad', 'activeLinkClass' : 'selected', 'inactiveLinkClass' : ''});
	}

	var employees_menu = document.getElementById('employees');
	if (employees_menu){
		new TabbedPanel(employees_menu, {'activeClass' : 'employee_selected', 'inactiveClass' : 'employee', 'activeLinkClass' : 'selected', 'inactiveLinkClass' : ''});
	}
	//Behaviour.apply();
}


/**********
*
*		(c) AlwinBlok 2004-2007, The Netherlands
*
**********/
events = {};
events.compatHandler = function(fn){
	return function(evt){
		var evt = evt||window.event||{};
		if(!evt.layerX) evt.layerX = evt.x;
		if(!evt.type) evt.type = type;
		if(!evt.target && evt.srcElement) evt.target = evt.srcElement;
	  if(typeof evt.preventDefault == 'function') evt.preventDefault();
		else {
			evt.returnValue = false;
			evt.cancelBubble = true;
		}
		fn(evt);
		return false;
	}
}
/********
*
*   domQuery - utility functions for querying the dom
*
********/

domQuery = {}

domQuery.ufValue = function(elem){
	if(!elem) return null;
	var tagName = elem.tagName;
	return (tagName == 'INPUT' ? elem.value : (tagName == 'ABBR' || tagName == 'HTML:ABBR') ? elem.title : elem.innerHTML);
}

domQuery.elementHasClass = function(elem, classn){
	return (new String(' '+elem.className+' ').search(' '+classn+' ') > -1);
}

domQuery.getChildNodesByClass = function(elem, classn){
	var children = elem.childNodes;
	var result = [];
	for(var i=0; i<children.length; i++){
		if(domQuery.elementHasClass(children[i], classn)) result.push(children[i])
		result = result.concat(domQuery.getChildNodesByClass(children[i], classn))
	}
	return result
}

domQuery.getComputedProperty = function(elem, prop){
  var computedStyle = (typeof(elem.currentStyle) != 'undefined') ? elem.currentStyle :
		document.defaultView.getComputedStyle(elem, null);
  return computedStyle[prop];
}

/********
*
*   Slider
*
********/

function Slider(elem){
	// dom refs
	this.input = domQuery.getChildNodesByClass(elem, 'value').pop()
	this.track = document.createElement('div');
	this.handle = document.createElement('a');
	// object values
	this.value = parseFloat(domQuery.ufValue(this.input))
	this.min = parseFloat(domQuery.ufValue(domQuery.getChildNodesByClass(elem, 'min').pop()))
	this.max = parseFloat(domQuery.ufValue(domQuery.getChildNodesByClass(elem, 'max').pop()))
	// dom setup
	this.track.className = 'slider-track'
	this.handle.className = 'slider-handle'
	elem.style.position = 'relative'
	elem.appendChild(this.track)
	elem.appendChild(this.handle)
	// initialization and event-handlers
	this.setValue(this.value);
	this.setupEventHandlers(elem)
}

Slider.prototype.setupEventHandlers = function(elem){
	var me = this
	var currentPosition = 0;

	var setValuePx = events.compatHandler(function(e){
		var width = parseFloat(domQuery.getComputedProperty(elem, 'width'))
		var x = (e.target == elem) ? e.layerX : (e.clientX - currentPosition);
		me.setValue(me.min+((me.max-me.min)*(x/width)))
		if(typeof(me.onchange) == 'function') me.onchange();
	})

	elem.onmousedown = events.compatHandler(function(e){
		var onmousemove = (document.all) ? 'onmouseover' : 'onmousemove'
		document[onmousemove] = setValuePx;
		currentPosition = (e.clientX - e.layerX);
		document.onmouseup = function(){ document[onmousemove] = null }
	})

	// prevent IE from selecting the handle IE
	this.handle.onselectstart = events.compatHandler(function(){});
	this.handle.onselect = events.compatHandler(function(){});

	elem.onclick = setValuePx;
}


Slider.prototype.setValue = function(val){
	var val = (val < this.min == this.min < this.max) ? this.min : val;
	var val = (val > this.max == this.max > this.min) ? this.max : val;
	this.value = val;
	this.input.value = val;
  var perc = (100*(val-this.min))/(this.max-this.min)
	this.track.style.width = perc+'%'
}
