/*
 * My Box Javascript
 *
 * Copyright (c) 2007 Alex Hoo (www.comicsand.com)
 *
 */

var ASPECT = ['left', 'top', 'right', 'bottom'];
var nU = navigator.userAgent, nA = navigator.appVersion;
var Env = {
	IE: !!(window.attachEvent && !window.opera),
	IE7: nA.indexOf('MSIE 7') != -1,
	IE6: nA.indexOf('MSIE 6') != -1,
	Opera: !!window.opera,
	Safari: nU.indexOf(' AppleWebKit/') != -1, 
	KHTML: (/Konqueror|Safari|KHTML/).test(nU),
	Gecko:  nU.indexOf('Gecko') != -1 && !nU.indexOf('KHTML') != -1
};
nU = nA = null;
var sStr = 'ghijklmnopqrstuvwxyz', sStrL = sStr.length;

if (Env.IE) {
	try {
		document.execCommand('BackgroundImageCache', false, true);
	} catch(e) {}
	/* Compatibility with IE 5.0 */
	if (typeof(encodeURIComponent) == 'undefined') {
		encodeURIComponent = function(uri) {
			return (escape(uri));
		};
	}
}

function extend(d, s) {
	for (p in s) {
		if (s[p] !== null) d[p] = (typeof(s[p]) == 'object' && !(s[p].nodeType) && !(s[p] instanceof Array)) ? extend({}, s[p]) : s[p];
	}
	return d;
}

extend(Function.prototype, {
	bind: function(obj) {
		var fn = this;
		return function() {
			return fn.apply(obj, arguments);
		};
	},
	listen: function(obj) {
		var fn = this;
		return function(event) {
			fn.call(obj, event || window.event);
		};
	}
});

extend(Array.prototype, {
	indexOf: function(obj) {
		for (var i = 0; i < this.length; i++) {
			if (this[i] == obj) {
				return i;
			}
		}
		return -1;
	},
	has: function(obj) {
		return this.indexOf(obj) !== -1;
	},
	each: function(fn, obj){
		for (var i = 0; i < this.length ; i++) {
			fn.call(obj, this[i], i);
		}
	}
});

if (typeof Array.prototype.push == 'undefined') {
	extend(Array.prototype,{
		push: function(obj) {
			this[this.length] = obj;
		}
	});
}

