var isMSIE = /*@cc_on!@*/false;
var IEVersion = 0 /*@cc_on+parseFloat(navigator.appVersion.split("MSIE")[1])@*/;
var isMOZILLA = navigator.userAgent.indexOf('Mozilla') > -1 && parseInt(navigator.appVersion.substring(0, 1)) >= 5;
try { document.execCommand("BackgroundImageCache", false, true); } catch(err) {}

var DEV = (location.host.indexOf(".")==-1) ? true : false;


var ObjectDefaultExtend = {
	'$t' : function(n){ return $t(n, this); },
	cE : function(_type, _id, _attr, _before) { return cE(_type, this, _id, _attr); },

	centralize : function() { centralizeElement(this); },

	classExists : function( cl ) { return classExists( this , cl ); },
	addClass : function( cl ) { return addClass( this , cl ); },
	removeClass : function( cl ) { return removeClass( this , cl ); },
	getStyle : function ( st ) { return getStyle( this , st ); },


	addEvent : function(type, fn) { Evt.add(this, type, fn); },
	removeEvent : function(type, fn) { Evt.rem(this, type, fn); },
	cancelEvent : function(evt) { Evt.cancel(evt); },
	keyCode : function(e) { Evt.keyCode(e); },

	createAndAttach : function( _type, _id, _attr, _before ) { return $(DOM.createAndAttach(_type, this, _id, _attr, _before)); },
	create : function( type, args ) { return $(DOM.create(type,args)); },
	isChildOf : function( el ) { return DOM.isChildOf(this,el); },
	remove : function( tgt ) { DOM.rem( tgt ? tgt : this ); },
	before : function( el ) { return DOM.before(this,el); },
	inside : function( el ) { return DOM.inside(this,el); },
	after : function( el ) { return DOM.after(this,el); },
	replace : function( el ) { return $(DOM.replace(this,el)); },

	replaceHTML : function( html ) {
		if(isMSIE) {
			this.innerHTML = html;
			return this;
		}

		var newEl = this.cloneNode(false);
		newEl.innerHTML = html;
		return this.replace(newEl);
	}
}

var ObjectExtend = function( toExtend , withWhat )
{
	if( !toExtend ) return;
	for ( var i in withWhat )
		toExtend[i] = withWhat[i];
}

var $ = function ()
{
	for(var i=0, elements=[], a, args=$.arguments; i<args.length; i++)
	{
		if(!args[i]) continue;
		if( typeof args[i]=='object' ) a=args[i];
		else a = ( ( (document.getElementById(args[i]) || (document.all && document.all[args[i]])) || document[args[i]] ) || null );
		ObjectExtend( a , ObjectDefaultExtend );
		elements.push(a);
	}
	return elements.length == 1 ? elements[0] : elements;
};

if (!Array.prototype.forEach)
{
	Array.prototype.forEach = function(fun /*, thisp*/)
	{
		var len = this.length;
		if (typeof fun != "function")
			throw new TypeError();

		var thisp = arguments[1];

		for (var i = 0; i < len; i++)
		{
			if (i in this)
				fun.call(thisp, this[i], i, this);
		}
	};
}

