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

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.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);
}
if(typeof sb.swf =='undefined'){
	sb.include('swf');
}
/*
@Name: sb.uploadButton
@Description: Instantiates a new upload
@Example:
var uploader = new sb.uploadButton({
	debug : true,
	maxFiles : 5,
	maxFileSizeK : 5000000,
	url : 'http://frameworkdev.sv/uploads/test',
	data : {
		friend : 'tim',
		nano : "Hello there timmy's dog"
	},
	onReturnData : function(file){
		sb.objects.alert(file);
	},
	onBeforeBrowse : function(){
		return true;
	},
	onSelect : function(filenames){
		return true;
	},
	onExceedsMaxFiles : function(){},
	onExceedsMaxFileSizeK : function(file){},
	onError : function(data){
		alert(data.message);
	},
	styles : {
		backgroundColor : '0x00FF00',
		backgroundColorRoll : '0xFFFF00',
		borderColor : '0xFF0000',
		color : '0xFF0000',
		cornerRadius : '15',
		borderThickness : '0',
		fontSize : 16,
		width : 62,
		height : 24,
		fontSize : 16,
		font : 'Tahoma'
	}
});
uploader.embed('#chicken');
*/

sb.uploadButton = function(parameters){
	
	this.id = sb.uploadButton.uploads.length;
	
	for(var prop in parameters){
		this[prop] = parameters[prop];
	}
	
	sb.uploadButton.uploads.push(this);

	//create swf and associate call to thei sb.uploadButton for event handling
	
	this.swf = new sb.swf({
		src : sb.base+"/UploadButton.swf?id="+this.id,
		width : this.styles.width || 62,
		height : this.styles.height || 24,
		id : 'upload'+this.id,
		bgcolor : '#000000',
		wmode: window.chrome ? '' : 'transparent',
		flashvars : {
			debug : (this.debug != null) ? this.debug : true,
			innerHTML : this.innerHTML || 'upload',
			debugLevel : this.debugLevel || 1
		},
		version : 9,
		alt : parameters.alt || '<h1>You need <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash">flash player 9+</a> to upload</h1>'
	});

	this.load_params = function(){
	
		this.swf.getInterface().create_upload(this.id);
		
	};
};

	

sb.uploadButton.uploads = [];

sb.uploadButton.prototype = {
	styles : {},
	
	
	toHTML : function(){
		return this.swf.toHTML();
	},
	
	
	embed : function(el){
		this.swf.embed(el);
	},
	
	
	setStyles : function(styles){
		this.swf.getInterface().set_button_styles(styles);
	},

	
	cancel : function(name){
		name = name || '';
		this.swf.getInterface().upload_cancel(name);
	},
	
	
	id: 0,
	
	
	maxFiles : 5,
	
	
	maxFileSizeK : 1024,

	
	acceptedFileTypes : '*.*',

	
	method : 'post',
	
	
	url : '',
	
	
	data : {},
	
	
	debug : true,
	
	
	debugLevel : 1,
	
	
	onBeforeBrowse : function(data){return true;},
	
	
	onSelect : function(data){return true;},
	
	
	onExceedsMaxFileSizeK : function(file){},
	
	
	onExceedsMaxFiles : function(files){},
	
	
	onError : function(file){},
	
	
	onOpen : function(file){},
	
	
	onReturnData : function(file){},
	
	
	onAllComplete : function(files){},
	
	
	onComplete : function(files){},
	
	
	onAllProgress : function(files){},
	
	
	onProgress : function(files){},
	//files.remaining
	
	
	onCancelBrowse : function(){},
	
	
	onCancelAll : function(){},
	
	
	onCancelFile : function(){}
		
};/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 
 *Modified for use with surebert.com javascript toolkit by Paul Visco http://paul.estrip.org.  Now has no global variables other than the md5 object and added String prototype for md5()
 */