extend(String.prototype, {
	encode: function(key) {
		if (key == '' || this.length == 0) return;
		str = encodeURIComponent(this + '');
		var result = '', sl = str.length, kl = key.length, strC, t; 
		for (var i = 0; i < sl; i++) {
			strC = str.charCodeAt(i);
			t = (i === sl - 1) ? '' : sStr.charAt(strC % sStrL);
			result += (strC ^ key.charCodeAt(i % kl)).toString(16) + t;
		}
		return result; 
	},
	decode: function(key) {
		if (key == '' || this.length == 0) return;
		var _temp, _array, result = '', i, tl, kl = key.length;
		
		_temp = this.match(/[^g-z]+/ig);
		tl = _temp.length;
		for (i = 0; i < tl; i++) {
			result += String.fromCharCode(parseInt(_temp[i], 16) ^ key.charCodeAt(i % kl));
		}
		return  decodeURIComponent(result);
	},
	trim: function() {
		return this.replace(/^(\s|\r|\n|\r\n)*|(\s|\r|\n|\r\n)*$/g, '');
	},
	rtrim: function() {
		return this.replace(/\s*$/g, '');
	},
	toInt: function() {
		var i = parseInt(this);
		if (isNaN(i)) i = 0;
		return i;
	},
	toFloat: function() {
		var i = parseFloat(this);
		if (isNaN(i)) i = 0;
		return i;
	},
	camelCase: function() {
		return this.replace(/-\D/gi, function(match){
			return match.charAt(match.length - 1).toUpperCase();
		});
	},
	stripScript: function() {
		return this.replace(/<script(?:.|\r|\n)*?>(\n|\r|.)*?<\/script\s*?>/ig, '');
	},
	toColor: function() {
		var str = this;
		var regColor = /\s*(#[0-9a-f]{3,6})\s*/ig;
		if (regColor.test(this)) {
			return str.replace(regColor, '$1');
		}
		regColor = /.*rgb\s*\(\s*([0-9]+).*,\s*([0-9]+).*,\s*([0-9]+)\s*\).*/ig;
		if (!regColor.test(this)) {
			return '';
		}
		var rgb = this.replace(regColor, '$1,$2,$3').split(',');
		var col =  '#';
		for (var i = 0; i < 3; i++) {
			var j = (rgb[i] - 0).toString(16);
			col += j.length == 1 ? '0' + j : j;
		}
		return col;
	},
	tranColor: function() {
		var str = this;
		var regColor = /rgb\s*\(\s*(\d+),\s*(\d+),\s*(\d+)\s*\)/i;
		while (m = regColor.exec(str)) {
			var s = '#';
			for(i = 1; i <= 3; i++) {
				var _s = (m[i] - 0).toString(16);
				s += (m[i] < 16) ? ('0' + _s) : _s;
			}
			str = str.replace(regColor, s);
		}
		return str;
	}
});

var Event = {
	target: function(e) {
		return e.target  || e.srcElement;
	},
	stop: function(e) {
		try{
			e.preventDefault();
			e.stopPropagation();
		} catch(er) {
			e.returnValue = false;
			e.cancelBubble = true;
		}
	}
};

var Element = function(el, arg, doc) {
	doc = doc ? doc : document;
	var attributes = arguments[1] || {};
	if (typeof(el) == 'string') {
		el = $(doc.createElement(el));
		if (attributes.style) {
			el.setStyle(attributes.style);
			attributes.style = null;
		}
		extend(el, attributes);
	}
	return el;
};

Element.prototype = {
	clean: function() {
		for (var i = 0; i < this.childNodes.length; i++) {
			var node = this.childNodes[i];
			if (node.nodeType == 3 && /\s/.test(node.nodeValue)) this.removeChild(node);
		}
		return this;
	},
	addEvent: function(eventName, fn) {
		fn = fn.listen(this);
		var el = this;
		Unload.listeners.push([el, eventName, fn]);
		
		if (this.addEventListener) {
			if (eventName.toLowerCase() == 'onmousewheel') {
				eventName = 'DOMMouseScroll';
			}
			this.addEventListener(eventName, fn, false);
		} else if(this.attachEvent) {
			this.attachEvent('on' + eventName, fn);
		}
		return this;
	},
	addKey: function(keyCode, fn) {
		fn = fn.listen(this);
		this.addEvent('keydown', function(e) {
			if (e.keyCode == keyCode) {
				fn();
			}
		});
		Unload.elements.push(fn);
		return this;
	},
	addClass: function(className) {
		if (className && !this.hasClass(className)) {
			this.className += (this.className ? ' ' : '') + className;
		}
		return this;
	},
	hasClass: function(className) {
		return this.allClass().has(className);
	},
	allClass: function() {
		return this.className.trim().split(/\s+/);
	},
	dropClass: function(className) {
		var classes = this.allClass();
		if (className && classes.has(className)) {
			classes.splice(classes.indexOf(className), 1);
		}
		this.className = classes.join(' ');
		return this;
	},
	dropEvent: function(eventName, fn) {
		if (this.removeEventListener) {
			this.removeEventListener(eventName, fn, false);
		} else if (this.detachEvent) {
			this.detachEvent('on' + eventName, fn);
		}
		return this;
	},
	getByTag: function(tag) {
		return this.getElementsByTagName(tag);
	},
	getByClass: function(className) {
		var els = this.getByTag('*');
		var result = [];
		var re = new RegExp('^\\s*'+className+'\\s*$', 'img');
		for (var i = 0, len = els.length; i < len; i++) {
			if (els[i].className.match(re)) {
				result.push($(els[i]));
			}
		}
		els = null;
		return result;
	},
	/*
	IE6.0, FF1.06+:
	clientWidth = width + padding
	clientHeight = height + padding
	offsetWidth = width + padding + border
	offsetHeight = height + padding + border
	IE5.0/5.5:
	clientWidth = width - border
	clientHeight = height - border
	offsetWidth = width
	offsetHeight = height
	*/
	getInnerSize: function() {
		var sizes = this.getSize(), b = [], p = [];
		ASPECT.each(function(v, i) {
			b[i] = this.getStyle('border-' + v + '-width').toInt();
			p[i] = this.getStyle('padding-' + v).toInt();
		}, this);
		return [
			sizes[0] - b[0] - b[2] - p[0] - p[2],
			sizes[1] - b[1] - b[3]  - p[1] - p[3]
		];
	},
	getOuterSize: function() {
		var sizes = this.getSize(), m = [];
		ASPECT.each(function(v, i) {
			m[i] = this.getStyle('margin-' + v).toInt();
		}, this);
		return [
			sizes[0] + m[0] + m[2],
			sizes[1] + m[1] + m[3]
		];
	},
	getSize: function() {
		if (this.style.display.toLowerCase() !== 'none') {
			return [this.offsetWidth, this.offsetHeight];
		}
		var oV = this.style.visibility, oP = this.style.position;
		this.setStyle({visibility: 'hidden', position: 'absolute', display: 'block'});
		var oSize= [this.offsetWidth, this.offsetHeight];
		this.setStyle({visibility: oV, position: oP, display: 'none'});
		return oSize;
	},
	getStyle: function(style) {
		var cStyle = style.camelCase();
		var value = this.style[cStyle];
		if ((typeof value == 'undefined' || value == '')) {
			if (document.defaultView) {
				value = document.defaultView.getComputedStyle(this, null).getPropertyValue(style);
				if (Env.Opera && (style == 'width' || style == 'height')) {
					value = '';
				}
			} else if (this.currentStyle) {
				value = this.currentStyle[cStyle];
			}
			if (['margin', 'padding'].has(cStyle) && value == '') {
				return [this.getStyle(cStyle + '-top') || 0, this.getStyle(cStyle + '-right') || 0, this.getStyle(cStyle + '-bottom') || 0, this.getStyle(cStyle + '-left') || 0].join(' ');
			}
		}
		if (typeof value == 'undefined') value = '';
		return value.toString().tranColor();
	},
	getOffset: function(absoluteOffset) {
		var el = this, offset = [0, 0];
		do {
			offset[0] += el.offsetLeft || 0;
			offset[1] += el.offsetTop  || 0;
			el = $(el.offsetParent);
			if (!absoluteOffset && el) {
				p = el.getStyle('position');
				if (p == 'relative' || p == 'absolute') break;
			}
		} while (el);
		el = null;
		return offset;
	},
	getOuterHTML: function() {
		if (this.outerHTML) return this.outerHTML;
		var attr, attrs = this.attributes, 
			name = this.tagName.toLowerCase(), 
			out = '<' + name;
			
		for (var i = 0; i < attrs.length; i++) {
			attr = attrs[i];
			if (attr.specified) {
				out += ' ' + attr.name + '="' + attr.value + '"';
			}
		}
		if (['area', 'base', 'basefont', 'col', 'frame', 'hr', 'img', 'br', 'input', 'isindex', 'link', 'meta', 'param'].has(this.tagName.toLowerCase())) return str + '>';
		return out + '>' + this.innerHTML + '</' + name + '>';
	},
	setOuterHTML: function(html) {
		if (this.outerHTML) {
			this.outerHTML = html;
		} else {
			var r = this.ownerDocument.createRange();
			r.setStartBefore(this);
			var df = r.createContextualFragment(html);
			this.parentNode.replaceChild(df, this);
		}
		return this;
	},
	within: function(x, y) {
		var o = this.getOffset(true), s = this.getSize();
		return (y >= o[1] && y <=  o[1] + s[1] && x >= o[0] && x <=  o[0] + s[0]);
	},
	setStyle: function(style) {
		var value;
		for (var name in style) {
			value = style[name];
			if (name.toLowerCase().trim() == 'opacity') {
				this.setOpacity(value);
			} else if (value !== '' && !isNaN(value)) {
				value += 'px';
			}
			try{
				this.style[name.camelCase()] = value;
			} catch(e) {}
		}
		return this;
	},
	setOpacity: function(opacity) {
		opacity = parseFloat(opacity);
		if (Env.IE) {
			this.style.filter = (opacity >= 1) ? '' : 'alpha(opacity=' + opacity * 100 + ')';
		} else {
			this.style.opacity = this.style['MozOpacity'] = opacity;
		}
		return this;
	},
	overLap: function(el) {
		el = $(el);
		var o = el.getOffset(), s = el.getSize();
		return (this.within(o[0], o[1]) || this.within(o[0], o[1] + s[1]) || this.within(o[0] + s[0], o[1]) || this.within(o[0] + s[0], o[1] + s[1]));
	},
	remove: function() {
		this.parentNode.removeChild(this);
		//return this;
	},
	addBefore: function(el) {
		this.parentNode.insertBefore(el, this);
		return this;
	},
	addAfter: function(el) {
		var p = this.parentNode;
		if (this.nextSibling) {
			p.insertBefore(el, this.nextSibling);
		} else {
			p.appendChild(el);
		}
		return this;
	},
	noFocus: function() {
		return this.addEvent('focus', function(){this.blur();});
	},
	dumb: function() {
		return this.noFocus().noMenu().stop();
	},
	noMenu: function() {
		return this.addEvent('contextmenu', function(e){Event.stop(e);});
	}, 
	stop: function(e) {
		return this.addEvent('click', function(e){Event.stop(e);});
	},
	hover: function() {
		return this.addEvent('mouseover', function() {this.addClass('hover')})
			.addEvent('mouseout', function() {this.dropClass('hover')})
			.addEvent('focus', function() {this.addClass('focus')})
			.addEvent('blur', function() {this.dropClass('focus')});
	}
};

extend(document, Element.prototype);
extend(document, {
	getSize: function() {
		var s = [];
		['Width', 'Height'].each(function(v, i) {
			s[i] = document.documentElement['scroll' + v];
		});
		return s;
	},
	getScroll: function() {
		return [
			document.body.scrollLeft || document.documentElement.scrollLeft || window.pageXOffset || 0,
			document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset || 0
		];
	}
});

extend(window, {
	getSize: function() {
		var s = [];
		['Width', 'Height'].each(function(v, i) {
			s[i] = window['inner' + v] || document.documentElement['client' + v] || 0;
		});
		return s;
	}
});

function $(el, doc) {
	doc = doc ? doc : document;
	if (typeof(el) == 'string') {
		el = doc.getElementById(el);
	}
	if (el && ((el.nodeName && el.nodeType == 1) || el.nodeType == 9)) {
		if (Unload.elements.has(el)) {
			return el;
		}
		if (typeof el.addEvent == 'undefined') {
		
			extend(el, Element.prototype);
		}
		Unload.elements.push(el);
		return el;
	}
	return false;
}

/*
Example: 
	$({tag:'li',parent: t}, {'class': 'hy'}) ;
*/
function $s(options, att, doc) {
	this.options = extend({
		tag: '*',
		parent: document,
		nested: true
	}, options || {});
	
	this.att = att || {};
	if (typeof this.att.id !== 'undefined') {
		return $(this.att.id);
	}
	var tag = this.options.tag ? this.options.tag.toLowerCase() : '*';
	if (!this.options.parent || !this.options.parent.nodeType) {
		this.options.parent = doc ? doc : document;
	}
	var result = [];
	var els = this.options.nested ? this.options.parent.getElementsByTagName(tag) :  this.options.parent.childNodes;
	Outer:
	for (var i =0; i < els.length; i++) {
		if (!this.options.nested && (els[i].nodeName.toLowerCase() !== tag || els[i].nodeType !== 1)) {
			continue;
		}
		for (var att in this.att) {
			var att1 = att;
			att = att.toLowerCase();
			if (att === 'for') {
				att1 = 'htmlFor';
			}
			if (!(att == 'class' && els[i].className.trim().split(/\s+/).has(this.att[att])) && els[i].getAttribute(att1) !== this.att[att]) {
				continue Outer;
			}
		}
		result.push($(els[i]));
	}
	return result;
}

var Load = [];
var Unload = {
	events: [],
	elements: [],
	listeners: [],
	functions: [],
	unload: function() {
		var i;
		for (i = 0; i < Unload.functions.length; i++) {
			Unload.functions[i]();
		}
		for (i = 0; i < Unload.listeners.length; i++) {
			var el = Unload.listeners[i][0];
			var eventName = Unload.listeners[i][1];
			var fn = Unload.listeners[i][2];
			if (el.dropEvent) {
				el.dropEvent(eventName, fn);
			}
			Unload.listeners[i][0] = null;
			Unload.listeners[i][2] = null;
		}
		el = null;
		fn = null;
		for (i = 0; i < Unload.elements.length; i++) {
			Unload.elements[i] = null;
		}
		Unload = null;
		for (i = 0; i < Load.length; i++) {
			Load[i] = null;
		}
		Load = null;
	}
};

window.addEvent = Element.prototype.addEvent;
window.addEvent('unload', Unload.unload);

var Loader = {
	done: false,
	init: function() {
		if (Env.KHTML) {
			var state = document.readyState;
			if ((/loaded|complete/i).test(state)) {
				return Loader.fire();
			}
			this.timer = setTimeout(Loader.init(), 100);
		} else if (Env.IE) {
			var script = $('_ie_ready_');
			if (!script) document.write('<script id="_ie_ready_" defer="true" src="javascript:void(0)"></script>');
			$('_ie_ready_').addEvent('readystatechange', function() {
				if (this.readyState == 'complete') {
					return Loader.fire();
				}
			});
		} else {
			window.addEvent('load', Loader.fire);
			document.addEvent('DOMContentLoaded', Loader.fire);
		}
	},
	fire: function() {
		if (Loader.done) return;
		Loader.done = true;
		for (var i = 0; i< Load.length; i++) {
			Load[i]();
		}
	}
};

Loader.init();


