
/************? tools ?***************/
 //MooTools, My Object Oriented Javascript Tools. Copyright (c) 2006-2007 Valerio Proietti, <http://mad4milk.net>, MIT Style License.

var MooTools = {
	version: '1.11'
};

function $defined(obj){
	return (obj != undefined);
};

function $type(obj){
	if (!$defined(obj)) return false;
	if (obj.htmlElement) return 'element';
	var type = typeof obj;
	if (type == 'object' && obj.nodeName){
		switch(obj.nodeType){
			case 1: return 'element';
			case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
		}
	}
	if (type == 'object' || type == 'function'){
		switch(obj.constructor){
			case Array: return 'array';
			case RegExp: return 'regexp';
			case Class: return 'class';
		}
		if (typeof obj.length == 'number'){
			if (obj.item) return 'collection';
			if (obj.callee) return 'arguments';
		}
	}
	return type;
};

function $merge(){
	var mix = {};
	for (var i = 0; i < arguments.length; i++){
		for (var property in arguments[i]){
			var ap = arguments[i][property];
			var mp = mix[property];
			if (mp && $type(ap) == 'object' && $type(mp) == 'object') mix[property] = $merge(mp, ap);
			else mix[property] = ap;
		}
	}
	return mix;
};

var $extend = function(){
	var args = arguments;
	if (!args[1]) args = [this, args[0]];
	for (var property in args[1]) args[0][property] = args[1][property];
	return args[0];
};

var $native = function(){
	for (var i = 0, l = arguments.length; i < l; i++){
		arguments[i].extend = function(props){
			for (var prop in props){
				if (!this.prototype[prop]) this.prototype[prop] = props[prop];
				if (!this[prop]) this[prop] = $native.generic(prop);
			}
		};
	}
};

$native.generic = function(prop){
	return function(bind){
		return this.prototype[prop].apply(bind, Array.prototype.slice.call(arguments, 1));
	};
};

$native(Function, Array, String, Number);

function $chk(obj){
	return !!(obj || obj === 0);
};

function $pick(obj, picked){
	return $defined(obj) ? obj : picked;
};

function $random(min, max){
	return Math.floor(Math.random() * (max - min + 1) + min);
};

function $time(){
	return new Date().getTime();
};

function $clear(timer){
	clearTimeout(timer);
	clearInterval(timer);
	return null;
};

var Abstract = function(obj){
	obj = obj || {};
	obj.extend = $extend;
	return obj;
};

var Window = new Abstract(window);
var Document = new Abstract(document);
document.head = document.getElementsByTagName('head')[0];

window.xpath = !!(document.evaluate);
if (window.ActiveXObject) window.ie = window[window.XMLHttpRequest ? 'ie7' : 'ie6'] = true;
else if (document.childNodes && !document.all && !navigator.taintEnabled) window.webkit = window[window.xpath ? 'webkit420' : 'webkit419'] = true;
else if (document.getBoxObjectFor != null) window.gecko = true;

window.khtml = window.webkit;

Object.extend = $extend;

if (typeof HTMLElement == 'undefined'){
	var HTMLElement = function(){};
	if (window.webkit) document.createElement("iframe");
	HTMLElement.prototype = (window.webkit) ? window["[[DOMElement.prototype]]"] : {};
}
HTMLElement.prototype.htmlElement = function(){};

if (window.ie6) try {document.execCommand("BackgroundImageCache", false, true);} catch(e){};

var Class = function(properties){
	var klass = function(){
		return (arguments[0] !== null && this.initialize && $type(this.initialize) == 'function') ? this.initialize.apply(this, arguments) : this;
	};
	$extend(klass, this);
	klass.prototype = properties;
	klass.constructor = Class;
	return klass;
};

Class.empty = function(){};

Class.prototype = {

	extend: function(properties){
		var proto = new this(null);
		for (var property in properties){
			var pp = proto[property];
			proto[property] = Class.Merge(pp, properties[property]);
		}
		return new Class(proto);
	},

	implement: function(){
		for (var i = 0, l = arguments.length; i < l; i++) $extend(this.prototype, arguments[i]);
	}

};

Class.Merge = function(previous, current){
	if (previous && previous != current){
		var type = $type(current);
		if (type != $type(previous)) return current;
		switch(type){
			case 'function':
			var merged = function(){
				this.parent = arguments.callee.parent;
				return current.apply(this, arguments);
			};
			merged.parent = previous;
			return merged;
			case 'object': return $merge(previous, current);
		}
	}
	return current;
};

var Chain = new Class({

	chain: function(fn){
		this.chains = this.chains || [];
		this.chains.push(fn);
		return this;
	},

	callChain: function(){
		if (this.chains && this.chains.length) this.chains.shift().delay(10, this);
	},

	clearChain: function(){
		this.chains = [];
	}

});

var Events = new Class({

	addEvent: function(type, fn){
		if (fn != Class.empty){
			this.$events = this.$events || {};
			this.$events[type] = this.$events[type] || [];
			this.$events[type].include(fn);
		}
		return this;
	},

	fireEvent: function(type, args, delay){
		if (this.$events && this.$events[type]){
			this.$events[type].each(function(fn){
				fn.create({'bind': this, 'delay': delay, 'arguments': args})();
			}, this);
		}
		return this;
	},

	removeEvent: function(type, fn){
		if (this.$events && this.$events[type]) this.$events[type].remove(fn);
		return this;
	}

});

var Options = new Class({

	setOptions: function(){
		this.options = $merge.apply(null, [this.options].extend(arguments));
		if (this.addEvent){
			for (var option in this.options){
				if ($type(this.options[option] == 'function') && (/^on[A-Z]/).test(option)) this.addEvent(option, this.options[option]);
			}
		}
		return this;
	}

});

Array.extend({

	forEach: function(fn, bind){
		for (var i = 0, j = this.length; i < j; i++) fn.call(bind, this[i], i, this);
	},

	filter: function(fn, bind){
		var results = [];
		for (var i = 0, j = this.length; i < j; i++){
			if (fn.call(bind, this[i], i, this)) results.push(this[i]);
		}
		return results;
	},

	map: function(fn, bind){
		var results = [];
		for (var i = 0, j = this.length; i < j; i++) results[i] = fn.call(bind, this[i], i, this);
		return results;
	},

	every: function(fn, bind){
		for (var i = 0, j = this.length; i < j; i++){
			if (!fn.call(bind, this[i], i, this)) return false;
		}
		return true;
	},

	some: function(fn, bind){
		for (var i = 0, j = this.length; i < j; i++){
			if (fn.call(bind, this[i], i, this)) return true;
		}
		return false;
	},

	indexOf: function(item, from){
		var len = this.length;
		for (var i = (from < 0) ? Math.max(0, len + from) : from || 0; i < len; i++){
			if (this[i] === item) return i;
		}
		return -1;
	},

	copy: function(start, length){
		start = start || 0;
		if (start < 0) start = this.length + start;
		length = length || (this.length - start);
		var newArray = [];
		for (var i = 0; i < length; i++) newArray[i] = this[start++];
		return newArray;
	},

	remove: function(item){
		var i = 0;
		var len = this.length;
		while (i < len){
			if (this[i] === item){
				this.splice(i, 1);
				len--;
			} else {
				i++;
			}
		}
		return this;
	},

	contains: function(item, from){
		return this.indexOf(item, from) != -1;
	},

	associate: function(keys){
		var obj = {}, length = Math.min(this.length, keys.length);
		for (var i = 0; i < length; i++) obj[keys[i]] = this[i];
		return obj;
	},

	extend: function(array){
		for (var i = 0, j = array.length; i < j; i++) this.push(array[i]);
		return this;
	},

	merge: function(array){
		for (var i = 0, l = array.length; i < l; i++) this.include(array[i]);
		return this;
	},

	include: function(item){
		if (!this.contains(item)) this.push(item);
		return this;
	},

	getRandom: function(){
		return this[$random(0, this.length - 1)] || null;
	},

	getLast: function(){
		return this[this.length - 1] || null;
	}

});

Array.prototype.each = Array.prototype.forEach;
Array.each = Array.forEach;

function $A(array){
	return Array.copy(array);
};

function $each(iterable, fn, bind){
	if (iterable && typeof iterable.length == 'number' && $type(iterable) != 'object'){
		Array.forEach(iterable, fn, bind);
	} else {
		for (var name in iterable) fn.call(bind || iterable, iterable[name], name);
	}
};

Array.prototype.test = Array.prototype.contains;

String.extend({

	test: function(regex, params){
		return (($type(regex) == 'string') ? new RegExp(regex, params) : regex).test(this);
	},

	toInt: function(){
		return parseInt(this, 10);
	},

	toFloat: function(){
		return parseFloat(this);
	},

	camelCase: function(){
		return this.replace(/-\D/g, function(match){
			return match.charAt(1).toUpperCase();
		});
	},

	hyphenate: function(){
		return this.replace(/\w[A-Z]/g, function(match){
			return (match.charAt(0) + '-' + match.charAt(1).toLowerCase());
		});
	},

	capitalize: function(){
		return this.replace(/\b[a-z]/g, function(match){
			return match.toUpperCase();
		});
	},

	trim: function(){
		return this.replace(/^\s+|\s+$/g, '');
	},

	clean: function(){
		return this.replace(/\s{2,}/g, ' ').trim();
	},

	rgbToHex: function(array){
		var rgb = this.match(/\d{1,3}/g);
		return (rgb) ? rgb.rgbToHex(array) : false;
	},

	hexToRgb: function(array){
		var hex = this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
		return (hex) ? hex.slice(1).hexToRgb(array) : false;
	},

	contains: function(string, s){
		return (s) ? (s + this + s).indexOf(s + string + s) > -1 : this.indexOf(string) > -1;
	},

	escapeRegExp: function(){
		return this.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
	}

});

Array.extend({

	rgbToHex: function(array){
		if (this.length < 3) return false;
		if (this.length == 4 && this[3] == 0 && !array) return 'transparent';
		var hex = [];
		for (var i = 0; i < 3; i++){
			var bit = (this[i] - 0).toString(16);
			hex.push((bit.length == 1) ? '0' + bit : bit);
		}
		return array ? hex : '#' + hex.join('');
	},

	hexToRgb: function(array){
		if (this.length != 3) return false;
		var rgb = [];
		for (var i = 0; i < 3; i++){
			rgb.push(parseInt((this[i].length == 1) ? this[i] + this[i] : this[i], 16));
		}
		return array ? rgb : 'rgb(' + rgb.join(',') + ')';
	}

});

Function.extend({

	create: function(options){
		var fn = this;
		options = $merge({
		'bind': fn,
		'event': false,
		'arguments': null,
		'delay': false,
		'periodical': false,
		'attempt': false
		}, options);
		if ($chk(options.arguments) && $type(options.arguments) != 'array') options.arguments = [options.arguments];
		return function(event){
			var args;
			if (options.event){
				event = event || window.event;
				args = [(options.event === true) ? event : new options.event(event)];
				if (options.arguments) args.extend(options.arguments);
			}
			else args = options.arguments || arguments;
			var returns = function(){
				return fn.apply($pick(options.bind, fn), args);
			};
			if (options.delay) return setTimeout(returns, options.delay);
			if (options.periodical) return setInterval(returns, options.periodical);
			if (options.attempt) try {return returns();} catch(err){return false;};
			return returns();
		};
	},

	pass: function(args, bind){
		return this.create({'arguments': args, 'bind': bind});
	},

	attempt: function(args, bind){
		return this.create({'arguments': args, 'bind': bind, 'attempt': true})();
	},

	bind: function(bind, args){
		return this.create({'bind': bind, 'arguments': args});
	},

	bindAsEventListener: function(bind, args){
		return this.create({'bind': bind, 'event': true, 'arguments': args});
	},

	delay: function(delay, bind, args){
		return this.create({'delay': delay, 'bind': bind, 'arguments': args})();
	},

	periodical: function(interval, bind, args){
		return this.create({'periodical': interval, 'bind': bind, 'arguments': args})();
	}

});

Number.extend({

	toInt: function(){
		return parseInt(this);
	},

	toFloat: function(){
		return parseFloat(this);
	},

	limit: function(min, max){
		return Math.min(max, Math.max(min, this));
	},

	round: function(precision){
		precision = Math.pow(10, precision || 0);
		return Math.round(this * precision) / precision;
	},

	times: function(fn){
		for (var i = 0; i < this; i++) fn(i);
	}

});

var Element = new Class({

	initialize: function(el, props){
		if ($type(el) == 'string'){
			if (window.ie && props && (props.name || props.type)){
				var name = (props.name) ? ' name="' + props.name + '"' : '';
				var type = (props.type) ? ' type="' + props.type + '"' : '';
				delete props.name;
				delete props.type;
				el = '<' + el + name + type + '>';
			}
			el = document.createElement(el);
		}
		el = $(el);
		return (!props || !el) ? el : el.set(props);
	}

});

var Elements = new Class({

	initialize: function(elements){
		return (elements) ? $extend(elements, this) : this;
	}

});

Elements.extend = function(props){
	for (var prop in props){
		this.prototype[prop] = props[prop];
		this[prop] = $native.generic(prop);
	}
};

function $(el){
	if (!el) return null;
	if (el.htmlElement) return Garbage.collect(el);
	if ([window, document].contains(el)) return el;
	var type = $type(el);
	if (type == 'string'){
		el = document.getElementById(el);
		type = (el) ? 'element' : false;
	}
	if (type != 'element') return null;
	if (el.htmlElement) return Garbage.collect(el);
	if (['object', 'embed'].contains(el.tagName.toLowerCase())) return el;
	$extend(el, Element.prototype);
	el.htmlElement = function(){};
	return Garbage.collect(el);
};

document.getElementsBySelector = document.getElementsByTagName;

function $$(){
	var elements = [];
	for (var i = 0, j = arguments.length; i < j; i++){
		var selector = arguments[i];
		switch($type(selector)){
			case 'element': elements.push(selector);
			case 'boolean': break;
			case false: break;
			case 'string': selector = document.getElementsBySelector(selector, true);
			default: elements.extend(selector);
		}
	}
	return $$.unique(elements);
};

$$.unique = function(array){
	var elements = [];
	for (var i = 0, l = array.length; i < l; i++){
		if (array[i].$included) continue;
		var element = $(array[i]);
		if (element && !element.$included){
			element.$included = true;
			elements.push(element);
		}
	}
	for (var n = 0, d = elements.length; n < d; n++) elements[n].$included = null;
	return new Elements(elements);
};

Elements.Multi = function(property){
	return function(){
		var args = arguments;
		var items = [];
		var elements = true;
		for (var i = 0, j = this.length, returns; i < j; i++){
			returns = this[i][property].apply(this[i], args);
			if ($type(returns) != 'element') elements = false;
			items.push(returns);
		};
		return (elements) ? $$.unique(items) : items;
	};
};

Element.extend = function(properties){
	for (var property in properties){
		HTMLElement.prototype[property] = properties[property];
		Element.prototype[property] = properties[property];
		Element[property] = $native.generic(property);
		var elementsProperty = (Array.prototype[property]) ? property + 'Elements' : property;
		Elements.prototype[elementsProperty] = Elements.Multi(property);
	}
};

Element.extend({

	set: function(props){
		for (var prop in props){
			var val = props[prop];
			switch(prop){
				case 'styles': this.setStyles(val); break;
				case 'events': if (this.addEvents) this.addEvents(val); break;
				case 'properties': this.setProperties(val); break;
				default: this.setProperty(prop, val);
			}
		}
		return this;
	},

	inject: function(el, where){
		el = $(el);
		switch(where){
			case 'before': el.parentNode.insertBefore(this, el); break;
			case 'after':
			var next = el.getNext();
			if (!next) el.parentNode.appendChild(this);
			else el.parentNode.insertBefore(this, next);
			break;
			case 'top':
			var first = el.firstChild;
			if (first){
				el.insertBefore(this, first);
				break;
			}
			default: el.appendChild(this);
		}
		return this;
	},

	injectBefore: function(el){
		return this.inject(el, 'before');
	},

	injectAfter: function(el){
		return this.inject(el, 'after');
	},

	injectInside: function(el){
		return this.inject(el, 'bottom');
	},

	injectTop: function(el){
		return this.inject(el, 'top');
	},

	adopt: function(){
		var elements = [];
		$each(arguments, function(argument){
			elements = elements.concat(argument);
		});
		$$(elements).inject(this);
		return this;
	},

	remove: function(){
		return this.parentNode.removeChild(this);
	},

	clone: function(contents){
		var el = $(this.cloneNode(contents !== false));
		if (!el.$events) return el;
		el.$events = {};
		for (var type in this.$events) el.$events[type] = {
		'keys': $A(this.$events[type].keys),
		'values': $A(this.$events[type].values)
		};
		return el.removeEvents();
	},

	replaceWith: function(el){
		el = $(el);
		this.parentNode.replaceChild(el, this);
		return el;
	},

	appendText: function(text){
		this.appendChild(document.createTextNode(text));
		return this;
	},

	hasClass: function(className){
		return this.className.contains(className, ' ');
	},

	addClass: function(className){
		if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean();
		return this;
	},

	removeClass: function(className){
		this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1').clean();
		return this;
	},

	toggleClass: function(className){
		return this.hasClass(className) ? this.removeClass(className) : this.addClass(className);
	},

	setStyle: function(property, value){
		switch(property){
			case 'opacity': return this.setOpacity(parseFloat(value));
			case 'float': property = (window.ie) ? 'styleFloat' : 'cssFloat';
		}
		property = property.camelCase();
		switch($type(value)){
			case 'number': if (!['zIndex', 'zoom'].contains(property)) value += 'px'; break;
			case 'array': value = 'rgb(' + value.join(',') + ')';
		}
		this.style[property] = value;
		return this;
	},

	setStyles: function(source){
		switch($type(source)){
			case 'object': Element.setMany(this, 'setStyle', source); break;
			case 'string': this.style.cssText = source;
		}
		return this;
	},

	setOpacity: function(opacity){
		if (opacity == 0){
			if (this.style.visibility != "hidden") this.style.visibility = "hidden";
		} else {
			if (this.style.visibility != "visible") this.style.visibility = "visible";
		}
		if (!this.currentStyle || !this.currentStyle.hasLayout) this.style.zoom = 1;
		if (window.ie) this.style.filter = (opacity == 1) ? '' : "alpha(opacity=" + opacity * 100 + ")";
		this.style.opacity = this.$tmp.opacity = opacity;
		return this;
	},

	getStyle: function(property){
		property = property.camelCase();
		var result = this.style[property];
		if (!$chk(result)){
			if (property == 'opacity') return this.$tmp.opacity;
			result = [];
			for (var style in Element.Styles){
				if (property == style){
					Element.Styles[style].each(function(s){
						var style = this.getStyle(s);
						result.push(parseInt(style) ? style : '0px');
					}, this);
					if (property == 'border'){
						var every = result.every(function(bit){
							return (bit == result[0]);
						});
						return (every) ? result[0] : false;
					}
					return result.join(' ');
				}
			}
			if (property.contains('border')){
				if (Element.Styles.border.contains(property)){
					return ['Width', 'Style', 'Color'].map(function(p){
						return this.getStyle(property + p);
					}, this).join(' ');
				} else if (Element.borderShort.contains(property)){
					return ['Top', 'Right', 'Bottom', 'Left'].map(function(p){
						return this.getStyle('border' + p + property.replace('border', ''));
					}, this).join(' ');
				}
			}
			if (document.defaultView) result = document.defaultView.getComputedStyle(this, null).getPropertyValue(property.hyphenate());
			else if (this.currentStyle) result = this.currentStyle[property];
		}
		if (window.ie) result = Element.fixStyle(property, result, this);
		if (result && property.test(/color/i) && result.contains('rgb')){
			return result.split('rgb').splice(1,4).map(function(color){
				return color.rgbToHex();
			}).join(' ');
		}
		return result;
	},

	getStyles: function(){
		return Element.getMany(this, 'getStyle', arguments);
	},

	walk: function(brother, start){
		brother += 'Sibling';
		var el = (start) ? this[start] : this[brother];
		while (el && $type(el) != 'element') el = el[brother];
		return $(el);
	},

	getPrevious: function(){
		return this.walk('previous');
	},

	getNext: function(){
		return this.walk('next');
	},

	getFirst: function(){
		return this.walk('next', 'firstChild');
	},

	getLast: function(){
		return this.walk('previous', 'lastChild');
	},

	getParent: function(){
		return $(this.parentNode);
	},

	getChildren: function(){
		return $$(this.childNodes);
	},

	hasChild: function(el){
		return !!$A(this.getElementsByTagName('*')).contains(el);
	},

	getProperty: function(property){
		var index = Element.Properties[property];
		if (index) return this[index];
		var flag = Element.PropertiesIFlag[property] || 0;
		if (!window.ie || flag) return this.getAttribute(property, flag);
		var node = this.attributes[property];
		return (node) ? node.nodeValue : null;
	},

	removeProperty: function(property){
		var index = Element.Properties[property];
		if (index) this[index] = '';
		else this.removeAttribute(property);
		return this;
	},

	getProperties: function(){
		return Element.getMany(this, 'getProperty', arguments);
	},

	setProperty: function(property, value){
		var index = Element.Properties[property];
		if (index) this[index] = value;
		else this.setAttribute(property, value);
		return this;
	},

	setProperties: function(source){
		return Element.setMany(this, 'setProperty', source);
	},

	setHTML: function(){
		this.innerHTML = $A(arguments).join('');
		return this;
	},

	setText: function(text){
		var tag = this.getTag();
		if (['style', 'script'].contains(tag)){
			if (window.ie){
				if (tag == 'style') this.styleSheet.cssText = text;
				else if (tag ==  'script') this.setProperty('text', text);
				return this;
			} else {
				this.removeChild(this.firstChild);
				return this.appendText(text);
			}
		}
		this[$defined(this.innerText) ? 'innerText' : 'textContent'] = text;
		return this;
	},

	getText: function(){
		var tag = this.getTag();
		if (['style', 'script'].contains(tag)){
			if (window.ie){
				if (tag == 'style') return this.styleSheet.cssText;
				else if (tag ==  'script') return this.getProperty('text');
			} else {
				return this.innerHTML;
			}
		}
		return ($pick(this.innerText, this.textContent));
	},

	getTag: function(){
		return this.tagName.toLowerCase();
	},

	empty: function(){
		Garbage.trash(this.getElementsByTagName('*'));
		return this.setHTML('');
	}

});