sb.md5 = {
	
	
	hexcase : 0,
	
	
	b64pad : '',
	
	
	chrsz : 8,
	
	/*
	 * These are the functions you'll usually want to call
	 * They take string arguments and return either hex or base-64 encoded strings
	 */
	
	/*
	 * Perform a simple self-test to see if the VM is working
	 */
	test : function (){
	  return this.hex("abc") == "900150983cd24fb0d6963f7d28e17f72";
	},
	
	
	binl2hex : function(binarray){
		
	  var hex_tab = this.hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
	  var str = "";
	  for(var i = 0; i < binarray.length * 4; i++)
	  {
	    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
	           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
	  }
	  return str;
	},
	
	
	hex : function(s){ 
		return this.binl2hex(this.core(this.str2binl(s), s.length * this.chrsz));
	},
	
	
	b64 : function(s){
		return this.binl2b64(this.core(this.str2binl(s), s.length * this.chrsz));
	},
	
	
	str : function(s){
		return this.binl2str(this.core(this.str2binl(s), s.length * this.chrsz));
	},
	
	
	hex_hmac : function(key, data){ 
		return this.binl2hex(this.core_hmac(key, data));
	},
	
	
	b64_hmac : function(key, data) {
		return this.binl2b64(this.core_hmac(key, data));
	},
	
	
	str_hmac : function(key, data) {
		return this.binl2str(this.core_hmac(key, data));
	},
	
	
	core : function(x, len){
		
	  /* append padding */
	  x[len >> 5] |= 0x80 << ((len) % 32);
	  x[(((len + 64) >>> 9) << 4) + 14] = len;
	
	  var a =  1732584193;
	  var b = -271733879;
	  var c = -1732584194;
	  var d =  271733878;
	
	  for(var i = 0; i < x.length; i += 16){
	    var olda = a;
	    var oldb = b;
	    var oldc = c;
	    var oldd = d;
	
	    a = this.ff(a, b, c, d, x[i+ 0], 7 , -680876936);
	    d = this.ff(d, a, b, c, x[i+ 1], 12, -389564586);
	    c = this.ff(c, d, a, b, x[i+ 2], 17,  606105819);
	    b = this.ff(b, c, d, a, x[i+ 3], 22, -1044525330);
	    a = this.ff(a, b, c, d, x[i+ 4], 7 , -176418897);
	    d = this.ff(d, a, b, c, x[i+ 5], 12,  1200080426);
	    c = this.ff(c, d, a, b, x[i+ 6], 17, -1473231341);
	    b = this.ff(b, c, d, a, x[i+ 7], 22, -45705983);
	    a = this.ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
	    d = this.ff(d, a, b, c, x[i+ 9], 12, -1958414417);
	    c = this.ff(c, d, a, b, x[i+10], 17, -42063);
	    b = this.ff(b, c, d, a, x[i+11], 22, -1990404162);
	    a = this.ff(a, b, c, d, x[i+12], 7 ,  1804603682);
	    d = this.ff(d, a, b, c, x[i+13], 12, -40341101);
	    c = this.ff(c, d, a, b, x[i+14], 17, -1502002290);
	    b = this.ff(b, c, d, a, x[i+15], 22,  1236535329);
	
	    a = this.gg(a, b, c, d, x[i+ 1], 5 , -165796510);
	    d = this.gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
	    c = this.gg(c, d, a, b, x[i+11], 14,  643717713);
	    b = this.gg(b, c, d, a, x[i+ 0], 20, -373897302);
	    a = this.gg(a, b, c, d, x[i+ 5], 5 , -701558691);
	    d = this.gg(d, a, b, c, x[i+10], 9 ,  38016083);
	    c = this.gg(c, d, a, b, x[i+15], 14, -660478335);
	    b = this.gg(b, c, d, a, x[i+ 4], 20, -405537848);
	    a = this.gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
	    d = this.gg(d, a, b, c, x[i+14], 9 , -1019803690);
	    c = this.gg(c, d, a, b, x[i+ 3], 14, -187363961);
	    b = this.gg(b, c, d, a, x[i+ 8], 20,  1163531501);
	    a = this.gg(a, b, c, d, x[i+13], 5 , -1444681467);
	    d = this.gg(d, a, b, c, x[i+ 2], 9 , -51403784);
	    c = this.gg(c, d, a, b, x[i+ 7], 14,  1735328473);
	    b = this.gg(b, c, d, a, x[i+12], 20, -1926607734);
	
	    a = this.hh(a, b, c, d, x[i+ 5], 4 , -378558);
	    d = this.hh(d, a, b, c, x[i+ 8], 11, -2022574463);
	    c = this.hh(c, d, a, b, x[i+11], 16,  1839030562);
	    b = this.hh(b, c, d, a, x[i+14], 23, -35309556);
	    a = this.hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
	    d = this.hh(d, a, b, c, x[i+ 4], 11,  1272893353);
	    c = this.hh(c, d, a, b, x[i+ 7], 16, -155497632);
	    b = this.hh(b, c, d, a, x[i+10], 23, -1094730640);
	    a = this.hh(a, b, c, d, x[i+13], 4 ,  681279174);
	    d = this.hh(d, a, b, c, x[i+ 0], 11, -358537222);
	    c = this.hh(c, d, a, b, x[i+ 3], 16, -722521979);
	    b = this.hh(b, c, d, a, x[i+ 6], 23,  76029189);
	    a = this.hh(a, b, c, d, x[i+ 9], 4 , -640364487);
	    d = this.hh(d, a, b, c, x[i+12], 11, -421815835);
	    c = this.hh(c, d, a, b, x[i+15], 16,  530742520);
	    b = this.hh(b, c, d, a, x[i+ 2], 23, -995338651);
	
	    a = this.ii(a, b, c, d, x[i+ 0], 6 , -198630844);
	    d = this.ii(d, a, b, c, x[i+ 7], 10,  1126891415);
	    c = this.ii(c, d, a, b, x[i+14], 15, -1416354905);
	    b = this.ii(b, c, d, a, x[i+ 5], 21, -57434055);
	    a = this.ii(a, b, c, d, x[i+12], 6 ,  1700485571);
	    d = this.ii(d, a, b, c, x[i+ 3], 10, -1894986606);
	    c = this.ii(c, d, a, b, x[i+10], 15, -1051523);
	    b = this.ii(b, c, d, a, x[i+ 1], 21, -2054922799);
	    a = this.ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
	    d = this.ii(d, a, b, c, x[i+15], 10, -30611744);
	    c = this.ii(c, d, a, b, x[i+ 6], 15, -1560198380);
	    b = this.ii(b, c, d, a, x[i+13], 21,  1309151649);
	    a = this.ii(a, b, c, d, x[i+ 4], 6 , -145523070);
	    d = this.ii(d, a, b, c, x[i+11], 10, -1120210379);
	    c = this.ii(c, d, a, b, x[i+ 2], 15,  718787259);
	    b = this.ii(b, c, d, a, x[i+ 9], 21, -343485551);
	
	    a = this.safe_add(a, olda);
	    b = this.safe_add(b, oldb);
	    c = this.safe_add(c, oldc);
	    d = this.safe_add(d, oldd);
	  }
	  return [a, b, c, d];
	
	},
	
	
	cmn : function(q, a, b, x, s, t){
	  return this.safe_add(this.bit_rol(this.safe_add(this.safe_add(a, q), this.safe_add(x, t)), s),b);
	},
	
	
	ff : function(a, b, c, d, x, s, t){
	  return this.cmn((b & c) | ((~b) & d), a, b, x, s, t);
	},
	
	
	gg : function(a, b, c, d, x, s, t){
	  return this.cmn((b & d) | (c & (~d)), a, b, x, s, t);
	},
	
	
	hh : function(a, b, c, d, x, s, t){
	  return this.cmn(b ^ c ^ d, a, b, x, s, t);
	},
	
	
	ii : function(a, b, c, d, x, s, t){
	  return this.cmn(c ^ (b | (~d)), a, b, x, s, t);
	},
	
	
	core_hmac : function(key, data){
		
	  var bkey = this.str2binl(key);
	  if(bkey.length > 16) {
	  	bkey = this.core(bkey, key.length * this.chrsz);
	  }
	
	  var ipad = new Array(16), opad = new Array(16);
	  for(var i = 0; i < 16; i++){
	    ipad[i] = bkey[i] ^ 0x36363636;
	    opad[i] = bkey[i] ^ 0x5C5C5C5C;
	  }
	
	  var hash = this.core(ipad.concat(this.str2binl(data)), 512 + data.length * this.chrsz);
	  return this.core(opad.concat(hash), 512 + 128);
	},
	
	
	safe_add : function (x, y){
	  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
	  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
	  return (msw << 16) | (lsw & 0xFFFF);
	},
	
	
	bit_rol : function(num, cnt){
	  return (num << cnt) | (num >>> (32 - cnt));
	},
		
	
	str2binl : function (str){
		var bin = [];
		var mask = (1 << this.chrsz) - 1;
		for(var i = 0; i < str.length * this.chrsz; i += this.chrsz){
			bin[i>>5] |= (str.charCodeAt(i / this.chrsz) & mask) << (i%32);
		}
		return bin;
	},
	
	
	binl2str : function (bin){
		var str = "";
		var mask = (1 << this.chrsz) - 1;
		for(var i = 0; i < bin.length * 32; i += this.chrsz){
			str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
		}
		return str;
	},
	
	
	binl2b64 : function(binarray){
		var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
		var str = "";
		for(var i = 0; i < binarray.length * 4; i += 3){
			var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16) |(((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 ) | ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
			            
			for(var j = 0; j < 4; j++){
				
			  if(i * 8 + j * 6 > binarray.length * 32) {
			  	str += sb.md5.b64pad;
			  } else {
			  	str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
			  }
		
			}
			return str;
		}

	}	
	
};


String.prototype.md5 = function(){
	return sb.md5.hex(this);
};
Array.prototype.iteration = function(){
	if(this.pointer === null){
		this.point = 0;
	}
};
	

Array.prototype.pointer = 0;


Array.prototype.current = function(){
	this.iteration();
	return this[this.pointer];
};
	
	
Array.prototype.end = function(){
	this.iteration();
	this.pointer = this.length-1;
	return this[this.pointer];
};


Array.prototype.first = function(){
	this.iteration();
	return this[0];
};


Array.prototype.last = function(){
	this.iteration();
	return this[this.length-1];
};


Array.prototype.next = function(){
	this.iteration();
	this.pointer +=1;
	return this[this.pointer];
};


Array.prototype.rewind = function(){
	this.iteration();
	this.pointer=0;
	return this[this.pointer];
};


Array.prototype.prev = function(){
	this.iteration();
	this.pointer -=1;
	return this[this.pointer];
};


Array.prototype.cycle = function(backwards){
    
    var val, b=backwards;
	this.iteration();
	if(!this.sb_beginCycle){
		this.sb_beginCycle =1;
        if(b){
            val = this.last();
        } else {
            val = this.first();
        }
	} else {
        if(b){
            val = this.prev();
        } else {
            val = this.next();
        }

	}
	
	if(typeof val == 'undefined'){
		
         if(b){
            return this.end();
        } else {
            return this.rewind();
        }
	} else {
		return val;
	}
};
