var sbBase = '/surebert/load/';
//v trunk - 02/05/2012 07:41:35

if(!Array.prototype.forEach){

	
	Array.prototype.forEach = function(func){
		var k;
		if(typeof func === 'function'){
			var len = this.length;
			for(k=0;k<len;k++){
				func(this[k], k, this);
			}
		}
	};

	
	Array.prototype.filter = function(func){
		var n=[];
		if(typeof func === 'function'){
			this.forEach(function(v,k,arr){
				if(func(arr[k], k, arr) === true){
					n.push(v);
				}
			});
		}

		return n;

	};

	
	Array.prototype.every = function(func){
		var k;
		if(typeof func === 'function'){
			for(k=0;k<this.length;k++){

				if(func(this[k], k, this) !== true){

					return false;
				}
			}
			return true;
		}
	};


	
	Array.prototype.indexOf = function(val){
		var k=0;
		for(k;k<this.length;k++){
			if(this[k] === val){
				return k;
			}
		}
		return -1;
	};

	
	Array.prototype.lastIndexOf = function(val){
		var p=-1,k;
		for(k=0;k<this.length;k++){
			if(this[k] === val){
				p=k;
			}
		}
		return p;
	};

	
	Array.prototype.map = function(func){
		var n=[];
		if(typeof func === 'function'){
			this.forEach(function(v,k,a){
				n.push(func(v,k,a));
			});
		}
		return n;
	};

	
	Array.prototype.some = function(func){
		var k;
		if(typeof func === 'function'){
			for(k=0;k<this.length;k++){
				if(func(this[k], k, this) === true){
					return true;
				}
			}
			return false;
		}
	};

}


if(typeof console === 'undefined'){
	console = {
		log : function(){}
	};
}



var sb = {

	
	base : (typeof window.sbBase !== 'undefined') ? window.sbBase : '/surebert',

	
	colors : {},

	
	date : {},

	
	consol : {
		log : function(){},
		write : function(){},
		error : function(){}
	},

	
	css : {},

	
	included : [],

	
	include : function(module, onload){
		onload = typeof onload === 'function' ? onload : function(){};
		
		if(module.match(',')){
			var modules = module.split(',');
			modules.forEach(function(v){
				sb.include(v);
			});

			return true;
		}

		var mods = module.split('.');
		var path ='', file, unit=sb,m;
		if(mods[0] === 'String' || mods[0] === 'Element' || mods[0] === 'Array'){
			unit = window;
		}

		for(m=0;m<mods.length;m++){

			if(m !==0 && m < mods.length && mods.length >1){
				path +='.';
			}
			path +=mods[m];
			
			try{

				unit = unit[mods[m]];

			} catch(e){}

			if(typeof unit === 'undefined'){
				
				this.included.push(path);
				if(sb.base === '/surebert'){
					file = sb.base+'/'+path.replace(/\./g, "/");
				} else {
					file = sb.base+path;
				}
				
				if(sb.base.match(/^http/)){
					var s = new sb.script({
						src : file
					});
					
					if(path === module){

						s.onload = onload;
					}

					s.load();
				} else {
					sb.load(file);
					if(path === module){
						onload();
					}
				}
				

			} else if(path === module){
				onload();
			}
		}
	},

	
	load : function(url){
		var evaled = 0;

		(function(){
			var load = new sb.ajax({
				url : url,
				async : 0,
				method : 'get',
				format : 'javascript',
				debug : sb.loadDebug ? 1 : 0,
				onResponse: function(r){
					//#######look into this

					try{
						evaled=1;
					}catch(e){

						evaled=0;
						delete e.stack;

						sb.consol.error(sb.messages[13]+"\nURL: "+url+"\n"+sb.objects.dump(e));

					}
					load=null;
				}
			}).fetch();
		}());

		return evaled;
	},
	
	script : function(o){
        
		var script = document.createElement("script");
		script.type = o.type || 'text/javascript';
		script.charset = o.charset || 'utf-8';
		script.src = o.src;
		
		script.onload = typeof o.onload === 'function' ? o.onload : function(){};
		script.load = function(){
			document.getElementsByTagName('head')[0].appendChild(this);
		};

		script.remove = function(){

			if(this.clearAttributes){
				this.clearAttributes();
			}

			this.parentNode.removeChild(this);
			this.onload = this.onreadystatechange = null;
			this.remove = null;
		};
        
		if(script.readyState){
			script.onreadystatechange = function(){
				//IE does not fire regular onloaded
				if (this.readyState && this.readyState !== "loaded") {
					return;
				}
                
				script.onload();
			};
		}

		return script;
            
	},

	
	math : {},

	

	messages : [],

	
	onbodyload : [],

	
	onleavepage : [],

	
	get : function(url, data, onResponse, params){

		if(typeof data === 'function'){
			params = onResponse;
			onResponse = data;
			data=null;
		} else if(typeof data === 'string'){
			onResponse = data;
			data = null;
		}
		params = params || {};
		params.method = 'get';
		return sb.ajax.shortcut(url, data, onResponse, params);
	},


	
	post : function(url, data, onResponse, params){

		if(typeof data === 'function'){
			params = onResponse;
			onResponse = data;
			data=null;
		} else if(typeof data === 'string'){
			onResponse = data;
			data = null;
		}
		
		params = params || {};
		params.method = 'post';
		return sb.ajax.shortcut(url, data, onResponse, params);
	},

	
	toArray : function(o){
		var a=[],x=0;
		var len=o.length;
		for(x;x<len;x++){
			a.push(o[x]);
		}
		return a;
	},

	
	typeOf : function(o){
		var type='';

		if(o === null){
			return 'null';
		} else if (o instanceof Function) {
			type = 'function';
		} else if (o instanceof Array) {
			type = 'array';
		} else if(typeof o === 'number'){
			type = 'number';
			if(String(o).match(/\./)){
				type = 'float';
			}
		} else if(typeof o === 'string'){
			type = 'string';
		} else if(o === true || o === false){
			type='boolean';
		} else {
			type = (typeof o).toLowerCase();
		}

		if(typeof o === 'object' ){

			if(typeof o.typeOf === 'function'){
				type = o.typeOf();
			} else if (o.nodeType){
				if (o.nodeType === 3) {
					type = 'textnode';

				} else if (o.nodeType === 1) {
					type = 'element';
				}
			} else if(typeof o.length !=='undefined' && type !=='array'){
				type = 'sb.nodeList';
			}
		}

		return type;
	},

	
	uid : 0,

	
	uniqueID : function(){
		return 'uid_'+(sb.uid +=1);
	},

	

	unixTime : function(){
		return parseInt(String(new Date().getTime()).substring(0,10), 10);
	},

	
	functions : {},

	
	utils : {},

	
	widget : {},

	
	ui : {},

	
	forms : {}

};



sb.$$ = function(selector, root){
	return sb.$(selector, root, true);
};

sb.$ = function(selector, root, asNodeList) {

	root = root || document;

	if(selector === ''){
		return new sb.nodeList();
	}
	
	//return items that are already objects
	if(typeof selector !== 'string'){

		if(Element.emulated === true && typeof selector === 'object' && selector !== null){
			
			if(selector.nodeType && selector.nodeType === 1){
				sb.$.copyElementPrototypes(selector);
				
			} else if (typeof selector.getElementPrototypes === 'function'){
				
				selector.getElementPrototypes();
			}
		}

		return selector;
	}

	var nodeList = new sb.nodeList();

	nodeList.setSelector(selector);

	if(root.querySelectorAll){
		nodeList.add(root.querySelectorAll(selector));

	} else {
		sb.$.parseSelectors(nodeList, root);
	}

	if(asNodeList){
		return nodeList;
	}
	
	if(nodeList.length() === 0 && nodeList.selector.match(/^\#[\w\-]+$/) ){
		return null;
	} else if(nodeList.length() === 1 && (nodeList.selector.match(/^\#[\w\-]+$/) || sb.nodeList.singleTags.some(function(v){
		return v === nodeList.selector;
	}))){

		return nodeList.nodes[0];
	} else {
		return nodeList;
	}

};

sb.$.copyElementPrototypes = function(node){
	var ep = Element.prototype,prop;
	for(prop in ep){
		if(ep.hasOwnProperty(prop)){
			node[prop] = ep[prop];
		}
	}
};


