﻿/* 20100414-1140 */
try {
		
document.write(
	'<script type="text/javascript">'+
		'window.onerror = function(description, file, line){'+
			'var msg = ""+'+
			'"[SyntaxError] -> " + description +'+
			'" -> Arquivo: " + file +'+
			'" -> Linha: " + line;'+
			
			'if(modMan) modMan.log.critical(msg);'+
			'else if(window.console) {console.log(msg);}'+
			//'else {(msg);}'+
			'else throw new Error(msg);'+
			
			//'return true;'+
		'}'+
	'</script>'
);
	
var modMan = function($){
	//=-=-=-=-=-=-=-=-=-=-
	// Local variables
	//=-=-=-=-=-=-=-=-=-=-
	var details = {
		coreVersion:2,
		lastUpdate:"20100414-1140",
		startupTime:new Date().getTime()
	}
	
	var globals = {}; // Stores section configs and shared observers
	
	
	// Error messages
	var errorMsgs = {
		defaultLNG:"br",
		br:{
			otherFrameworkFound:"modMan uses jQuery and cant work with other frameworks."
		},
		en:{
			otherFrameworkFound:"modMan uses jQuery and cant work with other frameworks."
		}
	}
	
	// Controlled Vocabulary
	var controlled = {
		defaultLNG:'br',
		defaultRGN:'BR',
		LNG:{
			br:{
				loading:"carregando"
			},
			en:{
				loading:"loading"
			},
			es:{
				loading:"cargando"
			}
		},
		RGN:{
			BR:{
				portalURL:"http://www.terra.com.br/"
			}
		}
	}	
	
	var dsvHosts = [
		{ domainMatchEXP:/^.+\/(portal\/hlg\/atm|webdev_hlg)\/\d\//i, redirect:false, type:"DSV" },
		{ domainMatchEXP:/^.+\/entregas\/[\d-]+\//i, redirect:false, type:"DSV" },
		{ domainMatchEXP:/^.+mainsite.int.[^\.]+.terra.com.br\/portal\//i, redirect:false, type:"DSV" },
		{ domainMatchEXP:/^.+(hlg.trrsf|(templates|(dev|dsv|hlg)-vgn).+terra)\./i, redirect:'http://hlg.trrsf.com.br/atm/2/core/2/', type:"HLG" }
	]
		
	/** 
	@updated 20100414-1140
	Base GMT extracted from: 
	- http://www.timeanddate.com/worldclock/ 
	- http://24timezones.com/
	
	* country codes expressed in ISO 3166-1 Alpha-2
	**/
	var Regions = {
		// HorÃ¡rio de verÃ£o suspenso temporariamente
		//AR:{id:1, isoCode:"AR", lang:"es", flag:"ARG", gmt:-180, domainMatchEXP:/\.?ar[\.-]|\.ar\//i, portalURL:"http://www.terra.com.ar/", dst:{gmt:-120, startLocalTimeStamp:"20091018-0000", endLocalTimeStamp:"20100315-0000"}},
		AR:{id:1, isoCode:"AR", lang:"es", flag:"ARG", gmt:-180, domainMatchEXP:/\.?ar[\.-]|\.ar\//i, portalURL:"http://www.terra.com.ar/"},
		BR:{id:2, isoCode:"BR", lang:"pt", flag:"BRA", gmt:-180, domainMatchEXP:/\.?br[\.-]|pt-br|\.br\//i, portalURL:"http://www.terra.com.br/", dst:{gmt:-120, startLocalTimeStamp:"20091018-0000", endLocalTimeStamp:"20100221-0000"}},
		CA:{id:19, isoCode:"CA", lang:"en", flag:"CAN", gmt:-480, dst:{gmt:-420, startLocalTimeStamp:"20100314-0200", endLocalTimeStamp:"20101107-0200"}},
		CL:{id:3, isoCode:"CL", lang:"es", flag:"CHI", gmt:-240, domainMatchEXP:/\.?cl[\.-]|\.cl\//i, portalURL:"http://www.terra.cl/", dst:{gmt:-180, startLocalTimeStamp:"20101010-0000", endLocalTimeStamp:"20110404-0000"}},
		CO:{id:4, isoCode:"CO", lang:"es", flag:"COL", gmt:-300, domainMatchEXP:/\.?co[\.-]|\.co\//i, portalURL:"http://www.terra.com.co/"},
		CR:{id:10, isoCode:"CR", lang:"es", flag:"COS", gmt:-360, domainMatchEXP:/\.?cr[\.-]|\.cr\//i, portalURL:"http://www.terra.com/"},
		DO:{id:17, isoCode:"DO", lang:"es", flag:"REP", gmt:-240, domainMatchEXP:/\.?do[\.-]|\.do\//i, portalURL:"http://www.terra.com/"},
		EC:{id:5, isoCode:"EC", lang:"es", flag:"ECU", gmt:-300, domainMatchEXP:/\.?ec[\.-]|\.ec\//i, portalURL:"http://www.terra.com.ec/"},
		ES:{id:18, isoCode:"ES", lang:"es", flag:"ESP", gmt:60, domainMatchEXP:/\.?es[\.-]terra|\.es\//i, portalURL:"http://www.terra.com.es/", dst:{gmt:120, startLocalTimeStamp:"20100328-0200", endLocalTimeStamp:"20101031-0300"}},
		GT:{id:11, isoCode:"GT", lang:"es", flag:"GUA", gmt:-360, domainMatchEXP:/\.?gt[\.-]|\.gt\//i, portalURL:"http://www.terra.com/"},
		HN:{id:12, isoCode:"HN", lang:"es", flag:"HON", gmt:-360, domainMatchEXP:/\.?hn[\.-]|\.hn\//i, portalURL:"http://www.terra.com/"},
		MX:{id:7, isoCode:"MX", lang:"es", flag:"MEX", gmt:-360, domainMatchEXP:/\.?mx[\.-]|\/es\/|\.mx\//i, portalURL:"http://www.terra.com.mx/", dst:{gmt:-300, startLocalTimeStamp:"20100404-0200", endLocalTimeStamp:"20101031-0200"}}, // default for spanish
		NI:{id:13, isoCode:"NI", lang:"es", flag:"NIC", gmt:-360, domainMatchEXP:/\.?ni[\.-]|\.ni\//i, portalURL:"http://www.terra.com/"},
		PA:{id:14, isoCode:"PA", lang:"es", flag:"PAN", gmt:-300, domainMatchEXP:/\.?pa[\.-]|\.pa\//i, portalURL:"http://www.terra.com/"},
		PE:{id:8, isoCode:"PE", lang:"es", flag:"PER", gmt:-300, domainMatchEXP:/\.?pe[\.-]|\.pe\//i, portalURL:"http://www.terra.com.pe/"},
		PR:{id:16, isoCode:"PR", lang:"es", flag:"POR", gmt:-240, domainMatchEXP:/\.?pr[\.-]|\.pr\//i, portalURL:"http://www.terra.com/"},
		SV:{id:15, isoCode:"SV", lang:"es", flag:"SAL", gmt:-360, domainMatchEXP:/\.?sv[\.-]|\.sv\//i, portalURL:"http://www.terra.com/"},
		VE:{id:9, isoCode:"VE", lang:"es", flag:"VEN", gmt:-270, domainMatchEXP:/\.?ve[\.-]|\.ve\//i, portalURL:"http://www.terra.com.ve/"},
		US:{id:6, isoCode:"US", lang:"en", flag:"USA", gmt:-300, domainMatchEXP:/(\.?us[\.-])?.+\.com\/|\/en\//i, portalURL:"http://www.terra.com/", dst:{gmt:-240, startLocalTimeStamp:"20100314-0200", endLocalTimeStamp:"20101107-0200"}},
		ZA:{id:20, isoCode:"ZA", lang:"en", flag:"ZAF", gmt:120}
	}
	
	var Library = {
		modules:{
			baseDIR:"apps/",
			modCommunities:{ scriptPath:"communities/_js/modCommunities.js", currentVersion:"20090526-1357" },
			modMoreNews:{ scriptPath:"morenews/_js/modMoreNews.js", currentVersion:"20090526-1357" },
			modClock:{ scriptPath:"clock/_js/moduleCore.js", currentVersion:"20090526-1357" },
			modTimer:{ scriptPath:"timer/_js/moduleCore.js", currentVersion:"20090526-1357" },
			modFeaturedMedia:{ scriptPath:"featuredmedia/_js/modFeaturedMedia.js", currentVersion:"20090526-1357" },
			modFootballDirectory:{ scriptPath:"footballdirectory/_js/modFootballDirectory.js", currentVersion:"20090526-1357"},
			modChampionship:{ scriptPath:"championship/_js/modChampionship.js", currentVersion:"20090526-1357" },
			modTeams:{ scriptPath:"teams/_js/modTeams.js", currentVersion:"20090526-1357" },
			modSonora:{ scriptPath:"sonora/_js/modSonora.js", currentVersion:"20090526-1357" },
			modTerraTv:{	scriptPath:"terratv/_js/modTerraTv.js",currentVersion:"20090526-1357" },
			modMulti: { scriptPath:"multi/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modHeaderFooter:{ scriptPath:"headerfooter/_js/modHeaderFooter.js", currentVersion:"20090526-1357"},
			modHeaderAux:{ scriptPath:"headeraux/_js/modHeaderAux.js", currentVersion:"20091014-1420"},
			modAudienceHorizontal:{ scriptPath:"audiencepulse_hor/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modAudiencePulseVertical:{ scriptPath:"audiencepulse_ver/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modPoll:{ scriptPath:"poll/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modFanzone:{ scriptPath:"fanzone/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modFanzoneFull:{ scriptPath:"fanzone_full/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modPhotoGallery:{ scriptPath:"photoGallery/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modExpandedPicsPlayer:{ scriptPath:"expandedPics/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modTeams:{ scriptPath:"teams/_js/modTeams.js", currentVersion:"20090526-1357" },
			modUserTeam:{ scriptPath:"soccer/userTeam/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modTop20:{ scriptPath:"soccer/top20/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modUserTeamField:{ scriptPath:"soccer/userSelecao/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modLatestNews:{ scriptPath:"latestnews/_js/moduleCore.js", currentVersion:"20090727-1638"},
			modSendFriends:{ scriptPath:"sendFriends/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modToolF1:{ scriptPath:"toolF1/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modSpotlightpics:{ scriptPath:"spotlightPics/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modHoroscope:{ scriptPath:"horoscope/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modNewspapersAndMagazines:{ scriptPath:"newspapers_and_magazines/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modNavigation:{ scriptPath:"navigation/_js/moduleCore.js", currentVersion:"20090526-1357"},

			modPlayList:{ scriptPath:"music/playlist/_js/moduleCore.js", currentVersion:"20091014-1420"},

			modArtistSonora:{ scriptPath:"music/sonora/_js/moduleCore.js", currentVersion:"20091027-1900"},

			modConsole:{ scriptPath:"console/_js/modConsole.js", currentVersion:"20090607-1744"},

			modPhotos24h:{ scriptPath:"photos24h/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modPPI:{ scriptPath:"ppi/_js/moduleCore.js", currentVersion:"20090526-1357"},
			modTwitterFollowers:{ scriptPath:"twitter/followers/_js/moduleCore.js", currentVersion:"20090831-1000"},

			terraTvLive:{	scriptPath:"terratv_live/_js/terraTvLive.js",currentVersion:"20090526-1357" },

			europeanFootball_games:{ scriptPath:"europeanfootball/games/_js/moduleCore.js", currentVersion:"20090626-1700"},
			europeanFootball_classification:{ scriptPath:"europeanfootball/classification/_js/moduleCore.js", currentVersion:"20090626-1700"},
			
			modWeather:{ scriptPath:"weather/_js/moduleCore.js", currentVersion:"20090526-1357" },
			modMaps:{ scriptPath:"google_maps/_js/moduleCore.js", currentVersion:"20090911-1730" },
			
			modPopularity:{ scriptPath:"popularity/_js/moduleCore.js", currentVersion:"20091202-1545" },
			modMoreLessPopular:{ scriptPath:"morelessPopular/_js/moduleCore.js", currentVersion:"20091202-1545" },      
			modThermometerPoll:{ scriptPath:"thermometerPoll/_js/modThermometerPoll.js", currentVersion:"20091203-1555" },
			modWeekParticipants:{ scriptPath:"weekParticipants/_js/modWeekParticipants.js", currentVersion:"20091204-1518" },
			modPopularityResume:{ scriptPath:"popularityResume/_js/moduleCore.js", currentVersion:"20091222-2040" }
		},
		helpers:{
			baseDIR:"_js/",
			dateOBJ:{
				scriptPath:"helper.dateOBJ.js",
				description:"Possui mÃ©todos para converter datas entre diferentes GTMs."
			},
			arrayOBJ:{
				scriptPath:"helper.arrayOBJ.js",
				description:"Possui mÃ©todos para reorganizar arrays."
			},
			stringOBJ:{
				scriptPath:"helper.stringOBJ.js",
				description:"Possui mÃ©todos para tratar strings."
			}
		},
		plugins:{
			baseDIR:"_js/",
			trrListCarousel:{
				scriptPath:"jquery.trrListCarousel.js",
				description:"Monta carrossel a partir de listas."
			},
			jprint:{
				scriptPath:"jquery.jprint.js",
				description:"Imprime o conteÃºdo de uma Layer"
			},
			zoomimagethumb:{
				scriptPath:"jquery.zoomimagethumb.js",
				description:"Cria efeito de layer sobreposta em mouse-over."
			},
			jcarousel_lite:{
				scriptPath:"jquery.jcarousel_lite.js",
				description:"http://www.gmarwaha.com/jquery/jcarousellite/index.php#what"
			},
			elementposition:{
				scriptPath:"jquery.elementposition.js",
				description:"http://www.gmarwaha.com/jquery/jcarousellite/index.php#what"
			},
			checkbox:{
				scriptPath:"jquery.checkbox.radiobutton.js",
				description:"http://www.gmarwaha.com/jquery/jcarousellite/index.php#what"
			},
			clickout:{
				scriptPath:"jquery.clickout.js",
				description:"http://www.gmarwaha.com/jquery/jcarousellite/index.php#what"
			},
			combobox:{
				scriptPath:"jquery.combobox.js",
				description:"http://www.gmarwaha.com/jquery/jcarousellite/index.php#what"
			},
			jqdnr:{
				scriptPath:"jquery.jqdnr.js",
				description:"http://www.gmarwaha.com/jquery/jcarousellite/index.php#what"
			},
			scrolling:{
				scriptPath:"jquery.scrolling.js",
				description:"http://www.gmarwaha.com/jquery/jcarousellite/index.php#what"
			},
			tabs:{
				scriptPath:"jquery.tabs.js",
				description:"http://www.gmarwaha.com/jquery/jcarousellite/index.php#what"
			},
			wheel:{
				scriptPath:"jquery.wheel.js",
				description:"http://www.gmarwaha.com/jquery/jcarousellite/index.php#what"
			},
			thickbox:{
				scriptPath:"jquery.thickbox.js",
				description:"For modal pop ups"
			},
			cookie:{
				scriptPath:"jquery.cookie.js",
				description:"For cookie in interface"
			},
			uicore:{
				scriptPath:"jquery.ui.core.js",
				description:"To support widgets interface jquery"
			},
			uidraggable:{
				scriptPath:"jquery.ui.draggable.js",
				description:"To drag interface elements"
			}
		},
		components:{
			combobox:{
				plugins:['jqdnr', 'elementposition', 'wheel', 'scrolling', 'clickout', 'combobox']
			},
			scrolling:{
				plugins:['jqdnr','elementposition', 'wheel', 'scrolling']
			}
		}
	}
	// Local variables //

	
	// ForÃ§ando renovaÃ§Ã£o de cache no safari
	if($.browser.safari) $.useBrowserCache = false;
	
	
	//=-=-=-=-=-=-=-=-=-
	// Section configs
	//=-=-=-=-=-=-=-=-=-
	(function(){
		
		// Stage detection >>
		var stageType = "PRD",
			baseURL = function(){
			for (var i = 0, currentHost; currentHost = dsvHosts[i]; i++){
				var detected = currentHost.domainMatchEXP.exec(document.location);
				if(detected && currentHost.type) {
					stageType = currentHost.type;					
					return currentHost.redirect || detected[0].replace(/\/$/,'') + '/core/'+ details.coreVersion+'/';
				}
			}
			
			//return (pageCountry == "BR") ? "http://s1.trrsf.com.br/atm/2/core/" + details.coreVersion + '/': "http://s1.trrsf.com/atm/2/core/" + details.coreVersion + '/';
			return (pageCountry == "BR") ? "http://stf.terra.com.br/portal/core/" + details.coreVersion + '/': "http://stf.terra.com/portal/core/" + details.coreVersion + '/';
		}();

		// Locale detection >>
		var autoDetectedCountryOBJ = function(){
			if(stageType == "PRD"){
				for (var isoCode in Regions){
					if(Regions[isoCode].domainMatchEXP && Regions[isoCode].domainMatchEXP.test(document.location)) {
						return Regions[isoCode];
					}
				}
			}
			// trying to extract country code from document lang attribute
			var documentLang = document.getElementsByTagName('html')[0].getAttribute('lang'),
				countryCodeExtractedFromDocument = (documentLang && documentLang.match(/\w\w/g)[1]) ? documentLang.match(/\w\w/g)[1].toUpperCase() : null;
			
			return Regions[countryCodeExtractedFromDocument] || Regions['BR'];
		}();

		var userAgentLocale = (navigator.language) ? navigator.language : navigator.userLanguage,
			userLang = userAgentLocale.split('-')[0].toLowerCase(),
			userCountry = typeof(userAgentLocale.split('-')[1]) != "undefined" ? userAgentLocale.split('-')[1].toUpperCase() : userAgentLocale.toUpperCase(),
			
			pageCountry = autoDetectedCountryOBJ.isoCode,
			pageLang = autoDetectedCountryOBJ.lang,
			
			locale = pageLang + '-' + pageCountry,
			
			contextId = (window.trrConstantData && window.trrConstantData.configs) ? window.trrConstantData.configs.contextId : undefined;
		
		//var underTerra = (/\.terra\.|stages\.com\.br/i).test(document.domain);
		var underTerra = false;
		
		// Converting exeptions
		if(userCountry == 'AR') userLang = 'ar';
		if(userCountry == 'BR') userLang = 'br';
		
		// FlashDetect
		// http://www.featureblend.com/license.txt
		if(!FlashDetect) var FlashDetect=new function(){var self=this;self.installed=false;self.raw="";self.major=-1;self.minor=-1;self.revision=-1;self.revisionStr="";var activeXDetectRules=[{"name":"ShockwaveFlash.ShockwaveFlash.7","version":function(obj){return getActiveXVersion(obj);}},{"name":"ShockwaveFlash.ShockwaveFlash.6","version":function(obj){var version="6,0,21";try{obj.AllowScriptAccess="always";version=getActiveXVersion(obj);}catch(err){}; return version;}},{"name":"ShockwaveFlash.ShockwaveFlash","version":function(obj){return getActiveXVersion(obj);}}];var getActiveXVersion=function(activeXObj){var version=-1;try{version=activeXObj.GetVariable("$version");}catch(err){}; return version;};var getActiveXObject=function(name){var obj=-1;try{obj=new ActiveXObject(name);}catch(err){}; return obj;};var parseActiveXVersion=function(str){var versionArray=str.split(",");return{"raw":str,"major":parseInt(versionArray[0].split(" ")[1],10),"minor":parseInt(versionArray[1],10),"revision":parseInt(versionArray[2],10),"revisionStr":versionArray[2]};};var parseStandardVersion=function(str){var descParts=str.split(/ +/);var majorMinor=descParts[2].split(/\./);var revisionStr=descParts[3];return{"raw":str,"major":parseInt(majorMinor[0],10),"minor":parseInt(majorMinor[1],10),"revisionStr":revisionStr,"revision":parseRevisionStrToInt(revisionStr)};};var parseRevisionStrToInt=function(str){return parseInt(str.replace(/[a-zA-Z]/g,""),10)||self.revision;};self.majorAtLeast=function(version){return self.major>=version;};self.FlashDetect=function(){if(navigator.plugins&&navigator.plugins.length>0){var type='application/x-shockwave-flash';var mimeTypes=navigator.mimeTypes;if(mimeTypes&&mimeTypes[type]&&mimeTypes[type].enabledPlugin&&mimeTypes[type].enabledPlugin.description){var version=mimeTypes[type].enabledPlugin.description;var versionObj=parseStandardVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revisionStr=versionObj.revisionStr;self.revision=versionObj.revision;self.installed=true;}}else if(navigator.appVersion.indexOf("Mac")==-1&&window.execScript){var version=-1;for(var i=0;i<activeXDetectRules.length&&version==-1;i++){var obj=getActiveXObject(activeXDetectRules[i].name);if(typeof obj=="object"){self.installed=true;version=activeXDetectRules[i].version(obj);if(version!=-1){var versionObj=parseActiveXVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revision=versionObj.revision;self.revisionStr=versionObj.revisionStr;}}}}}();};FlashDetect.release="1.0.3";
		
		// Set free section configs
		globals = {
			data:{
				log:[],
				feeds:{},
				instances:{}
			},
			stage:{
				type:stageType,
				debugging:(/debug/).test(document.location)
			},
			page:{
				contextId:contextId,
				lang:pageLang,
				country:pageCountry,
				underTerra:underTerra,
				baseURL:baseURL,
				portalURL:autoDetectedCountryOBJ.portalURL,
				startupTime:details.startupTime,
				transitionEffects:false
			},
			user:{
				lang:userLang,
				country:userCountry,
				flash:{
					installed:FlashDetect.installed,
					version:FlashDetect.major
				}
			},
			regions:Regions
		}
		
	})(); // Just once
	
	var Log = new function(moduleId){
		var stack = globals.data.log = [],
			foundCriticalErrors = false;

		this.CONSTRUCTOR = function(moduleId){
			var profile = moduleId || "System Message";
			var instanceStartupTime = new Date().getTime();
					
			var insertMsg = function(type, text){
				var logOBJ = {
					instanceCheckpoint:new Date().getTime() - instanceStartupTime,
					sessionCheckpoint:new Date().getTime() - globals.page.startupTime,
					profile:profile,
					type:type,
					message:text
				}
				stack.push(logOBJ);
				
				if(globals.data.instances.modConsole) updateConsole();
			}
					
			var updateConsole = function(){
				globals.data.instances.modConsole[0].report();
			}
			
			this.checkpoint = function(text) { insertMsg('checkpoint', text); return undefined; }
			this.warning = function(text) { insertMsg('warning', text); return undefined; }
			this.critical = function(text) { insertMsg('critical', text); if(window.console && !foundCriticalErrors && globals.stage.debugging){foundCriticalErrors = true; console.log("Erro(s) crÃ­tico(s) encontrado(s). Acione o console para verificar mais detalhes."); } return undefined; }
			
			this.trace = function(text) { insertMsg('trace', text); return undefined; }
			this.help = function(text) { insertMsg('help', text); return undefined; }
		}
		return undefined;	
	}
	var log = new Log.CONSTRUCTOR();
	
	// Include Plugin
	(function($){ $.extend({ ImportBasePath:globals.page.baseURL,convert2absolutePath:function(includePath){if((/^(http:\/\/|www\.)/).test(includePath)) return includePath;var base = document.location.toString().replace(/[^\/]+$/,''),fileRealPath = includePath.replace(/\.\.\//g,'');if((/^\//).test(includePath)) return (document.domain) ? document.domain + includePath : globals.page.baseURL + includePath;if((/^\.\.\//).test(includePath)){var backDirectories = includePath.match(/(\.\.\/)/g).length;for (var i = 0; i < backDirectories; i++){base = base.replace(/\/$/,'').replace(/[^\/]+$/,'');}}return base + fileRealPath;},useBrowserCache:true, loadedFiles:{}, fileinfo:function(data){ data=data.replace(/^\s|\s$/g,""); var m; if(/\.\w+$/.test(data)){ m=data.match(/([^\/\\]+)\.(\w+)$/); if(m){ if(m[2]=='js'){ return{ filename:m[1], ext:m[2], tag:'script' } } else if(m[2]=='css'){ return { filename:m[1], ext:m[2], tag:'link' } } else { return { filename:m[1], ext:m[2], tag:null } } } else { return { filename:null, ext:null } } } else { m=data.match(/([^\/\\]+)$/); if(m){ return { filename:m[1], ext:null, tag:null } } else { return { filename:null, ext:null, tag:null } } } }, checkTemplate:function(){ $.loadedFiles['link'] = {}; var elementsArray=document.getElementsByTagName('link'); for(var i=0;i<elementsArray.length;i++){ if(elementsArray[i].getAttribute('rel').toLowerCase()=='stylesheet' && elementsArray[i].getAttribute('href')){ $.loadedFiles.link[$.convert2absolutePath(elementsArray[i].getAttribute('href'))] = true; } } $.loadedFiles['script'] = {}; var elementsArray=document.getElementsByTagName('script'); for(var i=0;i<elementsArray.length;i++){ if (((/javascript/i).test(elementsArray[i].getAttribute('type')) || (/javascript/i).test(elementsArray[i].getAttribute('language'))) && elementsArray[i].getAttribute('src')){ $.loadedFiles.script[$.convert2absolutePath(elementsArray[i].getAttribute('src'))] = true; } } }, fileExist:function(filename,filetype,attrCheck){if($.loadedFiles[filetype][$.ImportBasePath+filename]) {return true;} else {return false;} }, createElement:function(filename,filetype){ switch(filetype){ case'script': if(!$.fileExist(filename,filetype,'src')){ var src = $.ImportBasePath+filename;  $.loadedFiles.script[src] = true; if(!$.useBrowserCache) { src += ((/\?/).test(src)) ? '&' : '?'; src += 'c_' + new Date().getTime();} var scriptTag=document.createElement(filetype); scriptTag.setAttribute('language','javascript'); scriptTag.setAttribute('type','text/javascript'); scriptTag.setAttribute('src',src); scriptTag.setAttribute('charset','UTF-8'); modMan.log.checkpoint('Including new JS:\n ' + $.ImportBasePath+filename); return scriptTag } else { return false } break; case'link': if(!$.fileExist(filename,filetype,'href')){ var href = $.ImportBasePath+filename; $.loadedFiles.link[href] = true; if(!$.useBrowserCache) { href += ((/\?/).test(href)) ? '&' : '?'; href += 'c_' + new Date().getTime();} var styleTag=document.createElement(filetype); styleTag.setAttribute('type','text/css'); styleTag.setAttribute('rel','stylesheet'); styleTag.setAttribute('href',href); $.loadedFiles.link[$.ImportBasePath+filename] = true; modMan.log.checkpoint('Including new CSS:\n ' + $.ImportBasePath+filename); return styleTag } else { return false } break; default: return false; break } }, cssReady:function(index,callback){ function check(){ if(document.styleSheets[index]){ if(typeof callback=='function'){callback()} window.clearInterval(checkInterval) } } var checkInterval=window.setInterval(check,200) }, include:function(file,callback){ var headerTag=document.getElementsByTagName('head')[0]; var fileArray=[]; typeof file=='string'?fileArray[0]=file:fileArray=file; for(var i=0;i<fileArray.length;i++){ var elementTag=$.fileinfo(fileArray[i]).tag; var el=[]; if(elementTag!==null){ el[i]=$.createElement(fileArray[i],elementTag); if(el[i]){ headerTag.appendChild(el[i]); if(typeof callback=='function' && i == fileArray.length - 1){ if($.browser.msie){ el[i].onreadystatechange=function(){ if(this.readyState==='complete' || this.readyState==='loaded'){ callback(); } } } else { if(elementTag =='link'){ $.cssReady(i,callback) } else { el[i].onload=function(){ callback(); } } } } } else if (i == fileArray.length - 1 && typeof callback=='function'){ callback(); } } else { return false } } } }); $.checkTemplate(); })(jQuery);

	
	
	var load = function(){
		//-+-+-+-+-+-+-+-+
		// Local VARS
		//-+-+-+-+-+-+-+-+
		var firstLoad = true,
			modulesQueue = [],
			modTypeInProgress = [],
			loaded = {};
		// Local VARS //
	
		var modules = function(modulesOBJ){
			var modByType = {};
			
			// Validation loop
			for(var no = 0; no < modulesOBJ.length; no++){
				var mod = modulesOBJ[no];
				
				// Valide template
				if(!mod.selector || !$(mod.selector).length) {
					log.critical(mod.id + " - Elemento container nÃ£o localizado. O parÃ¢metro '<strong>selector</strong>' estÃ¡ incorreto ou nÃ£o foi especificado. Seu valor atual Ã©: <strong>" + mod.selector + "</strong>");
					continue;
				}
				
				// Check if there are permission for this module in the library
				if(!Library.modules[mod.id]) {
					log.critical(mod.id + " - Script nÃ£o encontrado na biblioteca.");
					continue;
				}
								
				if(!modByType[mod.id]) {
					modTypeInProgress.push(mod.id);
					modByType[mod.id] = [];
				}
				modByType[mod.id].push(mod);				
			}
			
			// Execution loop			
			for(var modType in modByType){
								
				var url = globals.page.baseURL + Library.modules.baseDIR + Library.modules[modType].scriptPath;
				log.checkpoint('Requisitando script para: ' + modType + '\n' + url);
				
				if(modType == 'modConsole'){
					$.include(url.replace(globals.page.baseURL, ''), function(){
							var moduleOBJ = window[modType],
								moduleID = moduleOBJ.info.id;
							log.checkpoint('Executando callback do: ' + moduleID);
							
							var modPrefs = modByType[moduleID].shift();
							
							
							var sameTypeQueue = modByType[moduleID],
								callModPrefs = !!!modTypeInProgress.length;
							
							//alert(modTypeInProgress.length + '\n' + moduleID + '\n' + callModPrefs);
							
							if (moduleOBJ.dependencies){
								log.checkpoint(moduleID + " - Avaliando prÃ©-requisitos para o seletor " + modPrefs.selector);
								components(moduleOBJ, modPrefs, sameTypeQueue);
							} else {
								modulesQueue.push(modPrefs);
							}
					
					});
				
				} else {
					new tools.jsonP({
						url:url,
						wrapperName:modType,
						cache:$.useBrowserCache,
						callback:function(moduleOBJ){
							var moduleID = moduleOBJ.info.id;
							log.checkpoint('Executando callback do: ' + moduleID);
							window[moduleID] = moduleOBJ;
							
							var modPrefs = modByType[moduleID].shift();
							
							
							var sameTypeQueue = modByType[moduleID];
							var callModPrefs = !!!modTypeInProgress.length;
							
							//alert(modTypeInProgress.length + '\n' + moduleID + '\n' + callModPrefs);
							
							if (moduleOBJ.dependencies){
								log.checkpoint(moduleID + " - Avaliando prÃ©-requisitos para o seletor " + modPrefs.selector);
								components(moduleOBJ, modPrefs, sameTypeQueue);
							} else {
								modulesQueue.push(modPrefs);
							}
						}
					});
				}
			}	
			
		}
		
		var components = function(modOBJ, modPrefs, sameTypeQueue){
			var loadSkin = modPrefs.loadSkin;
			var dependenciesOBJ = modOBJ.dependencies;
			var urlsOBJ = {};
			//alert('aqui \n' + modOBJ.name);
			
			
			if(dependenciesOBJ.underTerra && !globals.page.underTerra) {
				log.critical(modPrefs.id + ' - Este mÃ³dulo sÃ³ pode ser carregado sob o domÃ­nio do Terra');
				if(callModPrefs) preferences();
				return false;
			}
			
			if(dependenciesOBJ.flash && !globals.user.flash.installed) {
				log.warning(modPrefs.id + ' - Este mÃ³dulo precisa de flash para ser instanciado');
				if(callModPrefs) preferences();
				contingency(modPrefs);
				return false;
			}
			
			if(dependenciesOBJ && dependenciesOBJ.js){
				urlsOBJ['js'] = [];
				for(var type in dependenciesOBJ.js){
					var item = dependenciesOBJ.js[type],
						//base = globals.page.baseURL + Library[type].baseDIR;
						base = Library[type].baseDIR;
					
					if(typeof(item) == 'string') urlsOBJ['js'].push(baseURL + item);
					else if(typeof(item) == 'object' && item.length){
						for (var i = 0; i < item.length; i++){
							if(!Library[type][item[i]]) {
								log.critical(item[i] + ' - nÃ£o encontrado na biblioteca '+ type);
								return false;
							}
							var url =  base + Library[type][item[i]].scriptPath;
							urlsOBJ['js'].push(url);
						}
					}
					/* alert(
						'type : ' + type +'\n'+
						'itemName : ' + itemName +'\n'+
						'baseURL : ' + baseURL +'\n'
					); */
				}
				//alert(urlsOBJ.toSource());
				tools.Components.set(urlsOBJ, function(){
					var shift = modTypeInProgress.shift();
					//log.checkpoint('chamando internalTimer\n' + modPrefs.id);
					modulesQueue.push(modPrefs);
					if(sameTypeQueue.length) {
						for(var i = 0; i < sameTypeQueue.length; i++){
							modulesQueue.push(sameTypeQueue[i]);
						}
					}
					if(!modTypeInProgress.length) {
						//alert('chamando mÃ³dulos. logo apÃ³s ' + modPrefs.id);
						preferences();
					}
				});
			} else {				
				var shift = modTypeInProgress.shift();
				modulesQueue.push(modPrefs);
				if(sameTypeQueue.length) {
					for(var i = 0; i < sameTypeQueue.length; i++){
						modulesQueue.push(sameTypeQueue[i]);
					}
				}
				
				if(!modTypeInProgress.length) {
					preferences();
				}
			}
		}
		
		var play = function() {
			var now = function(modPrefs){
				//alert("play para " + modPrefs.id);
				
				var PARAMS = Interface(modPrefs);
				if (!PARAMS) new contingency(modPrefs);
				else {
					var extraTools = {
						log: new Log.CONSTRUCTOR(modPrefs.id),
						pageReloader:tools.pageReloader
					}
					
					try{
						extraTools.log.checkpoint("Creating new instance.");
						var instance = new window[modPrefs.id].CONSTRUCTOR(PARAMS, jQuery, extraTools);					
						if(!globals.data.instances[modPrefs.id]) globals.data.instances[modPrefs.id] = [];
							globals.data.instances[modPrefs.id].push(instance);
						
						loaded[modPrefs.id + '_' + modPrefs.selector] = true;
					} catch (errorOBJ){
						var msg = ""+
							"Erro ao instanciar mÃ³dulo: "+modPrefs.id+" \n"+
							'['+errorOBJ.name+'] -> '+errorOBJ.message + "\n" +
							"Arquivo: " + errorOBJ.fileName +'\n'+
							"Linha: " + errorOBJ.lineNumber;
						
						log.critical(msg);
					}
					
					if(!modulesQueue.length && globals.page.lazyLoad) {
						$(window).unbind('scroll');
					}
				}
				
			}
			
			var onViewPort = function(modPrefs){
				if($(modPrefs.selector + ":in-viewport").length) {
					play.now(modPrefs); 
				} else {
					log.checkpoint('scrolling');
					
					$(window).scroll(function() { 		
						if(!loaded[modPrefs.id + '_' + modPrefs.selector] && $(modPrefs.selector + ":in-viewport").length) {
							new play.now(modPrefs);
						}
					});
				}
			}

			return {
				now:now,
				onViewPort:onViewPort
			}
			
		}();
		
		var preferences = function(){
			//alert('em preferences: ' + modulesQueue.length + " itens");
				if(firstLoad){		
					$(document).ready(function(){
						while(modulesQueue.length){
							var modPrefs = modulesQueue.shift();
							if(globals.page.lazyLoad) new play.onViewPort(modPrefs);
							else play.now(modPrefs);
							
							if(!modulesQueue.length) firstLoad = false;
						}
					});			
				} else {
					while(modulesQueue.length){
						var modPrefs = modulesQueue.shift();
						play.now(modPrefs);					
					}
				}
		}
		
		var Interface = function (modPrefs){
			log.checkpoint(modPrefs.id + " - Analisando interface.");
			
			
			var moduleOBJ = window[modPrefs.id];
			
			//-+-+-+-+-+-+-+-+-+-+-+-+-+
			// Double-check for basic dependencies
			//-+-+-+-+-+-+-+-+-+-+-+-+-+
			if(!$(modPrefs.selector).length) {
				log.critical(modPrefs.id+' - Recipiente (DOM element) nÃ£o encontrado. Favor, verificar seletor e template.');
				return false;
			}
					
			// Checking for module object
			if(!moduleOBJ) {
				log.critical(modPrefs.id + ' - NÃ£o foi possÃ­vel localizar o script para este mÃ³dulo. Confirme a localizaÃ§Ã£o do js e o nome do objeto carregado.' )
				return false;
			}
			
			// Checking for constructor
			if (!moduleOBJ.CONSTRUCTOR){
				log.critical(modPrefs.id + ' - NÃ£o foi possÃ­vel localizar um construtor para este mÃ³dulo. Verifique se o objeto possui um mÃ©todo chamado "CONSTRUCTOR".' )
				return false;
			}	
			
			// Checking for contingency method
			/* if (!moduleOBJ.CONTINGENCY){
				log.warning(modPrefs.id + ' - Este mÃ³dulo nÃ£o possui um mÃ©todo de contingÃªncia. Em caso de erros, apenas o procedimento padrÃ£o serÃ¡ adotado.' );
			}	 */		
			// Double-check for basic dependencies //
			
			
			var PARAMS = {}; // private object - stores valid params		
		
			//-+-+-+-+-+-+-+-+-+-+-+-+-+

			// Validate specific PARAMS
			//-+-+-+-+-+-+-+-+-+-+-+-+-+
			if (moduleOBJ.params) {
				var params = {};
				if(modPrefs.params) params = $.extend({}, modPrefs.params);
				
				var defaults = moduleOBJ.params.defaults || {};
				
				if(defaults) params = $.extend(defaults, modPrefs.params);				
				
				if(window.trrConstantData && window.trrConstantData && window.trrConstantData[modPrefs.id]) {
					params =  $.extend(params, window.trrConstantData[modPrefs.id]);	
					var msg = '';
					for (var paramName in window.trrConstantData[modPrefs.id]) {
						if(msg) msg += '<br/>';
						msg += '<strong>'+paramName + '</strong>: ' + window.trrConstantData[modPrefs.id][paramName];
					}
					log.checkpoint('Preservando parÃ¢emtros definidos como constantes para o mÃ³dulo <em>'+modPrefs.id+'</em>, neste contexto:<br/>'+msg);
				}
				
				var needed = moduleOBJ.params.needed;
				if (needed) {
					// Check if there are instructions for needed params (help propertie)
					if (!moduleOBJ.params.helpMsg /*deprecated*/ && !moduleOBJ.params.help) {
						log.critical(modPrefs.id + ' - There are no help instructions for needed params. Create an "help" propertie inside that object.');
						return false;
					}
					// if none was set
					if (!params) {
						log.critical(modPrefs.id + ' - Requires some especific params. Documentation: ' + moduleOBJ.params.helpMsg);
						return false;
					}
					for (var paramName in needed){
						// Checking if the needed param was especified
						if(!params[paramName] && typeof(params[paramName]) != 'boolean' && params[paramName] != 0){
							log.critical(modPrefs.id + ' - Param missing: "' + paramName +'". It also should match this model: ' + needed[paramName]);
							return false;
						}
						if(typeof(needed[paramName]) == 'string'){
							switch(needed[paramName].toLowerCase()){
								// Validating normal strings
								case 'string':
									if (typeof(params[paramName]) == 'string') continue;
									else {
										log.critical(modPrefs.id + ' - ' + paramName + ' should be an string');
										return false;
									}
								break;							
								
								// Validating boolean
								case 'boolean':
									if (typeof(params[paramName]) == 'boolean') continue;
									else {
										log.critical(modPrefs.id + ' - "' + paramName + '" should be boolean');
										return false;
									}
								break;
								
								// Validating number
								case 'number':
									if (typeof(params[paramName]) == 'number') continue;
									else {
										log.critical(modPrefs.id + ' - ' + paramName + ' should be an number');
										return false;
									}
								break;
								
								// Validating array
								case 'array':
									if (typeof(params[paramName]) == 'object' && params[paramName].length) continue;
									else {
										log.critical(modPrefs.id + ' - ' + paramName + ' should be an array');
										return false;
									}
								break;
								
								// if its not one of these, but its still string
								default:
									// Double check for RegExp (FIrefox 2)
									if(needed[paramName].exec(params[paramName])) continue;
									log.critical(modPrefs.id + ' - Unknown specified type inside the string "' + paramName + '". Check the constructor object.');
									return false;
								break;
							}
						} else if(typeof(needed[paramName]) == 'object' && (/^\/.*\/.*/).exec(needed[paramName].toString())) {
							// Validating RegExp
							if(needed[paramName].exec(params[paramName])) continue;
							else{
								log.critical(modPrefs.id + ' - ' + paramName + ' should match this RegExp: ' + needed[paramName]);
								return false;
							}
						} else {
							// Double check for RegExp (FIrefox 2)
							if(needed[paramName].exec(params[paramName])) continue;
							log.critical(modPrefs.id + ' - Unknown specified type for "' + paramName + '". Check the constructor object.');
							return false;
						}
					}
				}
				
				// If everything is alright
				for(var paramName in params){
					PARAMS[paramName] = params[paramName];
				}
				log.checkpoint(modPrefs.id + ' - ParÃ¢metros OK.');
			}
			// Validate specific PARAMS //
			
			
			//-+-+-+-+-+-+-+-+-+-+-+-+-+
			// Adjust module language and region
			//-+-+-+-+-+-+-+-+-+-+-+-+-+
			PARAMS["LNG"] = {};
			PARAMS["RGN"] = {};
			if (moduleOBJ.locale) {
				// LNG
				if(moduleOBJ.locale.LNG) {
					var primaryLNG = moduleOBJ.locale.LNG[globals.page.lang],
						secondaryLNG = moduleOBJ.locale.LNG[globals.page.locale];
					
					// dealing with exception language definitions (forgiving deprecated ones)
					if(!primaryLNG && globals.page.country == 'BR') primaryLNG = moduleOBJ.locale.LNG['br'];
					else if(!primaryLNG && globals.page.country == 'AR') primaryLNG = moduleOBJ.locale.LNG['ar'];
						
					if(primaryLNG || secondaryLNG) {
						PARAMS["LNG"] = primaryLNG || {};						
						
						if(secondaryLNG) PARAMS["LNG"] = $.extend(primaryLNG, secondaryLNG);
						
						// Check for default specification
						if (!moduleOBJ.locale.defaultLNG) log.warning(modPrefs.id + ' - A propriedade "defaultLNG" nÃ£o foi encontrada. Este mÃ³dulo pode nÃ£o funcionar corretamente em outros idiomas.');
					} else {
						// Check for default specification
						if (!moduleOBJ.locale.defaultLNG) {
							log.critical(modPrefs.id + ' - NÃ£o existem variÃ¡veis de idioma para "'+globals.user.lang+'". A propriedade "defaultLNG" tambÃ©m nÃ£o foi definida. ');
							return false;
						}
						else {
							PARAMS["LNG"] = moduleOBJ.locale.LNG[moduleOBJ.locale.defaultLNG.toLowerCase()];
							log.warning(modPrefs.id + ' - NÃ£o existem variÃ¡veis de idioma para "'+globals.user.lang+'". O padrÃ£o foi implementado.')
						}
					}
				} else {
					log.warning(modPrefs.id+ " - O objeto 'LNG' nÃ£o foi encontrado. Verifique se ele realmente Ã© desnecessÃ¡rio.");
				}
				
				// RGN
				if(moduleOBJ.locale.RGN) {
					if(moduleOBJ.locale.RGN[globals.page.country.toUpperCase()]) {
						PARAMS["RGN"] = moduleOBJ.locale.RGN[globals.page.country.toUpperCase()];
						// Check for default specification
						if (!moduleOBJ.locale.defaultRGN.toUpperCase()) log.warning(modPrefs.id + ' - A propriedade "defaultRGN" nÃ£o foi encontrada. Este mÃ³dulo pode nÃ£o funcionar corretamente em outros idiomas.');
					} else {
						// Check for default specification
						if (!moduleOBJ.locale.defaultRGN.toUpperCase()) {
							log.critical(modPrefs.id + ' - NÃ£o existem variÃ¡veis de regiÃ£o para "'+globals.page.country+'". A propriedade "defaultRGN" tambÃ©m nÃ£o foi definida. ');
							return false;
						}
						else {
							PARAMS["RGN"] = moduleOBJ.locale.RGN[moduleOBJ.locale.defaultRGN.toUpperCase()];
							log.warning(modPrefs.id + ' - NÃ£o existem variÃ¡veis de regiÃ£o para "'+globals.page.country+'". O padrÃ£o foi implementado.')
						}
					}
				} else {
					log.warning(modPrefs.id+ " - O objeto 'RGN' nÃ£o foi encontrado. Verifique se ele realmente Ã© desnecessÃ¡rio.");
				}
				
			}
				
			// Extendind locale objects with controlled vocabulary
			/*
			$.extend(PARAMS['LNG'], controlled.LNG);
			$.extend(PARAMS['RGN'], controlled.RGN); 
			*/
			PARAMS['LNG']['controlled'] = controlled.LNG;
			PARAMS['RGN']['controlled'] = controlled.RGN;
			
			log.checkpoint(modPrefs.id + ' - ConfiguraÃ§Ãµes de seÃ§Ã£o (LNG e/ou RGN) foram avaliadas.');			
			// Adjust module language and region //
			
			
			//-+-+-+-+-+-+-+-+-+-+-+-+-+
			// Skin interpretation
			//-+-+-+-+-+-+-+-+-+-+-+-+-+
					
			// Validating skin settings
			if(modPrefs.loadSkin){
				if(!moduleOBJ.skins) {
					log.critical(modPrefs.id + " - o parÃ¢metro 'loadSkin' foi definido como 'true', mas o mÃ³dulo nÃ£o possui a propriedade um objeto 'skins'. Certifique-se \que mÃ³dulo requer arquivos externos para habilitar esta opÃ§Ã£o.");
					return false;
				}
				
				var skinsOBJ = moduleOBJ.skins;			
				var skin = {};
				// Checking skin presence
				if(modPrefs.skinName && skinsOBJ.items[modPrefs.skinName]) {
					skin.id = modPrefs.skinName;
					log.checkpoint(modPrefs.id + " - Validando skin: " + modPrefs.skinName);
					
				} else if (skinsOBJ.items[skinsOBJ.defaultSkinName]) {				
					skin.id = skinsOBJ.defaultSkinName;
					log.checkpoint(modPrefs.id + " - Validando skin padrÃ£o.")
				} else if (skinsOBJ.items[skinsOBJ.backupSkinName]){
					skin.id = skinsOBJ.backupSkinName;
					log.critical(modPrefs.id + " - Validando skin de backup.");
					return false;
				} else {
					if (!skinsOBJ.items[skinsOBJ.defaultSkinName]) {
						log.critical(modPrefs.id + " - O skin padrÃ£o nÃ£o foi localizado. Verifique se o objeto Ã© uma pririedade de 'items' e se o o seu nome tem o sufix 'skn_'.");
						return false;
					}
				}
				
				// Validating skin interface
				var currentSkin = skinsOBJ.items[skin.id]
				if(!currentSkin.tplBody) {
					log.critical(modPrefs.id + " - o parÃ¢metro 'tplBody' nÃ£o foi encontrado.");
					return false;
				} else {
					if(typeof(currentSkin.tplBody) != 'string') {
						log.critical(modPrefs.id + " - o parÃ¢metro 'tplBody' deve ser uma string contendo a estrutura HTML para o mÃ³dulo.");
						return false;
					}
				}
				
				// Parsing template
				if (PARAMS["LNG"] || PARAMS["RGN"]) {
					var lngOBJ = (PARAMS["LNG"]) ? PARAMS["LNG"] : false;
					var rgnOBJ = (PARAMS["RGN"]) ? PARAMS["RGN"] : false;
					
					var TPL = tools.parseTPL({LNG:lngOBJ, RGN:rgnOBJ}, currentSkin.tplBody);
				}
				
				// Including styles
				if(currentSkin.css && currentSkin.css.length) {
					var moduleBaseURL = Library.modules.baseDIR + modPrefs.id.toLowerCase().replace('mod','') + '/';
					
					if(typeof(currentSkin.css) == 'string') {
						tools.Components.set({css:moduleBaseURL + currentSkin.css});
					} else {
						var newCssArray = [];
						for(var i = 0; i < currentSkin.css.length;i++){
							var currentCss = moduleBaseURL + currentSkin.css[i];
							newCssArray.push(currentCss);
						}
						tools.Components.set({css:newCssArray});
					}
				}
				
				if(TPL && modPrefs.loadSkin) {
					$(modPrefs.selector).replaceWith(TPL);
					var selectorAttr = TPL.match(/(id=|class=)+('|")[^'"]+['"]/gi)[0];
					var newSelector = ((/id/i).test(selectorAttr)) ? selectorAttr.replace(/(id=)|( )/gi, '#').replace(/['\"]/g,'') : selectorAttr.replace(/(class=)|( )/gi, '.').replace(/['\"]/g,'');
					//alert(newSelector);
				}
			}
			// Deliver recipient
			PARAMS['preLoadedSkin'] = !modPrefs.loadSkin;
			PARAMS['skinName'] = (skin && skin.id) ? skin.id : modPrefs.skinName;
			PARAMS["recipient"] = (newSelector) ? $(newSelector) : $(modPrefs.selector);
			
			// Define loading state
			//PARAMS["recipient"].addClass("loading");
			
			// Applying transition effects
			if(globals.page.transitionEffects) $(modPrefs.selector).hide().fadeIn('slow');
			// Skin interpretation//
			
			//alert(PARAMS.id + '\n' +  $(modPrefs.selector).length);
			return PARAMS;
		}
		
		var contingency = function(modOBJ){
			log.checkpoint(modOBJ.id + ' - Problemas encontratos. Disparando mÃ©todo de contingÃªncia.');
			if($(modOBJ.selector).length) {
				var skinsOBJ = window[modOBJ.id].skins;
				var backupSkinName = skinsOBJ.backupSkinName;
				if(backupSkinName && skinsOBJ.items[backupSkinName]){
					log.checkpoint(modOBJ.id + ' - Incluindo template de backup - ' + skinsOBJ.backupSkinName);
					
					tools.Components.set(skinsOBJ.items[backupSkinName].css, function(){
						$(modOBJ.selector).html(skinsOBJ.items[backupSkinName].tplBody);
					});
					
					
				} else $(modOBJ.selector).html('Um problema foi detectado neste mÃ³dulo.');
			}
			else log.critical(modOBJ.id + ' - NÃ£o foi possÃ­vel localizar um elemento HTML para receber o template de backup.');
		}
		
		return {
			modules:modules
		}
	}();
	
	// Public //
	var start = function(setupOBJ){
		
		//-+-+-+-+-+-+-+-+-+-+-+-+
		// Parsing configs
		//-+-+-+-+-+-+-+-+-+-+-+-+
		if(setupOBJ.configs) {
			var version = setupOBJ.configs.coreVersion || details.coreVersion;

			if(setupOBJ.configs.reloadInterval) tools.pageReloader.on(setupOBJ.configs.reloadInterval);

			if(setupOBJ.configs.locale && typeof(setupOBJ.configs.locale) == 'string') {
				var localeLevels = setupOBJ.configs.locale.match(/\w\w/gi);
				
				// forgiving country definition
				if(localeLevels.length == 1 && Regions[localeLevels[0].toUpperCase()]){
					var correctCountry = Regions[localeLevels[0].toUpperCase()].isoCode;
					localeLevels[1] = correctCountry;
					localeLevels[0] = Regions[correctCountry].lang;
				}
				
				globals.page.lang = localeLevels[0].toLowerCase();
				
				
				if(typeof(localeLevels[1]) == 'string' && localeLevels[1].match(/es/i))  localeLevels[1] = globals.page.country;
				if(localeLevels[1]) globals.page.country = localeLevels[1].toUpperCase();			
			
			} else { // deprecated params
				if(setupOBJ.configs.pageCountry && typeof(setupOBJ.configs.pageCountry) == 'string' && setupOBJ.configs.pageCountry.toLowerCase() != 'auto') globals.page.country = setupOBJ.configs.pageCountry.toUpperCase();
				if(setupOBJ.configs.pageLang && typeof(setupOBJ.configs.pageLang) == 'string' && setupOBJ.configs.pageLang.toLowerCase() != 'auto') {	
					var lngLevels = setupOBJ.configs.pageLang.match(/\w\w/gi);
					globals.page.lang = lngLevels[0].toLowerCase();
					if(lngLevels[1]) {
						globals.page.lang += '-' + lngLevels[1].toUpperCase();
						globals.page.country = lngLevels[1].toUpperCase();
					}
				}
			}
			globals.page.locale = globals.page.lang + '-' + globals.page.country;
			
			//if(!globals.stage.isDSV && setupOBJ.configs.pageCountry && !setupOBJ.configs.baseURL) globals.page.baseURL = (setupOBJ.configs.pageCountry == "BR") ? "http://s1.trrsf.com.br/atm/2/core/" + version + '/': "http://s1.trrsf.com.br/atm/2/core/" + version + '/';
			if(!globals.stage.type.match(/HLG|DSV/) && setupOBJ.configs.pageCountry && !setupOBJ.configs.baseURL) globals.page.baseURL = (setupOBJ.configs.pageCountry == "BR") ? "http://stf.terra.com.br/portal/core/" + version + '/': "http://stf.terra.com/portal/core/" + version + '/';
			if(setupOBJ.configs.baseURL) globals.page.baseURL = setupOBJ.configs.baseURL.replace(/\/$/,'') + '/';
			
			
			if(setupOBJ.configs.lazyLoad) {
				$.include(globals.page.baseURL + '/_js/jquery.viewport.js');
				globals.page.lazyLoad = true;
			}
			
			globals.page.transitionEffects = setupOBJ.configs.transitionEffects;
		}
		
		$.ImportBasePath = globals.page.baseURL;
		$.useBrowserCache = !(/trrDebug|noCache/).test(document.location);
		if($.browser.safari) $.useBrowserCache = false;
		
		// Set locale objects
		errorMsgs = (errorMsgs[globals.user.lang]) ? errorMsgs[globals.user.lang] : errorMsgs[globals.user.lang];
		controlled.LNG = (controlled.LNG[globals.page.lang]) ? controlled.LNG[globals.page.lang] : controlled.LNG[controlled.defaultLNG.toLowerCase()];
		controlled.RGN = (controlled.RGN[globals.page.country]) ? controlled.RGN[globals.page.country] : controlled.RGN[controlled.defaultRGN.toUpperCase()];
		
		// Habilitando exception locales em CSS (exceto BR)
		if(globals.page.country != 'BR') {
			
			// primary language class
			if(globals.page.lang.match(/ar/i)) $(document.body).addClass('LNG_es' ).addClass('LNG_es-AR' ); // AR extends ES
			else $(document.body).addClass('LNG_' + globals.page.locale.match(/\w\w/g)[0]);
			
			// locale language class - always extends primary language class
			$(document.body).addClass('LNG_'+globals.page.locale);		
			
			// defined country class
			$(document.body).addClass('RGN_' + globals.page.country);
		}		
	
		if(setupOBJ.modules) load.modules(setupOBJ.modules);
		
		if(globals.stage.debugging){
			document.onkeyup = function(evt){
				var e = window.event || evt,
					keyunicode= e.charCode || e.keyCode;

				var container = $('#mod-console'),
					cookieName = 'console',
					pwd ="dDNyckA=";
					
				if(keyunicode == 113) { // F2
					if(container.length) return container.toggle('normal');
					
					var savedPass = tools.cookie.read(cookieName);
						inputPass =  savedPass || tools.base64.encode(prompt("Por favor, digite a senha."));
					
					if(inputPass && inputPass == pwd){
						tools.cookie.create('console', pwd, 1); // renew current cookie
						
						var container = document.createElement('hr');
						container.id = "consoleContainer";
						document.body.appendChild(container);
						
						load.modules([
							{
								id:"modConsole",
								selector:"#consoleContainer",
								loadSkin:true
							}
						]);
					}
				}
				
				if(container.length && keyunicode == 9) { // tab
					globals.data.instances.modConsole[0].togglePosition();
				}
			}
		}
		
		return modMan.start = load.modules;
	}
	
	var tools = {
		metrics:new function Metrics(){

			var currentMetricsValues = { // default values for mandatory params
				terra_info_service : window.terra_info_service,
				terra_info_channel: window.terra_info_channel,
				terra_info_type: window.terra_info_type,
				terra_info_id: window.terra_info_id,
				terra_info_channeldetail: window.terra_info_channeldetail,
				
				terra_stats_regCLK: window.terra_stats_regCLK,
				terra_stats_idCrtfc: window.terra_stats_idCrtfc,
				terra_stats_uv_c: window.uv_c || window.terra_stats_uv_c
			}
			var hit = function(){
				try {
					terra_stats_regTraffic();
					modMan.log.checkpoint('[MÃ©tricas registradas] Â» terra_info_type: <strong>'+modMan.tools.metrics.getCurrentValues().terra_info_type+'</strong>');
				} catch(e) {
					var countryCode = (modMan.globals.page.country) ? modMan.globals.page.country.toLowerCase() : 'br',
						scriptUrl = (!document.domain || (/hlg\./i).exec(document.domain)) ? 'http://s1.trrsf.com.br/metrics/js/'+countryCode+'/content.js' : "/metrics/js/"+countryCode+"/content.js";
					
					modMan.log.critical('Erro ao disparar a funÃ§Ã£o que recarrega mÃ©tricaa: <strong>terra_stats_regTraffic</strong>. '+ (!window.terra_stats_regTraffic ? 'Por favor, certifique-se que o template faz include do seguinte script: ' + scriptUrl : 'Â» '+ e.message));
				}
			}
			
			var setValues = this.setValues = function(newMetricValues){
				currentMetricsValues = $.extend(currentMetricsValues, newMetricValues || {});
			}

			this.getCurrentValues = function(){
				return currentMetricsValues;
			}

			this.reg = function(newMetricValues){
				var notFoundValues = [];
					
				if(typeof newMetricValues == 'object') setValues(newMetricValues);				
				
				for(var current in currentMetricsValues){					
					if(typeof(currentMetricsValues[current]) != 'undefined') window[current] = currentMetricsValues[current];
					else {
						notFoundValues.push(current);
						delete currentMetricsValues[current];
					}
				}
				
				if(notFoundValues.length) modMan.log.critical('NÃ£o foi possÃ­vel encontrar o valor para as seguintes variÃ¡veis de mÃ©tricas: ' + notFoundValues.join(', ') + '. Registrando demais valores encontrados.');
				try {
					hit();
				} catch(e){
					modMan.log.critical('[Erro encontrado ao definir variÃ¡veis de mÃ©tricas] Â» ' + e.message);
				}
			}
		},
		reloadMetrics:function(){
			//var metricsProxyUrl = modMan.globals.page.baseURL + "_tpl/metrics.html?",
			var metricsProxyUrl = globals.page.baseURL.replace(/s\d\.trrsf/, 'stf.terra') + "_tpl/metrics.html?",
				requiredMetricsVariables = ['terra_info_service', 'terra_info_channel', 'terra_info_channeldetail', 'terra_info_type', 'terra_info_id', 'terra_stats_idCrtfc', 'terra_stats_uv_c'],
				notFoundValues = [],
				$metricsLoaderFrame = $('#metricsLoaderFrame');
				
			if(window.uv_c) var terra_stats_uv_c = window.uv_c;
			
			if(window.tabSelected){
				switch(window.tabSelected) {
					case "itm-article":
						terra_info_type = "NOT";
					break;
					case "itm-video":
						terra_info_type = "VID";
					break;
					case "itm-info":
						terra_info_type = "INF";
					break;
					default:
						terra_info_type = "GAL";
				}
			} else { window.tabSelected = ''; }
			
			for(var i = 0, current; current = requiredMetricsVariables[i]; i++){
				if(window[current]) window[current] = window[current][window.tabSelected] || window[current];
				
				if(window.trrConstantData && trrConstantData.metrics && trrConstantData.metrics[current]) window[current] = trrConstantData.metrics[current];
				
				//alert(current + ' = ' + window[current]);
				if(!window[current]) {
					notFoundValues.push(current);
					requiredMetricsVariables.splice(i,1);
					i--;
				}
			}
			
			if(notFoundValues.length) modMan.log.warning('NÃ£o foi possÃ­vel encontrar o valor para as seguintes variÃ¡veis de mÃ©tricas: ' + notFoundValues.join(', '));
			while(requiredMetricsVariables.length){
				var current = requiredMetricsVariables.shift();
				
				metricsProxyUrl += current + '=' + window[current];
				if(requiredMetricsVariables.length) metricsProxyUrl += '&';
			}

			metricsProxyUrl += "&country="+modMan.globals.page.country;
			
			if($metricsLoaderFrame.length) $metricsLoaderFrame.attr('src', metricsProxyUrl);
			else $(document.body).append('<iframe id="metricsLoaderFrame" src="'+metricsProxyUrl+'" width="0" height="0" style="position:absolute;left:-100px;top:-100px;"></iframe>');
		},
		photosSpecialHover:function(recipiente) {
			$(recipiente).find(".img-news").bind("mouseover", function(evt){
				
				if(evt.target.tagName == "LI") objTarget = $(evt.target);
				else if(evt.target.tagName == "A") objTarget = $(evt.target).parent();
				else if(evt.target.tagName == "IMG") objTarget = $(evt.target).parent().parent();
				
				objTarget.find('img').attr("title", objTarget.find('img').attr("title").split("<a")[0].replace(/<\/?[^>]+>/gi, ''));
				
				if (objTarget.find('.photo').length == 0) objTarget.find('.text').html('<em class="photo">Galeria de fotos:&nbsp;</em>'+objTarget.find('.text').html())
				
				$(recipiente).find(".especialHover").css("top", objTarget.position().top - 11);
				$(recipiente).find(".especialHover").css("left", objTarget.position().left - 11);
				$(recipiente).find(".especialHover").html( objTarget.html());
				
				$(recipiente).find(".especialHover").show();
			})

			$(recipiente).find(".especialHover").bind("mouseover", function(){
				$(recipiente).find(".especialHover").show();
			})


			$(recipiente).find(".especialHover").bind("mouseout", function(){
				$(recipiente).find(".especialHover").hide();
			})
		},
		photosLayer:function(recipient){
			
			$(".ctn-expanded-pics").bind("click",function(evt){ 
					
					if (evt.target.className != "seemore"){

						evt.preventDefault();
						
						var scrollPosition = window.pageYOffset || document.documentElement.scrollTop; 
						
						var tplBody = '<div id="layer"><!-- --></div>'
							+'<div id="picsCradle">'
							+'<span class=\"close\">X</span>'
							+'<span class=\"imagem\"><!-- #foto ampliada# --></span>'
							+'<span class=\"texto\"><p><!-- #texto# --></p><em><!-- #fonte# --></em></span>'
							+'<span id=\"tgm-adv-extendedPics\"><iframe scrolling="no" frameborder="0" src="http://stf.terra.com.br/portal/core/2/advertising.html?tag=br.carnaval.home&amp;area=top&amp;site=br.terra.carnaval&amp;zone=home"></iframe></span>'
							+'<span id=\"metrics\"></span>'
							+'</div>';
						
						$(recipient).html(tplBody);
						
						var maskHeight = $(document).height();
						var maskWidth = $(window).width();
						var evento = null;
						try{
							var stringMetricas = '<iframe height="0" width="0" style="position: absolute; left: -100px; top: -100px;" src="http://s1.trrsf.com.br/portal/core/2/_tpl/metrics.html?'+
							+'terra_info_service='+terra_info_service
							+'&amp;terra_info_channel='+ terra_info_channel
							+'&amp;terra_info_channeldetail='+ terra_info_channeldetail
							+'&amp;terra_info_type='+ terra_info_type
							+'&amp;terra_info_id='+ terra_info_id
							+'&amp;terra_stats_idCrtfc='+ terra_stats_idCrtfc
							+'&amp;terra_stats_uv_c='+ terra_stats_uv_c
							+'&amp;coutnry='+ modMan.globals.page.country+'" id="metricsLoaderFrame"></iframe>';
						} catch (e){}
						
						
						if (evt.target.tagName == "SPAN")evento = $(evt.target).parent();
						else if(evt.target.tagName == "A")evento = $(evt.target).parent();
						else if (evt.target.tagName == "IMG") evento = $(evt.target).parent().parent();
						

						
						if (scrollPosition < 200) scrollPosition = 200;

						$(recipient).find("#picsCradle").css("top",scrollPosition+"px");
						$(recipient).find("#picsCradle .imagem").html('<img  src="http://p2.trrsf.com.br/image/get?o=cf&w=917&src='+evento.find("a").attr("href")+'" />');
						$(recipient).find("#picsCradle .texto p").html(evento.find(".text").html());
						$(recipient).find("#picsCradle #metrics").html(stringMetricas);
						$(recipient).find("#picsCradle").css("left", maskWidth - (468 + maskWidth/2));
						$(recipient).css("width", maskWidth);
						$(recipient).css("height", maskHeight + 200);	

						$(recipient).show();
		
						$(recipient).bind("click",function(evt){ 
								$(recipient).hide();						
						})
					}
				}
			)
		
		},
		pubMan:new function(){
						
			var _SELF = this,
				PROXY_TPL_PATH = "advertising.html",
				ADS_CONTAINER_SELECTOR = '.trr-ctn-advertising:last',
				CURRENT_CONTAINER_SELECTOR = ADS_CONTAINER_SELECTOR + ' > div:last',
				AD_PLACEHOLDER_SELECTOR_PREFIX = "tgm-",
				AD_CONTAINER_SELECTOR_PREFIX = "ctn-tgm-",
				
				autoDetectedTags = ['top', 'right', 'particles', 'apulse', 'textlinks'],
				
				$interface = {
					adsContainer:null,
					placeholders:{},
					containers:{},
					framedAds:{}
				},
				
				info = {
					exibitions:{},
					rejected:{}
				},
				
				documentDone = false;
				
			var createIframeHTML = function(currentTagId){
				var placeholdersHeigth = $interface.placeholders[currentTagId].height(),
					placeholdersWidth = $interface.placeholders[currentTagId].width(),
					HTML = '<iframe height="'+placeholdersHeigth+'" width="'+placeholdersWidth+'" src="'+globals.page.baseURL.replace(/core.*$/i, '')+PROXY_TPL_PATH+'?tag='+(window.tgmKey || "br.test2010.home")+'&amp;area='+currentTagId+'&amp;site='+(window.site || "")+'&amp;zone='+(window.zone || "")+'" frameborder="0" scrolling="no" ><//iframe>';
				
				return HTML;
			}
			
			var placeAd = function(currentTagId){				
				var $container = $interface.containers[currentTagId],
					$placeholder = $interface.placeholders[currentTagId],
					scrollPosition = (navigator.userAgent.match(/ie/i)) ? (window.pageYOffset || document.documentElement.scrollTop) : 0,
					placeholderBorderLeftWidth = parseInt(($placeholder.css('borderLeftWidth')).replace(/[^\d]+/,'')) || 0,
					leftPosition = ($placeholder.offset().left + placeholderBorderLeftWidth) - $interface.adsContainer.offset().left ,
					topPosition = $placeholder.offset().top + scrollPosition;
					
				$container.attr("style","position:absolute; display:block; top:"+topPosition+"px; left:"+leftPosition+'px;');
				
				if(!info.exibitions[currentTagId]) info.exibitions[currentTagId] = 0;
				info.exibitions[currentTagId]++;
				
				return undefined;
			}
			
			// constructor Â»
				$(document).ready(function(){
					documentDone = true;
				});
			// constructor Â«
			
			this.getInfo = function(){
				return info;
			}
			
			this.load = function(currentTagId, extraInfo, tagId){
				tagId = tagId || currentTagId;
				
				if(tagId.match(/default/)) {
					tgm.ShowArea('default');
					return true;
				}
				
				if(!documentDone && !$interface.adsContainer){
					$interface.adsContainer = $(ADS_CONTAINER_SELECTOR);
					if(!$interface.adsContainer.length){
						$interface.adsContainer = null;
						log.critical('Erro ao localizar container reponssÃ¡vel por receber as tags de publicidade. O elemento deve casar com o seguinte seletor: <strong>'+ ADS_CONTAINER_SELECTOR + '</strong>.');
						return false;
					}
				}
				
				if($interface.placeholders[currentTagId]) return _SELF.reload([currentTagId]);
				
				$interface.placeholders[currentTagId] = $('#' + AD_PLACEHOLDER_SELECTOR_PREFIX + currentTagId);
				$interface.containers[currentTagId] = $(CURRENT_CONTAINER_SELECTOR);
				
				if(documentDone && $interface.placeholders[currentTagId].length){
					if($interface.framedAds[currentTagId]) return _SELF.reload([currentTagId]);
					else {
						var containerElement = document.createElement('div');
							containerElement.id = AD_CONTAINER_SELECTOR_PREFIX + currentTagId;
							containerElement.innerHTML = createIframeHTML(currentTagId);
						
						if(!$interface.adsContainer.length) {
							$('#trr-ctn-general').append('<div class="'+ADS_CONTAINER_SELECTOR.replace(/^\./,'')+'"></div>');
							$interface.adsContainer = $(ADS_CONTAINER_SELECTOR);
						}
						
						$interface.adsContainer.append(containerElement);
						$interface.containers[currentTagId] = $(containerElement);
						placeAd(currentTagId);
						
						if(!info.exibitions[currentTagId]) info.exibitions[currentTagId] = 0;
						info.exibitions[currentTagId]++;
						
						return;
					}
				}
				
				if(!$interface.placeholders[currentTagId].length || !$interface.containers[currentTagId].length) {
					var errrorMsg = ''+
					'Erro ao localizar container de origem ou destino para publicidade.\n'+
					'Seletor de origem (placeholder): <strong> '+ '#'+AD_PLACEHOLDER_SELECTOR_PREFIX + currentTagId + '</strong> (elemento '+($interface.placeholders[currentTagId].length ? 'encontrado' : '<strong style="color:red;">nÃ£o encontrado</strong>')+')\n'+
					'Seletor de destino (tag container): '+CURRENT_CONTAINER_SELECTOR+' (elemento '+($interface.containers[currentTagId].length ? 'encontrado' : '<strong style="color:red;">nÃ£o encontrado</strong>')+')';

				
					if(!info.rejected[currentTagId]) info.rejected[currentTagId] = errrorMsg;
					
					//log.warning(errrorMsg);
					return false;
				}
				
				if(extraInfo) tgm.ShowArea(tagId, extraInfo);
				else tgm.ShowArea(tagId, 'site='+(window.site || "br.teste"), 'zone='+(window.zone || "br.home"));
				
				placeAd(currentTagId);
				
				return true;
			}
			
			this.reload = function(tagIdsARRAY){
				tagIdsARRAY = tagIdsARRAY || autoDetectedTags;
				
				
				for(var i = 0, currentTagId; currentTagId = tagIdsARRAY[i]; i++){
					
					if(!$interface.placeholders[currentTagId]) {
						$interface.placeholders[currentTagId] = $('#'+ AD_PLACEHOLDER_SELECTOR_PREFIX + currentTagId);
						$interface.containers[currentTagId] = $('#'+ AD_CONTAINER_SELECTOR_PREFIX + currentTagId);
									
						if(!$interface.placeholders[currentTagId].length || !$interface.containers[currentTagId].length) {										
							if(!$interface.placeholders[currentTagId].length) delete $interface.placeholders[currentTagId];
							if(!$interface.containers[currentTagId].length) delete $interface.containers[currentTagId];
							
							if($interface.placeholders[currentTagId] && !$interface.containers[currentTagId]) {
								//log.warning('tag invÃ¡lida: '+ currentTagId);
								delete $interface.placeholders[currentTagId];
								_SELF.load(currentTagId);
							} else {									
								var errrorMsg = 'Erro ao localizar placeholder para publicidade <strong>'+currentTagId+'</strong>.';								
								if(!info.rejected[currentTagId]) info.rejected[currentTagId] = errrorMsg;									
							}
							
							continue;
						}
					}
					
				
					if ($interface.framedAds[currentTagId]) $interface.framedAds[currentTagId].get(0).src += '';
					else {								
						$interface.containers[currentTagId].html(createIframeHTML(currentTagId));
						$interface.framedAds[currentTagId] = $interface.containers[currentTagId].find('iframe:first');
					}

					if(!info.exibitions[currentTagId]) info.exibitions[currentTagId] = 0;
					info.exibitions[currentTagId]++;
					
				}
				
				return undefined;
			}
			
			this.placeAds = function(tagIdsARRAY){
				tagIdsARRAY = tagIdsARRAY || autoDetectedTags;
				if(!$interface.adsContainer) $interface.adsContainer = $(ADS_CONTAINER_SELECTOR);
				
				for(var i = 0, currentTagId; currentTagId = tagIdsARRAY[i]; i++){
					var $placeholder = $('#'+AD_PLACEHOLDER_SELECTOR_PREFIX + currentTagId),
						$container = $('#'+AD_CONTAINER_SELECTOR_PREFIX + currentTagId);
						
					if(!$interface.placeholders[currentTagId] && !$placeholder.length) {
						var errrorMsg = ''+
						'Erro ao localizar container de origem ou destino para publicidade.\n'+
						'Seletor de origem (placeholder): <strong> '+ '#'+AD_PLACEHOLDER_SELECTOR_PREFIX + currentTagId + '</strong> (elemento '+($placeholder.length ? 'encontrado' : '<strong style="color:red;">nÃ£o encontrado</strong>')+')\n'+
						'Seletor de destino (tag container): '+CURRENT_CONTAINER_SELECTOR+' (elemento '+($container.length ? 'encontrado' : '<strong style="color:red;">nÃ£o encontrado</strong>')+')';
					
						if(!info.rejected[currentTagId]) info.rejected[currentTagId] = errrorMsg;
					
						continue;
					}
					
					if(!$interface.placeholders[currentTagId]) $interface.placeholders[currentTagId] = $placeholder;
					if(!$interface.containers[currentTagId]) $interface.containers[currentTagId] = $container;
					
					placeAd(currentTagId);	

					return undefined;
				}				
			
			}
		},
		Cron:function Cron(secondsInterval){
			if(this == window) return new Cron(secondsInterval);

			var interval = typeof(secondsInterval) == 'number' ? secondsInterval * 1000 : 0,
				jobs = [],
				timer = null;
				
			var triggerJobs = function(){
				for(var i = 0, currentJob; currentJob = jobs[i]; i++){
					currentJob();
				}
			}
			
			this.setJob = function(jobFUNCTION) {
				if(typeof(jobFUNCTION) != 'function') return new Error('O mÃ©todo sÃ³ recebe funcÃµes como primeiro e Ãºnico parÃ¢metro.');
				
				jobs.push(jobFUNCTION);
				
				return this;
			}
			
			this.changeInterval = function(secondsInterval){
				if(typeof(secondsInterval) != 'number') return new Error('O mÃ©todo changeInterval deve receber uma variÃ¡vel tipo Number que represente o tempo desejado, em segundos.');
				
				return this;
			}
			
			this.start = function(){
				if(!interval || !jobs.length) return new Error('Ã‰ preciso definir intervalo e funÃ§Ãµes para este objeto.');
				
				timer = window.setInterval(triggerJobs, interval);
				
				return this;
			}
			
			this.stop = function(){
				timer = window.clearInterval(timer);
				
				return this;
			}
		},
		jsonP:function(configsOBJ){
			var callback = configsOBJ.callback;
			if(!callback) {
				log.critical("Ã‰ preciso indicar um mÃ©todo (callback) para tratar o arquivo:\n" + url );
				return false;
			}
			var wrapperName = configsOBJ.wrapperName || "jsonp";

			var url = configsOBJ.url;
			
			var extraParams = configsOBJ.extraParams || false;

			// Json in body
			if(window[wrapperName] && !configsOBJ.reuse) {
				log.checkpoint(wrapperName + " - Recuperando json do corpo da pÃ¡gina.");
				configsOBJ.callback(window[wrapperName], extraParams);
				return true;
			}

			if(!configsOBJ.cache){
				var cache = new Date().getTime();
				url +=  (url.indexOf('?') != -1) ? "&" : "?";
				url += "cache=" + cache;
			}

			if(!window[wrapperName]) {
				window[wrapperName] = function(jsonOBJ){
					if (typeof(jsonOBJ) != 'object') {
						log.critical("Erro no parse do arquivo:\n" + url);
						return false;
					}
					//log.checkpoint('disparando resposta para ' + wrapperName)
					configsOBJ.callback(jsonOBJ, extraParams);

					// Reuse
					if(configsOBJ.reuse) {
						window["reuse-"+wrapperName] = jsonOBJ;
					}
				};
			} else if (configsOBJ.reuse) {
				var timeReuse = setInterval(function() {
					if (window["reuse-"+wrapperName]) {
						configsOBJ.callback(window["reuse-"+wrapperName], extraParams);
						clearInterval(timeReuse);
					}
				}, 1000);
			}

			if (!window["reuse-"+wrapperName]) {
				var objHead = document.getElementsByTagName("head")[0];
				var objScript = document.createElement("script");
				objScript.type = "text/javascript";
				objScript.src = url;
				objScript.charset ="utf-8";
				objHead.appendChild(objScript);

				objScript.onload = objScript.onreadystatechange = function(){
					if(objScript.readyState) {
						if (objScript.readyState == 'complete') objHead.removeChild(objScript);
					} else objHead.removeChild(objScript);
				}
			}
		},
		Components:function(callback){
			
			var loaded = {} // Stores references to already loaded files
			
			var matchLibrary = function(ext, url){
				if (!loaded[ext]) return false;
				else {
					for(var i = 0; i < loaded[ext].length; i++){
						if(loaded[ext][i] == url) return true;
					}					
				}
				return false;
			}
			
			var set =function(componentsOBJ, callback){
				if(typeof(componentsOBJ) != 'object' || (!componentsOBJ['js'] && !componentsOBJ['css'])) {
					if(callback) callback();
					return false;
				}
				var componentsARRAY = [];
				if(componentsOBJ['css']) componentsARRAY = componentsARRAY.concat(componentsOBJ['css']);				
				if(componentsOBJ['js']) componentsARRAY = componentsARRAY.concat(componentsOBJ['js']);
			
				log.checkpoint('checking components: \n' + componentsARRAY.join('\n'));
				$.include(componentsARRAY, callback);
			}
			
			var confirm = function(ext, url){
				if(!loaded[ext]) loaded[ext] = [];
				loaded[ext].push(url);
			}
			
			return {
				matchLibrary:matchLibrary,
				set:set,
				confirm:confirm
			}
		}(),
		parseTPL:function (variablesOBJ, templateSTR){
			if(!variablesOBJ || !templateSTR) return templateSTR;
			
			var tagPrefix = "({|##)",
				tagSufix = "(}|##)",
				placeholderEXP = new RegExp('{\s?foreach([^{]|{[^\/])+{\/foreach}'+'|'+tagPrefix + '[\\w\\d._[\\]\'\"-]+' + tagSufix, 'gi'),
				tags = templateSTR.match(placeholderEXP);
			
			if(!tags) return templateSTR;
			
			while(tags.length){
				var currentTag = tags.shift(),
					levelsSTR = (currentTag.match(/foreach/gi)) ? currentTag.match(/from=[^}]+/)[0].replace(/from=/, '') : currentTag.replace(/\[['"]?/,'.').replace(/['"]?\]/,''),
					tagMarkersEXP = new RegExp('^' + tagPrefix + '|' + tagSufix + '$', 'gi'),
					levels = levelsSTR.replace(tagMarkersEXP,'').split('.'),
					dataOBJ = variablesOBJ;
					
				while(levels.length){
					var currentLevel = levels.shift(),
						currentData = dataOBJ[currentLevel];

					if(currentData === null) currentData = '';
					if(typeof(currentData) != 'undefined' && !levels.length) {
						if(currentTag.match(/foreach/gi) && typeof(currentData) == 'object') {
							var loopItem = currentTag.replace(/^{foreach[^}]+}|{\/foreach}$/gi,''),
								tmpData = '';

							for(var key in currentData){
								tmpData += loopItem.replace(/{value/gi,'{'+currentLevel+'["'+key+'"]').replace(/{key}/,key);
							}
							tags=tags.concat(tmpData.match(/{[^}]+}/g));
							currentData = tmpData;
						} 
						templateSTR = templateSTR.replace(currentTag, currentData);
					}
					else if(currentData) dataOBJ = currentData;
					else break;
				}
			}			

			return templateSTR;
		},
		base64:new function(){				
			var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

			this.encode = function(input) {
				if(input){
					var output = "";
					var chr1, chr2, chr3;
					var enc1, enc2, enc3, enc4;
					var i = 0;

					do {
						chr1 = input.charCodeAt(i++);
						chr2 = input.charCodeAt(i++);
						chr3 = input.charCodeAt(i++);

						enc1 = chr1 >> 2;
						enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
						enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
						enc4 = chr3 & 63;

						if (isNaN(chr2)) {
							enc3 = enc4 = 64;
						} else if (isNaN(chr3)) {
							enc4 = 64;
						}

						output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
						keyStr.charAt(enc3) + keyStr.charAt(enc4);
					} while (i < input.length);	
					
					return output;
				}
			}

			this.decode = function(input) {
			   var output = "";
			   var chr1, chr2, chr3;
			   var enc1, enc2, enc3, enc4;
			   var i = 0;

			   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
			   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

			   do {
				  enc1 = keyStr.indexOf(input.charAt(i++));
				  enc2 = keyStr.indexOf(input.charAt(i++));
				  enc3 = keyStr.indexOf(input.charAt(i++));
				  enc4 = keyStr.indexOf(input.charAt(i++));

				  chr1 = (enc1 << 2) | (enc2 >> 4);
				  chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
				  chr3 = ((enc3 & 3) << 6) | enc4;

				  output = output + String.fromCharCode(chr1);

				  if (enc3 != 64) {
					 output = output + String.fromCharCode(chr2);
				  }
				  if (enc4 != 64) {
					 output = output + String.fromCharCode(chr3);
				  }
			   } while (i < input.length);

			   return output;
			}
		},
		adjustTime:function(dateOBJ){
			var time = dateOBJ.toLocaleTimeString();
			
			//var hours = time.split(':')[0];
			var hours = dateOBJ.getHours();
			//var minutes = time.split(':')[1];
			var minutes = dateOBJ.getMinutes();
			
			var usa = (modMan.globals.page.country == 'US') ? true : false;
			var sufix = false;
			var sep = "h";
			
			if(modMan.globals.page.country != 'BR') sep = ":";
			if (usa){
				if(hours>12) {
					hours = hours - 12;
					sufix = "pm";
				} else {
					sufix = "am";
				}
			}
			if(hours<10) hours = '0' + hours.toString().match(/\d$/);
			if(minutes<10) minutes = '0'+minutes.toString().match(/\d$/);
			
			var parsedTime = hours + sep + minutes;
			if(sufix) parsedTime += sufix;
			
			return parsedTime;
		},
		/*
		 * PARAMETERS
		 * - url (URL of the popup)
		 * - name (Name of the popup)
		 * - w (Width)
		 * - h (Height)
		 * - scrolling (no = 0 / yes = 1)
		 */
		openPopup:function(url,name,w,h,scrolling) {
			var leftPosition = (screen.width) ? (screen.width-w)/2 : 0;
			var topPosition = (screen.height) ? (screen.height-h)/2 : 0;
			var settings = "toolbar=no,location=no,directories=no,status=no,menubar=no,height="+h+",width="+w+",top="+topPosition+",left="+leftPosition+",scrollbars="+scrolling+",resizable=0";
			return window.open(url,name,settings);
		},
		isNewGalleryUrl:function(url){
			if(globals.page.country == 'BR' && (/\/galeria(s)?\//).test(url)) return false;		
			return true;
		},
		cookie:{
			create:function(name,value,hours){
				if (hours) {
					var date = new Date();
					date.setTime(date.getTime()+(hours*60*60*1000));
					var expires = "; expires="+date.toGMTString();
				}
				else var expires = "";
				document.cookie = name+"="+value+expires+"; path=/";
				
				return undefined;
			},
			read:function(name){
				var nameEQ = name + "=";
				var ca = document.cookie.split(';');
				for(var i=0, c; c = ca[i];i++) {
					while (c.charAt(0)==' ') c = c.substring(1,c.length);
					if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
				}
				return null;
			},
			erase:function(name){
				this.create(name,"",-1);					
				//return undefined;
			}
		},
		getQueryStringVars:function(locationSTR){
			locationSTR = locationSTR || document.location;
			var queryStringEXP = /[^?]+$/,
				queryString = queryStringEXP.exec(locationSTR);

			if(!queryString) return null;

			var variables = queryString[0].replace('&amp;',"&").split('&'),
				valuesOBJ = {};
			
			while(variables.length){
				var values = variables.shift().split('=');
				valuesOBJ[values[0]] = (values[1]) ? unescape(values[1]) : true;
			}

			return valuesOBJ;
		},
		pageReloader:new function(){
			var timer = null,
				cookieName = 'trrScrollPosition',
				previousReloadInterval = 0;
			
			var reloadAction = function(){
				var scrollPosition = window.pageYOffset || document.documentElement.scrollTop;
				
				tools.cookie.create(cookieName, scrollPosition);
				document.location += '';				
			}
			
			this.on = function(secondsNumber){
				secondsNumber = secondsNumber || previousReloadInterval;
				
				if(!secondsNumber) return false;
				
				if( (/voidRefresh/i).test(document.location)) {
					log.checkpoint('Auto-refresh configurado para acontecer em ' + secondsNumber + ' segundos, mas IMPEDIDO pelo parÃ¢metro "voidRefresh" contido na url.');
					return false;
				}				
				
				previousReloadInterval = secondsNumber;				
				
				var currentCookie = tools.cookie.read(cookieName);					
				if(currentCookie) {
					window.scrollTo(0, currentCookie);
					tools.cookie.erase(cookieName)
				}
				
				log.checkpoint('Auto-refresh configurado para acontecer em ' + secondsNumber + ' segundos.');
				timer = setInterval(function(){reloadAction()}, secondsNumber * 1000);
			}			
			
			this.off = function(){
				log.checkpoint('Auto-refresh interrmpido.');
				if(timer) clearInterval(timer), timer = null;
			}
		}
	}
	
	var help = function(){
		if (!log.console.active) tools.console();
		var publicMethods = [];
		for(method in tools){
			if(method != 'help') publicMethods.push(method);
		}
		var msg = ""+
		"Total de mÃ©todos transversais: " + (publicMethods.length)+".\n"+
		"SÃ£o eles: " + publicMethods.join(', ') + ".";
		log.help(msg);
	}
	
	var observer = {
		list:{}, // stores cross-component methods
		set:function(name, method){
			if(!this.list[name]) this.list[name] = [];
			
			this.list[name].push(method);
		},
		play:function(name){
			if (this.list[name]) {
				for(var no = 0; no < this.list[name].length; no++){
					this.list[name][no].call();
				}
			} else log.warning(LNG.couldntFondMethodsFor + ' "' + name + '"');
		}
	}
	
	return {
		globals:globals,
		start:start,
		load:load.modules,
		log:log,
		tools:tools,
		help:help
	}
}(jQuery);

} catch (errorOBJ){
	var msg = ""+
		"Um erro foi encontrado no cÃ³digo da classe 'ModMan'. Detalhes: \n"+
		'['+errorOBJ.name+'] -> '+errorOBJ.message + "\n" +
		"Arquivo: " + errorOBJ.fileName +'\n'+
		"Linha: " + errorOBJ.lineNumber;
	
	if(window.console) console.log(msg);
	else throw new Error(msg);
}