Element.fixStyle = function(property, result, element){
	if ($chk(parseInt(result))) return result;
	if (['height', 'width'].contains(property)){
		var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom'];
		var size = 0;
		values.each(function(value){
			size += element.getStyle('border-' + value + '-width').toInt() + element.getStyle('padding-' + value).toInt();
		});
		return element['offset' + property.capitalize()] - size + 'px';
	} else if (property.test(/border(.+)Width|margin|padding/)){
		return '0px';
	}
	return result;
};

Element.Styles = {'border': [], 'padding': [], 'margin': []};
['Top', 'Right', 'Bottom', 'Left'].each(function(direction){
	for (var style in Element.Styles) Element.Styles[style].push(style + direction);
});

Element.borderShort = ['borderWidth', 'borderStyle', 'borderColor'];

Element.getMany = function(el, method, keys){
	var result = {};
	$each(keys, function(key){
		result[key] = el[method](key);
	});
	return result;
};

Element.setMany = function(el, method, pairs){
	for (var key in pairs) el[method](key, pairs[key]);
	return el;
};

Element.Properties = new Abstract({
'class': 'className', 'for': 'htmlFor', 'colspan': 'colSpan', 'rowspan': 'rowSpan',
'accesskey': 'accessKey', 'tabindex': 'tabIndex', 'maxlength': 'maxLength',
'readonly': 'readOnly', 'frameborder': 'frameBorder', 'value': 'value',
'disabled': 'disabled', 'checked': 'checked', 'multiple': 'multiple', 'selected': 'selected'
});
Element.PropertiesIFlag = {
'href': 2, 'src': 2
};

Element.Methods = {
	Listeners: {
		addListener: function(type, fn){
			if (this.addEventListener) this.addEventListener(type, fn, false);
			else this.attachEvent('on' + type, fn);
			return this;
		},

		removeListener: function(type, fn){
			if (this.removeEventListener) this.removeEventListener(type, fn, false);
			else this.detachEvent('on' + type, fn);
			return this;
		}
	}
};

window.extend(Element.Methods.Listeners);
document.extend(Element.Methods.Listeners);
Element.extend(Element.Methods.Listeners);

var Garbage = {

	elements: [],

	collect: function(el){
		if (!el.$tmp){
			Garbage.elements.push(el);
			el.$tmp = {'opacity': 1};
		}
		return el;
	},

	trash: function(elements){
		for (var i = 0, j = elements.length, el; i < j; i++){
			if (!(el = elements[i]) || !el.$tmp) continue;
			if (el.$events) el.fireEvent('trash').removeEvents();
			for (var p in el.$tmp) el.$tmp[p] = null;
			for (var d in Element.prototype) el[d] = null;
			Garbage.elements[Garbage.elements.indexOf(el)] = null;
			el.htmlElement = el.$tmp = el = null;
		}
		Garbage.elements.remove(null);
	},

	empty: function(){
		Garbage.collect(window);
		Garbage.collect(document);
		Garbage.trash(Garbage.elements);
	}

};

window.addListener('beforeunload', function(){
	if (window.ie) {
		window.addListener('unload', CollectGarbage);
	} else {
		window.addListener('unload', Garbage.empty);
	}
});

var Event = new Class({

	initialize: function(event){
		if (event && event.$extended) return event;
		this.$extended = true;
		event = event || window.event;
		this.event = event;
		this.type = event.type;
		this.target = event.target || event.srcElement;
		if (this.target.nodeType == 3) this.target = this.target.parentNode;
		this.shift = event.shiftKey;
		this.control = event.ctrlKey;
		this.alt = event.altKey;
		this.meta = event.metaKey;
		if (['DOMMouseScroll', 'mousewheel'].contains(this.type)){
			this.wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3;
		} else if (this.type.contains('key')){
			this.code = event.which || event.keyCode;
			for (var name in Event.keys){
				if (Event.keys[name] == this.code){
					this.key = name;
					break;
				}
			}
			if (this.type == 'keydown'){
				var fKey = this.code - 111;
				if (fKey > 0 && fKey < 13) this.key = 'f' + fKey;
			}
			this.key = this.key || String.fromCharCode(this.code).toLowerCase();
		} else if (this.type.test(/(click|mouse|menu)/)){
			this.page = {
			'x': event.pageX || event.clientX + document.documentElement.scrollLeft,
			'y': event.pageY || event.clientY + document.documentElement.scrollTop
			};
			this.client = {
			'x': event.pageX ? event.pageX - window.pageXOffset : event.clientX,
			'y': event.pageY ? event.pageY - window.pageYOffset : event.clientY
			};
			this.rightClick = (event.which == 3) || (event.button == 2);
			switch(this.type){
				case 'mouseover': this.relatedTarget = event.relatedTarget || event.fromElement; break;
				case 'mouseout': this.relatedTarget = event.relatedTarget || event.toElement;
			}
			this.fixRelatedTarget();
		}
		return this;
	},

	stop: function(){
		return this.stopPropagation().preventDefault();
	},

	stopPropagation: function(){
		if (this.event.stopPropagation) this.event.stopPropagation();
		else this.event.cancelBubble = true;
		return this;
	},

	preventDefault: function(){
		if (this.event.preventDefault) this.event.preventDefault();
		else this.event.returnValue = false;
		return this;
	}

});

Event.fix = {

	relatedTarget: function(){
		if (this.relatedTarget && this.relatedTarget.nodeType == 3) this.relatedTarget = this.relatedTarget.parentNode;
	},

	relatedTargetGecko: function(){
		try {Event.fix.relatedTarget.call(this);} catch(e){this.relatedTarget = this.target;}
	}

};

Event.prototype.fixRelatedTarget = (window.gecko) ? Event.fix.relatedTargetGecko : Event.fix.relatedTarget;

Event.keys = new Abstract({
'enter': 13,
'up': 38,
'down': 40,
'left': 37,
'right': 39,
'esc': 27,
'space': 32,
'backspace': 8,
'tab': 9,
'delete': 46
});

Element.Methods.Events = {

	addEvent: function(type, fn){
		this.$events = this.$events || {};
		this.$events[type] = this.$events[type] || {'keys': [], 'values': []};
		if (this.$events[type].keys.contains(fn)) return this;
		this.$events[type].keys.push(fn);
		var realType = type;
		var custom = Element.Events[type];
		if (custom){
			if (custom.add) custom.add.call(this, fn);
			if (custom.map) fn = custom.map;
			if (custom.type) realType = custom.type;
		}
		if (!this.addEventListener) fn = fn.create({'bind': this, 'event': true});
		this.$events[type].values.push(fn);
		return (Element.NativeEvents.contains(realType)) ? this.addListener(realType, fn) : this;
	},

	removeEvent: function(type, fn){
		if (!this.$events || !this.$events[type]) return this;
		var pos = this.$events[type].keys.indexOf(fn);
		if (pos == -1) return this;
		var key = this.$events[type].keys.splice(pos,1)[0];
		var value = this.$events[type].values.splice(pos,1)[0];
		var custom = Element.Events[type];
		if (custom){
			if (custom.remove) custom.remove.call(this, fn);
			if (custom.type) type = custom.type;
		}
		return (Element.NativeEvents.contains(type)) ? this.removeListener(type, value) : this;
	},

	addEvents: function(source){
		return Element.setMany(this, 'addEvent', source);
	},

	removeEvents: function(type){
		if (!this.$events) return this;
		if (!type){
			for (var evType in this.$events) this.removeEvents(evType);
			this.$events = null;
		} else if (this.$events[type]){
			this.$events[type].keys.each(function(fn){
				this.removeEvent(type, fn);
			}, this);
			this.$events[type] = null;
		}
		return this;
	},

	fireEvent: function(type, args, delay){
		if (this.$events && this.$events[type]){
			this.$events[type].keys.each(function(fn){
				fn.create({'bind': this, 'delay': delay, 'arguments': args})();
			}, this);
		}
		return this;
	},

	cloneEvents: function(from, type){
		if (!from.$events) return this;
		if (!type){
			for (var evType in from.$events) this.cloneEvents(from, evType);
		} else if (from.$events[type]){
			from.$events[type].keys.each(function(fn){
				this.addEvent(type, fn);
			}, this);
		}
		return this;
	}

};

window.extend(Element.Methods.Events);
document.extend(Element.Methods.Events);
Element.extend(Element.Methods.Events);

Element.Events = new Abstract({

'mouseenter': {
	type: 'mouseover',
	map: function(event){
		event = new Event(event);
		if (event.relatedTarget != this && !this.hasChild(event.relatedTarget)) this.fireEvent('mouseenter', event);
	}
},

'mouseleave': {
	type: 'mouseout',
	map: function(event){
		event = new Event(event);
		if (event.relatedTarget != this && !this.hasChild(event.relatedTarget)) this.fireEvent('mouseleave', event);
	}
},

'mousewheel': {
	type: (window.gecko) ? 'DOMMouseScroll' : 'mousewheel'
}

});

Element.NativeEvents = [
'click', 'dblclick', 'mouseup', 'mousedown',
'mousewheel', 'DOMMouseScroll',
'mouseover', 'mouseout', 'mousemove',
'keydown', 'keypress', 'keyup',
'load', 'unload', 'beforeunload', 'resize', 'move',
'focus', 'blur', 'change', 'submit', 'reset', 'select',
'error', 'abort', 'contextmenu', 'scroll'
];

Function.extend({

	bindWithEvent: function(bind, args){
		return this.create({'bind': bind, 'arguments': args, 'event': Event});
	}

});

Elements.extend({

	filterByTag: function(tag){
		return new Elements(this.filter(function(el){
			return (Element.getTag(el) == tag);
		}));
	},

	filterByClass: function(className, nocash){
		var elements = this.filter(function(el){
			return (el.className && el.className.contains(className, ' '));
		});
		return (nocash) ? elements : new Elements(elements);
	},

	filterById: function(id, nocash){
		var elements = this.filter(function(el){
			return (el.id == id);
		});
		return (nocash) ? elements : new Elements(elements);
	},

	filterByAttribute: function(name, operator, value, nocash){
		var elements = this.filter(function(el){
			var current = Element.getProperty(el, name);
			if (!current) return false;
			if (!operator) return true;
			switch(operator){
				case '=': return (current == value);
				case '*=': return (current.contains(value));
				case '^=': return (current.substr(0, value.length) == value);
				case '$=': return (current.substr(current.length - value.length) == value);
				case '!=': return (current != value);
				case '~=': return current.contains(value, ' ');
			}
			return false;
		});
		return (nocash) ? elements : new Elements(elements);
	}

});

function $E(selector, filter){
	return ($(filter) || document).getElement(selector);
};

function $ES(selector, filter){
	return ($(filter) || document).getElementsBySelector(selector);
};

