/**
 * @author WW
 */
 
window.ie8 = navigator.appVersion.indexOf('MSIE 8.0') > -1;
window.ie7 = navigator.appVersion.indexOf('MSIE 7.0') > -1;
window.ie6 = navigator.appVersion.indexOf('MSIE 6.0') > -1;
if(ie8) ie6 = ie7 = false;
if(ie7) ie6 = false;
 
//Fix some IE6 issues
if(window.ie6){
	if (document.all && document.styleSheets && document.styleSheets[0] && document.styleSheets[0].addRule){
	    new Asset.javascript(rooturl+(jacket ? 'javascript/?iepngfix_tilebg' : 'webapp/shared/javascript/?iepngfix_tilebg'));
        var htcurl = jacket ? rooturl+'webapp/templates/styles/' : rooturl+'webapp/templates/default/styles/';
		document.styleSheets[0].addRule('input', 'behavior: url('+htcurl+'/pngfix.htc)');
		document.styleSheets[0].addRule('body', 'behavior: url('+htcurl+'/csshover.htc)');
		document.styleSheets[0].addRule('body', 'behavior: url('+htcurl+'/minmax.htc)');
		document.styleSheets[0].addRule('div', 'behavior: url('+htcurl+'/minmax.htc)');
		document.styleSheets[0].addRule('div', 'behavior: url('+htcurl+'/pngfix.htc)');
		document.styleSheets[0].addRule('img', 'behavior: url('+htcurl+'/pngfix.htc)');
	}
}

/**
 * Class Ajax_Hash
 *
 * Allows easier manipulation of the location.hash string.
 * Fires an event onChange whenever a hash variable is
 * changed using setValue(key, value) 
 *
 * hash = new AJAX.Hash;
 *
 * getHash						- mostly internal, returns an object
 * getValue(key)			- gets the value stored in the hash key
 * setValue(key,value)	- sets the key to the specified value
 *
 * hash.setValue('mykey', 'myvalue');
 * alert(hash.getValue('mykey'));
 *
 * => would alert 'myvalue'
 */
var Ajax_Hash = new Class({
	initialize: function(){
		Ajax_Hash.implement(new Events);
		this.lastChange = '';
		this.importHash();
	},

	getHash: function() {
		var ret = new Object();
		var curhash = location.hash.substring(1);
		if(curhash.length > 0) {
			curhash = curhash.split('|');
			curhash.each(function(curitem,i) {
				curitem = curitem.split('=');
				if(curitem.length == 2)
					eval('ret["'+curitem[0]+'"] = "'+curitem[1]+'"');
			});
		}
		return ret;
	}, 
	
	getValue: function(key) {
		var curhash = this.getHash();
		var ret = eval('curhash["'+key+'"]');
		if(ret=='undefined') ret = undefined;
		return ret;
	},
	
	setValue: function(key, value) {
			var curhash = this.getHash();
			var oldvalue = curhash[key];
			eval('curhash["'+key+'"] = "'+value+'"');
			var str = new Array();
			for(var i in curhash)
				if(curhash[i] !== undefined && curhash[i] != 'undefined')
					str.push(i+'='+curhash[i]);
			location.hash = str.join('|');
			if(oldvalue != value)
				this.fireEvent('onChange', [key, value, this.lastChange]);
			this.lastChange = key;
	},
	
	importHash: function() {
		var hash = this.getHash();
		for(var i in hash)
			this.setValue(i, hash[i]);
	}
});

/**
 * Ajax_Queue
 *
 * Automated AJAX calling queue. Will automatically begin checking
 * for a Request to be added to it when initialised into a variable,
 * and then continue to execute any future Request's that are added
 *
 * the submit URL will be set to rooturl + 'ajax.php' if not defined
 * and the method will be set to post
 *
 * queue = new AJAX.Queue;
 * queue.addToQueue(new Request({}));
 */