var $t = function(n/*,t*/)
{
	var t,at,e, _tags=[] ,l,er, temp=[];

	t = arguments[1]==null ? document : arguments[1];
	er = /([^[]*)(\[([0-9A-Za-z]*)=(.*)\])?/;

	n.split(',').forEach(function( act )
		{
			at = er.exec(act);
			temp = objectToArray(t.getElementsByTagName(at[1]));

			if( ! at[3] )
				_tags = _tags.concat(_tags , temp);
			else
			{
				temp.forEach( function( ele )
					{
						if( at[3]=='class' ) {
							if( classExists(ele,at[4]) )_tags.push(ele);
						} else if(isMSIE) {
							if( ele.attributes[at[3]].value == at[4] ) _tags.push(ele);
						} else if(ele.getAttribute(at[3])==at[4]) _tags.push(ele);
					}
				)
			}
		}
	);

	if(!_tags.length) return [];

	return _tags;

};


var require = function(pathToFile) {
	if( $t('script[src='+ URL + pathToFile +']').lenght>0 ) return;
	var s = DOM.createAndAttach("script", $t('head')[0], null,
		{ type: "text/javascript", src: URL + pathToFile } );
	return s;
}
var require_once = function(pathToFile) {
	var s = $t("script[src="+pathToFile+"]");
	if(s.length) return;
	return require(pathToFile);
}

var isset = function(v){
	if(typeof v != "undefined") {
		if(v != null) return true;
	}
	return false;
}
var empty = function(v){
	if(!isset(v)) return false;
	if(v.toString().length < 1) return true;
	return false;
}
var isnumeric = function(v){
	if(!isset(v)) return false;
	if(isNaN(parseFloat(v))) return false;
	return true;
}
var ERROR = function(msg) {
	var r = 'Ocorreu um erro ao executar a ação solicitada.';
	r += (isset(msg)) ? "\n" + msg : '';
	return r;
}
var generateSwfCode = function(_src,_w,_h,_tr,_v){
	var r = '<object data="' + _src + '" type="application/x-shockwave-flash" width="' + _w + '" height="' + _h;
	if( isMSIE ) r += 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,24,0"';
	r +=  '">';
	r += '<param name="MOVIE" value="' + _src + '">';
	if(_tr) r += '<param name="wmode" value="transparent" />';
	else r += '<param name="wmode" value="opaque" />';

	if(_v) {
		r += '<param name="FlashVars" value="';
		for (var i in _v)
			r += i +'='+ escape(_v[i]) +'&';
		r = r.substring( 0 , r.length-1 );
		r += '" />';
	}
	r += '<param name="menu" value="false" /><param name="quality" value="high" />';
	r += '</object>';


	return r;
}
var loadSwf = function(_t,_src,_w,_h,_tr,_v) { _t.innerHTML = generateSwfCode(_src,_w,_h,_tr,_v); }


var argumentsToArray = function(args, ini, end) {
	if(args.length<ini+1) return [];
	end = end ? end : args.length;
	var r = [];
	for( var i=ini; i<end; i++) r.push(args[i]);
	return r;
}

var objectToArray = function(obj) {
	return argumentsToArray(obj, 0, obj.length);
}

var openPopUp = function(_url, _width, _height, _windowName) {
	_windowName = isset(_windowName) ? _windowName : 'popUp';
	var w = window.open(_url, _windowName, 'width=' + _width + ',height=' + _height + '');
	if (w) w.focus();
	return w;
}

/* centralize */
var getCentralizedValues = function(obj,ow,oh){
	var ua, su, deltaY, w, tw, h, th, x, y;
	ua = usefullArea();
	su = scrolledUntil();
	deltaY = su['y'];

	w = Math.ceil(ua['x']/2);
	if(!ow)ow=obj.offsetWidth;
	ow = Math.ceil(ow/2);

	h = Math.ceil((ua['y']/2)+deltaY);
	if(!oh)oh=obj.offsetHeight;
	oh = Math.ceil(oh/2);

	x = ow<w ? w-ow : 10;
	y = oh<h ? h-oh : 10;

	return [ x , y ];
}
var centralizeElement = function(obj)
{
	var a=getCentralizedValues(obj);
	obj.style.left = a[0] + "px";
	obj.style.top = a[1] + "px";
};

var usefullArea = function() {
	var r = [];
	r['x'] = self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0;
	r['y'] = self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0;
	return r;
};

var scrolledUntil = function() {
	var r = [];
	r['x'] = self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
	r['y'] = self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
	return r;
}

var addCss = function(src){
	var head = $t("head")[0];
	var s = $t("link[href="+src+"]", head);

	if(s.length) return true;
	cE("link", head, null,
		{ rel: "stylesheet", href: src } );
	return true;
};

var classExists = function(el , cl){ if(!el.className) return false; return el.className.indexOf(cl)!=-1; }
var addClass = function( el , cn ){ if(classExists( el , cn )) return; el.className += ' '+ cn; }
var removeClass = function( el , cn ){ if(!classExists( el , cn )) return; var er = new RegExp( '\s?'+ cn, 'g'); el.className = el.className.replace( er , '' ) }
function getStyle(el,styleProp)
{
	var x = (typeof el == 'string') ? $(el) : el;
	if(!isMOZILLA)
	{
		var t = styleProp.split('-');
		if(t.length>1) styleProp=t[0]+t[1].substring(0,1).toUpperCase()+t[1].substring(1);
	}
	if (x.currentStyle)
		return x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		return document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
}

/* DOM */
var DOM = {
	corType: function(t, at) { /*IE*/
		if(isMSIE && at!=null) {
			var c = (at['name']) ? 'name="'+at['name']+'" ' : '';
			c += (at['enctype']) ? 'enctype="'+at['enctype']+'" ' : '';
			if(!empty(c))
				return '<'+t+' '+c+'>';
		}
		return t;
	},

	createAndAttach: function(_type, _target, _id, _attr, _before) { // style e class bugam o ie
		_target = (typeof _target == "string") ? $(_target) : _target ;
		_type = DOM.corType(_type, _attr);
		var createdElement = document.createElement(_type);
		if(_attr!=null) {
			for (var a in _attr)
				createdElement.setAttribute(a, _attr[a]);
		}
		if(isset(_id)) {
			if(typeof _id == 'object') {
				var nid = _id.getAttribute('id');
				_target.replaceChild(createdElement, _id);
				_id = nid;
			}
			createdElement.setAttribute("id", _id);
		}
		if(_before!=null) _target.insertBefore(createdElement, _before);
		else {
			_target.appendChild(createdElement);
		}
		return createdElement;
	},

	create: function(type/*,attribs*/){
		var ce, i, at;
		type = DOM.corType(type, arguments[1]);
		ce = document.createElement(type);
		if(at = arguments[1]) {
			for(var i in at)
				ce.setAttribute(i, at[i]);
		}
		return ce;
	},

	rem: function() {
		for(var i=0, a; i<arguments.length; i++)
		{
			a=arguments[i];
			a = typeof a == 'string' ? $(a) : a ;
			if(!a) continue;
			a.parentNode.removeChild(a);
		}
	},

	isChildOf: function(e, a)
	{
		if(!e || !a) return false;
		var pn = e.parentNode;
		while( pn!==a && pn!=null )
		{
			pn = pn.parentNode;
		}
		return pn;
	},
	before: function(e, a) { a.parentNode.insertBefore(e,a); },
	inside: function(e, a) { a.appendChild(e); },
	after: function(e, a) { a.parentNode.insertBefore(e,a.nextSibling); },

	replace: function(search,replace) {
		DOM.before(replace,search);
		DOM.rem(search);
		return replace;
	}
}
/* eventos */
var addListener = function() {
	if ( window.addEventListener ) {
		return function(el, type, fn) {
			el.addEventListener(type, fn, false);
		};
	} else if ( window.attachEvent ) {
		return function(el, type, fn) {
			el[type+fn] = function() {
				fn.call(el, event);
			};
			el.attachEvent( 'on'+type, el[type+fn] );
		};
	} else {
		return function(el, type, fn) {
			el['on'+type] = fn;
		}
	}
}();

var remListener = function() {
	if ( window.removeEventListener )
	{
		return function(el, type, fn) {
			el.removeEventListener(type, fn, false);
		};
	}
	else if ( window.detachEvent ) {
		return function(el, type, fn) {
			el.detachEvent( 'on'+type, el[type+fn] );
			el[type+fn] = null;
		};
	} else {
		return function(el, type, fn) {
			el['on'+type] = null;
		}
	}
}();

var Evt = {
	add: function(target, type, fn) {
		type = type.split(',');
		for(var i=0; i<type.length; i++)
			addListener(target, type[i], fn);
	},

	rem: function(target, type, fn) {
		type = type.split(',');
		for(var i=0; i<type.length; i++)
			remListener(target, type[i], fn);
	},

	cancel: function(evt) {
		if(!evt){ return false; }
		if(evt.preventDefault){
			evt.stopPropagation();
			evt.preventDefault();
		}else{
			if(window.event){
				window.event.cancelBubble = true;
				window.event.returnValue = false;
			}
		}
		return false;
	},

	keyCode: function(e){
		e = (!e) ? window.event : e;
		var code;
		if (e.keyCode) code = e.keyCode;
		if (e.which) code = e.which;
		return code;
	}
}


var onElementLoad = function( elementName , fc )
{
	var el = $(elementName);
	if( el || bodyLoad.loaded ) return fc( el );
	setTimeout( function(){ onElementLoad(elementName, fc); }, 100 );
}

var bodyLoad = {
	after: [],
	afterContent: [],
	loaded:false,

	add: function (fn/*, window.onload */)
	{
		if(!arguments[1]) bodyLoad.afterContent.push(fn);
		else bodyLoad.after.push(fn);
	},

	load: function ()
	{
		bodyLoad.onContent(function() { bodyLoad.exec(bodyLoad.afterContent); bodyLoad.afterContent = []; });

		if(!window.onload) window.onload = function() { bodyLoad.exec(bodyLoad.after); bodyLoad.after=[]; }
		else {
			var o = window.onload;
			window.onload = function() {
				o();
				bodyLoad.exec(bodyLoad.after);
				bodyLoad.after = [];
				bodyLoad.loaded=true;
			};
		}
	},

	exec: function(a)
	{
		if(!a) return;
		for( var i=0; i<a.length; i++ )
			a[i]();
	},

	onContent: function(f)
	{
		var a,b=navigator.userAgent,d=document,w=window,
		c="__onContent__",e="addEventListener",o="opera",r="readyState",
		s="<scr".concat("ipt defer src='//:' on",r,"change='if(this.",r,"==\"complete\"){this.parentNode.removeChild(this);",c,"()}'></scr","ipt>");
		w[c]=(function(o){return function(){w[c]=function(){};for(a=arguments.callee;!a.done;a.done=1)f(o?o():o)}})(w[c]);
		if(d[e])d[e]("DOMContentLoaded",w[c],false);
		if(/WebKit|Khtml/i.test(b)||(w[o]&&parseInt(w[o].version())<9))
		(function(){/loaded|complete/.test(d[r])?w[c]():setTimeout(arguments.callee,1)})();
		else if(/MSIE/i.test(b))d.write(s);
	}
}

bodyLoad.load();

//window.onerror = null;

var cE = DOM.createAndAttach;


URL = '';
if(!empty(s = $t("script")))
	URL = s[0].src.toString().split("js/core/")[0];

CORE = {
	uri: URL,
	language: $t('html',document)[0].getAttribute('lang')
};