$$.shared = {

'regexp': /^(\w*|\*)(?:#([\w-]+)|\.([\w-]+))?(?:\[(\w+)(?:([!*^$]?=)["']?([^"'\]]*)["']?)?])?$/,

'xpath': {

	getParam: function(items, context, param, i){
		var temp = [context.namespaceURI ? 'xhtml:' : '', param[1]];
		if (param[2]) temp.push('[@id="', param[2], '"]');
		if (param[3]) temp.push('[contains(concat(" ", @class, " "), " ', param[3], ' ")]');
		if (param[4]){
			if (param[5] && param[6]){
				switch(param[5]){
					case '*=': temp.push('[contains(@', param[4], ', "', param[6], '")]'); break;
					case '^=': temp.push('[starts-with(@', param[4], ', "', param[6], '")]'); break;
					case '$=': temp.push('[substring(@', param[4], ', string-length(@', param[4], ') - ', param[6].length, ' + 1) = "', param[6], '"]'); break;
					case '=': temp.push('[@', param[4], '="', param[6], '"]'); break;
					case '!=': temp.push('[@', param[4], '!="', param[6], '"]');
				}
			} else {
				temp.push('[@', param[4], ']');
			}
		}
		items.push(temp.join(''));
		return items;
	},

	getItems: function(items, context, nocash){
		var elements = [];
		var xpath = document.evaluate('.//' + items.join('//'), context, $$.shared.resolver, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
		for (var i = 0, j = xpath.snapshotLength; i < j; i++) elements.push(xpath.snapshotItem(i));
		return (nocash) ? elements : new Elements(elements.map($));
	}

},

'normal': {

	getParam: function(items, context, param, i){
		if (i == 0){
			if (param[2]){
				var el = context.getElementById(param[2]);
				if (!el || ((param[1] != '*') && (Element.getTag(el) != param[1]))) return false;
				items = [el];
			} else {
				items = $A(context.getElementsByTagName(param[1]));
			}
		} else {
			items = $$.shared.getElementsByTagName(items, param[1]);
			if (param[2]) items = Elements.filterById(items, param[2], true);
		}
		if (param[3]) items = Elements.filterByClass(items, param[3], true);
		if (param[4]) items = Elements.filterByAttribute(items, param[4], param[5], param[6], true);
		return items;
	},

	getItems: function(items, context, nocash){
		return (nocash) ? items : $$.unique(items);
	}

},

resolver: function(prefix){
	return (prefix == 'xhtml') ? 'http://www.w3.org/1999/xhtml' : false;
},

getElementsByTagName: function(context, tagName){
	var found = [];
	for (var i = 0, j = context.length; i < j; i++) found.extend(context[i].getElementsByTagName(tagName));
	return found;
}

};

$$.shared.method = (window.xpath) ? 'xpath' : 'normal';

Element.Methods.Dom = {

	getElements: function(selector, nocash){
		var items = [];
		selector = selector.trim().split(' ');
		for (var i = 0, j = selector.length; i < j; i++){
			var sel = selector[i];
			var param = sel.match($$.shared.regexp);
			if (!param) break;
			param[1] = param[1] || '*';
			var temp = $$.shared[$$.shared.method].getParam(items, this, param, i);
			if (!temp) break;
			items = temp;
		}
		return $$.shared[$$.shared.method].getItems(items, this, nocash);
	},

	getElement: function(selector){
		return $(this.getElements(selector, true)[0] || false);
	},

	getElementsBySelector: function(selector, nocash){
		var elements = [];
		selector = selector.split(',');
		for (var i = 0, j = selector.length; i < j; i++) elements = elements.concat(this.getElements(selector[i], true));
		return (nocash) ? elements : $$.unique(elements);
	}

};

Element.extend({

	getElementById: function(id){
		var el = document.getElementById(id);
		if (!el) return false;
		for (var parent = el.parentNode; parent != this; parent = parent.parentNode){
			if (!parent) return false;
		}
		return el;
	}/*compatibility*/,

	getElementsByClassName: function(className){
		return this.getElements('.' + className);
	}

});

document.extend(Element.Methods.Dom);
Element.extend(Element.Methods.Dom);

Element.extend({

	getValue: function(){
		switch(this.getTag()){
			case 'select':
			var values = [];
			$each(this.options, function(option){
				if (option.selected) values.push($pick(option.value, option.text));
			});
			return (this.multiple) ? values : values[0];
			case 'input': if (!(this.checked && ['checkbox', 'radio'].contains(this.type)) && !['hidden', 'text', 'password'].contains(this.type)) break;
			case 'textarea': return this.value;
		}
		return false;
	},

	getFormElements: function(){
		return $$(this.getElementsByTagName('input'), this.getElementsByTagName('select'), this.getElementsByTagName('textarea'));
	},

	toQueryString: function(){
		var queryString = [];
		this.getFormElements().each(function(el){
			var name = el.name;
			var value = el.getValue();
			if (value === false || !name || el.disabled) return;
			var qs = function(val){
				queryString.push(name + '=' + encodeURIComponent(val));
			};
			if ($type(value) == 'array') value.each(qs);
			else qs(value);
		});
		return queryString.join('&');
	}

});

Element.extend({

	scrollTo: function(x, y){
		this.scrollLeft = x;
		this.scrollTop = y;
	},

	getSize: function(){
		return {
		'scroll': {'x': this.scrollLeft, 'y': this.scrollTop},
		'size': {'x': this.offsetWidth, 'y': this.offsetHeight},
		'scrollSize': {'x': this.scrollWidth, 'y': this.scrollHeight}
		};
	},

	getPosition: function(overflown){
		overflown = overflown || [];
		var el = this, left = 0, top = 0;
		do {
			left += el.offsetLeft || 0;
			top += el.offsetTop || 0;
			el = el.offsetParent;
		} while (el);
		overflown.each(function(element){
			left -= element.scrollLeft || 0;
			top -= element.scrollTop || 0;
		});
		return {'x': left, 'y': top};
	},

	getTop: function(overflown){
		return this.getPosition(overflown).y;
	},

	getLeft: function(overflown){
		return this.getPosition(overflown).x;
	},

	getCoordinates: function(overflown){
		var position = this.getPosition(overflown);
		var obj = {
		'width': this.offsetWidth,
		'height': this.offsetHeight,
		'left': position.x,
		'top': position.y
		};
		obj.right = obj.left + obj.width;
		obj.bottom = obj.top + obj.height;
		return obj;
	}

});

Element.Events.domready = {

	add: function(fn){
		if (window.loaded){
			fn.call(this);
			return;
		}
		var domReady = function(){
			if (window.loaded) return;
			window.loaded = true;
			window.timer = $clear(window.timer);
			this.fireEvent('domready');
		}.bind(this);
		if (document.readyState && window.webkit){
			window.timer = function(){
				if (['loaded','complete'].contains(document.readyState)) domReady();
			}.periodical(50);
		} else if (document.readyState && window.ie){
			if (!$('ie_ready')){
				var src = (window.location.protocol == 'https:') ? '//:' : 'javascript:void(0)';
				document.write('<script id="ie_ready" defer src="' + src + '"><\/script>');
				$('ie_ready').onreadystatechange = function(){
					if (this.readyState == 'complete') domReady();
				};
			}
		} else {
			window.addListener("load", domReady);
			document.addListener("DOMContentLoaded", domReady);
		}
	}

};

window.onDomReady = function(fn){
	return this.addEvent('domready', fn);
};

window.extend({

	getWidth: function(){
		if (this.webkit419) return this.innerWidth;
		if (this.opera) return document.body.clientWidth;
		return document.documentElement.clientWidth;
	},

	getHeight: function(){
		if (this.webkit419) return this.innerHeight;
		if (this.opera) return document.body.clientHeight;
		return document.documentElement.clientHeight;
	},

	getScrollWidth: function(){
		if (this.ie) return Math.max(document.documentElement.offsetWidth, document.documentElement.scrollWidth);
		if (this.webkit) return document.body.scrollWidth;
		return document.documentElement.scrollWidth;
	},

	getScrollHeight: function(){
		if (this.ie) return Math.max(document.documentElement.offsetHeight, document.documentElement.scrollHeight);
		if (this.webkit) return document.body.scrollHeight;
		return document.documentElement.scrollHeight;
	},

	getScrollLeft: function(){
		return this.pageXOffset || document.documentElement.scrollLeft;
	},

	getScrollTop: function(){
		return this.pageYOffset || document.documentElement.scrollTop;
	},

	getSize: function(){
		return {
		'size': {'x': this.getWidth(), 'y': this.getHeight()},
		'scrollSize': {'x': this.getScrollWidth(), 'y': this.getScrollHeight()},
		'scroll': {'x': this.getScrollLeft(), 'y': this.getScrollTop()}
		};
	},
	getPosition: function(){return {'x': 0, 'y': 0};}

});

var Fx = {};

Fx.Base = new Class({

	options: {
		onStart: Class.empty,
		onComplete: Class.empty,
		onCancel: Class.empty,
		transition: function(p){
			return -(Math.cos(Math.PI * p) - 1) / 2;
		},
		duration: 500,
		unit: 'px',
		wait: true,
		fps: 50
	},

	initialize: function(options){
		this.element = this.element || null;
		this.setOptions(options);
		if (this.options.initialize) this.options.initialize.call(this);
	},

	step: function(){
		var time = $time();
		if (time < this.time + this.options.duration){
			this.delta = this.options.transition((time - this.time) / this.options.duration);
			this.setNow();
			this.increase();
		} else {
			this.stop(true);
			this.set(this.to);
			this.fireEvent('onComplete', this.element, 10);
			this.callChain();
		}
	},

	set: function(to){
		this.now = to;
		this.increase();
		return this;
	},

	setNow: function(){
		this.now = this.compute(this.from, this.to);
	},

	compute: function(from, to){
		return (to - from) * this.delta + from;
	},

	start: function(from, to){
		if (!this.options.wait) this.stop();
		else if (this.timer) return this;
		this.from = from;
		this.to = to;
		this.change = this.to - this.from;
		this.time = $time();
		this.timer = this.step.periodical(Math.round(1000 / this.options.fps), this);
		this.fireEvent('onStart', this.element);
		return this;
	},

	stop: function(end){
		if (!this.timer) return this;
		this.timer = $clear(this.timer);
		if (!end) this.fireEvent('onCancel', this.element);
		return this;
	}/*compatibility*/,

	custom: function(from, to){
		return this.start(from, to);
	},

	clearTimer: function(end){
		return this.stop(end);
	}

});

Fx.Base.implement(new Chain, new Events, new Options);

Fx.CSS = {

	select: function(property, to){
		if (property.test(/color/i)) return this.Color;
		var type = $type(to);
		if ((type == 'array') || (type == 'string' && to.contains(' '))) return this.Multi;
		return this.Single;
	},

	parse: function(el, property, fromTo){
		if (!fromTo.push) fromTo = [fromTo];
		var from = fromTo[0], to = fromTo[1];
		if (!$chk(to)){
			to = from;
			from = el.getStyle(property);
		}
		var css = this.select(property, to);
		return {'from': css.parse(from), 'to': css.parse(to), 'css': css};
	}

};

Fx.CSS.Single = {

	parse: function(value){
		return parseFloat(value);
	},

	getNow: function(from, to, fx){
		return fx.compute(from, to);
	},

	getValue: function(value, unit, property){
		if (unit == 'px' && property != 'opacity') value = Math.round(value);
		return value + unit;
	}

};

Fx.CSS.Multi = {

	parse: function(value){
		return value.push ? value : value.split(' ').map(function(v){
			return parseFloat(v);
		});
	},

	getNow: function(from, to, fx){
		var now = [];
		for (var i = 0; i < from.length; i++) now[i] = fx.compute(from[i], to[i]);
		return now;
	},

	getValue: function(value, unit, property){
		if (unit == 'px' && property != 'opacity') value = value.map(Math.round);
		return value.join(unit + ' ') + unit;
	}

};

Fx.CSS.Color = {

	parse: function(value){
		return value.push ? value : value.hexToRgb(true);
	},

	getNow: function(from, to, fx){
		var now = [];
		for (var i = 0; i < from.length; i++) now[i] = Math.round(fx.compute(from[i], to[i]));
		return now;
	},

	getValue: function(value){
		return 'rgb(' + value.join(',') + ')';
	}

};

Fx.Style = Fx.Base.extend({

	initialize: function(el, property, options){
		this.element = $(el);
		this.property = property;
		this.parent(options);
	},

	hide: function(){
		return this.set(0);
	},

	setNow: function(){
		this.now = this.css.getNow(this.from, this.to, this);
	},

	set: function(to){
		this.css = Fx.CSS.select(this.property, to);
		return this.parent(this.css.parse(to));
	},

	start: function(from, to){
		if (this.timer && this.options.wait) return this;
		var parsed = Fx.CSS.parse(this.element, this.property, [from, to]);
		this.css = parsed.css;
		return this.parent(parsed.from, parsed.to);
	},

	increase: function(){
		this.element.setStyle(this.property, this.css.getValue(this.now, this.options.unit, this.property));
	}

});

Element.extend({

	effect: function(property, options){
		return new Fx.Style(this, property, options);
	}

});

Fx.Styles = Fx.Base.extend({

	initialize: function(el, options){
		this.element = $(el);
		this.parent(options);
	},

	setNow: function(){
		for (var p in this.from) this.now[p] = this.css[p].getNow(this.from[p], this.to[p], this);
	},

	set: function(to){
		var parsed = {};
		this.css = {};
		for (var p in to){
			this.css[p] = Fx.CSS.select(p, to[p]);
			parsed[p] = this.css[p].parse(to[p]);
		}
		return this.parent(parsed);
	},

	start: function(obj){
		if (this.timer && this.options.wait) return this;
		this.now = {};
		this.css = {};
		var from = {}, to = {};
		for (var p in obj){
			var parsed = Fx.CSS.parse(this.element, p, obj[p]);
			from[p] = parsed.from;
			to[p] = parsed.to;
			this.css[p] = parsed.css;
		}
		return this.parent(from, to);
	},

	increase: function(){
		for (var p in this.now) this.element.setStyle(p, this.css[p].getValue(this.now[p], this.options.unit, p));
	}

});

Element.extend({

	effects: function(options){
		return new Fx.Styles(this, options);
	}

});

Fx.Elements = Fx.Base.extend({

	initialize: function(elements, options){
		this.elements = $$(elements);
		this.parent(options);
	},

	setNow: function(){
		for (var i in this.from){
			var iFrom = this.from[i], iTo = this.to[i], iCss = this.css[i], iNow = this.now[i] = {};
			for (var p in iFrom) iNow[p] = iCss[p].getNow(iFrom[p], iTo[p], this);
		}
	},

	set: function(to){
		var parsed = {};
		this.css = {};
		for (var i in to){
			var iTo = to[i], iCss = this.css[i] = {}, iParsed = parsed[i] = {};
			for (var p in iTo){
				iCss[p] = Fx.CSS.select(p, iTo[p]);
				iParsed[p] = iCss[p].parse(iTo[p]);
			}
		}
		return this.parent(parsed);
	},

	start: function(obj){
		if (this.timer && this.options.wait) return this;
		this.now = {};
		this.css = {};
		var from = {}, to = {};
		for (var i in obj){
			var iProps = obj[i], iFrom = from[i] = {}, iTo = to[i] = {}, iCss = this.css[i] = {};
			for (var p in iProps){
				var parsed = Fx.CSS.parse(this.elements[i], p, iProps[p]);
				iFrom[p] = parsed.from;
				iTo[p] = parsed.to;
				iCss[p] = parsed.css;
			}
		}
		return this.parent(from, to);
	},

	increase: function(){
		for (var i in this.now){
			var iNow = this.now[i], iCss = this.css[i];
			for (var p in iNow) this.elements[i].setStyle(p, iCss[p].getValue(iNow[p], this.options.unit, p));
		}
	}

});

Fx.Scroll = Fx.Base.extend({

	options: {
		overflown: [],
		offset: {'x': 0, 'y': 0},
		wheelStops: true
	},

	initialize: function(element, options){
		this.now = [];
		this.element = $(element);
		this.bound = {'stop': this.stop.bind(this, false)};
		this.parent(options);
		if (this.options.wheelStops){
			this.addEvent('onStart', function(){
				document.addEvent('mousewheel', this.bound.stop);
			}.bind(this));
			this.addEvent('onComplete', function(){
				document.removeEvent('mousewheel', this.bound.stop);
			}.bind(this));
		}
	},

	setNow: function(){
		for (var i = 0; i < 2; i++) this.now[i] = this.compute(this.from[i], this.to[i]);
	},

	scrollTo: function(x, y){
		if (this.timer && this.options.wait) return this;
		var el = this.element.getSize();
		var values = {'x': x, 'y': y};
		for (var z in el.size){
			var max = el.scrollSize[z] - el.size[z];
			if ($chk(values[z])) values[z] = ($type(values[z]) == 'number') ? values[z].limit(0, max) : max;
			else values[z] = el.scroll[z];
			values[z] += this.options.offset[z];
		}
		return this.start([el.scroll.x, el.scroll.y], [values.x, values.y]);
	},

	toTop: function(){
		return this.scrollTo(false, 0);
	},

	toBottom: function(){
		return this.scrollTo(false, 'full');
	},

	toLeft: function(){
		return this.scrollTo(0, false);
	},

	toRight: function(){
		return this.scrollTo('full', false);
	},

	toElement: function(el){
		var parent = this.element.getPosition(this.options.overflown);
		var target = $(el).getPosition(this.options.overflown);
		return this.scrollTo(target.x - parent.x, target.y - parent.y);
	},

	increase: function(){
		this.element.scrollTo(this.now[0], this.now[1]);
	}

});

Fx.Slide = Fx.Base.extend({

	options: {
		mode: 'vertical'
	},

	initialize: function(el, options){
		this.element = $(el);
		this.wrapper = new Element('div', {'styles': $extend(this.element.getStyles('margin'), {'overflow': 'hidden'})}).injectAfter(this.element).adopt(this.element);
		this.element.setStyle('margin', 0);
		this.setOptions(options);
		this.now = [];
		this.parent(this.options);
		this.open = true;
		this.addEvent('onComplete', function(){
			this.open = (this.now[0] === 0);
		});
		if (window.webkit419) this.addEvent('onComplete', function(){
			if (this.open) this.element.remove().inject(this.wrapper);
		});
	},

	setNow: function(){
		for (var i = 0; i < 2; i++) this.now[i] = this.compute(this.from[i], this.to[i]);
	},

	vertical: function(){
		this.margin = 'margin-top';
		this.layout = 'height';
		this.offset = this.element.offsetHeight;
	},

	horizontal: function(){
		this.margin = 'margin-left';
		this.layout = 'width';
		this.offset = this.element.offsetWidth;
	},

	slideIn: function(mode){
		this[mode || this.options.mode]();
		return this.start([this.element.getStyle(this.margin).toInt(), this.wrapper.getStyle(this.layout).toInt()], [0, this.offset]);
	},

	slideOut: function(mode){
		this[mode || this.options.mode]();
		return this.start([this.element.getStyle(this.margin).toInt(), this.wrapper.getStyle(this.layout).toInt()], [-this.offset, 0]);
	},

	hide: function(mode){
		this[mode || this.options.mode]();
		this.open = false;
		return this.set([-this.offset, 0]);
	},

	show: function(mode){
		this[mode || this.options.mode]();
		this.open = true;
		return this.set([0, this.offset]);
	},

	toggle: function(mode){
		if (this.wrapper.offsetHeight == 0 || this.wrapper.offsetWidth == 0) return this.slideIn(mode);
		return this.slideOut(mode);
	},

	increase: function(){
		this.element.setStyle(this.margin, this.now[0] + this.options.unit);
		this.wrapper.setStyle(this.layout, this.now[1] + this.options.unit);
	}

});

Fx.Transition = function(transition, params){
	params = params || [];
	if ($type(params) != 'array') params = [params];
	return $extend(transition, {
		easeIn: function(pos){
			return transition(pos, params);
		},
		easeOut: function(pos){
			return 1 - transition(1 - pos, params);
		},
		easeInOut: function(pos){
			return (pos <= 0.5) ? transition(2 * pos, params) / 2 : (2 - transition(2 * (1 - pos), params)) / 2;
		}
	});
};

Fx.Transitions = new Abstract({

	linear: function(p){
		return p;
	}

});

Fx.Transitions.extend = function(transitions){
	for (var transition in transitions){
		Fx.Transitions[transition] = new Fx.Transition(transitions[transition]);
		Fx.Transitions.compat(transition);
	}
};

Fx.Transitions.compat = function(transition){
['In', 'Out', 'InOut'].each(function(easeType){
	Fx.Transitions[transition.toLowerCase() + easeType] = Fx.Transitions[transition]['ease' + easeType];
});
};

Fx.Transitions.extend({

	Pow: function(p, x){
		return Math.pow(p, x[0] || 6);
	},

	Expo: function(p){
		return Math.pow(2, 8 * (p - 1));
	},

	Circ: function(p){
		return 1 - Math.sin(Math.acos(p));
	},

	Sine: function(p){
		return 1 - Math.sin((1 - p) * Math.PI / 2);
	},

	Back: function(p, x){
		x = x[0] || 1.618;
		return Math.pow(p, 2) * ((x + 1) * p - x);
	},

	Bounce: function(p){
		var value;
		for (var a = 0, b = 1; 1; a += b, b /= 2){
			if (p >= (7 - 4 * a) / 11){
				value = - Math.pow((11 - 6 * a - 11 * p) / 4, 2) + b * b;
				break;
			}
		}
		return value;
	},

	Elastic: function(p, x){
		return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x[0] || 1) / 3);
	}

});

['Quad', 'Cubic', 'Quart', 'Quint'].each(function(transition, i){
	Fx.Transitions[transition] = new Fx.Transition(function(p){
		return Math.pow(p, [i + 2]);
	});
	Fx.Transitions.compat(transition);
});

var Drag = {};

Drag.Base = new Class({

	options: {
		handle: false,
		unit: 'px',
		onStart: Class.empty,
		onBeforeStart: Class.empty,
		onComplete: Class.empty,
		onSnap: Class.empty,
		onDrag: Class.empty,
		limit: false,
		modifiers: {x: 'left', y: 'top'},
		grid: false,
		snap: 6
	},

	initialize: function(el, options){
		this.setOptions(options);
		this.element = $(el);
		this.handle = $(this.options.handle) || this.element;
		this.mouse = {'now': {}, 'pos': {}};
		this.value = {'start': {}, 'now': {}};
		this.bound = {
		'start': this.start.bindWithEvent(this),
		'check': this.check.bindWithEvent(this),
		'drag': this.drag.bindWithEvent(this),
		'stop': this.stop.bind(this)
		};
		this.attach();
		if (this.options.initialize) this.options.initialize.call(this);
	},

	attach: function(){
		this.handle.addEvent('mousedown', this.bound.start);
		return this;
	},

	detach: function(){
		this.handle.removeEvent('mousedown', this.bound.start);
		return this;
	},

	start: function(event){
		this.fireEvent('onBeforeStart', this.element);
		this.mouse.start = event.page;
		var limit = this.options.limit;
		this.limit = {'x': [], 'y': []};
		for (var z in this.options.modifiers){
			if (!this.options.modifiers[z]) continue;
			this.value.now[z] = this.element.getStyle(this.options.modifiers[z]).toInt();
			this.mouse.pos[z] = event.page[z] - this.value.now[z];
			if (limit && limit[z]){
				for (var i = 0; i < 2; i++){
					if ($chk(limit[z][i])) this.limit[z][i] = ($type(limit[z][i]) == 'function') ? limit[z][i]() : limit[z][i];
				}
			}
		}
		if ($type(this.options.grid) == 'number') this.options.grid = {'x': this.options.grid, 'y': this.options.grid};
		document.addListener('mousemove', this.bound.check);
		document.addListener('mouseup', this.bound.stop);
		this.fireEvent('onStart', this.element);
		event.stop();
	},

	check: function(event){
		var distance = Math.round(Math.sqrt(Math.pow(event.page.x - this.mouse.start.x, 2) + Math.pow(event.page.y - this.mouse.start.y, 2)));
		if (distance > this.options.snap){
			document.removeListener('mousemove', this.bound.check);
			document.addListener('mousemove', this.bound.drag);
			this.drag(event);
			this.fireEvent('onSnap', this.element);
		}
		event.stop();
	},

	drag: function(event){
		this.out = false;
		this.mouse.now = event.page;
		for (var z in this.options.modifiers){
			if (!this.options.modifiers[z]) continue;
			this.value.now[z] = this.mouse.now[z] - this.mouse.pos[z];
			if (this.limit[z]){
				if ($chk(this.limit[z][1]) && (this.value.now[z] > this.limit[z][1])){
					this.value.now[z] = this.limit[z][1];
					this.out = true;
				} else if ($chk(this.limit[z][0]) && (this.value.now[z] < this.limit[z][0])){
					this.value.now[z] = this.limit[z][0];
					this.out = true;
				}
			}
			if (this.options.grid[z]) this.value.now[z] -= (this.value.now[z] % this.options.grid[z]);
			this.element.setStyle(this.options.modifiers[z], this.value.now[z] + this.options.unit);
		}
		this.fireEvent('onDrag', this.element);
		event.stop();
	},

	stop: function(){
		document.removeListener('mousemove', this.bound.check);
		document.removeListener('mousemove', this.bound.drag);
		document.removeListener('mouseup', this.bound.stop);
		this.fireEvent('onComplete', this.element);
	}

});

Drag.Base.implement(new Events, new Options);

Element.extend({

	makeResizable: function(options){
		return new Drag.Base(this, $merge({modifiers: {x: 'width', y: 'height'}}, options));
	}

});