var Ajax_Queue = new Class({

	initialize: function(){
		this.queue = [];
		this.startTimer();
	},
	
	addToQueue: function(calldata){
		this.queue.push(calldata);
	},
	
	startTimer: function(){
		this.timer = this.doQueue.periodical(300, this);
	},
	
	doQueue: function(){
		if(this.queue.length > 0) {
			$clear(this.timer);
			var call = this.queue.shift();
			call.addEvent('onComplete', this.doQueue.bind(this));
			if(call.options.url == '')
				call.options.url = rooturl + 'ajax.php';
			if(call.method == undefined)
				call.method = 'post';
			call.send();
		} else {
			$clear(this.timer);
			this.startTimer();
		}
	} 
});

/**
 * class AJAX
 *
 * Wraps up AJAX functions.
 *
 * AJAX.Hash - manipulation of the location.hash string
 *						to allow Back/Forward navigation
 *
 * AJAX.Queue - queue for Ajax.Request calls so they run
 *						one after the other without having to check
 *						if an AJAX call is in progress. Requires one
 *						parameter of type AJAX.Call
 */
var AJAX = new Class();
AJAX.Hash = Ajax_Hash;
AJAX.Queue = Ajax_Queue;

var ajax_hash = new AJAX.Hash;
var ajax_queue = new AJAX.Queue;


/**
 * [].eachDelayed(delay, function(), bind)
 */
Array.implement({
    eachDelayed: function (delay, fn, bind) {
        var self = this, i = 0;
        (function () {
            fn.call(bind, self[i], i, self);
            if (++i < self.length) {
                setTimeout(arguments.callee, delay);
            }
       })();
    }
});

function waitForCSS(css, func){	
	var chkObj = {
		'css': css,
		'callback': func,
		'timer': 0,
		'bind': this,
		'func': function(){
			for(var i = 0; i < document.styleSheets.length; i++){
				if(document.styleSheets[i].href.contains(this.css)){
					$clear(this.timer);
					this.callback.attempt([], this.bind);
				}
			}
		}
	};
	chkObj.timer = chkObj.func.periodical(50, chkObj);
}

/*
 * scaleDimensions(objectWidth, objectHeight, maxWidth, maxHeight)
 *
 * Scales a width/height based on a maximum width/height it can fit into.
 * If the passed in dimensions are smaller, the values will be scaled up
 * For larger dimensions, they will be scaled down to fit in the maximum
 * sizes specified. If you set overflow = true, the dimensions will be scaled up
 * to overflow the box but cover the entire area of the box.
 *
 * Returns an [object]
 *  return.width	- new width of object based on scale
 *  return.height	- new height of object based on scale
 *  return.left		- offset to use to keep the object centered horizontally
 *  return.top		- offset to use to keep the object centered vertically
 *  return.ratio	- ratio that was used to scale the parameters
 */
function scaleDimensions(objectWidth, objectHeight, maxWidth, maxHeight, overflow){
	if(!$defined(overflow) || overflow != true) overflow = false;
	
	var object = {'ratio': maxWidth / objectWidth};
    if (eval('maxHeight / objectHeight ' + (overflow ? '>' : '<') + ' object.ratio')) object.ratio = maxHeight / objectHeight;
	
	object.width = objectWidth * object.ratio;
	object.height = objectHeight * object.ratio;
	object.left = (maxWidth / 2) - (object.width / 2);
	object.top = (maxHeight / 2) - (object.height / 2);
	
	return object;
}


/*
 * setupMorph(eElement, sDisplayStyle)
 *
 * Sets up the morph event of an element as to hide it when 
 * its opacity is morphed to 0 or to show it when its 
 * opacity is morphed from 0
 *
 * sDisplayStyle is optional, defaults to 'block' which is
 * usually ok.
 *
 * Can be set up with class="defaultMorph" on elements
 */