sb.$.parseSelectors = function(nodes, within){

	within = within || document;
	var root = [within], s=0, selectors = nodes.selector.split(",");

	var len = selectors.length;

	for(s=0;s<len;s++){
	
		root = [within];

		selectors[s].split(" ").forEach(function(selector,k,a){

			if(selector.indexOf(">")+1){

				root = sb.$.getElementsByParent(selector);

				if(k+1 === a.length){
					nodes.add(root);

				}

				return true;

			} else if(selector.indexOf('[')+1){

				///look for attribute's by searching for sqaure brackets //
				root = sb.$.getElementsByAttributes(root, selector);

				if(k+1 === a.length){
					nodes.add(root);
				}

				return true;
			} else if(selector.indexOf("~")+1){

				root = sb.$.getElementsBySiblingCombinator(root, selector);

				if(k+1 === a.length){
					nodes.add(root);

				}

				return true;

			} else if(selector.indexOf("+")+1){

				root = sb.$.getElementsByAdjacentSibling(root, selector);

				if(k+1 === a.length){
					nodes.add(root);

				}

				return true;

			} else if(selector.indexOf(":")+1){
				//look for pseudo selectors
				root = sb.$.parsePseudoSelectors(root, selector);

				if(k+1 === a.length){
					nodes.add(root);
				}

				return true;

			} else if((selector.indexOf("#") === 0 && selector.match(/^\#[\w\-]+$/)) || selector.match(/\w+\#[\w\-]+/)) {

				var element = sb.$.getElementById(selector);

				if(element){
					root = (element instanceof Array) ? element : [element];

					if(k+1 === a.length){
						nodes.add(root);

					}
				}

				return true;

			} else if (selector.indexOf(".") !== false){

				var period_pos = selector.indexOf(".");

				var left_bracket_pos = selector.indexOf("[");
				var right_bracket_pos = selector.indexOf("]");

				if(period_pos+1 && !(period_pos > left_bracket_pos && period_pos < right_bracket_pos)) {

					root = sb.$.getElementsByClassName(selector, root[0]);

					if(k+1 === a.length){
						nodes.add(root);
					}

					return true;
				}
			}
			
			//Tag selectors - no class or id specified.
			root = sb.$.getElementsByTagName(root, selector);

			if(k+1 === a.length){
				nodes.add(root);
			}

			return true;
		});

	}

	return nodes;
};


sb.$.getElementById = function(selector){

	var parts = selector.split("#");
	var element = document.getElementById(parts[1]);
	return element;
};


sb.$.getElementsByClassName = function(selector, root){

	var nodes,elements = [],x=0;
	
	if(root.getElementsByClassName && selector.charAt(0) === '.'){

		nodes = root.getElementsByClassName(selector.replace(/\./, ''));

		for(x=0;x<nodes.length;x++){
			elements.push(nodes[x]);
		}
		return elements;
	}

	var parts = selector.split('.');
	nodes = root.getElementsByTagName(parts[0] || '*');
	var className = parts[1], node, cur_class_name,len = nodes.length;
	x=0;
	var rg = RegExp("\\b"+className+"\\b");
	
	if(nodes.length > 0){
		do{
			node = nodes[x];
			cur_class_name = node.className;
			if (cur_class_name.length && (cur_class_name === className || rg.test(cur_class_name))){

				elements.push(node);
			}
			x++;


		} while(x<len);
	}
	return elements;
};


sb.$.getElementsByTagName = function(root, tag) {
	root = (root instanceof Array) ? root : [root];

	var matches = [],len1 = root.length,len2,x=0,i=0,nodes,elements;

	for(x=0;x<len1;x++){

		nodes = root[x].getElementsByTagName(tag || '*');
		elements = [];
		len2 = nodes.length;

		for(i=0;i<len2;i++){
			elements.push(nodes[i]);
		}
		matches = matches.concat(elements);
	}

	return matches;
};


sb.$.getElementsByAttributes = function(within, selector){
	var tag,attr,operator,value;

	if (selector.match(/^(?:(\w*|\*))\[(\w+)([=~\|\^\$\*]?)=?['"]?([^\]'"]*)['"]?\]$/)) {
		tag = RegExp.$1;
		attr = (typeof sb.nodeList.attrConvert === 'function') ? sb.nodeList.attrConvert(RegExp.$2) : RegExp.$2;

		operator = RegExp.$3;
		value = RegExp.$4 ||'';
	}

	var elements = sb.$.getElementsByTagName(within, tag);

	within = elements.filter(function(el,k,a){

		el.attrVal = el.getAttribute(attr, 2);

		//if attribute is null
		if(!el.attrVal){
			return false;
		}

		switch(operator){
			case '=':
				if(el.attrVal !== value){
					return false;
				}
				break;

			case '~':

				if(!el.attrVal.match(new RegExp('(^|\\s)'+value+'(\\s|$)'))){
					return false;
				}
				break;

			case '|':

				if(!el.attrVal.match(new RegExp(value+'-'))) {
					return false;
				}
				break;

			case '^':
				if(el.attrVal.indexOf(value) !== 0){
					return false;
				}
				break;

			case '$':
				if(el.attrVal.lastIndexOf(value)!==(el.attrVal.length-value.length)){
					return false;
				}
				break;

			case '*':
				if(el.attrVal.indexOf(value)+1 === 0){
					return false;
				}
				break;

			default:
				if(!el.getAttribute(attr)){
					return false;
				}
		}

		return true;

	});

	return within;

};


sb.$.getNextSibling = function(node){
	while((node = node.nextSibling) && node.nodeType === 3){}
	return node;
};


sb.$.getPreviousSibling = function(node){
	while((node = node.previousSibling) && node.nodeType === 3){}
	return node;
};


sb.$.getFirstChild = function(node){
	node = node.firstChild;
	while (node && node.nodeType && node.nodeType === 3) {
		node = sb.$.getNextSibling(node);
	}
	return node;
};


sb.$.getLastChild = function(node){

	node = node.lastChild;
	while (node && node.nodeType && node.nodeType === 3) {
		node = sb.$.getPreviousSibling(node);
	}
	return node;
};


sb.$.getElementsByParent = function(selector){
	var parents ,n=0, tags = selector.split(">");

	var elements = sb.$.getElementsByTagName([document.body], tags[1]);

	var nodes = [];
	var len = elements.length;

	var rg = new RegExp(tags[0], 'i');

	if(tags[0].match(/\./)){
		parents = sb.$(tags[0]);
	}
	for(n;n<len;n++){
		if(rg.test(elements[n].parentNode.nodeName) || (parents && parents.nodes.inArray(elements[n].parentNode))){
			elements[n].sbid = sb.uniqueID();
			nodes.push(elements[n]);
		}
	}

	return nodes;

};


sb.$.getElementsBySiblingCombinator = function(within, selector){
	var parts = selector.split("~");

	var nodeName = parts[0],siblingNodeName = parts[1],elements = [],x=0,nn;

	var siblings = sb.$.getElementsByTagName(within, nodeName);
	var len = siblings.length;

	for(x=0;x<len;x++){
		var node = siblings[x];

		while((node = node.nextSibling)){
			nn = node.nodeName.toLowerCase();
			if(nn === nodeName){
				break;
			}
			if(node.nodeType === 1 && nn === siblingNodeName){
				node.sbid = sb.uniqueID();
				elements.push(node);
			}
		}
	}
	return elements;

};


sb.$.getElementsByAdjacentSibling = function(within, selector){
	var parts = selector.split("+");

	var nodeName =parts[0];
	var adjacentNodeName = parts[1].toUpperCase();
	var elements = sb.$.getElementsByTagName([document.body], nodeName);
	elements = (!elements.length) ? [elements] : elements;
	//put in the proper adajcent siblings
	var nodes = [], x=0,node,len = elements.length;
	for(x=0;x<len;x++){
		node = sb.$.getNextSibling(elements[x]);
		if(node && node.nodeName === adjacentNodeName){
			nodes.push(node);
		}
	}

	return nodes;

};


sb.$.parsePseudoSelectors = function(within, selector){

	var notSelector,elements = [],parts = selector.split(":");

	selector =parts[0];
	var pseudo = parts[1];

	var nodes = sb.$.getElementsByTagName(within, selector);

	nodes.forEach(function(node,k,a){

		switch(pseudo){

			case 'before':

				var bf = new sb.element({
					nodeName : 'span',
					innerHTML : 'ddd'
				}).appendToTop(node);
				elements.push(bf);

				break;

			case 'first-child':

				if(!sb.$.getPreviousSibling(node)){
					elements.push(node);
				}
				break;

			case 'last-child':
				if(!sb.$.getNextSibling(node)){
					elements.push(node);
				}
				break;

			case 'empty':
				if(node.innerHTML ===''){
					elements.push(node);
				}
				break;

			case 'only-child':

				if(!sb.$.getPreviousSibling(node) && !sb.$.getNextSibling(node)){
					elements.push(node);
				}

				break;

			default:

				if(pseudo.indexOf('not')+1){
					notSelector = pseudo.match(/not\((.*?)\)/);

					if(node.nodeName.toLowerCase() !== notSelector[1]){
						elements.push(node);
					}
				}
		}


	});

	return elements;
};


sb.browser ={

	
	ie6 : 0,

	
	agent : '',

	
	version : 0,

	
	getAgent : function(){

		var opera = new RegExp("opera/(\\d{1}.\\d{1})", "i");
		var safari = new RegExp("safari/(\\d{3})", "i");
		var chrome = new RegExp("chrome/(\\d{1}\\.\\d{1})", "i");
		var firefox = new RegExp("firefox/(\\d{1}.\\d{1})", "i");
		var ie = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		var agent = window.navigator.userAgent;
		var str;

		if(window.opera && window.document.childNodes) {
			this.agent = 'op';
			str = agent.match(opera);
			this.version = str[1];

		} else if (document.all){
			var dbs=document.body.style;
			this.agent = 'ie';
			if(dbs.opacity!=undefined) {
				this.version = 9;
			} else if(dbs.msBlockProgression!=undefined){
				this.version = 8;
				if (ie.exec(agent) != null){
					this.version = parseFloat(RegExp.$1);
				}
			} else if(dbs.msInterpolationMode!=undefined){
				this.version = 7;
			} else if(dbs.textOverflow!=undefined){
				this.version = 6;
				sb.browser.ie6 =1;
			} else {
				this.version = 5;
			}
		} else if(agent.match(firefox)){
			this.agent = 'ff';
			str = agent.match(firefox);
			this.version = str[1];
		} else if(agent.match(chrome)){
			this.agent = 'cr';
			str = agent.match(chrome);
			this.version = str[1];
		} else if(agent.match(safari)){
			str = agent.match(safari);
			this.agent = 'sf';
			if(agent.match(/iphone/i)){
				this.agent += '_iphone';
			} else if(agent.match(/ipod/i)){
				this.agent += '_ipod';
			}
			this.version = str[1];

		} else {
			this.agent='other';
		}

		return this.agent;
	},

	
	measure : function(){
		sb.browser.w=0;
		sb.browser.h =0;
		if( typeof window.innerWidth === 'number' ) {
			sb.browser.w = window.innerWidth;
			sb.browser.h = window.innerHeight;
		} else if( window.document.documentElement && ( window.document.documentElement.clientWidth || window.document.documentElement.clientHeight ) ) {
			sb.browser.w = document.documentElement.clientWidth;
			sb.browser.h = document.documentElement.clientHeight;
		}

		return [sb.browser.w, sb.browser.h];
	},

	
	init : function(){

		this.getAgent();
		this.measure();
	}
};

sb.browser.init();

sb.objects = {

	
	serialize : function(o){
		var str, arr, a=[];

		sb.objects.forEach.call(o, function(value, prop, object){

			if(sb.typeOf(value) === 'array'){
				
				value.forEach(function(v, k){
					a.push(prop+'[]='+encodeURIComponent(v));
				});
				
			} else if(typeof value === 'object'){
				
				if(value === null){
					return null;
				}
				
				sb.objects.forEach.call(value, function(v2, k2, o2){

					if(typeof v2 === 'object' || sb.typeOf(v2) === 'array'){

						str = sb.objects.serialize(v2);
						arr = str.split("&");
						str ='';
						arr.forEach(function(v3, k3, a3){
							arr[k3]= v3.replace(/(.*?)=(.*?)/g, prop+"['"+k2+"']['$1']=$2");

						});

						a.push(arr.join("&"));

					} else {
						a.push(prop+"['"+k2+"']="+encodeURIComponent(v2));
					}
				});
			} else {

				a.push(prop+'='+encodeURIComponent(value));
			}
		});

		return a.join("&");
	},

	
	infuse : function(from, to){

		to = to || this;
		from = from || {};
		sb.objects.forEach.call(from, function(val,prop,o){

			try{
				to[prop] = val;
			} catch(e){}
		});
		from = null;
		return to;
	},

	

	copy : function(o){
		var copy = {};

		sb.objects.forEach.call(o, function(val,prop,obj){
			copy[prop] = val;
		});

		return copy;
	},

	hardcopy : function(o){
		var c = {},p;
		for(p in o){
			try{
				c[p] = o[p];
			}catch(e){}
		}
		return c;
	},

	
	dump : function(o, pre){
		var str ='';
		sb.objects.forEach.call(o, function(v,p,o){
			try{
				str+="\n\n"+p+' = '+v;
			} catch(e){
				str += "\n"+p+' = CANNOT PROCESS VALUE!';
			}
		});

		if(!pre){
			return str;
		} else {
			return '<pre style="margin:5px;border:1px;padding:5px;">'+str+'</pre>';
		}

	},

	forEach : function(func){
		var prop;
		for(prop in this){
			if((this.hasOwnProperty(prop) && !sb.objects[prop]) || prop === 'infuse'){
				func(this[prop], prop, this);
			}
		}
	}
};


//sb.nodeList
sb.nodeList = function(params){
	var prop;
	for(prop in params){
		this[prop] = params[prop];
	}

	//initialize internal arrays
	this.nodes = [];
	this.sb_ids = {};

	var nls= this;
	['forEach', 'map', 'filter', 'every', 'some', 'indexOf', 'lastIndexOf', 'inArray'].forEach(function(v,k,a){
		nls[v] = function(func){
			if(v === 'forEach'){
				nls.nodes[v](func);
				return nls;
			}
			return nls.nodes[v](func);
		};
	});

};

sb.nodeList.copyFunc = function(prop, node){
	return function(){
		
		return Element.prototype[prop].apply(node, sb.toArray(arguments));
	};
};

sb.nodeList.prototype = {

	
	selector : '',

	
	getElementPrototypes : function(){

		var x,prop,ep = Element.prototype,len = this.nodes.length;

		for(x=0;x<len;x++){
			for(prop in ep){
				this.nodes[x][prop] = ep[prop];
			}
		}

	},

	
	empty : function(){
		this.nodes = [];

	},

	
	setSelector : function(selector){
		this.selector = sb.nodeList.cleanSelector(selector);

	},

	

	add : function(nodes){

		if(nodes === null  || nodes.length === 0){
			return false;
		}

		if(!nodes.length){
			nodes = [nodes];
		}

		var len = nodes.length;

		var prop,x=0,node;

		var emulated = Element.emulated;
		var ep = Element.prototype;

		for(x=0;x<len;x++){
			node=nodes[x];
			var sb_id = node.getAttribute('sb_id');
			if(!sb_id){
				sb_id = sb.nodeList.sb_id++;
				node.setAttribute('sb_id',  sb_id);
			}

			if(!this.sb_ids[sb_id]){

				if(!node.xml && emulated){
					for(prop in ep){
						node[prop] = ep[prop];
					}
				}

				this.nodes.push(node);
				this.sb_ids[sb_id] = true;
			}

		}
	},
	
	
	drop : function(el){

		var t = this;
		el = sb.$(el);

		this.nodes = t.nodes.filter(function(v){
			if(sb.typeOf(el) === 'sb.element'){
				return v !== el;
			} else {
				return !el.nodes.some(function(v1){
					return v===v1;
				});
			}

		});
		this.length = this.nodes.length;

		return this;
	},

	
	length : function(){
		return this.nodes.length;
	},

	
	firePerNode : function(func){
		var args = sb.toArray(arguments);
		var func = args.shift();
		var f = function(v){
			return func.apply(v, args);
		};
		this.nodes.forEach(f);
		return this;
	},

	
	styles : function(styles){
		return this.firePerNode(Element.prototype.styles, styles);
	},
	
	
	typeOf : function(){

		return 'sb.nodeList';
	}

};

sb.nodeList.cleanSelector = function(selector){

	selector = selector.replace(/^\s+/, '');
	selector = selector.replace(/\s+$/, '');

	//remove excess space after commas
	selector = selector.replace(/, /g, ',');
	selector = selector.replace(/\s*([>~\+])\s*/g, "$1");
	return selector;
};


sb.nodeList.sb_id = 0;


sb.nodeList.singleTags = ['html', 'body', 'base', 'head', 'title'];


sb.json = {};


sb.ajax = function (params){

	if(window.XMLHttpRequest){
		this.ajax = new XMLHttpRequest();
	} else {
		try{
			this.ajax=new window.ActiveXObject("Microsoft.XMLHTTP");
		}catch(e3){
			throw('This browser does not support surebert');
		}
	}
	
	this.async = true;
	
	sb.objects.infuse(params, this);

	if(params.data && sb.typeOf(params.data) != 'string'){
		this.data = sb.objects.serialize(params.data);
	}

	this.method = params.method || sb.ajax.defaultMethod;
	var self = this;
	this.ajax.onreadystatechange=function(){
		self.onreadystatechange();
	};

};


sb.ajax.defaultMethod = 'post';


sb.ajax.defaultFormat = 'text';


sb.ajax.shortcut = function(url, data, onResponse, params){
	params = params || {};
	var aj = new sb.ajax({
		url : url,
		data : data
	});
	
	sb.objects.infuse(params, aj);
	
	if(typeof onResponse === 'function'){
		aj.onResponse = onResponse;
	} else if (typeof onResponse === 'string'){
		aj.node = onResponse;
	}
	aj.fetch();
	return aj;
};

sb.ajax.prototype = {

	
	debug : sb.ajax.debug || 0,

	
	timeout : 0,

	
	async : true,

	
	onreadystatechange : function(){

		var js = '';

		if(this.ajax.readyState !== 4 || this.completed){
			return true;
		}

		this.completed = 1;

		//for backwards compatibility, remove soon
		if(typeof this.handler === 'function'){
			this.onResponse = this.handler;
		}

		this.contentType = this.ajax.getResponseHeader("Content-Type");
		this.contentLength = this.ajax.getResponseHeader("Content-Length");

		if(this.contentLength > this.maxContentLength){

			//this.addToLog(7);
			if(typeof this.onContentLengthExceeded === 'function'){
				this.onContentLengthExceeded();
			}
			//TODO does this work? after IE8 and safari 4
			this.ajax.abort();
			return;
		}

		if(!this.format){
			
			if(this.contentType){
				if(this.contentType.match('application/json')){
					this.format = 'json';
				} else if (this.contentType.match('text/javascript')){
					this.format = 'javascript';
				} else if (this.contentType.match('text/xml')){
					this.format = 'xml';
				} else if(this.contentType.match('boolean/value')){
					this.format = 'boolean';
				}
			} else {
				this.format = sb.ajax.defaultFormat;
			}
		}

		if(this.debug){
			this.log("\nHEADERS\nStatus: "+this.ajax.status+"\nStatus Text: "+this.ajax.statusText+"\n"+this.ajax.getAllResponseHeaders()+"\nRESPONSE: \n"+(this.ajax.responseText ||'PAGE WAS BLANK ;(')+"\n");
		}

		if(this.onHeaders(this.ajax.status, this.ajax.statusText) === false || this.ajax.status !== 200){
			return false;
		}

		switch(this.format){

			case 'head':
				if(typeof this.header ==='undefined'){
					this.response = this.ajax.getAllResponseHeaders();
				} else {
					this.response = this.ajax.getResponseHeader(this.header);

				}
				break;
			case 'xml':

				if(this.ajax.responseXML !== null){
					this.response = this.ajax.responseXML.documentElement;
				} else {
					this.log('invalid XML returned');
				}
				break;

			case 'javascript':
				js =  this.ajax.responseText;
				break;

			case 'json':

				js = 'this.response='+this.ajax.responseText;

				break;

			case 'boolean':
				this.response = this.ajax.responseText === '1' ? true : false;
				break;

			default:
				
				this.response = this.ajax.responseText;
		}

		if(js !==''){

			try{
				(new Function(js)).call(this);
			} catch(e2){
				this.log('Could not eval javascript from server: '+js);
			}
		}
		if(typeof this.onResponse === 'function'){
			this.onResponse(this.response);
		}

		if(typeof this.node !== 'undefined'){

			if(sb.$(this.node)){
				this.node = sb.$(this.node);
				if(typeof this.node.value !== 'undefined'){
					this.node.value = this.ajax.responseText;
				} else {
					this.node.innerHTML = this.ajax.responseText;
				}
			} else {
				this.log('Cannot set innerHTML of: '+this.node+' as it does not exist');
			}
		}

		return this;

	},

	
	abort : function(){
		this.ajax.abort();

		if(typeof this.onmillisec !== 'undefined'){
			this.timer.reset();
		}

		this.onAbort();

	},

	
	fetch : function(){

		if(!this.url){
			throw('A sb.ajax instance has no url set? But is trying to send the following data: '+this.data);
		}

		var url = this.url;

		this.completed = 0;
		if(this.data && sb.typeOf(this.data) != 'string'){
			this.data = sb.objects.serialize(this.data)
		}
		
		//This must be set to tru or false as IE 8 does not understand 0 or 1
		if(this.async === 0){
			this.async = false;
		}

		this.format = this.format || '';
		this.method = this.method.toUpperCase();

		if(this.method === 'GET' && this.data !== undefined){
			url = url+'?'+this.data;
		}

		this.ajax.open(this.method, url, this.async);

		if(this.method === 'POST'){
			this.ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		}

		if(this.timeout){

			this.count = 0;

			var self = this;

			this.timer = window.setInterval(function(){
				if(self.count >= self.timeout){
					self.abort();
					self.count = 0;

					if(typeof self.onTimeout === 'function'){
						self.onTimeout();
					}

					window.clearInterval(self.timer);
				} else {
					self.count++;
				}
			}, 1);
		}

		this.ajax.send(this.data);
		if(!this.async){
			this.onreadystatechange();
		}
	},

	log : function(message){
		if(this.debug){

			var info = (message || '')+"\nSENT\nURL: "+this.url;

			info += "\nMETHOD: "+this.method+"\nFORMAT: "+this.format+"\nASYNC: "+this.async+"\nDATA: "+this.data;

			if(sb.consol.ajaxLog){
				sb.consol.ajaxLog(info);
			} else if(typeof console !== 'undefined'){
				console.log(info);
			}

			if(typeof this.onLog === 'function'){

				this.onLog(info);
			}
		}
	},
	
	onResponse : function(){},

	
	onTimeout : function(){},

	
	onHeaders : function(status, statusText){
		var self = this;
		var headers = this.ajax.getAllResponseHeaders();
		headers.split(/\r?\n/).forEach(function(h){
			var m = h.match(/^sb_on_response\d+: (.*)/);
			if(m && m[1]){
					try{(new Function(m[1])).call(self);}
				catch(e){
					self.log('Cannot eval sb_on_headers js: '+m[1]);
				}
				
			}
		});
	},

	
	onAbort : function(){}
};

sb.dom = {

	

	onReady : function(o){
		var found = 0, timer, count=0;
		o.args = o.args || [];
		o.interval = o.interval || 10;

		o.tries = o.tries || 600;
		if(o.tries === -1){
			o.tries = 99999999;
		}

		if(typeof o.onReady === 'function'){

			timer = window.setInterval(function(){

				count +=1;

				if(count >= o.tries){
					window.clearTimeout(timer);

					if(typeof o.onTimeout === 'function'){
						o.onTimeout(o.id);
					}
					return;
				}

				if(o.id === 'body' && document.body){
					window.clearTimeout(timer);
					found=1;
					o.id = document.body;
				} else if(o.id !== 'body' && sb.$(o.id)){

					window.clearTimeout(timer);
					found=1;
				}

				if(found){
					o.onReady.apply(sb.$(o.id), o.args);

				}

			}, o.interval);

		} else {
			throw('sb.dom.onReady: You object argument must have a onReady property that runs when the dom element "'+o.id+'" is available');
		}
	}

};


Array.prototype.inArray = function(val){
	return this.some(function(v){
		return v===val;
	});
};


Array.prototype.remove = function(values){

	return this.filter(function(v){
		if(sb.typeOf(values) !== 'array'){
			return v !== values;
		} else {
			return !values.inArray(v);
		}
	});
};


String.prototype.hex2rgb = function(asArray){
	var hex = this.replace(/(^\s+|\s+$)/).replace("#", "");
	var rgb = parseInt(hex, 16);
	var r   = (rgb >> 16) & 0xFF;
	var g = (rgb >> 8) & 0xFF;
	var b  = rgb & 0xFF;

	if(asArray){
		return [r,g,b];
	} else {
		return 'rgb('+r+', '+g+', '+b+')';
	}
};


String.prototype.toCamel = function(){
	return String(this).replace(/[\-_\s]\D/gi, function(m){
		return m.charAt(m.length - 1).toUpperCase();
	});
};

sb.styles = {

	
	numRules : 1,

	
	sheets : [],

	

	pxProps : ['fontSize', 'width', 'height', 'padding', 'border', 'margin', 'left', 'top', 'right', 'bottom']

};


sb.events = {

	
	add : function() {
		
		if ( window.attachEvent){
			return function(el, type, fn) {
				el = sb.$(el);
				
				var f = function() {
					var e = window.event,tar = null,d= document.documentElement,b=document.body;
					if(e){
						e.pageX = e.clientX+d.scrollLeft+b.scrollLeft;
						e.pageY = e.clientY+d.scrollTop+b.scrollTop;
						switch(e.type){
							case 'mouseout':
								tar = e.relatedTarget || e.toElement;
								break;

							case 'mouseover':
								tar = e.relatedTarget || e.fromElement;
								break;
						}

						if(tar){
							e.relatedTarget = sb.events.distillTarget(tar);
						}

						if(e.srcElement){
							e.target = sb.events.distillTarget(e.srcElement);
						}

						e.preventDefault = function(){
							e.returnValue = false;
						};

						e.stopPropagation = function(){
							e.cancelBubble = true;
						};
					} else {
						e = {
							pageX : 0,
							pageY : 0,
							clientX : 0,
							clientY : 0,
							type : 'unknown'
						};
						
					}
					
					fn.call(el, e);
				};
				var evt = {
					el:el,
					type:type,
					fn:f,
					remove : sb.events.removeThis
				};
				el.attachEvent('on'+type, f);
				return sb.events.record(evt);
			};
		} else if(window.addEventListener){

			return function(el, type, fn) {
				el = sb.$(el);
				var f = function(e){

					var sb_target = e.target;
					var sb_related_target = e.relatedTarget;
					delete e.target;
					delete e.relatedTarget;
					e.__defineGetter__("target", function() {
						return sb.events.distillTarget(sb_target);
					});
					e.__defineGetter__("relatedTarget", function() {
						return sb.events.distillTarget(sb_related_target);
					});
					fn.call(el, e);
				};
				var evt = {
					el:el,
					type:type,
					fn:f,
					remove : sb.events.removeThis
				};
				el.addEventListener(type, f, false);
				return sb.events.record(evt);
			};
		}
	}(),

	
	removeThis : function(){
		sb.events.remove(this);
	},

	
	log : [],

	
	record : function(evt){
		sb.events.log.push(evt);
		return evt;
	},
	
	
	remove : function(evt){

		if (evt.el.removeEventListener){
			evt.el.removeEventListener( evt.type, evt.fn, false );
		} else if (evt.el.detachEvent){
			evt.el.detachEvent( "on"+evt.type, evt.fn );
		}

	},

	
	removeAll: function(){
		sb.events.log.forEach(function(evt){
			sb.events.remove(evt);
		});
		sb.events.log=[];
	},

	
	distillTarget : function(tar){
		if (tar && tar.nodeType && (tar.nodeType === 3 || tar.nodeName === 'EMBED')){
			tar = tar.parentNode;
		}

		return sb.$(tar);
	}

};


sb.element = function(o){
	var el,c;

	if(sb.typeOf(o) === 'sb.element'){
		return o;
	}

	el = document.createElement(o.tag);

	//copy properties from the sb.element prototype
	if(Element.emulated){
		sb.objects.infuse(Element.prototype, el);
		o = sb.objects.copy(o);
	}

	if(typeof o.styles !== 'undefined'){
		el.styles(o.styles);
		delete o.styles;
	}

	if(typeof o.children !== 'undefined'){
		var len = o.children.length;
		for(c=0;c<len;c++){
			el.appendChild(new sb.element(o.children[c]));
		}
		delete o.children;
	}

	this.eventsAdded = [];

	if(typeof o.events !== 'undefined'){

		sb.objects.forEach.call(o.events, function(func,event,obj){
			el.evt(event, func);
		});

		delete o.events;
	}

	//copy additional props from o
	sb.objects.infuse(o, el);

	if(sb.browser.agent === 'ie'){
		
		//remove attributes for ie's sake
		el.removeAttribute('tag');
	}

	return el;
};


sb.el = function(str){
	var matches = str.match(/^([a-zA-Z]+)(?:#([\w\-]+))?(?:\.([\w\- ]+))?/);
	if(!matches){
		throw("You must pass a string to sb.el constructor");
	}

	var el = sb.element({
		tag : matches[1],
		id : matches[2] || '',
		className : matches[3] || '',
		html : function(html){
			this.innerHTML = html;
			return this;
		},
		innerHTML : ''
	});
	var attr = str.match(/([\w\-]+=[\w\-]+)/g);

	if(attr){
		attr.forEach(function(v){
			var a = v.split('=');
			el.setAttribute(a[0], a[1]);
		});
	}

	return el;
};


if(typeof Element === 'undefined'){
	Element = function(){};
	Element.emulated = true;
	Element.prototype = {};
}


Element.prototype.$ = function(selector){
	return sb.$(selector, this);
};


Element.prototype.attr = function(attr, val){
	var prop;
	if(typeof attr === 'object'){
		for(prop in attr){
			this.setAttribute(prop, attr[prop]);
		}
		return this;
	} else if(typeof val !== 'undefined'){
		if(typeof val === 'function'){
			val = val.call(this);
		}
		
		this.setAttribute(attr, val);

		return this;
	} else {
		return this.getAttribute(attr);
	}
};


Element.prototype.addClassName = function(className){
	this.className += ' '+className;

	return this;
};


Element.prototype.append = function(el){
	return this.appendChild(sb.$(el));
};


Element.prototype.appendTo = function(el){
	return sb.$(el).appendChild(this);
};


Element.prototype.appendToTop = function(el){
	el = sb.$(el);

	if(el.childNodes.length ===0){
		return this.appendTo(el);
	} else {
		return this.appendBefore(el.firstChild);
	}
};


Element.prototype.appendAfter = function(after){
	var a = sb.$(after);
	var b = a,nxtSib = a.nextSibling || false;
	
	if(a.nextSibling && a.nodeType !== 3){
		while((a = a.nextSibling) && a.nodeType === 3){
			nxtSib = a;
		}
	}
	
	if(nxtSib){
		return nxtSib.parentNode.insertBefore(this, nxtSib);
	} else {
		return this.appendTo(b.parentNode);
	}

};


Element.prototype.appendBefore = function(before){
	before = sb.$(before);
	return before.parentNode.insertBefore(this, before);
};


Element.prototype.getX = function(){
	var x = 0, el=this;
	while(el !== null){
		x += el.offsetLeft;
		el = el.offsetParent;
	}
	return x;
};


Element.prototype.getY = function(){
	var y = 0, el=this;
	while(el !== null){
		y += el.offsetTop;
		el = el.offsetParent;
	}
	return y;
};


Element.prototype.html = function(html){
	if(typeof html === 'undefined'){
		return this.innerHTML;
	} else if(typeof html === 'function'){
		this.innerHTML = html.call(this);
	} else {
		this.innerHTML = html;
	}

	return this;
};


Element.prototype.hasClassName = function(classname){

	return this.className.match("\\b"+classname+"\\b");
};


Element.prototype.remove = function(){
	if(this.parentNode){
		this.parentNode.removeChild(this);
	}
	return this;
};


Element.prototype.removeClassName = function(className){
	this.className = this.className.replace(new RegExp("\b*"+className+"\b*"), "");
	return this;
};


Element.prototype.replace = function(node){
	node = sb.$(node);
	if(node.parentNode){
		node.parentNode.replaceChild(this, node);
	}
	node = null;
	return this;
};


Element.prototype.evt = function (evt, func){

	var event = sb.events.add(this, evt, func);

	this.eventsAdded.push(event);
	return event;

};


Element.prototype.eventsAdded = [];


Element.prototype.events = function(events){
	var event;
	for(event in events){
		if(typeof events[event] === 'function'){
			this.evt(event, events[event]);
		}
	}

	return this;
};


Element.prototype.eventRemove = function (evt){
	sb.events.remove(evt);
	return this;
};


Element.prototype.eventsRemoveAll = function(){
	this.eventsAdded.forEach(function(evt){
		sb.events.remove(evt);
	});
	this.eventsAdded = [];
	return this;
};


Element.prototype.styles = function(params){
	var prop;
	for(prop in params){
		if(params.hasOwnProperty(prop)){
			try{
				this.setStyle(prop, params[prop]);
			}catch(e){}
		}
	}

	return this;
};


Element.prototype.getStyle = function(prop){
	var val;

	if(prop.match(/^border$/)){
		prop = 'border-left-width';
	}

	if(prop.match(/^padding$/)){
		prop = 'padding-left';
	}

	if(prop.match(/^margin$/)){
		prop = 'margin-left';
	}

	if(prop.match(/^border-color$/)){
		prop = 'border-left-color';
	}

	if (this.style[prop]) {
		val = this.style[prop];

	} else if (this.currentStyle) {

		prop = prop.toCamel();
		val = this.currentStyle[prop];

	} else if (document.defaultView && document.defaultView.getComputedStyle) {

		prop = prop.replace(/([A-Z])/g, "-$1");
		prop = prop.toLowerCase();

		val = document.defaultView.getComputedStyle(this,"").getPropertyValue(prop);

	} else {
		val=null;
	}

	if(prop === 'opacity' && val === undefined){
		val = 1;
	}

	if(val){
		if(typeof val === 'string'){

			val = val.toLowerCase();
			if(val === 'rgba(0, 0, 0, 0)'){
				val = 'transparent';
			}

			if(typeof sb.colors.html !== 'undefined'){
				if(sb.colors.html[val]){
					val = sb.colors.html[val].hex2rgb();
				}
			}

			if(val.match("^#")){
				val = val.hex2rgb();
			}

		}

		return val;
	} else {
		return null;
	}

};


Element.prototype.setStyle = function(prop, val){

	if(sb.styles.pxProps.inArray(prop) && val !== '' && !val.match(/em|cm|pt|px|%/)){
		val +='px';
	}

	if(prop === 'opacity' && typeof this.style.filter === 'string' && typeof this.style.zoom === 'string'){
		this.style.opacity = val;
		this.style.zoom = 1;
		this.style.filter = "alpha(opacity:"+val*100+")";
	} else {

		if(prop === 'cssFloat' && typeof this.style.styleFloat === 'string'){
			prop = 'styleFloat';
		}

		if(typeof this.style[prop] === 'string'){
			this.style[prop] = val;
		} else {
			throw("style["+prop+"] does not exist in this browser's style implemenation");
		}
	}
};

Element.prototype.typeOf = function(){
	return 'sb.element';
};

sb.dom.onReady({
	id : 'body',
	onReady : function(){
		sb.onbodyload.forEach(function(v){
			if(typeof v === 'function'){
				v();
			}
		});
	},
	tries : 600,
	ontimeout : function(){
		if(typeof sb.onbodynotready === 'function'){
			sb.onbodynotready();
		}
	}
});

if(sb.browser.agent == 'ie' && sb.browser.version >= 8){
	sb.events.add('html', 'keydown', function(e){
		if(e.target.nodeName === 'INPUT' && e.keyCode === 13){
			e.preventDefault();
		}
	});
}

sb.events.add(window, 'resize', sb.browser.measure);
sb.events.add(window, 'unload', function(e){

	sb.onleavepage.forEach(function(v){
		if(typeof(v) === 'function'){
			v(e);
		}
	});
	sb.events.removeAll();
});

window.sb = document.sb = sb;
if(typeof sbNo$ === 'undefined'){
	var $ = sb.$;
	var $$ = sb.$$;
}

sb.events.observer = {
	
	
	html : sb.$('html'),

	
	delegateEvents : function(e){
		
		sb.events.observer.eventHandlers.forEach(function(v){
			if(v.events && v.events[e.type]){
				v.events[e.type](e);
			}
		});
		
	},
	
	
	observe : function(eventHandler){
		
		if(!this.eventHandlers.inArray(eventHandler)){
			this.eventHandlers.push(eventHandler);
		}
	},
	
	
	unobserve : function(eventHandler){
		this.eventHandlers = this.eventHandlers.remove(eventHandler);
	},

	
	getEvents : function(){
		return ['change', 'click', 'mouseup', 'mousedown', 'dblclick', 'contextmenu', 'submit', 'keydown', 'keyup', 'keypress', 'mousemove', 'mouseover', 'mouseout', 'dragstart', 'dragend', 'drag', 'dragenter', 'dragleave', 'drop'];
	},

	
	handleIEEventBubbles : function(){
		sb.events.add(document, 'mousedown', function(e){
			var t= e.target;
			var nn = t.nodeName;
			if(nn === 'SELECT'){
				if(!t.attr('sb_ie_onchange_bubbler')){
					t.attr('sb_ie_onchange_bubbler', 1);
					sb.events.add(t, 'change', sb.events.observer.delegateEvents);
				}
			} else if((nn === 'INPUT' && t.type === 'submit') || nn === 'BUTTON'){
				var form = t.getContaining('form');
				if(form && !form.attr('sb_ie_onsubmit_bubbler')){
					form.attr('sb_ie_onsubmit_bubbler', 1);
					sb.events.add(form, 'submit', sb.events.observer.delegateEvents);
				}
			}

		});
	},
	
	
	init : function(){
		this.eventHandlers = [];
		this.html.events({
			click : this.delegateEvents,
			mousedown : this.delegateEvents,
			dblclick : this.delegateEvents,
			mouseover : this.delegateEvents,
			mouseout : this.delegateEvents,
			mousemove : this.delegateEvents,
			drag : this.delegateEvents,
			dragstart : this.delegateEvents,
			dragend : this.delegateEvents,
			dragenter : this.delegateEvents,
			dragleave : this.delegateEvents,
			drop : this.delegateEvents,
			submit : this.delegateEvents,
			change : this.delegateEvents
		});
		
		//handle keyups
		this.documentKeyUp = sb.events.add(document, 'keyup', this.delegateEvents);

		//handle contextmenu
		this.documentContextMenu = sb.events.add(document, 'contextmenu', this.delegateEvents);

		//handle keydowns
		this.documentKeyDown = sb.events.add(document, 'keydown', this.delegateEvents);
		
		//handle keypresses
		this.documentKeyPress = sb.events.add(document, 'keypress', this.delegateEvents);
		
		if(sb.browser.agent === 'ie' && sb.browser.version < 8){
		
			this.handleIEEventBubbles();
		}

	}
};

sb.events.observer.init();
sb.browser.getScrollPosition = function(){
	var x=0,y=0;;

    if (typeof window.pageYOffset != 'undefined'){
        x = window.pageXOffset;
        y = window.pageYOffset;
    } else if (typeof document.documentElement.scrollTop != 'undefined'){
        x = document.documentElement.scrollLeft;
        y = document.documentElement.scrollTop;
    } else if (typeof document.body.scrollTop != 'undefined'){
        x = document.body.scrollLeft;
        y = document.body.scrollTop;
    }

    sb.browser.x = x;
    sb.browser.y = y;

    return [x,y];
};

sb.events.add(window, 'scroll', sb.browser.getScrollPosition);
Element.prototype.getDimensions = function() {
	
    var display = this.getStyle('display');
    // Safari bug
    if (display != 'none' && display !== null) {
    	this.width = this.offsetWidth;
    	this.height = this.offsetHeight;
     
    } else {
    	
	    // All *Width and *Height properties give 0 on els with display none,so enable the el temporarily
	
	    var origStyles = {
	    	visibility : this.style.visibility,
	    	position : this.style.position,
	    	display : this.style.display
	    };
	    
	    this.styles({
	    	visibility : 'hidden',
	    	position : 'absolute',
	    	display : 'block'
	    });
		
	  	this.width = this.clientWidth;
	  	this.height = this.clientHeight;
	  	this.styles(origStyles);
    }
    return this;
};
sb.include('Element.prototype.getDimensions');
sb.include('browser.getScrollPosition');



Element.prototype.getPosition = function(params){
	params = params || {};
	var orig = this;

	var el=this;
	
	orig.top =0;
	orig.left =0;
	
	do{
		orig.top += el.offsetTop;
		orig.left += el.offsetLeft;
		
		if(params.pos =='rel'){
			el = false;
		} else{
			try{el = el.offsetParent;}catch(e){el = false;}
			
		}
	} while(el);
	
	if(params.accountForScrollBar){
		sb.browser.getScrollPosition();
		if(sb.browser.scrollY){
			orig.top -=sb.browser.scrollY;
		}
		
		if(sb.browser.scrollX){
			orig.left -=sb.browser.scrollX;
		}
	}
	
	orig.getDimensions();
	
	//alias for w and h
	orig.w = orig.width;
	orig.h = orig.height;
	orig.bottom = orig.top+orig.width;
	orig.right = orig.left+orig.height;
	
	return orig;	
};
Element.prototype.disableSelection = function(){
	
    this.onselectstart = function() {
        return false;
    };
    this.unselectable = "on";
    this.style.MozUserSelect = "none";
	
	return this;
};
Element.prototype.mv = function(x,y,z){
	
	this.style.left = x+'px';
	this.style.top = y+'px';
	if(z){
		this.style.zIndex = z;
	}
	
	if(this.getStyle('position') == 'static'){this.style.position = 'absolute';}
	
	this.getPosition();
	return this;
};
sb.math.rand = function(min,max){
	min = min || 0;
	max = max || 100;
	return Math.floor(Math.random()*max+min);
};

sb.css.rules = {
	numRules : 0,
	
	write : function(domEl, rule){
	
		var sheet;
		if(typeof this.sheet ==='undefined'){
			if(document.createStyleSheet) {
				this.sheet = document.createStyleSheet('');
			} else {
			
				sheet = document.createElement('style');
				sheet.type="text/css";
				sheet.appendChild(document.createTextNode(domEl+'{'+rule+'}'));
				this.sheet = sb.$('head').appendChild(sheet);
				sheet=null;
			}
		}
		
		if(this.sheet.insertRule){
			this.sheet.insertRule(domEl+'{'+rule+'}', this.numRules);
		} else if(this.sheet.addRule){
			this.sheet.addRule(domEl, rule);
		} else if (document.styleSheets.length > 0){
		
			document.styleSheets[document.styleSheets.length-1].insertRule(domEl+'{'+rule+'}', this.numRules);
		}
		
		this.numRules++;
	}
};
sb.colors.rand = function(grey){
	var rand = sb.math.rand;
	if(grey == 1){
		grey = rand(0,255);
		return "rgb("+grey+","+grey+","+grey+")";	
	} else {
		return "rgb("+rand(0,255)+","+rand(0,255)+","+rand(0,255)+")";	
	}
};
String.prototype.numpad = function(){
	return (this<=9) ? '0'+this : this;
};


String.prototype.nl2br = function(){
	var re = new RegExp("\n", "ig");
	return this.replace(re, "<br />");
};


String.prototype.escapeHTML = function(){
	var str = this.replace(/</g, '&lt;');
	return str.replace(/>/g, '&gt;');
};
throw('ERROR: Surebert module "date.js" could not be located by /surebert/load ');
Notice: Undefined variable: data in /var/www/html/surebert/private/views/surebert/SurebertView.php on line 162

Call Stack:
    0.0001     654872   1. {main}() /var/www/html/surebert/public/gateway.php:0
    0.0003     712960   2. Gateway::render_main_request() /var/www/html/surebert/public/gateway.php:591
    0.0004     712960   3. Gateway::render_view() /var/www/html/surebert/public/gateway.php:447
    0.0006     758976   4. sb_View->render() /var/www/html/surebert/public/gateway.php:434
    0.0006     801376   5. require('/var/www/html/surebert/private/views/surebert/load.view') /var/www/html/surebert/public/gateway.php:158
    0.0006     801472   6. SurebertView->concat_files() /var/www/html/surebert/private/views/surebert/load.view:14
    0.0016     899800   7. SurebertView->grab_file() /var/www/html/surebert/private/views/surebert/SurebertView.php:106


sb.include('String.prototype.numpad');


sb.date.formatter = function(timestamp, offset){

	this.timestamp = timestamp || false;
	offset = offset || 0;
	if(timestamp && typeof timestamp.match =='function' && timestamp.match(/T/)){
		var d = timestamp.replace(/[ZT\-]/g, ':').split(':');
		this.date = new Date(d[0], d[1]-1, d[2], d[3]-offset, d[4], d[5]);
	} else {
		this.date = new Date();
		if(this.timestamp){
			this.date.setTime(this.timestamp*1000);
		}
	}

	this.getDate();
};

sb.date.formatter.prototype= {

	
	getDate : function(str){
		//'2011-01-14T00:21:07Z'
		var d=this.date,self=this;

		d.m = String(d.getMonth()+1).numpad();
		d.F = sb.dates.months[d.getMonth()];
		d.M = d.F.substr(0,3);
		d.d = String(d.getDate()).numpad();

		d.l = String(sb.dates.days[d.getDay()]);
		d.D = d.l.substr(0,3);
		//d.w = sb.dates.days.indexOf(d.l);
		d.Y = String(d.getFullYear());
		d.y = d.Y.substr(2,4);

		d.H = String(d.getHours()).numpad();
		d.G = d.getHours();
		d.g = (d.H >12) ?  d.H-12 : d.H;
		d.h = (d.H >12) ?  String(d.H-12).numpad() : d.H;
		d.a = (d.H < 12) ? 'am' : 'pm';
		d.A = d.a.toUpperCase();

		d.i = d.getMinutes();
		d.s = String(d.getSeconds()).numpad();
		d.U = Date.parse(d)/1000;
		d.n = d.getMilliseconds();
		d.date = d.m+'/'+d.d+'/'+d.y;
		d.time = d.h+':'+d.i;
		d.time24 = d.H+':'+d.i;
		sb.objects.forEach.call(d, function(val, prop, o){

			self[prop] = val;
		});

	},

	
	format : function(str){
		var x,f='';
		if(str !== undefined){

			for(x=0;x<str.length;x++){
				switch(str.charAt(x)){

					case 'm':
						f += str.charAt(x).replace(/m/, this.m);
					break;

					case 'M':
						f += str.charAt(x).replace(/M/, this.M);
					break;

					case 'F':
						f += str.charAt(x).replace(/F/, this.F);
					break;

					case 'd':
						f += str.charAt(x).replace(/d/, this.d);
					break;

					case 'D':
						f += str.charAt(x).replace(/D/, this.D);
					break;

					case 'l':
						f += str.charAt(x).replace(/l/, this.l);
					break;

					case 'w':
						f += str.charAt(x).replace(/w/, this.w);
					break;

					case 'Y':
						f += str.charAt(x).replace(/Y/, this.Y);
					break;

					case 'y':
						f += str.charAt(x).replace(/y/, this.y);
					break;

					case 'H':
						f += str.charAt(x).replace(/H/, this.H);
					break;

					case 'h':
						f += str.charAt(x).replace(/h/, this.h);
					break;

					case 'G':
						f += str.charAt(x).replace(/G/, this.G);
					break;

					case 'g':
						f += str.charAt(x).replace(/g/, this.g);
					break;

					case 'i':
						f += str.charAt(x).replace(/i/, this.i);
					break;

					case 's':
						f += str.charAt(x).replace(/s/, this.s);
					break;

					case 'U':
						f += str.charAt(x).replace(/U/, this.U);
					break;

					case 'n':
						f += str.charAt(x).replace(/n/, this.n);
					break;

					case 'w':
						f += str.charAt(x).replace(/w/, this.w);
					break;

					case 'a':
						f += str.charAt(x).replace(/a/, this.a);
					break;

					case 'A':
						f += str.charAt(x).replace(/A/, this.A);
					break;

					default:
						f+= str.charAt(x);
				}
			}

			this.formatted =f;
			f=null;
			return this.formatted;
		}
	}
};

sb.dates = {
	months : ["January","Febuary","March","April","May","June","July","August","September","October","November","December"],

	days : ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

};

sb.cookies ={

	path : '/',
	domain : '',
	onlog : '',
	
	
	get : function(name){
		
		var i,n, parts = document.cookie.split(';');
		
		for(i=0;i<parts.length;i++){
			n = parts[i].split('=');
			n[0] = n[0].replace(/ /, "");
			
			if(name==n[0]){
				return unescape(n[1]);
			} 
		}
		return false;
	},
	
	
	
	set : function(name, value, days){
        
        var ck, date = new Date();
        var exp = '';
    
        if(days){
            date.setTime(date.getTime()+(days*24*60*60*1000));
            exp = '; expires='+date.toGMTString();
        }
                     
        ck=name+'=' + escape(value) + exp + '; path=' + sb.cookies.path + ';' + ' host=' + sb.cookies.domain;
        
        document.cookie = ck;
                    
    },
	
	
	forget : function(name){
		return this.clear(name);
	},
        
        
        unset : function(name){
		return this.clear(name);
	},
	
	
	clear : function(name){
		this.set(name, "", -1);
	},
	
	
	forgetAll : function(){
		return this.clearAll();
	},
	
	
	clearAll : function(){
		var n,i,deleted =[], parts = document.cookie.split(';');
		for(i=0;i<parts.length;i++){
			n = parts[i].split('=');
			
			if(n[0] !== undefined){
				deleted.push(n[0]);
				this.set(n[0], "", -1);
			}
		}
	},
	
	
	listAll : function(){
		var i, c, list=[], parts = document.cookie.split(';');
		
		for(i=0;i<parts.length;i++){
			c = parts[i].split('=');
			list.push(c[0].replace(/ /, ""));
		}
		
		return list;
	},
	
	typeOf : function(){
		return 'sb.cookies';
	}
	
};
sb.swf = function(params){
	if(typeof params == 'object'){
		sb.objects.infuse(params, this);
	} 
	this.width = this.width || '400px';
	this.height = this.height || '300px';
	this.bgColor = this.bgColor || '#FFFFFF';
	this.version = this.version || 5;
	this.allowFullScreen = this.allowFullScreen || 'true';
	this.alt = this.alt || '';
	this.src = this.src || '';
	this.wmode = this.wmode || '';
	if(typeof this.id =='undefined'){
		this.id = 'sb_swf_'+sb.swf.instanceId;
		sb.swf.instanceId++;
	}
};


sb.swf.prototype = {
	
		
	getInterface : function(){
		var movieName = this.id;
		if (navigator.appName.indexOf("Microsoft") != -1) {
            return window[movieName];
        } else {
        	return document.getElementById(movieName);
        }
	},
	
	
	toHTML : function(){
		var html='';
		
		if(this.version > sb.swf.version){
			return this.alt;
		}
		
		if(sb.swf.format=='embed'){
			
			html = '<embed type="application/x-shockwave-flash" src="'+this.src+'"  id="'+this.id+'" name="'+this.id+'" wmode="'+this.wmode+'" allowScriptAccess="always" allowFullScreen="'+this.allowFullScreen+'" bgcolor="'+this.bgColor+'" ';
				
			if(typeof this.flashvars =='object'){
				
				html +='FlashVars="'+sb.objects.serialize(this.flashvars)+'" ';
			
			}
			
			html +=' width="'+this.width+'" height="'+this.height+'"  />';
		
		} else if(sb.swf.format=='object'){
				
				html = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="'+this.width+'" height="'+this.height+'" id="'+this.id+'" ><param name="movie" value="'+this.src+'" /><param name="bgcolor" value="'+this.bgColor+'" /><param name="wmode" value="'+this.wmode+'" /><param name="allowFullScreen" value="'+this.allowFullScreen+'" /><param name="allowScriptAccess" value="always" />';
				if(typeof this.flashvars =='object'){
					html +='<param name="FlashVars" value="'+sb.objects.serialize(this.flashvars)+'">';
				}
				html +='</object>';
				
		}
		return html;
		
	},
	
	
	embed : function(el){
		el = sb.$(el);
		el.innerHTML = this.toHTML();
		return el;
	}
};

sb.swf.infuse = sb.objects.infuse;

sb.swf.infuse({
	
	version : 0,

	
	fullVersion : '0,0,0',
	
	
	swfs : [],

	
	instanceId : 0,
	
	
	cleanup : function() {
		try{
		sb.$('object').forEach(function(obj){
			obj.style.display='none';
			for(var prop in obj){
				if(typeof obj == 'function'){obj[prop] = function(){};}
			}
		});
		}catch(e){}
	},
	
	
	unload : function() {
		__flash_unloadHandler = function(){};
		__flash_savedUnloadHandler = function(){};
		window.attachEvent( "onunload", sb.swf.cleanup );
		
	},
	
	
	detect : function(){
		this.fullVersion = '0,0,0';
		try {
			if(navigator && navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]){

				if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
					this.fullVersion = (navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
				}
				this.format = 'embed';
			} else {
				this.fullVersion = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
				this.format = 'object';
			}

		} catch(e) {}
		this.version = this.fullVersion.split(',')[0];
	}
	
});

sb.swf.detect();

if(sb.browser.ie6){
	
	//fix for bad adobe code in IE
	var __flash__removeCallback = function(instance, name){
		if(typeof instance != 'null'){
			instance[name] = null;
		}
	};

	//cleanup flash players for IE
	window.attachEvent( "onbeforeunload", sb.swf.unload);
}


sb.include('date.formatter');
sb.include('css.rules');

sb.include('math.rand');
sb.include('colors.rand');
sb.include('String.prototype.nl2br');
sb.include('String.prototype.escapeHTML');
sb.include('Element.prototype.disableSelection');
sb.include('Element.prototype.mv');
sb.include('Element.prototype.getPosition');

sb.debug =1;
sb.developer = {};

//sb.devel =1;


sb.messages = {
	
	10 :"FlashPlayer not installed or not detected.  You will need at least Flash play 8 to use sb's flash functionality\n GET FLASH PLAYER: http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash",
	11 :"You have disabled flash functionality. i.e. sound and flash shared object storage space access by setting the sbNoFlash=1 before calling surebert.",
	12 :"Surebert has tried to play this track 5 times with no sucess, perhaps you have flash functionality disabled or the sound does not exist.",
	13: " is not a well formatted javascript file and cannot be loaded by sb.javascript",
	14: ' cannot be used by $, perhaps it does not exist or is not in the DOM yet?',
	15 : 'The surebert.swf has not loaded yet and cannot receive calls to its internal functions, e.g. upload, sound, setDebug.',
	16 : "sb.sound has tried to play the following file 10 times but surebert.flashGate has not loaded.  Try pushing the play function into the sb.onFlashGateLoad array \nSOUND: ",
	17 : "The following image is not reporting height or width properly, perhaps because it has never been in view and so will not work with sb.ie6.pngFix, try running pngFix after it is in view\n",
	18 : "Cannot read style: "
};


sb.objects.alert =  function(o){
	window.alert(sb.objects.dump(o));
};
	

sb.debugMe = function(){
	/*
	if(sb.initialized !=1){
		sb.ondomload.push(sb.debugMe);
		return;
	}*/
	
	//list all cookies that are stored
	sb.include('cookies');
	sb.include('swf');
	
	sb.consol.log([
		'agent='+window.navigator.userAgent,
		'browser detection:'+"\nsb.browser.agent="+sb.browser.agent+"\nsb.browser.version="+sb.browser.version,
		'window.width='+sb.browser.w+"\n"+'window.height='+sb.browser.h,
		'flashPlayer='+sb.swf.version,
		'cookies found: '+sb.cookies.listAll()
		].join("\n\n")
	);

};


sb.debugStyle = function(color, backgroundColor, allowHTML){
	return function(message){
		sb.consol.write(message, color, backgroundColor, allowHTML);
	};
};



sb.consol = {
	
	write : function(str, color, bgColor, allowHTML){
			
		
		var note,preWrap;
		str = String(str);
		
		if(sb.debug ==1){
			color = color || 'green';
			bgColor = bgColor || 'black';
			
			if(typeof this.onlog == "function"){
				this.onlog(str);
			} else {
				
				if(typeof this.box == 'undefined'){
					this.open();
				}
				
				if(allowHTML !== true){
					str = String(str).escapeHTML();
				}
				
			 	sb.css.rules.write("sbConsolNote", 'display:block;font-size:0.8em;margin-bottom:20px;padding:10px;font-size:12px;font-family:tahoma,verdana;text-align:left;');
			 	sb.css.rules.write("sbConsolNote a", 'color:orange;font-size:1.2em;');
			 	sb.css.rules.write("sbConsolNote h1", 'margin-bottom:0;font-size:1.2em;');	
			 	sb.css.rules.write("sbConsolNote hr", 'height:2px;margin:3px 0 3px 0;color:orange;background-color:orange;');

			 	str = str.replace(/\n/g, "<br />");
			 	str = str.replace(/\t/g, "&nbsp;&nbsp;&nbsp;&nbsp; ");
			
			 	note = new sb.element({
			 		tag : 'sbConsolNote',
			 		innerHTML : this.num+'. '+new sb.date.formatter().format('m/d - g:i:s a')+"<hr />"+str
			 	});
			 	
			 	
			 	note.styles({
			 		backgroundColor : bgColor,
			 		color : color
			 	});
			 	
			 	note.appendToTop(this.box.firstChild);
				note = null;
				str =null;
				this.num++;
			}
		}
		
	},
	
	
	error : new sb.debugStyle('white', 'red'),
	
	
	warning : new sb.debugStyle('red', 'yellow'),
	
	
	debug : new sb.debugStyle('white', '#19a29a'),
	
	
	ajaxLog : new sb.debugStyle('#8fb0d2', '#1866b7', 0),
	
	
	dump : function(str){
		var obj;
		if(typeof str =='string'){
			obj = eval(str);
		} else {
			obj = str;
		}
		
		this.debug('OBJECT: '+str+"\n"+sb.objects.dump(obj), 'white', 'red', 1);
	},
	
	
	log : new sb.debugStyle('yellow', 'green'),
	
	
	num : 1,
	
	
	open : function(){
		var self = this;
		this.box = new sb.element({
			tag : 'sbConsol',
			styles : {
				width:'100%',
				height:'200px',
				marginBottom: '20px',
				borderTop : '5px solid black',
				backgroundColor: '#84b439',
				display : 'block'
				
			},
			resize : function(h){
				self.box.style.height = h+'px';
				self.box.firstChild.style.height = h+'px';
			},
			children : [
				{
					tag : 'div',
					styles: {
						height : '100%',
						overflow : 'auto'
					}
				}
			]
		});
		
		this.box.appendToTop(((sb.browser.ie6) ? 'body' : 'html'));
		
		this.resizer = new sb.element({
			resizing : 0,
			tag : 'div',
				children : [
			{
				tag : 'span',
				innerHTML : 'clear',
				styles : {
					marginLeft : '10px',
					cursor : 'pointer'
				},
				events : {
					mousedown : function(){
						self.box.firstChild.innerHTML ='';
					}
				}
			},{
				tag : 'span',
				innerHTML : 'hide',
				styles : {
					marginLeft : '10px',
					cursor : 'pointer'
				},
				events : {
					mousedown : function(){
						self.box.resize(self.box.getY());
						self.resizer.mv(self.box.getX(), 0, 999);
					}
				}
				
			},
			{
				tag : 'span',
				innerHTML : 'capture',
				styles : {
					marginLeft : '10px',
					cursor : 'pointer'
				},
				events : {
					click : function(){
						var randColor = sb.colors.rand(1);
						
						var pwin = window.open('', sb.uniqueID(), 'width=500,height=600,resizeable=yes,scrollbars=yes');
						pwin.document.write('<style type="text/css">body{background-color:black;color:green;}</style><h2>Captured At'+new Date()+' from '+window.location+'</h2>'+self.box.firstChild.innerHTML);
						pwin.document.close();
						pwin.focus();
					}
				}
				
			}
			],
			title : 'Drag to resize consol, double click to hide',
			styles: {
				height : '15px',
				width : '100%',
				backgroundColor :'black',
				color: 'white',
				cursor : 'n-resize',
				position : 'relative',
				left : '0px',
				padding: '2px 0 2px 0',
				textAlign : 'left'
			},
			events : {
				mousedown : function(e){
					var target = e.target;
					target.origY = target.getY();
					target.style.width = self.box.offsetWidth+'px';
					target.style.position = 'absolute';
					target.resizing =1;
				},
				dblclick : function(e){
					if(e.target.nodeName == 'DIV'){
						self.box.resize(0);
						self.resizer.mv(self.box.getX(), self.box.getY(), 999);
					}
				}
			}
		});
		this.resizer.disableSelection();
		
		sb.events.add(document, 'mouseup', function(){
			self.resizer.resizing =0;
		});
		
		sb.events.add(document, 'mousemove', function(e){
			var rszr = self.resizer;
			
			if(rszr.resizing ==1 && e.clientY > self.box.getY()){
				rszr.mv(self.box.getX(), e.clientY, 999);
				self.box.resize(e.clientY);
				
			}
			
		});
		this.resizer.appendTo(this.box);
        return;
		
	},
	
	
	flashGateDebug : function(message){
	
		if(sb.flashGateDebug ==1){
			sb.consol.write(message, 'orange', '#660066', 1);
		}
		
	}
	
};


sb.performance = function(func){
    var t0 = new Date().getTime();
    func();
    return new Date().getTime() - t0;
};