Drag.Move = Drag.Base.extend({

	options: {
		droppables: [],
		container: false,
		overflown: []
	},

	initialize: function(el, options){
		this.setOptions(options);
		this.element = $(el);
		this.droppables = $$(this.options.droppables);
		this.container = $(this.options.container);
		this.position = {'element': this.element.getStyle('position'), 'container': false};
		if (this.container) this.position.container = this.container.getStyle('position');
		if (!['relative', 'absolute', 'fixed'].contains(this.position.element)) this.position.element = 'absolute';
		var top = this.element.getStyle('top').toInt();
		var left = this.element.getStyle('left').toInt();
		if (this.position.element == 'absolute' && !['relative', 'absolute', 'fixed'].contains(this.position.container)){
			top = $chk(top) ? top : this.element.getTop(this.options.overflown);
			left = $chk(left) ? left : this.element.getLeft(this.options.overflown);
		} else {
			top = $chk(top) ? top : 0;
			left = $chk(left) ? left : 0;
		}
		this.element.setStyles({'top': top, 'left': left, 'position': this.position.element});
		this.parent(this.element);
	},

	start: function(event){
		this.overed = null;
		if (this.container){
			var cont = this.container.getCoordinates();
			var el = this.element.getCoordinates();
			if (this.position.element == 'absolute' && !['relative', 'absolute', 'fixed'].contains(this.position.container)){
				this.options.limit = {
				'x': [cont.left, cont.right - el.width],
				'y': [cont.top, cont.bottom - el.height]
				};
			} else {
				this.options.limit = {
				'y': [0, cont.height - el.height],
				'x': [0, cont.width - el.width]
				};
			}
		}
		this.parent(event);
	},

	drag: function(event){
		this.parent(event);
		var overed = this.out ? false : this.droppables.filter(this.checkAgainst, this).getLast();
		if (this.overed != overed){
			if (this.overed) this.overed.fireEvent('leave', [this.element, this]);
			this.overed = overed ? overed.fireEvent('over', [this.element, this]) : null;
		}
		return this;
	},

	checkAgainst: function(el){
		el = el.getCoordinates(this.options.overflown);
		var now = this.mouse.now;
		return (now.x > el.left && now.x < el.right && now.y < el.bottom && now.y > el.top);
	},

	stop: function(){
		if (this.overed && !this.out) this.overed.fireEvent('drop', [this.element, this]);
		else this.element.fireEvent('emptydrop', this);
		this.parent();
		return this;
	}

});

Element.extend({

	makeDraggable: function(options){
		return new Drag.Move(this, options);
	}

});

var XHR = new Class({

	options: {
		method: 'post',
		async: true,
		onRequest: Class.empty,
		onSuccess: Class.empty,
		onFailure: Class.empty,
		urlEncoded: true,
		encoding: 'utf-8',
		autoCancel: false,
		headers: {}
	},

	setTransport: function(){
		this.transport = (window.XMLHttpRequest) ? new XMLHttpRequest() : (window.ie ? new ActiveXObject('Microsoft.XMLHTTP') : false);
		return this;
	},

	initialize: function(options){
		this.setTransport().setOptions(options);
		this.options.isSuccess = this.options.isSuccess || this.isSuccess;
		this.headers = {};
		if (this.options.urlEncoded && this.options.method == 'post'){
			var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : '';
			this.setHeader('Content-type', 'application/x-www-form-urlencoded' + encoding);
		}
		if (this.options.initialize) this.options.initialize.call(this);
	},

	onStateChange: function(){
		if (this.transport.readyState != 4 || !this.running) return;
		this.running = false;
		var status = 0;
		try {status = this.transport.status;} catch(e){};
		if (this.options.isSuccess.call(this, status)) this.onSuccess();
		else this.onFailure();
		this.transport.onreadystatechange = Class.empty;
	},

	isSuccess: function(status){
		return ((status >= 200) && (status < 300));
	},

	onSuccess: function(){
		this.response = {
		'text': this.transport.responseText,
		'xml': this.transport.responseXML
		};
		this.fireEvent('onSuccess', [this.response.text, this.response.xml]);
		this.callChain();
	},

	onFailure: function(){
		this.fireEvent('onFailure', this.transport);
	},

	setHeader: function(name, value){
		this.headers[name] = value;
		return this;
	},

	send: function(url, data){
		if (this.options.autoCancel) this.cancel();
		else if (this.running) return this;
		this.running = true;
		if (data && this.options.method == 'get'){
			url = url + (url.contains('?') ? '&' : '?') + data;
			data = null;
		}
		this.transport.open(this.options.method.toUpperCase(), url, this.options.async);
		this.transport.onreadystatechange = this.onStateChange.bind(this);
		if ((this.options.method == 'post') && this.transport.overrideMimeType) this.setHeader('Connection', 'close');
		$extend(this.headers, this.options.headers);
		for (var type in this.headers) try {this.transport.setRequestHeader(type, this.headers[type]);} catch(e){};
		this.fireEvent('onRequest');
		this.transport.send($pick(data, null));
		return this;
	},

	cancel: function(){
		if (!this.running) return this;
		this.running = false;
		this.transport.abort();
		this.transport.onreadystatechange = Class.empty;
		this.setTransport();
		this.fireEvent('onCancel');
		return this;
	}

});

XHR.implement(new Chain, new Events, new Options);

var Ajax = XHR.extend({

	options: {
		data: null,
		update: null,
		onComplete: Class.empty,
		evalScripts: false,
		evalResponse: false
	},

	initialize: function(url, options){
		this.addEvent('onSuccess', this.onComplete);
		this.setOptions(options);
		this.options.data = this.options.data || this.options.postBody;
		if (!['post', 'get'].contains(this.options.method)){
			this._method = '_method=' + this.options.method;
			this.options.method = 'post';
		}
		this.parent();
		this.setHeader('X-Requested-With', 'XMLHttpRequest');
		this.setHeader('Accept', 'text/javascript, text/html, application/xml, text/xml, */*');
		this.url = url;
	},

	onComplete: function(){
		if (this.options.update) $(this.options.update).empty().setHTML(this.response.text);
		if (this.options.evalScripts || this.options.evalResponse) this.evalScripts();
		this.fireEvent('onComplete', [this.response.text, this.response.xml], 20);
	},

	request: function(data){
		data = data || this.options.data;
		switch($type(data)){
			case 'element': data = $(data).toQueryString(); break;
			case 'object': data = Object.toQueryString(data);
		}
		if (this._method) data = (data) ? [this._method, data].join('&') : this._method;
		return this.send(this.url, data);
	},

	evalScripts: function(){
		var script, scripts;
		if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) scripts = this.response.text;
		else {
			scripts = [];
			var regexp = /<script[^>]*>([\s\S]*?)<\/script>/gi;
			while ((script = regexp.exec(this.response.text))) scripts.push(script[1]);
			scripts = scripts.join('\n');
		}
		if (scripts) (window.execScript) ? window.execScript(scripts) : window.setTimeout(scripts, 0);
	},

	getHeader: function(name){
		try {return this.transport.getResponseHeader(name);} catch(e){};
		return null;
	}

});

Object.toQueryString = function(source){
	var queryString = [];
	for (var property in source) queryString.push(encodeURIComponent(property) + '=' + encodeURIComponent(source[property]));
	return queryString.join('&');
};

Element.extend({

	send: function(options){
		return new Ajax(this.getProperty('action'), $merge({data: this.toQueryString()}, options, {method: 'post'})).request();
	}

});

var Cookie = new Abstract({

	options: {
		domain: false,
		path: false,
		duration: false,
		secure: false
	},

	set: function(key, value, options){
		options = $merge(this.options, options);
		value = encodeURIComponent(value);
		if (options.domain) value += '; domain=' + options.domain;
		if (options.path) value += '; path=' + options.path;
		if (options.duration){
			var date = new Date();
			date.setTime(date.getTime() + options.duration * 24 * 60 * 60 * 1000);
			value += '; expires=' + date.toGMTString();
		}
		if (options.secure) value += '; secure';
		document.cookie = key + '=' + value;
		return $extend(options, {'key': key, 'value': value});
	},

	get: function(key){
		var value = document.cookie.match('(?:^|;)\\s*' + key.escapeRegExp() + '=([^;]*)');
		return value ? decodeURIComponent(value[1]) : false;
	},

	remove: function(cookie, options){
		if ($type(cookie) == 'object') this.set(cookie.key, '', $merge(cookie, {duration: -1}));
		else this.set(cookie, '', $merge(options, {duration: -1}));
	}

});

var Json = {

	toString: function(obj){
		switch($type(obj)){
			case 'string':
			return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
			case 'array':
				return '[' + obj.map(Json.toString).join(',') + ']';
			case 'object':
				var string = [];
				for (var property in obj) string.push(Json.toString(property) + ':' + Json.toString(obj[property]));
				return '{' + string.join(',') + '}';
			case 'number':
				if (isFinite(obj)) break;
			case false:
				return 'null';
		}
		return String(obj);
	},

	evaluate: function(str, secure){
		return (($type(str) != 'string') || (secure && !str.test(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/))) ? null : eval('(' + str + ')');
	}
};

Json.Remote = XHR.extend({

	initialize: function(url, options){
		this.url = url;
		this.addEvent('onSuccess', this.onComplete);
		this.parent(options);
		this.setHeader('X-Request', 'JSON');
	},

	send: function(obj){
		return this.parent(this.url, 'json=' + Json.toString(obj));
	},

	onComplete: function(){
		this.fireEvent('onComplete', [Json.evaluate(this.response.text, this.options.secure)]);
	}

});

var Asset = new Abstract({

	javascript: function(source, properties){
		properties = $merge({
			'onload': Class.empty
		}, properties);
		var script = new Element('script', {'src': source}).addEvents({
			'load': properties.onload,
			'readystatechange': function(){
				if (this.readyState == 'complete') this.fireEvent('load');
			}
		});
		delete properties.onload;
		return script.setProperties(properties).inject(document.head);
	},

	css: function(source, properties){
		return new Element('link', $merge({
			'rel': 'stylesheet', 'media': 'screen', 'type': 'text/css', 'href': source
		}, properties)).inject(document.head);
	},

	image: function(source, properties){
		properties = $merge({
			'onload': Class.empty,
			'onabort': Class.empty,
			'onerror': Class.empty
		}, properties);
		var image = new Image();
		image.src = source;
		var element = new Element('img', {'src': source});
		['load', 'abort', 'error'].each(function(type){
			var event = properties['on' + type];
			delete properties['on' + type];
			element.addEvent(type, function(){
				this.removeEvent(type, arguments.callee);
				event.call(this);
			});
		});
		if (image.width && image.height) element.fireEvent('load', element, 1);
		return element.setProperties(properties);
	},

	images: function(sources, options){
		options = $merge({
			onComplete: Class.empty,
			onProgress: Class.empty
		}, options);
		if (!sources.push) sources = [sources];
		var images = [];
		var counter = 0;
		sources.each(function(source){
			var img = new Asset.image(source, {
				'onload': function(){
					options.onProgress.call(this, counter);
					counter++;
					if (counter == sources.length) options.onComplete();
				}
			});
			images.push(img);
		});
		return new Elements(images);
	}

});

var Hash = new Class({

	length: 0,

	initialize: function(object){
		this.obj = object || {};
		this.setLength();
	},

	get: function(key){
		return (this.hasKey(key)) ? this.obj[key] : null;
	},

	hasKey: function(key){
		return (key in this.obj);
	},

	set: function(key, value){
		if (!this.hasKey(key)) this.length++;
		this.obj[key] = value;
		return this;
	},

	setLength: function(){
		this.length = 0;
		for (var p in this.obj) this.length++;
		return this;
	},

	remove: function(key){
		if (this.hasKey(key)){
			delete this.obj[key];
			this.length--;
		}
		return this;
	},

	each: function(fn, bind){
		$each(this.obj, fn, bind);
	},

	extend: function(obj){
		$extend(this.obj, obj);
		return this.setLength();
	},

	merge: function(){
		this.obj = $merge.apply(null, [this.obj].extend(arguments));
		return this.setLength();
	},

	empty: function(){
		this.obj = {};
		this.length = 0;
		return this;
	},

	keys: function(){
		var keys = [];
		for (var property in this.obj) keys.push(property);
		return keys;
	},

	values: function(){
		var values = [];
		for (var property in this.obj) values.push(this.obj[property]);
		return values;
	}

});

function $H(obj){
	return new Hash(obj);
};

Hash.Cookie = Hash.extend({

	initialize: function(name, options){
		this.name = name;
		this.options = $extend({'autoSave': true}, options || {});
		this.load();
	},

	save: function(){
		if (this.length == 0){
			Cookie.remove(this.name, this.options);
			return true;
		}
		var str = Json.toString(this.obj);
		if (str.length > 4096) return false;
		Cookie.set(this.name, str, this.options);
		return true;
	},

	load: function(){
		this.obj = Json.evaluate(Cookie.get(this.name), true) || {};
		this.setLength();
	}

});

Hash.Cookie.Methods = {};
['extend', 'set', 'merge', 'empty', 'remove'].each(function(method){
	Hash.Cookie.Methods[method] = function(){
		Hash.prototype[method].apply(this, arguments);
		if (this.options.autoSave) this.save();
		return this;
	};
});
Hash.Cookie.implement(Hash.Cookie.Methods);

var Color = new Class({

	initialize: function(color, type){
		type = type || (color.push ? 'rgb' : 'hex');
		var rgb, hsb;
		switch(type){
			case 'rgb':
				rgb = color;
				hsb = rgb.rgbToHsb();
				break;
			case 'hsb':
				rgb = color.hsbToRgb();
				hsb = color;
				break;
			default:
				rgb = color.hexToRgb(true);
				hsb = rgb.rgbToHsb();
		}
		rgb.hsb = hsb;
		rgb.hex = rgb.rgbToHex();
		return $extend(rgb, Color.prototype);
	},

	mix: function(){
		var colors = $A(arguments);
		var alpha = ($type(colors[colors.length - 1]) == 'number') ? colors.pop() : 50;
		var rgb = this.copy();
		colors.each(function(color){
			color = new Color(color);
			for (var i = 0; i < 3; i++) rgb[i] = Math.round((rgb[i] / 100 * (100 - alpha)) + (color[i] / 100 * alpha));
		});
		return new Color(rgb, 'rgb');
	},

	invert: function(){
		return new Color(this.map(function(value){
			return 255 - value;
		}));
	},

	setHue: function(value){
		return new Color([value, this.hsb[1], this.hsb[2]], 'hsb');
	},

	setSaturation: function(percent){
		return new Color([this.hsb[0], percent, this.hsb[2]], 'hsb');
	},

	setBrightness: function(percent){
		return new Color([this.hsb[0], this.hsb[1], percent], 'hsb');
	}

});

function $RGB(r, g, b){
	return new Color([r, g, b], 'rgb');
};

function $HSB(h, s, b){
	return new Color([h, s, b], 'hsb');
};

Array.extend({

	rgbToHsb: function(){
		var red = this[0], green = this[1], blue = this[2];
		var hue, saturation, brightness;
		var max = Math.max(red, green, blue), min = Math.min(red, green, blue);
		var delta = max - min;
		brightness = max / 255;
		saturation = (max != 0) ? delta / max : 0;
		if (saturation == 0){
			hue = 0;
		} else {
			var rr = (max - red) / delta;
			var gr = (max - green) / delta;
			var br = (max - blue) / delta;
			if (red == max) hue = br - gr;
			else if (green == max) hue = 2 + rr - br;
			else hue = 4 + gr - rr;
			hue /= 6;
			if (hue < 0) hue++;
		}
		return [Math.round(hue * 360), Math.round(saturation * 100), Math.round(brightness * 100)];
	},

	hsbToRgb: function(){
		var br = Math.round(this[2] / 100 * 255);
		if (this[1] == 0){
			return [br, br, br];
		} else {
			var hue = this[0] % 360;
			var f = hue % 60;
			var p = Math.round((this[2] * (100 - this[1])) / 10000 * 255);
			var q = Math.round((this[2] * (6000 - this[1] * f)) / 600000 * 255);
			var t = Math.round((this[2] * (6000 - this[1] * (60 - f))) / 600000 * 255);
			switch(Math.floor(hue / 60)){
				case 0: return [br, t, p];
				case 1: return [q, br, p];
				case 2: return [p, br, t];
				case 3: return [p, q, br];
				case 4: return [t, p, br];
				case 5: return [br, p, q];
			}
		}
		return false;
	}

});

var Scroller = new Class({

	options: {
		area: 20,
		velocity: 1,
		onChange: function(x, y){
			this.element.scrollTo(x, y);
		}
	},

	initialize: function(element, options){
		this.setOptions(options);
		this.element = $(element);
		this.mousemover = ([window, document].contains(element)) ? $(document.body) : this.element;
	},

	start: function(){
		this.coord = this.getCoords.bindWithEvent(this);
		this.mousemover.addListener('mousemove', this.coord);
	},

	stop: function(){
		this.mousemover.removeListener('mousemove', this.coord);
		this.timer = $clear(this.timer);
	},

	getCoords: function(event){
		this.page = (this.element == window) ? event.client : event.page;
		if (!this.timer) this.timer = this.scroll.periodical(50, this);
	},

	scroll: function(){
		var el = this.element.getSize();
		var pos = this.element.getPosition();

		var change = {'x': 0, 'y': 0};
		for (var z in this.page){
			if (this.page[z] < (this.options.area + pos[z]) && el.scroll[z] != 0)
				change[z] = (this.page[z] - this.options.area - pos[z]) * this.options.velocity;
			else if (this.page[z] + this.options.area > (el.size[z] + pos[z]) && el.scroll[z] + el.size[z] != el.scrollSize[z])
				change[z] = (this.page[z] - el.size[z] + this.options.area - pos[z]) * this.options.velocity;
		}
		if (change.y || change.x) this.fireEvent('onChange', [el.scroll.x + change.x, el.scroll.y + change.y]);
	}

});

Scroller.implement(new Events, new Options);

var Slider = new Class({

	options: {
		onChange: Class.empty,
		onComplete: Class.empty,
		onTick: function(pos){
			this.knob.setStyle(this.p, pos);
		},
		mode: 'horizontal',
		steps: 100,
		offset: 0
	},

	initialize: function(el, knob, options){
		this.element = $(el);
		this.knob = $(knob);
		this.setOptions(options);
		this.previousChange = -1;
		this.previousEnd = -1;
		this.step = -1;
		this.element.addEvent('mousedown', this.clickedElement.bindWithEvent(this));
		var mod, offset;
		switch(this.options.mode){
			case 'horizontal':
				this.z = 'x';
				this.p = 'left';
				mod = {'x': 'left', 'y': false};
				offset = 'offsetWidth';
				break;
			case 'vertical':
				this.z = 'y';
				this.p = 'top';
				mod = {'x': false, 'y': 'top'};
				offset = 'offsetHeight';
		}
		this.max = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
		this.half = this.knob[offset]/2;
		this.getPos = this.element['get' + this.p.capitalize()].bind(this.element);
		this.knob.setStyle('position', 'relative').setStyle(this.p, - this.options.offset);
		var lim = {};
		lim[this.z] = [- this.options.offset, this.max - this.options.offset];
		this.drag = new Drag.Base(this.knob, {
			limit: lim,
			modifiers: mod,
			snap: 0,
			onStart: function(){
				this.draggedKnob();
			}.bind(this),
			onDrag: function(){
				this.draggedKnob();
			}.bind(this),
			onComplete: function(){
				this.draggedKnob();
				this.end();
			}.bind(this)
		});
		if (this.options.initialize) this.options.initialize.call(this);
	},

	set: function(step){
		this.step = step.limit(0, this.options.steps);
		this.checkStep();
		this.end();
		this.fireEvent('onTick', this.toPosition(this.step));
		return this;
	},

	clickedElement: function(event){
		var position = event.page[this.z] - this.getPos() - this.half;
		position = position.limit(-this.options.offset, this.max -this.options.offset);
		this.step = this.toStep(position);
		this.checkStep();
		this.end();
		this.fireEvent('onTick', position);
	},

	draggedKnob: function(){
		this.step = this.toStep(this.drag.value.now[this.z]);
		this.checkStep();
	},

	checkStep: function(){
		if (this.previousChange != this.step){
			this.previousChange = this.step;
			this.fireEvent('onChange', this.step);
		}
	},

	end: function(){
		if (this.previousEnd !== this.step){
			this.previousEnd = this.step;
			this.fireEvent('onComplete', this.step + '');
		}
	},

	toStep: function(position){
		return Math.round((position + this.options.offset) / this.max * this.options.steps);
	},

	toPosition: function(step){
		return this.max * step / this.options.steps;
	}

});

Slider.implement(new Events);
Slider.implement(new Options);