function setupMorph(eElement, sDisplayStyle, iDuration){
	if(!$defined(iDuration)) iDuration = 1;
	if(!$defined(sDisplayStyle)) sDisplayStyle = 'block';
	eElement = $(eElement);
	eElement.setStyle('opacity', 0);
	eElement.set('morph', {'duration': iDuration * 1000});
	eElement.get('morph').addEvents({
		'onStart': function(e){var show = true; $try(function(){show = this.to.opacity[0].value != 0;}.bind(this)); if(e.getStyle('opacity') == 0 && show) e.style.display = sDisplayStyle;},
		'onComplete': function(e){if(e.getStyle('opacity') == 0) e.style.display = 'none';}
	});
}

/*
 * fadeImages(eElement, iDuration, iFadeDelay)
 *
 * Fades between all the images in an element showing each
 * for iDuration seconds
 */
function fadeImages(eElement, iDuration, iFadeDelay){
	if(!$defined(window._fadeImages_autoRotate)) window._fadeImages_autoRotate = [];
	
	if(!$defined(iFadeDelay)) iFadeDelay = 1;
	if(!$defined(iDuration)) iDuration = 5;
	
	var eImages = ($type(eElement) == 'string' ? $(eElement) : eElement);

	if(eImages.getStyle('position') != 'relative' && eImages.getStyle('position') != 'absolute' && eImages.getStyle('position') != 'fixed')
		eImages.style.position = 'relative';
	
	eImages = eImages.getElements('img');

	if(eImages.length == 0) return;

	$each(eImages, function(img){img.setStyles({'position': 'absolute', 'top': 0, 'left': 0}); setupMorph(img, 'block', iFadeDelay);});
	eImages[0].setStyles({'opacity': 1, 'display': 'block'});
	
	var rotateFunction = function(eImages){
		if(!this.curImage) this.curImage = 0;
		this.curImage += 1;
		if(this.curImage > eImages.length - 1) this.curImage = 0;
		$each(eImages, function(img, i){img.morph({'opacity': i == this.curImage ? 1 : 0})}.bind(this));
	};

	window._fadeImages_autoRotate.include(rotateFunction.periodical(iDuration * 1000, rotateFunction, [eImages]));

    window.addEvent('beforeunload', function(){
		for(var i = window._fadeImages_autoRotate.length - 1; i >= 0; i--)
        	$clear(window._fadeImages_autoRotate[i]);
    });
}

/*
 * hideDialog(eElement) / showDialog(eElement);
 *
 * Shows an element in modal form.
 */
function hideDialog(eElement)
{
	if($type(eElement) == 'string') eElement = $(eElement);
	eElement.morph({'opacity': 0});
}

function showDialog(eElement,eWidth,eHeight)
{
	if($type(eElement) == 'string') eElement = $(eElement);
			 
	if(eElement.retrieve('dialog', false) == false){
		setupMorph(eElement);
		eElement.store('dialog', true);
	}

	eElement.inject(document.body);

	eElement.morph({'opacity': 1});
	
	if(!$defined(eWidth))
		eWidth = eElement.getCoordinates().width;
	
	if(!$defined(eHeight))
		eHeight = eElement.getCoordinates().height;
	
	eElement.setStyles({
		'width': eWidth,
		'height': eHeight				   
	});

	eElement.setStyles({
		'position': 'absolute',
		'z-index': 320000 + (isNaN(parseInt(eElement.getStyle('z-index'))) ? 0 : parseInt(eElement.getStyle('z-index'))),
		'left': window.getScrollLeft() + (getWindowSize().width / 2) - (eElement.getCoordinates().width / 2),
		'top': window.getScrollTop() + (getWindowSize().height / 2) - (eElement.getCoordinates().height / 2)
	});
}

/*
 * hideModal(eElement) / showModal(eElement);
 *
 * Shows an element in modal form.
 */
function hideModal(eElement)
{
	if($type(eElement) == 'string') eElement = $(eElement);
	var eDiv = eElement.getParent();
	eDiv.morph({'opacity': 0});
}