var SmoothScroll = Fx.Scroll.extend({

	initialize: function(options){
		this.parent(window, options);
		this.links = (this.options.links) ? $$(this.options.links) : $$(document.links);
		var location = window.location.href.match(/^[^#]*/)[0] + '#';
			this.links.each(function(link){
				if (link.href.indexOf(location) != 0) return;
				var anchor = link.href.substr(location.length);
				if (anchor && $(anchor)) this.useLink(link, anchor);
			}, this);
			if (!window.webkit419) this.addEvent('onComplete', function(){
				window.location.hash = this.anchor;
			});
		},

		useLink: function(link, anchor){
			link.addEvent('click', function(event){
				this.anchor = anchor;
				this.toElement(anchor);
				event.stop();
			}.bindWithEvent(this));
		}

	});

	var Sortables = new Class({

		options: {
			handles: false,
			onStart: Class.empty,
			onComplete: Class.empty,
			ghost: true,
			snap: 3,
			onDragStart: function(element, ghost){
				ghost.setStyle('opacity', 0.7);
				element.setStyle('opacity', 0.7);
			},
			onDragComplete: function(element, ghost){
				element.setStyle('opacity', 1);
				ghost.remove();
				this.trash.remove();
			}
		},

		initialize: function(list, options){
			this.setOptions(options);
			this.list = $(list);
			this.elements = this.list.getChildren();
			this.handles = (this.options.handles) ? $$(this.options.handles) : this.elements;
			this.bound = {
			'start': [],
			'moveGhost': this.moveGhost.bindWithEvent(this)
			};
			for (var i = 0, l = this.handles.length; i < l; i++){
				this.bound.start[i] = this.start.bindWithEvent(this, this.elements[i]);
			}
			this.attach();
			if (this.options.initialize) this.options.initialize.call(this);
			this.bound.move = this.move.bindWithEvent(this);
			this.bound.end = this.end.bind(this);
		},

		attach: function(){
			this.handles.each(function(handle, i){
				handle.addEvent('mousedown', this.bound.start[i]);
			}, this);
		},

		detach: function(){
			this.handles.each(function(handle, i){
				handle.removeEvent('mousedown', this.bound.start[i]);
			}, this);
		},

		start: function(event, el){
			this.active = el;
			this.coordinates = this.list.getCoordinates();
			if (this.options.ghost){
				var position = el.getPosition();
				this.offset = event.page.y - position.y;
				this.trash = new Element('div').inject(document.body);
				this.ghost = el.clone().inject(this.trash).setStyles({
				'position': 'absolute',
				'left': position.x,
				'top': event.page.y - this.offset
				});
				document.addListener('mousemove', this.bound.moveGhost);
				this.fireEvent('onDragStart', [el, this.ghost]);
			}
			document.addListener('mousemove', this.bound.move);
			document.addListener('mouseup', this.bound.end);
			this.fireEvent('onStart', el);
			event.stop();
		},

		moveGhost: function(event){
			var value = event.page.y - this.offset;
			value = value.limit(this.coordinates.top, this.coordinates.bottom - this.ghost.offsetHeight);
			this.ghost.setStyle('top', value);
			event.stop();
		},

		move: function(event){
			var now = event.page.y;
			this.previous = this.previous || now;
			var up = ((this.previous - now) > 0);
			var prev = this.active.getPrevious();
			var next = this.active.getNext();
			if (prev && up && now < prev.getCoordinates().bottom) this.active.injectBefore(prev);
			if (next && !up && now > next.getCoordinates().top) this.active.injectAfter(next);
			this.previous = now;
		},

		serialize: function(converter){
			return this.list.getChildren().map(converter || function(el){
				return this.elements.indexOf(el);
			}, this);
		},

		end: function(){
			this.previous = null;
			document.removeListener('mousemove', this.bound.move);
			document.removeListener('mouseup', this.bound.end);
			if (this.options.ghost){
				document.removeListener('mousemove', this.bound.moveGhost);
				this.fireEvent('onDragComplete', [this.active, this.ghost]);
			}
			this.fireEvent('onComplete', this.active);
		}

	});

	Sortables.implement(new Events, new Options);

	var Tips = new Class({

		options: {
			onShow: function(tip){
				tip.setStyle('visibility', 'visible');
			},
			onHide: function(tip){
				tip.setStyle('visibility', 'hidden');
			},
			maxTitleChars: 30,
			showDelay: 100,
			hideDelay: 100,
			className: 'tool',
			offsets: {'x': 16, 'y': 16},
			fixed: false
		},

		initialize: function(elements, options){
			this.setOptions(options);
			this.toolTip = new Element('div', {
			'class': this.options.className + '-tip',
			'styles': {
			'position': 'absolute',
			'top': '0',
			'left': '0',
			'visibility': 'hidden'
			}
			}).inject(document.body);
			this.wrapper = new Element('div').inject(this.toolTip);
			$$(elements).each(this.build, this);
			if (this.options.initialize) this.options.initialize.call(this);
		},

		build: function(el){
			el.$tmp.myTitle = (el.href && el.getTag() == 'a') ? el.href.replace('http://', '') : (el.rel || false);
			if (el.title){
				var dual = el.title.split('::');
				if (dual.length > 1){
					el.$tmp.myTitle = dual[0].trim();
					el.$tmp.myText = dual[1].trim();
				} else {
					el.$tmp.myText = el.title;
				}
				el.removeAttribute('title');
			} else {
				el.$tmp.myText = false;
			}
			if (el.$tmp.myTitle && el.$tmp.myTitle.length > this.options.maxTitleChars) el.$tmp.myTitle = el.$tmp.myTitle.substr(0, this.options.maxTitleChars - 1) + "&hellip;";
			el.addEvent('mouseenter', function(event){
				this.start(el);
				if (!this.options.fixed) this.locate(event);
				else this.position(el);
			}.bind(this));
			if (!this.options.fixed) el.addEvent('mousemove', this.locate.bindWithEvent(this));
			var end = this.end.bind(this);
			el.addEvent('mouseleave', end);
			el.addEvent('trash', end);
		},

		start: function(el){
			this.wrapper.empty();
			if (el.$tmp.myTitle){
				this.title = new Element('span').inject(new Element('div', {'class': this.options.className + '-title'}).inject(this.wrapper)).setHTML(el.$tmp.myTitle);
			}
			if (el.$tmp.myText){
				this.text = new Element('span').inject(new Element('div', {'class': this.options.className + '-text'}).inject(this.wrapper)).setHTML(el.$tmp.myText);
			}
			$clear(this.timer);
			this.timer = this.show.delay(this.options.showDelay, this);
		},

		end: function(event){
			$clear(this.timer);
			this.timer = this.hide.delay(this.options.hideDelay, this);
		},

		position: function(element){
			var pos = element.getPosition();
			this.toolTip.setStyles({
			'left': pos.x + this.options.offsets.x,
			'top': pos.y + this.options.offsets.y
			});
		},

		locate: function(event){
			var win = {'x': window.getWidth(), 'y': window.getHeight()};
			var scroll = {'x': window.getScrollLeft(), 'y': window.getScrollTop()};
			var tip = {'x': this.toolTip.offsetWidth, 'y': this.toolTip.offsetHeight};
			var prop = {'x': 'left', 'y': 'top'};
			for (var z in prop){
				var pos = event.page[z] + this.options.offsets[z];
				if ((pos + tip[z] - scroll[z]) > win[z]) pos = event.page[z] - this.options.offsets[z] - tip[z];
				this.toolTip.setStyle(prop[z], pos);
			};
		},

		show: function(){
			if (this.options.timeout) this.timer = this.hide.delay(this.options.timeout, this);
			this.fireEvent('onShow', [this.toolTip]);
		},

		hide: function(){
			this.fireEvent('onHide', [this.toolTip]);
		}

	});

	Tips.implement(new Events, new Options);

	var Group = new Class({

		initialize: function(){
			this.instances = $A(arguments);
			this.events = {};
			this.checker = {};
		},

		addEvent: function(type, fn){
			this.checker[type] = this.checker[type] || {};
			this.events[type] = this.events[type] || [];
			if (this.events[type].contains(fn)) return false;
			else this.events[type].push(fn);
			this.instances.each(function(instance, i){
				instance.addEvent(type, this.check.bind(this, [type, instance, i]));
			}, this);
			return this;
		},

		check: function(type, instance, i){
			this.checker[type][i] = true;
			var every = this.instances.every(function(current, j){
				return this.checker[type][j] || false;
			}, this);
			if (!every) return;
			this.checker[type] = {};
			this.events[type].each(function(event){
				event.call(this, this.instances, instance);
			}, this);
		}

	});
	String.extend({
		encodeComponent: function(){
			return encodeURIComponent(this);
		},	
		stripTags: function() {
			return this.replace(/<\/?[^>]+>/gi, '');
		},
		stripScripts: function() {
			return this.replace(/<script[^>]*?>.*?<\/script>/img, '');
		},
		evalScripts: function() {
			var scripts = this.match(/<script[^>]*?>.*?<\/script>/g);
			if(scripts) scripts.each(function(script){
				eval(script.replace(/^<script[^>]*?>/, '').replace(/<\/script>$/, ''));
			});
		},
		replaceAll: function(searchValue, replaceValue, regExOptions) {
			return this.replace(new RegExp(searchValue, $pick(regExOptions,'gi')), replaceValue);
		},
		urlEncode: function() {
			return (this.test('%'))?this:escape(this);
		},
		parseQuery: function() {
			var vars = this.split(/[&;]/);
			var rs = {};
			if (vars.length) vars.each(function(val) {
				var keys = val.split('=');
				if (keys.length && keys.length == 2) rs[encodeURIComponent(keys[0])] = encodeURIComponent(keys[1]);
			});
			return rs;
		},
		tidy: function() {
			var txt = this.toString();
			$each({
			"[\xa0\u2002\u2003\u2009]": " ",
			"\xb7": "*",
			"[\u2018\u2019]": "'",
			"[\u201c\u201d]": '"',
			"\u2026": "...",
			"\u2013": "-",
			"\u2014": "--"
			}, function(value, key){
				txt = txt.replace(new RegExp(key, 'g'), value);
			});
			return txt;
		}
	});
	window.extend({
		isLoaded: window.loaded,
		getHost:function(url){
			url = $pick(url, window.location.href);
			var host = url;
			if(url.test('http://')){
				url = url.substring(url.indexOf('http://')+7,url.length);
				if(url.test(':')) url = url.substring(0, url.indexOf(":"));
				if(url.test('/')) return url.substring(0,url.indexOf('/'));
				return url;
			}
			return false;
		},
		getQueryStringValue: function(key, url) {
			try {
				return window.getQueryStringValues(url)[key];
			}catch(e){return null;}
		},
		getQueryStringValues: function(url){
			var qs = $pick(url, $pick(window.location.search, '')).split('?')[1]; //get the query string
			if(qs) return qs.parseQuery();
			return {}; //if there isn't one, return null
		},
		getPort: function(url) {
			url = $pick(url, window.location.href);
			var re = new RegExp(':([0-9]{4})');
			var m = re.exec(url);
			if (m == null) return false;
			else {
				var port = false;
				m.each(function(val){
					if($chk(parseInt(val))) port = val;
				});
			}
			return port;
		},
		qs: {}
	});
	window.qs = window.getQueryStringValues(); 
/************? default ?***************/
 /* Immprove 1.0 */
var prevCli;
var windowLoaded = false;
var bkup  = new Object();
var saBar = [];
window.addEvent('load',function(){
  windowLoaded = true;
});
window.addEvent('domready', function(){
  var Tips2 = new Tips($$('.tips'), {
    offsets:{
      x:-50,
      y:30
    },
    initialize:function(){
      this.fx = new Fx.Style(this.toolTip, 'opacity', {
        duration: 500, 
        wait: false
      }).set(0);
    },
    onShow: function(toolTip) {
      this.fx.start(1);
    },
    onHide: function(toolTip) {
      this.fx.start(0);
    },
    hideDelay: 400,
    fixed: false 
  });
  Cookie.set('jsChk', 'true');
});
if(!$chk(console)) {
  var console = {};
  console.dir = function(){};
  console.log = function(){};
}
function setAk(k){
  if(!k) return;
  Cookie.remove('akey');
  Cookie.set('akey',k,{
    path:"/"
  });
}
function toggleBox(ele,content) {
  if($(ele).style.display == "block"){
    $(ele).style.display= 'none';
  } else {
    $(ele).style.display='block';
  }
  if(content != '') $(ele).innerHTML= content;
}
function show(ele) {
  if($(ele) != null) {
    if($(ele).style.display == "block") {
      $(ele).style.display= 'none';
    }	else {
      $(ele).style.display='block';
    }
    return false;
  }
};
function IsNumeric(sText) {
  var ValidChars = "0123456789.$";
  var IsNumber=true;
  var Char;
  for (i = 0; i < sText.length && IsNumber == true; i++){
    Char = sText.charAt(i);
    if (ValidChars.indexOf(Char) == -1)	IsNumber = false;
  }
  return IsNumber;
};
function changeClass(elem, myClass) {
  $(elem).addClass(myClass);
};
function changeBackground(Elem, Back) {
  try {
    var type = $(Elem).getProperty('type');
  } catch(err) {
    return false;
  }
  if(type == 'radio') {
    if($(Elem + 'Label')) $(Elem + 'Label').setStyle('background',Back);
  } else {
    $(Elem).setStyle('background',Back);
  }

};
function toClipboard(t) {
  var p   = t.getParent().getElement('input');
  p.setStyle('background','red');
//var txt = p.getElement('input').createTextRange();
//txt.execCommand('Copy');
}
function watchChange(ele) {
  $(ele).addEvent('focus',function(){
    $(ele).setStyle('background','#FFF');
    $(ele).setStyle('color','#000');
  });
}
function toggleCb(ele) {
  $$(ele).each(function(item){
    item.checked = (item.checked) ? false:true;
  });
};
function toggleChecks(c){
  $$(c).each(function(item){
    item.checked = (item.checked) ? false:true;
  });
}
function validateCheckbox(ele) {
  var btn = $$('#' + ele);
  for(i=0;i<btn.length;i++){
    if(btn[i].checked) return true;
  }
  return false;
}
function uncheckAll(field) {
  for (i = 0; i < field.length; i++)	field[i].checked = false ;
};
function splitFrames() {
  document.write('<HTML><HEAD><TITLE>Immerse Support</TITLE></HEAD><FRAMESET COLS="*, 300"><FRAME SRC="');
  document.write(top.location.href);
  document.write('" NAME="leftcolumn"><FRAME SRC="http://support.immersegraphics.com" NAME="leftcolumn"></FRAMESET></HTML>');
  return false;
};
function confirmRedirect(t,l){
  if(confirm(t)) {
    window.location = l;
  }
}
function closeConfirm(al) {
  al.parentNode.removeChild(al);
};
function validateEmail(ele){
  var x = $(ele).value;
  if(x != '') {
    var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (filter.test(x)) {
      return true;
    }	else {
      return false;
    }
  }
};
function clearTxt(ele) {
  $(ele).value = '';
}
function clearExpand(ele,sz) {
  clearTxt(ele);
  $(ele).setProperty('size',sz);
}
var expSaved ;
var tFx = {};
function expandTextarea(id) {
  if(!expSaved) {
    var ot = $(id).getCoordinates();
    expSaved = new Array(ot.width,ot.height);
    if(!$defined(tFx[id])) tFx[id] = new Fx.Styles($(id),{
      'duration':1000,
      transition: Fx.Transitions.Bounce.easeOut
      });
    tFx[id].start({
      'height':[expSaved[1],400]
      });
  } else {
    tFx[id].start({
      'height':expSaved[1]
      });
    expSaved = false;
  }
}
function strobeBg(id) {
  var myFx = new Fx.Style($(id), 'opacity');
  myFx.start(1,0).chain(function(){
    myFx.start(0,1);
  });
}
function strobeThenFade(id) {
  var myFx = new Fx.Style($(id), 'opacity',{
    'duration':1500
  });
  myFx.start(1,.5).chain(function(){
    myFx.start(.5,1)
    }).chain(function(){
    myFx.start(1,.2)
    }).chain(function(){
    myFx.start(.2,1)
    }).chain(function(){
    myFx.start(1,.2)
    }).chain(function(){
    myFx.start(.2,1)
    }).chain(function(){
    myFx.start(1,.0)
    }).chain(function(){
    $(id).setStyle('display','none')
    });
}
function clickObjElement(obj, ele) {
  if(prevCli) $(prevCli).setStyle('background', '#FFFFFF');
  $E('input',obj).checked = true;
  $(obj).setStyle('background', '#F3F3F3');
  prevCli = obj;
}
function gup( name ) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
function disableEnterKey(e) {
  var key;
  if(window.event)key = window.event.keyCode;     //IE
  else key = e.which;     //firefox
  if(key == 13) return false;
  else return true;
}
function popupNoteClose(msg) {
  popupNote(msg);
}
function popupNote(msg) {
  window.addEvent('domready',function(){
    window.scroll(0,-5000);
    var bg = new Element('div',{
      'id':'popupNote'
    }).setStyle('opacity','.5').injectBefore($('container'));
    var inf = new Element('div',{
      'id':'popupContainer'
    }).setHTML(unescape(msg)).injectBefore(bg);
    var close = new Element('div',{
      'id':'popupClose'
    }).setHTML('close').injectInside($('popupContainer'));
    close.onclick = closePopupNote;
    bg.onclick    = closePopupNote;
  });
}
function popupNoteLarge(msg) {
  var bg = new Element('div',{
    'id':'popupNote'
  });
  var inf = new Element('div',{
    'id':'popupWide'
  });
  inf.setHTML(msg);
  bg.injectBefore($('container'));
  inf.injectBefore(bg);
}
function fadeThenRemove(id){
  if($chk($(id))) {
    var f = new Fx.Style($(id), 'opacity',{
      'duration':1000
    }).start(0);
    f.addEvent('onComplete',function(){
      $(id).removeEvents().remove();
    });
  }
}
var statBox = function(txt, s) {
  var b = new Element('div',{
    'class':'sBox '+s
    }).setHTML('<p>'+txt+'</p>');
  return b;
}
function popupBox(title,text,type){
  var ph  = new Element('div').setStyles({
    'cursor':'pointer',
    'opacity':0
  }).injectInside(document.body);
  var bg  = new Element('div',{
    'class':'opaqueBackground'
  }).injectInside(ph).centerScreen();
  var box = new Element('div',{
    'class':'sBox ' + type
    }).setStyle('z-index',10000);

  new Element('h1').setHTML(title).injectInside(box);
  new Element('p').setHTML(text).injectInside(box);
  box.setStyles({
    'width':300
  });
  box.injectInside(ph).centerScreen();

  var f = new Fx.Style(ph, 'opacity',{
    'duration':500
  }).start(1);
  ph.addEvent('click',function(){
    fadeThenRemove(this);
  });
}
var closePopupNote = function(){
  fadeThenRemove('popupNote');
  fadeThenRemove('popupWide');
  fadeThenRemove('popupContainer');
}
function popupLoading(ele) {
  var bg = new Element('div',{
    'id':'popupLoading',
    'class':'opaqueBackground'
  });
  var inf = new Element('div',{
    'id':'popupBar'
  });
  inf.setHTML('Working.. Please Wait...<br><img src="/design/icons/ajax-loader.gif">');
  bg.injectBefore(ele);
  inf.injectBefore(bg);
}
function ajaxLoading(ele) {
  return loIcon(ele,'lg')
  }
function loIcon(ele, s) {
  if($type(ele) != 'elememt') ele = $(ele);
  ele.empty();
  var icon = '/design/icons/' + (s == 'sm' ? 'loadSm.gif':'ajax-loader.gif');
  var i = new Asset.image(icon, {
    id: 'loIcon', 
    onload: function(){
      this.injectInside(ele).centerElement();
    }
  });
  return i;
}
function popupLoadingFs() {
  var bg 	 = new Element('div',{
    'id':'popupLoading',
    'class':'opaqueBackground'
  });
  var lTxt = 'Loading Data.. Please Wait...<br><img src="/design/icons/ajax-loader.gif" />';
  var inf  = new Element('div',{
    'id':'popupBar'
  }).setHTML(lTxt);
  window.addEvent('domready',function(){
    bg.injectInside(document.body);
    inf.injectAfter(bg).centerScreen();
  });
  window.addEvent('load',function(){
    removeLoading.delay(3000);
  });
}
var popupAlert = function(txt) {
  if($chk($('alertB'))) {
    $('alertB').remove();
  }
  var alertBox = new Element('div',{
    id: 'alertB'
  })
  .addClass('alertBox').setHTML('<h1>Please fix the following errors</h1>');
  alertBox.setStyle('opacity','0');
  var sty = 'cursor:pointer;position:absolute;bottom:0px;right:0px;padding:4px;';
  alertBox.innerHTML += txt + '<div style="'+sty+'"><a href="#" onclick="return false"><strong>Close</strong></a></div>';
  window.scroll(0,-1000);
  alertBox.injectInside(document.body).centerScreen();
  var ef = new Fx.Style(alertBox, 'opacity', {
    duration:1000
  }).start(0,1);
  alertBox.addEvent('click',function() {
    alertBox.removeEvents();
    fadeThenRemove('alertB')
  });
}
var removeLoading = function() {
  window.removeEvent('load',removeLoading);
  fadeThenRemove('popupLoading');
  fadeThenRemove('popupBar');
}
function popupRedirect(text, loc){
  var bg = new Element('div',{
    'class':'opaqueBackground'
  }).injectInside(document.body);
  var box = new Element('div',{
    'class':'popupBox'
  }).setHTML(fullDecode(text));
  var red = new Element('input',{
    'type':'button',
    'value':'continue',
    'class':'popupButton'
  }).injectInside(box);
  red.addEvent('click',function(){
    window.location = loc
    });
  box.injectAfter(bg).centerScreen();

}
function btoa(input) {
  return Base64.encode(input);
}

var expand = function(ele) {
  if(!$chk($(ele))) return false;
  var icon = $(ele).getElement('img');
  var par = $(ele).getParent();
  if(par.getTag() != 'div') {
    var par = par.getParent();
  }
  var con = ['div','fieldset','tr']
  if(!con.contains(par.getTag())) {
    return false;
  }
  var h = par.getElement('.hidden');
  if(!h) alert('no hidden areas');
  if(h.getStyle('display') == 'none') {
    h.setStyles('display:block;overflow:hidden;height:0px;');
  }
  var hid = h.getFirst().getCoordinates();
  var ef = new Fx.Style(h,'height',{
    duration:500
  });
  if(h.getStyle('height').toInt() > 0) {
    icon.setProperty('src','/design/icons/expand.png');
    ef.start(0);
  } else {
    icon.setProperty('src','/design/icons/contract.png');
    ef.start(hid.height+20);
  }
}
function validateRadio(ele) {
  var btn = document.getElementsByName(ele);
  for(i=0;i<btn.length;i++){
    if(btn[i].checked) return true;
  }
  return false;
}
function dump(arr,level) {
  var dumped_text = "";
  if(!level) level = 0;
  var level_padding = "";
  for(var j=0;j<level+1;j++) level_padding += "    ";
  if(typeof(arr) == 'object') { //Array/Hashes/Objects
    for(var item in arr) {
      var value = arr[item];
      if(typeof(value) == 'object') { //If it is an array,
        dumped_text += level_padding + "'" + item + "'=>\"\"\n";
        dumped_text += dump(value,level+1);
      } else {
        dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
      }
    }
  } else {
    dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
  }
  return dumped_text;
}
var Base64 = {
  _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
  encode : function (input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;
    input = Base64._utf8_encode(input);
    while (i < input.length) {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
        enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
        enc4 = 64;
      }

      output = output +
      this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
      this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

    }

    return output;
  },
  decode : function (input) {
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;

    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

    while (i < input.length) {

      enc1 = this._keyStr.indexOf(input.charAt(i++));
      enc2 = this._keyStr.indexOf(input.charAt(i++));
      enc3 = this._keyStr.indexOf(input.charAt(i++));
      enc4 = this._keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
      }

    }

    output = Base64._utf8_decode(output);

    return output;

  },
  _utf8_encode : function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

      var c = string.charCodeAt(n);

      if (c < 128) {
        utftext += String.fromCharCode(c);
      }
      else if((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128);
      }
      else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128);
      }

    }

    return utftext;
  },
  _utf8_decode : function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

      c = utftext.charCodeAt(i);

      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      }
      else if((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i+1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      }
      else {
        c2 = utftext.charCodeAt(i+1);
        c3 = utftext.charCodeAt(i+2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }
    }
    return string;
  }
}
function fullEncode(s) {
  return encodeURIComponent(Base64.encode(s));
}
function fullDecode(s) {
  return decodeURIComponent(Base64.decode(s));
}
function insertAtCursor(myField, myValue) {
  if (document.selection) {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
  }
  //MOZILLA/NETSCAPE support
  else if (myField.selectionStart || myField.selectionStart == '0') {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos)
    + myValue
    + myField.value.substring(endPos, myField.value.length);
  } else {
    myField.value += myValue;
  }
}
String.extend({
  fullEncode: function(){
    return encodeURIComponent(Base64.encode(this));
  }
})
function makehtml(s) {
  var ss = new String();
  for( i = 0; i < s.length; i++) {
    var fs = s.charCodeAt(i);
    ss += '&#' + fs + ';';
  }
  return ss;
}

var playerControls = function(pre) {
  var mp 	= pre.getParent();
  mp.setStyle('position','relative');
  var tp 	= new Element('div',{
    'class':'playerControls'
  }).addEvent('click',stopProp).injectInside(mp);
  var pl  = new Element('img',{
    'src':'/img/icons/play.png'
  }).addEvent('mousedown',playMovie.bind(pre)).injectInside(tp);
  var li  = new Element('img',{
    'src':'/img/icons/stop_play.png'
  }).addEvent('mousedown',stopMovie.bind(pre)).injectInside(tp);
}
var stopProp = function(eve){
  new Event(eve).stop();
}
var playMovie = function(){
  this.Play();
}
var stopMovie = function(){
  this.StopPlay();
}


if(window.ie6) {
  new Asset.javascript('/scripts/fixPng.js', {
    id: 'pngFIX'
  });
}

Element.extend({
  centerScreen: function(){
    var ele = this.getCoordinates();
    var y = window.getScrollTop() + ((window.getHeight()/2)-(ele.height/2));
    var x = ((window.getWidth()/2) - (ele.width/2));
    var styles = {};
    styles.position = (this.getStyle('position') != 'fixed' ? 'absolute':'fixed');
    styles.top  		= y+'px';
    styles.left 		= x+'px';
    this.setStyles(styles);
  },
  centerElement: function(){
    var par = this.getParent();
    var ps 	= par.getStyle('position');
    if(ps != 'absolute' && ps != 'relative') {
      this.getParent().setStyle('position','relative');
    }
    var c = this.getCoordinates();
    var sty = {
      'top':'50%',
      'left':'50%',
      'position':'absolute',
      'margin-top':'-'+(c.height.toInt() / 2)+'px',
      'margin-left':'-'+(c.width.toInt() / 2)+'px'
    };
    this.setStyles(sty);
  },
  toJsonStringEncoded:function(){
    var queryString = [];
    this.getFormElements().each(function(el){
      var name  = el.name;
      var v = el.getValue();
      if(typeof v == 'string'){
        var value = fullEncode(v);
      } else {
        var value = v;
      }
      if (value === false || !name || el.disabled) return;
      var qs = function(val){
        queryString.push('"' + name.replace(/(["\\])/g, '\\$1') + '":"' + val.replace(/(["\\])/g, '\\$1') + '"');
      };
      if ($type(value) == 'array') value.each(qs);
      else qs(value);
    });
    return '{' + queryString.join(',') + '}';
  },
  toJsonString:function(){
    var queryString = [];
    this.getFormElements().each(function(el){
      var name = el.name;
      var value = el.getValue();
      if (value === false || !name || el.disabled) return;
      value.urlEncode();
      var qs = function(val){
        queryString.push('"' + name.replace(/(["\\])/g, '\\$1') + '":"' + val.replace(/(["\\])/g, '\\$1') + '"');
      };
      if ($type(value) == 'array') value.each(qs);
      else qs(value);
    });
    return '{' + queryString.join(',') + '}';
  },
  formToJson:function(){
    return Json.evaluate(this.toJsonString());
  },
  formToJsonEncoded:function(){
    var e = this.toJsonStringEncoded();
    return Json.evaluate(e);
  }
});
var TimePicker = new Class({
  initialize: function(field){
    this.field = $(field);
    this.field.setStyle('display','none');
    this.showPicker();
  },
  showPicker: function(){
    var ps = {
      'border':'1px solid #000',
      'padding':'0px',
      'position':'absolute',
      'width':'160px'
    };
    this.picker = new Element('div').setStyles(ps);
    var ts = 'padding:4px;border:0px solid #FFF !important;width:20px;float:left;';

    this.hours = new Element('input',{
      'class':'hours',
      'type':'text',
      'value':'00',
      'size':2,
      'maxlength':2
    }).setStyles(ts).injectInside(this.picker);
    this.hours.addEvent('keydown',this.numOnly.bind(this));
    this.hours.addEvent('mousedown',this.editItem.bind(this));

    this.tSelector(this.hours).injectBefore(this.hours);

    this.dots = new Element('div').setStyles('float:left;padding:13px 2px;font-size:20px;line-height:0px;font-weight:bolder;').setHTML(':').injectInside(this.picker);

    this.minutes = new Element('input',{
      'class':'minutes',
      'type':'text',
      'value':'00',
      'size':2,
      'maxlength':2
    }).setStyles(ts).injectInside(this.picker);
    this.tSelector(this.minutes).injectBefore(this.minutes);

    this.ampm = new Element('input',{
      'class':'ampm',
      'type':'text',
      'value':'am',
      'size':2,
      'maxlength':2
    }).setStyles(ts).injectInside(this.picker);
    this.tSelector(this.ampm).injectBefore(this.ampm);

    this.picker.injectAfter(this.field);
  },
  editItem: function(eve){
    var e = new Event(eve);
    e.target.value = '';
    e.target.focus();
  },
  chkVal: function(eve){
    var e = new Event(eve);
    var val = new Number(e.target.value);
    if(e.target.hasClass('hours')) {
      alert(val);
      if(val > 12) {
        alert(val);
        e.stop();
        return false;
      }
    }
  },
  numOnly: function(eve){
    var e = new Event(eve);
    if(!IsNumeric(e.key)) {
      e.stop();
      return false;
    }

  },
  tSelector: function(target){
    var style = 'float:left;margin:0px 3px;padding-top:7px;';
    var ts = new Element('div').setStyles(style);
    var as = 'margin:0px;padding:0px;line-height:0px;height:10px;';
    var up = new Element('div').setStyles(as).setHTML('<img src="/img/time/selUp.png" width="10">').injectInside(ts);
    var down = new Element('div').setStyles(as).setHTML('<img src="/img/time/selDown.png"  width="10">').injectInside(ts);
    up.addEvent('click',function(){
      if(target.hasClass('hours')) this.changeHour('up');
      if(target.hasClass('minutes')) this.changeMinute('up');
    //if(target.hasClass('ampm')) this.changeAmpm('up');
    }.bind(this));
    down.addEvent('click',function(){
      if(target.hasClass('hours')) this.changeHour('up');
      if(target.hasClass('minutes')) this.changeMinute('up');
    //if(target.hasClass('ampm')) this.changeAmpm('up');
    }.bind(this));
    return ts;

  },
  changeHour: function(d){
    var hour = new Number(this.hours.value);
    var ne;
    if(d=='up') {
      ne = ((hour==12) ? 1 : (hour+1));
    } else {
      ne = ((hour==1) ? 12 : (hour-1));
    }
    this.hours.value = ne;
  },
  changeMinute: function(d){
    var minute = new Number(this.minutes.value);
    var ne;
    if(d=='up') {
      ne = ((minute==59) ? 1 : (minute+1));
    } else {
      ne = ((minute==1) ? 59 : (minute-1));
    }
    if(ne<10) ne = '0'+ne;
    this.minutes.value = ne;
  }

});

/*
MooCal v0.2 - A simple and easy to use calendar control built upon mooTools
by Chris Martin (http://www.redantdesign.com/) - MIT-style license.

The draw function is modified from a date picker control written by David Kelly
* Copyright 2007 David Kelly for CJD Systems Limited
* version 0.1 - 21st May 2007
* url - http://ng100.cjdsystems.co.uk/moo/dates/DateTimePicker.htm

*/

var MooCal = new Class({
  initialize: function(){
    this.setOptions({
      base: 1,
      x:0,
      y:0,
      calendarClass: "calendar",
      todayClass: "today",
      selectedClass: "selected",
      dayNames: ["Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat", "Sun"],
      monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    });
    this.sqlCompatable = true;
    this.calendarID = null;
    this.visible = false;
    this.displayTimer = 0;
    this.minYear = '2000';
    this.maxYear = '2020';
  },
  showCal: function(ele,value) {
    this.elementID   = ele;
    this.chosenDate = new Date();
    if(value=='' || value == "0000-00-00") {
      var d = new Date();
      value = d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate();
    }
    if(value.test(' ')) {
      var dat = value.split(' ');
      var parts = dat[0].split('-');
      this.times = dat[1].split(':');
    } else {
      var parts = value.split('-');
    }

    this.chosenDate.setYear(parts[0]);
    var month = new Number(parts[1]);
    this.chosenDate.setMonth(month-1);
    this.chosenDate.setDate(parts[2]);
    this.currentDate = this.chosenDate;
    this.monthAndYear = null;
    var c = $(ele).getCoordinates();
    this.show(c.left,c.top);
  },
  setTimeSelect:function(){
    this.displayTime = true;
  },
  show: function(x, y) {
    if(!this.visible){
      this.calendarID = "calendar_" + Date.parse(new Date());
      this.draw($pick(x, this.options.x), $pick(y, this.options.y));
    }
    this.visible = true;
  },
  hide: function() {
    if(this.visible){
      $(this.calendarID).remove();
      this.visible = false;
      clearTimeout(this.displayTimer);
    }
  },
  setValue: function(d){
    this.currentDate.setDate(d);
    this.chosenDate = this.currentDate;
    var day = this.currentDate.getDate().toString();
    if(day.length == 1) day = '0' + day;
    var month = this.currentDate.getMonth()+1;
    month = month.toString();
    if(month.length == 1) month = '0' + month;


    if(!this.displayTime) {
      $(this.elementID).setProperty("value", this.currentDate.getFullYear() + '-' + month + '-' + day);
      this.hide();
    } else {
      var hrs = this.hoursSelect.value;
      if(this.ampmSelect.value == 'pm' && hrs!=12) {
        var it = new Number(this.hoursSelect.value);
        var hrs =  it+12;
      }
      if(hrs == 12 &&this.ampmSelect.value == 'am') hrs = '00';
      var time = hrs+':'+this.minutesSelect.value+':00';
      $(this.elementID).setProperty("value", this.currentDate.getFullYear() + '-' + month + '-' + day + ' ' + time);
      this.redraw();
    }
  },
  selectDate: function(e,d) {
    new Event(e).stop();
    if($type(d) != "number")return;
    this.setValue(d);
  },
  dispTime: function(){
    var dDate = this.options.monthNames[this.currentDate.getMonth()] + " " + this.currentDate.getDate() + " " +  this.currentDate.getFullYear();
    var time = this.hoursSelect.value+':'+this.minutesSelect.value+' '+this.ampmSelect.value;
    this.ct.setHTML(dDate+' '+time);
    this.setValue(this.currentDate.getDate());
  },
  setDates: function(){
    this.lastMonth = new Date(this.currentDate).setMonth(this.currentDate.getMonth() - 1);
    this.nextMonth = new Date(this.currentDate).setMonth(this.currentDate.getMonth() + 1);
    this.lastYear = new Date(this.currentDate).setFullYear(this.currentDate.getFullYear() - 1);
    this.nextYear = new Date(this.currentDate).setFullYear(this.currentDate.getFullYear() + 1);
    this.today = new Date();
  },

  repaint: function(e,d) {
    new Event(e).stop();
    var dateToCheck = new Date(d);
    if(dateToCheck.getFullYear() < this.minYear || dateToCheck.getFullYear() > this.maxYear){
      return;
    }
    this.currentDate = dateToCheck;
    this.setDates();
    this.redraw();
  },

  mouseOver: function() {
    clearTimeout(this.displayTimer);
  },

  mouseOut: function() {
    this.displayTimer = this.hide.delay(500, this);
  },

  draw: function(x, y) {
    var tableContainer, table, thead, tbody, row, td;
    tableContainer = new Element("div",{
      "class": this.options.calendarClass,
      "id": this.calendarID,
      "events": {
        "mouseover": this.mouseOver.bind(this),
        "mouseout": this.mouseOut.bind(this)
        }
      }).setStyles({
    "position":"absolute",
    "left": x,
    "top": y
  });
  table = new Element("table", {
    "id": this.calendarID + "-table",
    "class": this.calendarID + "-table"
    });
  thead = new Element("thead").injectInside(table);

  row = new Element("tr").injectInside(thead);
  new Element("a", {
    "href":"#",
    "events":{
      "click": (function(e){
        this.repaint(e, this.lastYear);
      }).bindWithEvent(this)
      }
    }).setHTML("&laquo;").injectInside(new Element("th", {
  "class": this.options.calendarClass + "-yearswitch"
  }).injectInside(row));
  new Element("a", {
    "href":"#",
    "events":{
      "click": (function(e){
        this.repaint(e, this.lastMonth);
      }).bindWithEvent(this)
      }
    }).setHTML("&#139;").injectInside(new Element("th", {
  "class": this.options.calendarClass + "-monthswitch"
  }).injectInside(row));

this.monthAndYear = new Element("th", {
  "colSpan": 3,
  "class" : this.options.calendarClass + "-monthandyear"
  }).appendText(this.options.monthNames[this.currentDate.getMonth()] + " " + this.currentDate.getFullYear()).injectInside(row);
new Element("a", {
  "href":"#",
  "events":{
    "click": (function(e){
      this.repaint(e, this.nextMonth);
    }).bindWithEvent(this)
    }
  }).setHTML("&#155;").injectInside(new Element("th", {
  "class": this.options.calendarClass + "-monthswitch"
  }).injectInside(row));
new Element("a", {
  "href":"#",
  "events":{
    "click": (function(e){
      this.repaint(e, this.nextYear);
    }).bindWithEvent(this)
    }
  }).setHTML("&raquo;").injectInside(new Element("th", {
  "class": this.options.calendarClass + "-yearswitch"
  }).injectInside(row));

row = new Element("tr").injectInside(thead);
for (i = 0; i < 7; i++)	{
  new Element("th").appendText(this.options.dayNames[i]).injectInside(row);
}

tbody = new Element("tbody").injectInside(table);
for(r=0;r<6;r++){
  row = new Element("tr").injectInside(tbody);
  for(c=0;c<7;c++){
    td = new Element("td",{
      'class':'cday'
    }).injectInside(row);
    new Element("a",{
      "href": "#"
    }).setHTML("&nbsp;").injectInside(td);
  }
}
table.injectInside(tableContainer);
if(this.displayTime) {
  row = new Element('tr',{
    'class':'cDT'
  }).injectInside(table);
  td = new Element("td").setProperty('colspan',7).injectInside(row);
  var dDate = this.options.monthNames[this.currentDate.getMonth()] + " " + this.currentDate.getDate() + " " +  this.currentDate.getFullYear() + ' 12:00 AM';
  this.ct = new Element('div',{
    'id':'ct'
  }).setHTML(dDate).injectInside(td);
  row = new Element('tr',{
    'class':'timePicker'
  }).injectInside(table);
  td = new Element("td").setProperty('colspan',7).injectInside(row);
  //setStyles('margin:0px;padding:5px;').setHTML('Time: ');
  this.hoursSelect = new Element('select',{
    'name':'chours',
    'id':'chours'
  }).addEvent('change',this.dispTime.bind(this)).injectInside(td);
  var ampm;
  if(this.times) {
    if(this.times[0] == '00') {
      this.times[0] = 12;
      ampm = 'am';
    }
    if(this.times[0] > 12) {
      var ti = new Number(this.times[0]);
      this.times[0] =  ti-12;
      ampm = 'pm';
    } else if(this.times[0] == 12 && ampm!='am') {
  var ampm = 'pm';
  }
  }
  for(i=1;i<=12;i++){
    var hr = new Element('option',{
      'value':i
    }).setHTML(i).injectInside(this.hoursSelect);
    if(this.times) {
      if(this.times[0] == i) hr.selected = true;
    }
  }
  this.minutesSelect = new Element('select',{
    'name':'cminutes',
    'id':'cminutes'
  }).addEvent('change',this.dispTime.bind(this)).injectInside(td);
  for(h=0;h<=59;h++){
    minute = new String(h);
    if(minute.length < 2) {
      mi = "0"+minute;
    } else mi = minute;
    var min = new Element('option',{
      'value':mi
    }).setHTML(mi).injectInside(this.minutesSelect);
    if(this.times) {
      if(this.times[1] == mi) min.selected = true;
    }
  }
  this.ampmSelect = new Element('select',{
    'name':'campm',
    'id':'campm'
  }).addEvent('change',this.dispTime.bind(this)).injectInside(td);
  var am = new Element('option',{
    'value':'am'
  }).setHTML('AM').injectInside(this.ampmSelect);
  var pm = new Element('option',{
    'value':'pm'
  }).setHTML('PM').injectInside(this.ampmSelect);
  if(ampm=='pm') pm.selected = true;
  if(ampm=='am') am.selected = true;
//holder.injectAfter(table);
}
tableContainer.injectInside(document.body);
this.redraw();
},
redraw: function() {
  this.setDates();
  this.monthAndYear.setText(this.options.monthNames[this.currentDate.getMonth()] + " " + this.currentDate.getFullYear());
  var firstDay = new Date(this.currentDate);
  firstDay.setDate(1);

  if (firstDay.getDay() > 0) {
    firstDay.setDate(-firstDay.getDay() + 1);
  }

  var currentDay = new Date(firstDay);
  var today = new Date();
  $ES("tbody a", $(this.calendarID)).each(function(item,i){
    var txt = "&nbsp;";
    if (currentDay.getMonth() == this.currentDate.getMonth()) {
      txt = currentDay.getDate();
    }
    item.removeClass(this.options.todayClass);
    item.getParent().removeClass(this.options.selectedClass);

    item.removeEvents();
    item.addEvent("click", (function(e, day){
      this.selectDate(e, day);
    }).bindWithEvent(this, txt));
    item.setHTML(txt);
    if (currentDay.getDate() == today.getDate() && currentDay.getMonth() == today.getMonth() && currentDay.getFullYear() == today.getFullYear()) {
      item.addClass(this.options.todayClass);
    }
    if (currentDay.getMonth() == this.chosenDate.getMonth() &&
      currentDay.getDate() == this.chosenDate.getDate() &&
      currentDay.getMonth() == this.chosenDate.getMonth() &&
      currentDay.getFullYear() == this.chosenDate.getFullYear()) {
      item.getParent().addClass(this.options.selectedClass);
    }
    currentDay.setDate(currentDay.getDate() + 1);
  }.bind(this));
}
});