function showModal(eElement,preventClickClose)
{
	if(!$defined(preventClickClose)) preventClickClose = false;
	var eDiv;
	if($type(eElement) == 'string') eElement = $(eElement);

	if(eElement.retrieve('modal', false) == false){
		eDiv = new Element('div', {
			'styles': {
				'opacity': 0,
				'display': 'none',
				'position': 'fixed',
				'width': '100%',
				'height': '100%',
				'top': 0,
				'left': 0,
				'z-index': 40000,
				'background': 'url('+rooturl+'webapp/shared/javascript/resources/ModalDialog/ModalDialog_blackback.png)'
			},
			'events': {
				'click': function(e){
					if(!preventClickClose && e.target == eDiv) hideModal(eElement);
				}
			}
		});
		eElement.setStyles({
			'display': 'block',
			'position': 'absolute'
		});
		eElement.inject(eDiv);
		eElement.store('modal', true);
		eDiv.inject(document.body);

		setupMorph(eDiv);
		window.addEvent('resize', function(){
			eDiv.setStyles('width', document.body.clientWidth);
			eElement.setStyles({
				'left': (eDiv.getCoordinates().width / 2) - (eElement.getCoordinates().width / 2),
				'top': (eDiv.getCoordinates().height / 2) - (eElement.getCoordinates().height / 2)
			});
		});
	} else {
		eDiv = eElement.getParent();
	}
	eDiv.morph({'opacity': 1});

	window.fireEvent('resize');
}


Element.implement({
  showModal: function(preventClickClose){
    showModal(this,preventClickClose);
  },
  hideModal: function(){
    hideModal(this);
  },
  showDialog: function(eWidth,eHeight){
    showDialog(this,eWidth,eHeight);
  },
  hideDialog: function(){
    hideDialog(this);
  },
  fadeImages: function(iDuration, iFadeDelay){
  	fadeImages(this, iDuration, iFadeDelay);
  }
});

function getWindowSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return {'width': myWidth,'height': myHeight};
}

function log(){
	if(window.debugService){
		if(arguments.length == 2 && arguments[1] === true)
			window.debugService.inspect($type(arguments[0]), arguments[0]);
		else
			for(var i = 0; i < arguments.length; i++)
				window.debugService.trace(arguments[i]);
	}else if(window.console && console.log) {
        if(arguments.length == 1 && $type(arguments[0]) == 'object' || arguments.length == 2 && $type(arguments[0]) == 'object' && arguments[1] === true)
            console.dir(arguments[0]);
        else if(arguments.length == 1)
            console.log(arguments[0]);
        else
            console.log(arguments);
    }else if(Debug.writeln){
		for(var i = 0; i < arguments.length; i++)
			Debug.writeln(arguments[i]);
	}
}

function fadeBackgrounds(){
	iDuration = $('backgrounds').className;
	if(iDuration == '') iDuration = 5;
	var eImages = $('backgrounds');

	if(eImages.getStyle('position') != 'relative' && eImages.getStyle('position') != 'absolute' && eImages.getStyle('position') != 'fixed')
		eImages.setStyle('position', 'relative');

	eImages = eImages.getElements('img');

	if(eImages.length == 0) return;
	
	window._fadeBackgrounds = true;
	
	$each(eImages, function(img){setupMorph(img);});
	
	var curImage = 0;
	window._fadeBackgrounds_autoRotate = function(){
		curImage += 1;
		if(curImage > eImages.length - 1) curImage = 0;
		
		$each(eImages, function(img, i){img.morph({'opacity': i == curImage ? 1 : 0})});
	};
	
	eImages[0].setStyles({'opacity': 1, 'display': 'block'});
	window._fadeBackgrounds_autoRotate.periodical(iDuration * 1000); //time between image switches in milliseconds

	window.addEvent('resize', function(){bgImageFix();});

    window.addEvent('beforeunload', function(){
        $clear(window._fadeBackgrounds_autoRotate);
    });
}