MooCal.implement(new Options);
window.addEvent('domready',function(){
  $ES('.dpick',document.body).each(function(item){
    item.addEvent('click',dSelect);
  });
  $ES('.dtpick',document.body).each(function(item){
    item.addEvent('click',dtSelect);
  });
});
var dSelect = function(eve){
  var e = new Event(eve).stop();
  var item = $(e.target);
  var date = item.value;
  var DTCalendar = new MooCal();
  DTCalendar.showCal(item,date);
};
var dtSelect = function(eve){
  var e = new Event(eve).stop();
  var item = $(e.target);
  var date = item.value;
  var DTCalendar = new MooCal();
  DTCalendar.setTimeSelect();
  DTCalendar.showCal(item,date);
};
 
/************? menu ?***************/
 var menuMaker = new Class({
	initialize: function(tab, items){
		this.tab = tab;
		this.items = items;
		this.container = '';
		this.effect    = '';
		window.addEvent('domready',this.create.bind(this));
	},
	create: function(){
		$(this.tab).addEvent('mouseenter',this.sMenu.bind(this));
		$(this.tab).addEvent('mouseleave',this.hMenu.bind(this));
		$(this.tab).setStyles({'position':'relative'});
		var aValues = $(this.tab).getCoordinates();
		this.container = new Element('span',{'class':'container'}).setStyles({'position':'absolute','display':'none'});
		switch(this.effect) {
			case 'slide':
			//this.menuFx = new Fx.Slide(this.container, {duration: 500}).hide();
			this.menuFx = new Fx.Style(this.container, 'height', {duration:500}).set(0);
			//this.container.setStyle('display','block');
			break;
			case 'fade':
			this.menuFx = new Fx.Style(this.container, 'opacity', {duration:1000}).set(0);
			//this.container.setStyle('display','block');
			break;
		}
		this.container.injectInside($(this.tab));
		this.items.each(function(item){
			var holder = new Element('div', {'class':'menuItem'});
			var js     = new Boolean(item[2].toInt());
			if(js==false) {
				holder.setHTML('<a href="' + item[1]  + '" onclick="event.cancelBubble=true;">' + item[0] + '</a>');
				holder.addEvent('click',function(){window.location = item[1]});
			} else {
				holder.setHTML('<a href="#">' + item[0] + '</a>');
				holder.addEvent('click',function(){eval(item[1])});
			}
			if(item[3]) {
				new Element('img',{'src':'/img/icons/'+item[3]+'.png','class':'tabIcon'}).injectBefore(holder.getFirst());
			}
			holder.injectInside(this.container);
		}.bind(this));
	},
	sMenu: function(){
		switch(this.effect){
			default:
			this.container.setStyle('display','block');
			break;
			case 'slide':
			this.menuFx.start(100);
			break;
			case 'fade':
			this.menuFx.start(100);
			break;
		}
	},
	hMenu: function(){
		if($chk(window.ie7)) {
		var cont = this.container;
		(function(){ cont.setStyle('display','none') }).delay(1000);
		} else {
			this.container.setStyle('display','none')
		}
	}
}); 
/************? flaobj ?***************/
 /*	SWFObject v2.2 <http://code.google.com/p/swfobject/> 
	is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+encodeURI(O.location).toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}(); 
/************? immWindow ?***************/
 var immWindow = new Class({
	initialize: function(title){
		this.title = title;
		this.multiple  = false;
		this.editorContent = '';
		this.warnclose = new String();
		this.editors   = new Array();
		this.editor    = '';
		this.loading   = '';
		this.fx        = {};
		this.editor    = {};
		this.editProps = {};
		this.debug     = false;
		this.centered  = true;
		this.back      = false;
		this.aviewable = true;
		this.setSize(400,350);
		this.addEvent('contentLoaded',this.contentDone.bind(this));
		return this
	},
	contentDone: function(){
		if($type(this.loading)=='element'){
			var sty = new Fx.Styles(this.loading);
			sty.addEvent('onComplete',function(){
				this.loading.remove();
				this.loading = false;
			}.bind(this));
			sty.start({'opacity':0})
		}
	},
	createWindow: function(wName, multi){
		if(wName!=undefined) {
			this.title = wName;
			if(this.windowOpened == wName) return false;
		}
		editor = new Element('div',{'class':'wHolder'});
		if(!this.title.test('img') && !this.title.test('div')) this.title = '<div style="padding:10px;">' + this.title + '</div>';
		editor.mover  = new Element('div',{'class':'wMover'}).addEvents({'click':this.bringtotop.bind(this)}).setHTML(this.title);
		editor.closer  = new Element('div',{'class':'wCloser'}).addEvent('mouseup',this.close.bind(this)).injectInside(editor.mover);
		editor.min  = new Element('div',{'class':'wMin'}).injectInside(editor.mover).addEvent('click',this.minimize.bind(this));
		editor.content = new Element('div',{'class':'wContent'}).setStyles('overflow:auto;').injectInside(editor);
		if(this.debug) {
			editor.de = new Element('div').injectInside(editor);
			var text = new Element('input',{'type':'text','id':'debug'}).injectInside(editor.de);
			var text2 = new Element('input',{'type':'text','id':'debug2'}).injectInside(editor.de);
		}
		editor.mover.injectBefore(editor.content);
		editor.content.setStyles(this.editProps);
		this.editor = editor;
		this.editors.include(editor);
		this.fireEvent('onStart');
		this.editor.status = 'open';
		this.fx = new Fx.Styles(this.editor,{duration: 500, transition: Fx.Transitions.Sine.easeInOut});
		this.editor.setStyle('opacity',0);
		if($chk(this.position)) {
			var ww = window.getWidth() / 2;
			var wh = window.getHeight() / 2;
			if(this.position.left > ww) this.editor.setStyle('left','10px');
		}
		this.editor.injectInside(document.body);
		this.fx.start({'opacity':1});
		if(this.centered) this.centerWindow();
		this.move();
		if(wName!='') {
			this.windowOpened = wName;
		}
		if(this.aviewable) this.keepView();
		this.fireEvent('onComplete');
		return this;
	},
	setCloseEvent: function(event) {
		this.editor.closer.removeEvent('mouseup',this.close);
	},
	minimize:function(){
		if(!this.minimized) {
			this.contentOrig = this.editor.content.getCoordinates();
			this.contentFx = this.fx = new Fx.Styles(this.editor.content);
			this.editor.content.setStyle('overflow','hidden');
			this.fx.start({'height':0});
			this.minimized=true;
		} else {
			this.fx.start({'height':this.contentOrig.height});
			this.editor.content.setStyle('overflow','auto');
			this.minimized=false;
		}
	},
	addFooter: function(){
		this.removeFooter();
		this.editor.footer = new Element('div',{'id':'wFooter'});
		this.editor.footer.injectAfter(this.editor.content);
	},
	removeFooter: function(){
		if($type(this.editor.footer) == 'element') {
			this.editor.footer.remove();
			this.editor.footer = false;
		}
	},
	keepView:function(){
		window.addEvent('scroll',function(){
			if(this.editor) {
				var cur = this.editor.getCoordinates();
				var wtop = window.getScrollTop();
				if(cur.top < wtop) this.fx.start({'top':wtop + 50});
				var wbot = wtop + window.getHeight();
				if(cur.bottom > wbot) this.fx.start({'top':wbot - cur.height});
			}
		}.bind(this));
	},
	setPosition: function(t,l){
		this.fx.addEvent('onComplete',f = (function(){
			this.removeEvent('onComplete',f);
			this.set({'top':t+'px','left':l+'px'});
		}));
	},
	avoid: function(item){
		var av = item.getCoordinates();
		this.position = this.editor.getCoordinates();
		if(this.position.right > av.right){
			this.editor.setStyles({'left':av.right+'px'});
			console.log('Noving');
		}
	},
	remainingWindows: function(){
		debugData('Windows Found:' + this.editors.length);
	},
	setSize: function(width,height){
		if(width > 0) this.editProps.width = width;
		if(height > 0) this.editProps.height = height;
	},
	fadeIn: function(){
		this.fx.start({'opacity':1});
	},
	hideContent: function(){
		this.hider = new Element('div').setStyles('height:100%;width:100%');
	},
	windowSize: function(){
		if(MooTools.version == '1.11') {
			return window.getSize();
		} else {
			var si = window.getSize();
			var sc = window.getScroll();
			var ss = window.getScrollSize();
			return {
        'scroll': {'x': sc.x, 'y': sc.y},
        'size': {'x': si.x, 'y': si.y},
        'scrollSize': {'x': ss.x, 'y': ss.y}
    	}
		}
	},
	centerWindow:function(){
		var ws = this.windowSize();
		var left = (((ws.size.x / 2)  + ws.scroll.x) - (this.editProps.width /2));
		this.editor.setStyle('left',left + 'px');
		var top = (((ws.size.y / 2) + ws.scroll.y) - (this.editProps.height /2));
		this.editor.setStyle('top',top + 'px');
	},
	changeHeight: function(){
		this.fx.start({'height':500,'width':800});
	},
	expandSize:function(w,h){
		var props = {};
		if($defined(w)) props.width  = w;
		if($defined(h)) props.height = h;
		this.fx.set(this.fx.to);
		this.start(props);
	},
	showLoading:function(){
		this.loading = new Element('div',{'class':'wLoading'});
		var c = this.editor.content.getCoordinates();
		this.loading.setStyle('height',c.height+'px');
		this.loading.injectBefore(this.editor.content);
		var lo = new Element('div',{'class':'loadInfo'});
		lo.setHTML('<p><strong>Loading....</strong></p><img src="/design/icons/ajax-loader.gif">');
		lo.injectInside(this.loading).centerElement();
	},
	showWorking: function(){
		this.working = new Element('div',{'class':'working'})
		.setHTML('<strong>Please Wait....</strong><br /><img src="/design/icons/ajax-loader.gif">')
		.injectInside(this.editor.content);
	},
	bringtotop:function(){
		if(this.editors.length == 1) return;
		this.editors.each(function(item, index){
			debugData(index + " = " + item);
			item.setStyle('z-index','1');
		},this);
		this.editor.setStyle('z-index','2');
	},
	move:function(){
		var ws = this.windowSize();
		var wx = ws.scrollSize.x - this.editProps.width;
		var wy = ws.scrollSize.y - this.editProps.height;
		var dr = new Drag.Move(this.editor,{'handle':this.editor.mover});
	},
	removeWindow: function(){
		if($chk(this.editor)) {
			this.editors.remove(this.editor);
			this.editor.getParent().removeChild(this.editor);
			this.editor = false;
			this.fireEvent('onClose');
		}
	},
	close: function(e){
		//var eve = new Event(e).stop();
		this.windowOpened = '';
		this.fx.start({'opacity':0});
		this.fx.addEvent('onComplete',this.removeWindow.bind(this));
	}
});
immWindow.implement({
	setIframe: function(loc){
		this.editor.content.setStyle('overflow','hidden');
		this.iFrame = new Element('iframe',{'id':'windowFrame','src':loc,'scrolling':'no'}).injectInside(this.editor.content);
		this.iFrame.setStyles({'width':this.editProps.width,'height':this.editProps.height});
	},
	jReq: function(p,m){
		new Json.Remote('/?immJax=module&n='+p+'&c='+m, {
			onComplete: function(data){
				if(data.html) this.setContent(data.html);
			}.bind(this)
		}).send();
	},
	setFooter: function(c){
		this.addFooter();
		this.editor.footer.setHTML(c);
	},
	addBeforeContent: function(item){
		var con = this.editor.content.getFirst();
		item.injectBefore(con);
	},
	setContent: function(c){
		this.editor.content.empty();
		var tHold = new Element('div',{'id':'tHold'}).setHTML(c);
		tHold.injectInside(this.editor.content);
		var ts = tHold.getSize();
		var cs = this.editor.content.getSize();
		//if(ts.size.y > cs.size.y) {
			//this.editor.setStyle('height',ts.size.y+'px');
		//}
		this.editor.content.scrollTop = 0;
		this.fireEvent('contentLoaded',this,500);
		return this;
	},
	popOver: function(c){
		this.working = new Element('div',{'class':'popOver'})
		.setHTML(c)
		.injectInside(this.editor.content);
	},
	addContent: function(c){
		this.editor.content.appendText(c);
		return this;
	},
	addElement: function(c){
		c.injectInside(this.editor.content);
		return this;
	},
	debugInfo: function(){
		var t = this.editor.getSize();
		this.editor.content.setHTML(dump(t));
	}
});
immWindow.implement(new Events); 
/************? cufon ?***************/
 /*
 * Copyright (c) 2009 Simo Kinnunen.
 * Licensed under the MIT license.
 *
 * @version 1.09
 */