function bgImageFix(){
	var imgs = $('backgrounds').getElements('img');
	var style = $('backgrounds').retrieve('style', {});
	var wSize = getWindowSize();
	
	$each(imgs, function(img){
		img.setStyles({
			'left': style.margin == 'auto' ? wSize.width / 2 - img.width / 2 : img.getStyle('left'),
			'position': 'absolute'
		});
	});
}

function createHoverBackground(eElement, withClickState){
  if(!$defined(withClickState) || withClickState !== true) var withClickState = false;

  window.getAndStoreDivDetails = function(target){
      target = $(target);

	  var pngFix = false;
      if(window.ie6){
    	  if(!target.retrieve('root'))
    		  target = target.getParent();
        target.store('outer', true);
        target.store('pngFix', true);
        pngFix = true;
      }
      
      
      var returnData = {'height': 0, 'bgPos': 0, 'pngFix': pngFix, 'target': target};
      
	  
      var divHeight = parseInt(target.retrieve('height', 0));

      if(divHeight == 0) {
          divHeight = parseInt(target.getStyle('height'));
          target.store('height', divHeight);
          
          if(pngFix){
              var eDiv = target.getElement('div');
			  try{
              	var bgPos = eDiv.getStyle('clip').split(' ');
			  }catch(ex){
          		target.store('height', 0);
				return;
			  }
              bgPos[0] = parseInt(bgPos[0].substring(bgPos[0].indexOf('(')+1));
              bgPos[1] = parseInt(bgPos[1]);
              bgPos[2] = parseInt(bgPos[2]);
              bgPos[3] = parseInt(bgPos[3]);
              target.store('top', parseInt(eDiv.getStyle('top')));
              divHeight = parseInt(target.getStyle('height'));
              target.store('innerHeight', parseInt(eDiv.getStyle('height')));
              target.store('height', divHeight);
          } else if(Browser.Engine.trident)
              var bgPos = parseInt(target.getStyle('background-position-y'));
          else {
              var bgPos = target.getStyle('background-position').split(' ');
              bgPos[0] = parseInt(bgPos[0]);
              bgPos[1] = parseInt(bgPos[1]);
          }
          target.store('background-position', bgPos);
      }

      returnData.top = parseInt(target.retrieve('top', 0));
      returnData.height = divHeight;
      if(pngFix) {
        returnData.pngFix = true;
        returnData.innerHeight = target.retrieve('innerHeight', 0);
      }
      returnData.bgPos = target.retrieve('background-position');

      return returnData;
  };
  
  if(eElement.get('tag') == 'input') eElement.value = '';

  eElement.style.cursor = 'pointer';
  
  eElement.disable = function(){
    this.style.cursor = 'auto';
    this.store('holdDown', false);
    this.fireEvent('mouseleave', {'target': this});
    this.store('disabled', true);
    if(this.get('tag') != 'input') this.setStyle('opacity', 0.5);
  }.bind(eElement);
  
  eElement.enable = function(){
    this.style.cursor = 'pointer';
    this.store('disabled', false);
    if(this.get('tag') != 'input') this.setStyle('opacity', 1);
  }.bind(eElement);
  
  eElement.enable();
  
  eElement.isdisabled = function(){
    return this.retrieve('disabled', false);
  }.bind(eElement);
  
  window.addEvent('beforeunload', function(){
		eElement.removeEvents();
		try{
			delete eElement.disable;
			delete eElement.enable;
			delete eElement.isdisabled;
		}catch(ex){}
		eElement.disable = null;
		eElement.enable = null;
		eElement.isdisabled = null;
  }.bind(this));

  var events = {
  	'mouseenter': function(e){
        var targetData = getAndStoreDivDetails(e.target);
		
		if(!targetData || !targetData.target) return;

        if(targetData.target.retrieve('holdDown', false) == true) return;
        if(targetData.target.retrieve('disabled', false) == true) return;

        if(targetData.pngFix) {
            var eDiv = targetData.target.getElement('div');

            var bgPos = $A(targetData.bgPos);
            bgPos[0] += targetData.height;
            bgPos[2] += targetData.height;
  			bgPos = 'rect('+bgPos.join('px ')+'px)';
  			eDiv.setStyles({
                'clip': bgPos,
                'top': targetData.top - targetData.height,
                'height': targetData.innerHeight + targetData.height
            });
        } else if(Browser.Engine.trident)
  			targetData.target.setStyle('background-position-y', (targetData.bgPos - targetData.height) + 'px');
  		else
  			targetData.target.setStyle('background-position', targetData.bgPos[0] + 'px ' + (targetData.bgPos[1] - targetData.height) + 'px');
  	},
  	'mouseleave': function(e){
        var targetData = getAndStoreDivDetails(e.target);
		
		if(!targetData || !targetData.target) return;

        if(targetData.target.retrieve('holdDown', false) == true) return;

        if(targetData.pngFix) {
            var eDiv = targetData.target.getElement('div');

  			eDiv.setStyles({
                'clip': 'rect('+targetData.bgPos.join('px ')+'px)',
                'top': targetData.top,
                'height': targetData.innerHeight
            });
        } else if(Browser.Engine.trident)
  			targetData.target.setStyle('background-position-y', targetData.bgPos + 'px');
  		else
            targetData.target.setStyle('background-position', targetData.bgPos[0] + 'px ' + targetData.bgPos[1] + 'px');
  	}
  };
  if(withClickState) {
    events.mousedown = function(e){
        var targetData = getAndStoreDivDetails(e.target);
		
        if(targetData.target.retrieve('disabled', false) == true) return;

        if(targetData.pngFix) {
            var eDiv = targetData.target.getElement('div');

            var bgPos = $A(targetData.bgPos);
            bgPos[0] += targetData.height*2;
            bgPos[2] += targetData.height*2;
  			bgPos = 'rect('+bgPos.join('px ')+'px)';
  			eDiv.setStyles({
                'clip': bgPos,
                'top': targetData.top - targetData.height*2,
                'height': targetData.innerHeight + targetData.height*2
            });
        } else if(Browser.Engine.trident)
  			targetData.target.setStyle('background-position-y', (targetData.bgPos - (targetData.height * 2)) + 'px');
  		else
  			targetData.target.setStyle('background-position', targetData.bgPos[0] + 'px ' + (targetData.bgPos[1] - (targetData.height *2)) + 'px');
    };
    events.mouseup = function(e){
  	    var target = $(e.target);

        if(target.retrieve('holdDown', false) == true) return;

        if(Browser.Engine.trident4)
            target.getParent().fireEvent('mouseenter', e);
        else
  	        target.fireEvent('mouseenter', e);
    };
  }
  
  eElement.store('root', true);

  eElement.addEvents(events);
}


function buildRatings(field, rating){
	if(!$defined(rating))
		var rating = field.value;

	var divRating = field.retrieve('divRating', false);

	if(divRating == false) {
		divRating = new Element('div', {
			'class': 'rating'
		}).inject(field, 'after');

		divRating.addEvents({
			'mousemove': function(e){
				if(e.target.get('tag') == 'img'){
					buildRatings(field, e.target.retrieve('rating'));
				}
			},
			'mouseleave': function(e){
				buildRatings(field);
			}
		});
		
		for(var i = 0; i < 5; i++){
			var img = new Element('img', {
				'src': rooturl + 'webapp/shared/icon/?star' + (rating > i ? '' : '_grey') + '.png',
				'width': 16,
				'height': 16,
				'alt': 'Star',
				'events': {
					'click': function(e){
						e.target.retrieve('field').value = e.target.retrieve('rating');
						buildRatings(e.target.retrieve('field'));
					}
				}
			}).inject(divRating);
			img.store('rating', i + 1);
			img.store('field', field);
		}
		
		field.store('divRating', divRating);
		
		buildRatings(field);
		return;
	}
	
	var imgs = divRating.getElements('img');
	for(var i = 0; i < 5; i++)
		imgs[i].src = rooturl + 'webapp/shared/icon/?star' + (rating > i ? '' : '_grey') + '.png'
}