var Cufon=(function(){var m=function(){return m.replace.apply(null,arguments)};var x=m.DOM={ready:(function(){var C=false,E={loaded:1,complete:1};var B=[],D=function(){if(C){return}C=true;for(var F;F=B.shift();F()){}};if(document.addEventListener){document.addEventListener("DOMContentLoaded",D,false);window.addEventListener("pageshow",D,false)}if(!window.opera&&document.readyState){(function(){E[document.readyState]?D():setTimeout(arguments.callee,10)})()}if(document.readyState&&document.createStyleSheet){(function(){try{document.body.doScroll("left");D()}catch(F){setTimeout(arguments.callee,1)}})()}q(window,"load",D);return function(F){if(!arguments.length){D()}else{C?F():B.push(F)}}})(),root:function(){return document.documentElement||document.body}};var n=m.CSS={Size:function(C,B){this.value=parseFloat(C);this.unit=String(C).match(/[a-z%]*$/)[0]||"px";this.convert=function(D){return D/B*this.value};this.convertFrom=function(D){return D/this.value*B};this.toString=function(){return this.value+this.unit}},addClass:function(C,B){var D=C.className;C.className=D+(D&&" ")+B;return C},color:j(function(C){var B={};B.color=C.replace(/^rgba\((.*?),\s*([\d.]+)\)/,function(E,D,F){B.opacity=parseFloat(F);return"rgb("+D+")"});return B}),fontStretch:j(function(B){if(typeof B=="number"){return B}if(/%$/.test(B)){return parseFloat(B)/100}return{"ultra-condensed":0.5,"extra-condensed":0.625,condensed:0.75,"semi-condensed":0.875,"semi-expanded":1.125,expanded:1.25,"extra-expanded":1.5,"ultra-expanded":2}[B]||1}),getStyle:function(C){var B=document.defaultView;if(B&&B.getComputedStyle){return new a(B.getComputedStyle(C,null))}if(C.currentStyle){return new a(C.currentStyle)}return new a(C.style)},gradient:j(function(F){var G={id:F,type:F.match(/^-([a-z]+)-gradient\(/)[1],stops:[]},C=F.substr(F.indexOf("(")).match(/([\d.]+=)?(#[a-f0-9]+|[a-z]+\(.*?\)|[a-z]+)/ig);for(var E=0,B=C.length,D;E<B;++E){D=C[E].split("=",2).reverse();G.stops.push([D[1]||E/(B-1),D[0]])}return G}),quotedList:j(function(E){var D=[],C=/\s*((["'])([\s\S]*?[^\\])\2|[^,]+)\s*/g,B;while(B=C.exec(E)){D.push(B[3]||B[1])}return D}),recognizesMedia:j(function(G){var E=document.createElement("style"),D,C,B;E.type="text/css";E.media=G;try{E.appendChild(document.createTextNode("/**/"))}catch(F){}C=g("head")[0];C.insertBefore(E,C.firstChild);D=(E.sheet||E.styleSheet);B=D&&!D.disabled;C.removeChild(E);return B}),removeClass:function(D,C){var B=RegExp("(?:^|\\s+)"+C+"(?=\\s|$)","g");D.className=D.className.replace(B,"");return D},supports:function(D,C){var B=document.createElement("span").style;if(B[D]===undefined){return false}B[D]=C;return B[D]===C},textAlign:function(E,D,B,C){if(D.get("textAlign")=="right"){if(B>0){E=" "+E}}else{if(B<C-1){E+=" "}}return E},textShadow:j(function(F){if(F=="none"){return null}var E=[],G={},B,C=0;var D=/(#[a-f0-9]+|[a-z]+\(.*?\)|[a-z]+)|(-?[\d.]+[a-z%]*)|,/ig;while(B=D.exec(F)){if(B[0]==","){E.push(G);G={};C=0}else{if(B[1]){G.color=B[1]}else{G[["offX","offY","blur"][C++]]=B[2]}}}E.push(G);return E}),textTransform:(function(){var B={uppercase:function(C){return C.toUpperCase()},lowercase:function(C){return C.toLowerCase()},capitalize:function(C){return C.replace(/\b./g,function(D){return D.toUpperCase()})}};return function(E,D){var C=B[D.get("textTransform")];return C?C(E):E}})(),whiteSpace:(function(){var D={inline:1,"inline-block":1,"run-in":1};var C=/^\s+/,B=/\s+$/;return function(H,F,G,E){if(E){if(E.nodeName.toLowerCase()=="br"){H=H.replace(C,"")}}if(D[F.get("display")]){return H}if(!G.previousSibling){H=H.replace(C,"")}if(!G.nextSibling){H=H.replace(B,"")}return H}})()};n.ready=(function(){var B=!n.recognizesMedia("all"),E=false;var D=[],H=function(){B=true;for(var K;K=D.shift();K()){}};var I=g("link"),J=g("style");function C(K){return K.disabled||G(K.sheet,K.media||"screen")}function G(M,P){if(!n.recognizesMedia(P||"all")){return true}if(!M||M.disabled){return false}try{var Q=M.cssRules,O;if(Q){search:for(var L=0,K=Q.length;O=Q[L],L<K;++L){switch(O.type){case 2:break;case 3:if(!G(O.styleSheet,O.media.mediaText)){return false}break;default:break search}}}}catch(N){}return true}function F(){if(document.createStyleSheet){return true}var L,K;for(K=0;L=I[K];++K){if(L.rel.toLowerCase()=="stylesheet"&&!C(L)){return false}}for(K=0;L=J[K];++K){if(!C(L)){return false}}return true}x.ready(function(){if(!E){E=n.getStyle(document.body).isUsable()}if(B||(E&&F())){H()}else{setTimeout(arguments.callee,10)}});return function(K){if(B){K()}else{D.push(K)}}})();function s(D){var C=this.face=D.face,B={"\u0020":1,"\u00a0":1,"\u3000":1};this.glyphs=D.glyphs;this.w=D.w;this.baseSize=parseInt(C["units-per-em"],10);this.family=C["font-family"].toLowerCase();this.weight=C["font-weight"];this.style=C["font-style"]||"normal";this.viewBox=(function(){var F=C.bbox.split(/\s+/);var E={minX:parseInt(F[0],10),minY:parseInt(F[1],10),maxX:parseInt(F[2],10),maxY:parseInt(F[3],10)};E.width=E.maxX-E.minX;E.height=E.maxY-E.minY;E.toString=function(){return[this.minX,this.minY,this.width,this.height].join(" ")};return E})();this.ascent=-parseInt(C.ascent,10);this.descent=-parseInt(C.descent,10);this.height=-this.ascent+this.descent;this.spacing=function(L,N,E){var O=this.glyphs,M,K,G,P=[],F=0,J=-1,I=-1,H;while(H=L[++J]){M=O[H]||this.missingGlyph;if(!M){continue}if(K){F-=G=K[H]||0;P[I]-=G}F+=P[++I]=~~(M.w||this.w)+N+(B[H]?E:0);K=M.k}P.total=F;return P}}function f(){var C={},B={oblique:"italic",italic:"oblique"};this.add=function(D){(C[D.style]||(C[D.style]={}))[D.weight]=D};this.get=function(H,I){var G=C[H]||C[B[H]]||C.normal||C.italic||C.oblique;if(!G){return null}I={normal:400,bold:700}[I]||parseInt(I,10);if(G[I]){return G[I]}var E={1:1,99:0}[I%100],K=[],F,D;if(E===undefined){E=I>400}if(I==500){I=400}for(var J in G){if(!k(G,J)){continue}J=parseInt(J,10);if(!F||J<F){F=J}if(!D||J>D){D=J}K.push(J)}if(I<F){I=F}if(I>D){I=D}K.sort(function(M,L){return(E?(M>=I&&L>=I)?M<L:M>L:(M<=I&&L<=I)?M>L:M<L)?-1:1});return G[K[0]]}}function r(){function D(F,G){if(F.contains){return F.contains(G)}return F.compareDocumentPosition(G)&16}function B(G){var F=G.relatedTarget;if(!F||D(this,F)){return}C(this,G.type=="mouseover")}function E(F){C(this,F.type=="mouseenter")}function C(F,G){setTimeout(function(){var H=d.get(F).options;m.replace(F,G?h(H,H.hover):H,true)},10)}this.attach=function(F){if(F.onmouseenter===undefined){q(F,"mouseover",B);q(F,"mouseout",B)}else{q(F,"mouseenter",E);q(F,"mouseleave",E)}}}function u(){var C=[],D={};function B(H){var E=[],G;for(var F=0;G=H[F];++F){E[F]=C[D[G]]}return E}this.add=function(F,E){D[F]=C.push(E)-1};this.repeat=function(){var E=arguments.length?B(arguments):C,F;for(var G=0;F=E[G++];){m.replace(F[0],F[1],true)}}}function A(){var D={},B=0;function C(E){return E.cufid||(E.cufid=++B)}this.get=function(E){var F=C(E);return D[F]||(D[F]={})}}function a(B){var D={},C={};this.extend=function(E){for(var F in E){if(k(E,F)){D[F]=E[F]}}return this};this.get=function(E){return D[E]!=undefined?D[E]:B[E]};this.getSize=function(F,E){return C[F]||(C[F]=new n.Size(this.get(F),E))};this.isUsable=function(){return !!B}}function q(C,B,D){if(C.addEventListener){C.addEventListener(B,D,false)}else{if(C.attachEvent){C.attachEvent("on"+B,function(){return D.call(C,window.event)})}}}function v(C,B){var D=d.get(C);if(D.options){return C}if(B.hover&&B.hoverables[C.nodeName.toLowerCase()]){b.attach(C)}D.options=B;return C}function j(B){var C={};return function(D){if(!k(C,D)){C[D]=B.apply(null,arguments)}return C[D]}}function c(F,E){var B=n.quotedList(E.get("fontFamily").toLowerCase()),D;for(var C=0;D=B[C];++C){if(i[D]){return i[D].get(E.get("fontStyle"),E.get("fontWeight"))}}return null}function g(B){return document.getElementsByTagName(B)}function k(C,B){return C.hasOwnProperty(B)}function h(){var C={},B,F;for(var E=0,D=arguments.length;B=arguments[E],E<D;++E){for(F in B){if(k(B,F)){C[F]=B[F]}}}return C}function o(E,M,C,N,F,D){var K=document.createDocumentFragment(),H;if(M===""){return K}var L=N.separate;var I=M.split(p[L]),B=(L=="words");if(B&&t){if(/^\s/.test(M)){I.unshift("")}if(/\s$/.test(M)){I.push("")}}for(var J=0,G=I.length;J<G;++J){H=z[N.engine](E,B?n.textAlign(I[J],C,J,G):I[J],C,N,F,D,J<G-1);if(H){K.appendChild(H)}}return K}function l(D,M){var C=D.nodeName.toLowerCase();if(M.ignore[C]){return}var E=!M.textless[C];var B=n.getStyle(v(D,M)).extend(M);var F=c(D,B),G,K,I,H,L,J;if(!F){return}for(G=D.firstChild;G;G=I){K=G.nodeType;I=G.nextSibling;if(E&&K==3){if(H){H.appendData(G.data);D.removeChild(G)}else{H=G}if(I){continue}}if(H){D.replaceChild(o(F,n.whiteSpace(H.data,B,H,J),B,M,G,D),H);H=null}if(K==1){if(G.firstChild){if(G.nodeName.toLowerCase()=="cufon"){z[M.engine](F,null,B,M,G,D)}else{arguments.callee(G,M)}}J=G}}}var t=" ".split(/\s+/).length==0;var d=new A();var b=new r();var y=new u();var e=false;var z={},i={},w={autoDetect:false,engine:null,forceHitArea:false,hover:false,hoverables:{a:true},ignore:{applet:1,canvas:1,col:1,colgroup:1,head:1,iframe:1,map:1,optgroup:1,option:1,script:1,select:1,style:1,textarea:1,title:1,pre:1},printable:true,selector:(window.Sizzle||(window.jQuery&&function(B){return jQuery(B)})||(window.dojo&&dojo.query)||(window.Ext&&Ext.query)||(window.YAHOO&&YAHOO.util&&YAHOO.util.Selector&&YAHOO.util.Selector.query)||(window.$$&&function(B){return $$(B)})||(window.$&&function(B){return $(B)})||(document.querySelectorAll&&function(B){return document.querySelectorAll(B)})||g),separate:"words",textless:{dl:1,html:1,ol:1,table:1,tbody:1,thead:1,tfoot:1,tr:1,ul:1},textShadow:"none"};var p={words:/\s/.test("\u00a0")?/[^\S\u00a0]+/:/\s+/,characters:"",none:/^/};m.now=function(){x.ready();return m};m.refresh=function(){y.repeat.apply(y,arguments);return m};m.registerEngine=function(C,B){if(!B){return m}z[C]=B;return m.set("engine",C)};m.registerFont=function(D){if(!D){return m}var B=new s(D),C=B.family;if(!i[C]){i[C]=new f()}i[C].add(B);return m.set("fontFamily",'"'+C+'"')};m.replace=function(D,C,B){C=h(w,C);if(!C.engine){return m}if(!e){n.addClass(x.root(),"cufon-active cufon-loading");n.ready(function(){n.addClass(n.removeClass(x.root(),"cufon-loading"),"cufon-ready")});e=true}if(C.hover){C.forceHitArea=true}if(C.autoDetect){delete C.fontFamily}if(typeof C.textShadow=="string"){C.textShadow=n.textShadow(C.textShadow)}if(typeof C.color=="string"&&/^-/.test(C.color)){C.textGradient=n.gradient(C.color)}else{delete C.textGradient}if(!B){y.add(D,arguments)}if(D.nodeType||typeof D=="string"){D=[D]}n.ready(function(){for(var F=0,E=D.length;F<E;++F){var G=D[F];if(typeof G=="string"){m.replace(C.selector(G),C,true)}else{l(G,C)}}});return m};m.set=function(B,C){w[B]=C;return m};return m})();Cufon.registerEngine("canvas",(function(){var b=document.createElement("canvas");if(!b||!b.getContext||!b.getContext.apply){return}b=null;var a=Cufon.CSS.supports("display","inline-block");var e=!a&&(document.compatMode=="BackCompat"||/frameset|transitional/i.test(document.doctype.publicId));var f=document.createElement("style");f.type="text/css";f.appendChild(document.createTextNode(("cufon{text-indent:0;}@media screen,projection{cufon{display:inline;display:inline-block;position:relative;vertical-align:middle;"+(e?"":"font-size:1px;line-height:1px;")+"}cufon cufontext{display:-moz-inline-box;display:inline-block;width:0;height:0;overflow:hidden;text-indent:-10000in;}"+(a?"cufon canvas{position:relative;}":"cufon canvas{position:absolute;}")+"}@media print{cufon{padding:0;}cufon canvas{display:none;}}").replace(/;/g,"!important;")));document.getElementsByTagName("head")[0].appendChild(f);function d(p,h){var n=0,m=0;var g=[],o=/([mrvxe])([^a-z]*)/g,k;generate:for(var j=0;k=o.exec(p);++j){var l=k[2].split(",");switch(k[1]){case"v":g[j]={m:"bezierCurveTo",a:[n+~~l[0],m+~~l[1],n+~~l[2],m+~~l[3],n+=~~l[4],m+=~~l[5]]};break;case"r":g[j]={m:"lineTo",a:[n+=~~l[0],m+=~~l[1]]};break;case"m":g[j]={m:"moveTo",a:[n=~~l[0],m=~~l[1]]};break;case"x":g[j]={m:"closePath"};break;case"e":break generate}h[g[j].m].apply(h,g[j].a)}return g}function c(m,k){for(var j=0,h=m.length;j<h;++j){var g=m[j];k[g.m].apply(k,g.a)}}return function(V,w,P,t,C,W){var k=(w===null);if(k){w=C.getAttribute("alt")}var A=V.viewBox;var m=P.getSize("fontSize",V.baseSize);var B=0,O=0,N=0,u=0;var z=t.textShadow,L=[];if(z){for(var U=z.length;U--;){var F=z[U];var K=m.convertFrom(parseFloat(F.offX));var I=m.convertFrom(parseFloat(F.offY));L[U]=[K,I];if(I<B){B=I}if(K>O){O=K}if(I>N){N=I}if(K<u){u=K}}}var Z=Cufon.CSS.textTransform(w,P).split("");var E=V.spacing(Z,~~m.convertFrom(parseFloat(P.get("letterSpacing"))||0),~~m.convertFrom(parseFloat(P.get("wordSpacing"))||0));if(!E.length){return null}var h=E.total;O+=A.width-E[E.length-1];u+=A.minX;var s,n;if(k){s=C;n=C.firstChild}else{s=document.createElement("cufon");s.className="cufon cufon-canvas";s.setAttribute("alt",w);n=document.createElement("canvas");s.appendChild(n);if(t.printable){var S=document.createElement("cufontext");S.appendChild(document.createTextNode(w));s.appendChild(S)}}var aa=s.style;var H=n.style;var j=m.convert(A.height);var Y=Math.ceil(j);var M=Y/j;var G=M*Cufon.CSS.fontStretch(P.get("fontStretch"));var J=h*G;var Q=Math.ceil(m.convert(J+O-u));var o=Math.ceil(m.convert(A.height-B+N));n.width=Q;n.height=o;H.width=Q+"px";H.height=o+"px";B+=A.minY;H.top=Math.round(m.convert(B-V.ascent))+"px";H.left=Math.round(m.convert(u))+"px";var r=Math.max(Math.ceil(m.convert(J)),0)+"px";if(a){aa.width=r;aa.height=m.convert(V.height)+"px"}else{aa.paddingLeft=r;aa.paddingBottom=(m.convert(V.height)-1)+"px"}var X=n.getContext("2d"),D=j/A.height;X.scale(D,D*M);X.translate(-u,-B);X.save();function T(){var x=V.glyphs,ab,l=-1,g=-1,y;X.scale(G,1);while(y=Z[++l]){var ab=x[Z[l]]||V.missingGlyph;if(!ab){continue}if(ab.d){X.beginPath();if(ab.code){c(ab.code,X)}else{ab.code=d("m"+ab.d,X)}X.fill()}X.translate(E[++g],0)}X.restore()}if(z){for(var U=z.length;U--;){var F=z[U];X.save();X.fillStyle=F.color;X.translate.apply(X,L[U]);T()}}var q=t.textGradient;if(q){var v=q.stops,p=X.createLinearGradient(0,A.minY,0,A.maxY);for(var U=0,R=v.length;U<R;++U){p.addColorStop.apply(p,v[U])}X.fillStyle=p}else{X.fillStyle=P.get("color")}T();return s}})());Cufon.registerEngine("vml",(function(){var e=document.namespaces;if(!e){return}e.add("cvml","urn:schemas-microsoft-com:vml");e=null;var b=document.createElement("cvml:shape");b.style.behavior="url(#default#VML)";if(!b.coordsize){return}b=null;var h=(document.documentMode||0)<8;document.write(('<style type="text/css">cufoncanvas{text-indent:0;}@media screen{cvml\\:shape,cvml\\:rect,cvml\\:fill,cvml\\:shadow{behavior:url(#default#VML);display:block;antialias:true;position:absolute;}cufoncanvas{position:absolute;text-align:left;}cufon{display:inline-block;position:relative;vertical-align:'+(h?"middle":"text-bottom")+";}cufon cufontext{position:absolute;left:-10000in;font-size:1px;}a cufon{cursor:pointer}}@media print{cufon cufoncanvas{display:none;}}</style>").replace(/;/g,"!important;"));function c(i,j){return a(i,/(?:em|ex|%)$|^[a-z-]+$/i.test(j)?"1em":j)}function a(l,m){if(m==="0"){return 0}if(/px$/i.test(m)){return parseFloat(m)}var k=l.style.left,j=l.runtimeStyle.left;l.runtimeStyle.left=l.currentStyle.left;l.style.left=m.replace("%","em");var i=l.style.pixelLeft;l.style.left=k;l.runtimeStyle.left=j;return i}function f(l,k,j,n){var i="computed"+n,m=k[i];if(isNaN(m)){m=k.get(n);k[i]=m=(m=="normal")?0:~~j.convertFrom(a(l,m))}return m}var g={};function d(p){var q=p.id;if(!g[q]){var n=p.stops,o=document.createElement("cvml:fill"),i=[];o.type="gradient";o.angle=180;o.focus="0";o.method="sigma";o.color=n[0][1];for(var m=1,l=n.length-1;m<l;++m){i.push(n[m][0]*100+"% "+n[m][1])}o.colors=i.join(",");o.color2=n[l][1];g[q]=o}return g[q]}return function(ac,G,Y,C,K,ad,W){var n=(G===null);if(n){G=K.alt}var I=ac.viewBox;var p=Y.computedFontSize||(Y.computedFontSize=new Cufon.CSS.Size(c(ad,Y.get("fontSize"))+"px",ac.baseSize));var y,q;if(n){y=K;q=K.firstChild}else{y=document.createElement("cufon");y.className="cufon cufon-vml";y.alt=G;q=document.createElement("cufoncanvas");y.appendChild(q);if(C.printable){var Z=document.createElement("cufontext");Z.appendChild(document.createTextNode(G));y.appendChild(Z)}if(!W){y.appendChild(document.createElement("cvml:shape"))}}var ai=y.style;var R=q.style;var l=p.convert(I.height),af=Math.ceil(l);var V=af/l;var P=V*Cufon.CSS.fontStretch(Y.get("fontStretch"));var U=I.minX,T=I.minY;R.height=af;R.top=Math.round(p.convert(T-ac.ascent));R.left=Math.round(p.convert(U));ai.height=p.convert(ac.height)+"px";var F=Y.get("color");var ag=Cufon.CSS.textTransform(G,Y).split("");var L=ac.spacing(ag,f(ad,Y,p,"letterSpacing"),f(ad,Y,p,"wordSpacing"));if(!L.length){return null}var k=L.total;var x=-U+k+(I.width-L[L.length-1]);var ah=p.convert(x*P),X=Math.round(ah);var O=x+","+I.height,m;var J="r"+O+"ns";var u=C.textGradient&&d(C.textGradient);var o=ac.glyphs,S=0;var H=C.textShadow;var ab=-1,aa=0,w;while(w=ag[++ab]){var D=o[ag[ab]]||ac.missingGlyph,v;if(!D){continue}if(n){v=q.childNodes[aa];while(v.firstChild){v.removeChild(v.firstChild)}}else{v=document.createElement("cvml:shape");q.appendChild(v)}v.stroked="f";v.coordsize=O;v.coordorigin=m=(U-S)+","+T;v.path=(D.d?"m"+D.d+"xe":"")+"m"+m+J;v.fillcolor=F;if(u){v.appendChild(u.cloneNode(false))}var ae=v.style;ae.width=X;ae.height=af;if(H){var s=H[0],r=H[1];var B=Cufon.CSS.color(s.color),z;var N=document.createElement("cvml:shadow");N.on="t";N.color=B.color;N.offset=s.offX+","+s.offY;if(r){z=Cufon.CSS.color(r.color);N.type="double";N.color2=z.color;N.offset2=r.offX+","+r.offY}N.opacity=B.opacity||(z&&z.opacity)||1;v.appendChild(N)}S+=L[aa++]}var M=v.nextSibling,t,A;if(C.forceHitArea){if(!M){M=document.createElement("cvml:rect");M.stroked="f";M.className="cufon-vml-cover";t=document.createElement("cvml:fill");t.opacity=0;M.appendChild(t);q.appendChild(M)}A=M.style;A.width=X;A.height=af}else{if(M){q.removeChild(M)}}ai.width=Math.max(Math.ceil(p.convert(k*P)),0);if(h){var Q=Y.computedYAdjust;if(Q===undefined){var E=Y.get("lineHeight");if(E=="normal"){E="1em"}else{if(!isNaN(E)){E+="em"}}Y.computedYAdjust=Q=0.5*(a(ad,E)-parseFloat(ai.height))}if(Q){ai.marginTop=Math.ceil(Q)+"px";ai.marginBottom=Q+"px"}}return y}})());