/*
 * Site-wide setup functions:
 *
 *  - setupMorph() called on all class=".defaultMorph" elements
 *  - replacement of all <a rel="external"> links to open in a new window
 *  - fadeImages() called on all class=".fadeImages"
 *  - all <img/input class="hover"> elements will toggle their src parameters with _off/_on
 */
window.addEvent('domready', function(){
	$each($$('.defaultMorph'), function(eElement){setupMorph(eElement);});
	
	$each($$('.fadeImages'), function(eElement){
		var iFadeDelay = 1;
		var iDuration = 5;
		
		if(eElement.className.length > 11){
			var tDuration, tFadeDelay;
			var elClass = eElement.className;
			tDuration = elClass.substring(elClass.indexOf('fadeImages')+11);		
			tDuration = tDuration.substring(0, tDuration.indexOf(' ') > -1 ? tDuration.indexOf(' ') : tDuration.length);
			if(tDuration - 0 == parseInt(tDuration)) iDuration = tDuration;
			
			tFadeDelay = elClass.substring(elClass.indexOf('fadeImages')+11);
			tFadeDelay = tFadeDelay.substring(tDuration.toString().length+1);
			tFadeDelay = tFadeDelay.substring(0, tFadeDelay.indexOf(' ') > -1 ? tFadeDelay.indexOf(' ') : tFadeDelay.length);
			if(tFadeDelay - 0 == parseInt(tFadeDelay)) iFadeDelay = tFadeDelay;
		}

		fadeImages(eElement, iDuration, iFadeDelay);
	});
	$each($$('a[rel="external"]'), function(eA){
		eA.addEvent('click', function(e){
			e.preventDefault();
			if(window.pageTracker && pageTracker._trackPageview)
				pageTracker._trackPageview(eA.getProperty('href'));
				window.open(eA.getProperty('href'), '_blank');
		});
		window.addEvent('beforeunload', function(){this.removeEvents()}.bind(eA));
	});
	
	$each($$('img.hover,input.hover'), function(eElement){eElement.setStyle('cursor', 'pointer');eElement.addEvents({'mouseenter': function(e){eElement.src = eElement.src.replace('_off','_on');},'mouseleave': function(e){eElement.src = eElement.src.replace('_on','_off');}});});
	
	$each($$('.hoverbg'), function(eElement){
		createHoverBackground(eElement);
	});

	if($('backgrounds')){
		$('backgrounds').inject(document.body, 'top');
		$('backgrounds').setStyles({
			'z-index': -1,
			'position': 'fixed',
			'overflow': 'hidden'
		});
		
		for(var i = 0; i < document.styleSheets.length; i++){
			var rules = document.styleSheets[i].cssRules;
			if(!$defined(rules)) rules = document.styleSheets[i].rules;
			for(var j = 0; j < rules.length; j++){
				if(rules[j].selectorText.toLowerCase() == '#backgrounds img'){
					var style = {};
					if(rules[j].style.marginLeft.toLowerCase() == 'auto') style.margin = 'auto';
					$('backgrounds').store('style', style);
				}
			}
		}
		
		bgImageFix();
		fadeBackgrounds();
	}
	
	$each($$('input.rating'), buildRatings);
	
	$each($$('input.boolean'), function(input){
		var hidden = new Element('input', {
			'type': 'hidden',
			'name': input.name,
			'value': input.checked ? '1' : '0'
		}).inject(input, 'after');	
		
		input.checked = input.value == '1' ? true : false;
		
		input.setProperty('name', '');
		
		input.addEvent('change', function(e){
			hidden.value = e.target.checked ? '1' : '0';
		}.bind(this));
	});
});