var L10n={};var TEMPLATES={$element:null,debug:false,options:{templates_to_load:[],load_ajax:false,cache_partials:true,cache_l10n:true},cache:{},cache_partials:{},defaults:{seo_optimized:function(){return seo_optimized;},seo_from_param:function(){return seo_from_param;},seo_from_crawler:function(){return seo_from_crawler;},path_domain:function(){return path_domain;},path_root:function(){return path_root;},path_lib:function(){return path_lib;},path_images:function(){return path_images;},use_facebook:function(){return use_facebook;},use_linkedin:function(){return use_linkedin;},use_mailchimp:function(){return use_mailchimp;},lang:function(){return lang;},l:{},nl2br:function(){return function(val,render){return render(val).replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g,'$1<br>$2');};},unquote:function(){return function(val,render){return render(val).replace(/"/g,"&quot;");};},slugify:function(){return function(val,render){return UTILS.encode_to_url(render(val),true);};},text:function(){return function(val,render){return UTILS.unescape_text(render(val));};},time:function(){return new Date().getTime();},dateHM:function(){return function(val,render){return moment(new Date(render(val))).format('HH[H]mm[M]');};},dateMS:function(){return function(val,render){return moment(new Date(render(val))).format('mm[M]ss[S]');};},dateHMorMS:function(){return function(val,render){var d=new Date(render(val));return moment(d).format(d.getTime()>3600000?'HH[H]mm[M]':'mm[M]ss[S]');};},round0:function(){return function(val,render){return parseFloat(render(val)).toFixed(0);};},round1:function(){return function(val,render){return parseFloat(render(val)).toFixed(1);};},round2:function(){return function(val,render){return parseFloat(render(val)).toFixed(2);};},targetfor:function(){return function(val,render){var url=render(val);if(!_.str.startsWith(url,'javascript:'))return'_blank';return'';};}},initialized:false,init_callback:function(){},init:function($e,cb){this.$element=(!(this.$element instanceof jQuery)||this.$element.length==0)?$('body'):$e;this.init_callback=cb||this.init_callback;if(this.options.load_ajax){if(!_.isEmpty(this.options.templates_to_load)){this.fetch_from_ajax(this.options.templates_to_load,this.init_callback);return;}
if(this.debug)console.warn('TEMPLATES.init: load_ajax is set to true but no templates are set to load!');}
else{this.fetch_all_from_dom();this.initialized=true;}
this.init_callback();},fetch_l10n:function(l,cb){if(typeof lang_strings!='undefined'&&lang_strings[l]){L10n=lang_strings[l];TEMPLATES.defaults.l=lang_strings[l];return(cb||function(){})();}
var url=path_lib+'l10n/'+l+'.json';$.ajax({url:url,cache:this.options.cache_l10n,method:'get',dataType:'json',error:function(jqxhr,text,thrown){if(TEMPLATES.debug)console.log('TEMPLATES.fetch_l10n: could not load file '+url);},success:function(data,text,jqxhr){L10n=data;TEMPLATES.defaults.l=data;if(TEMPLATES.debug)console.log('TEMPLATES.fetch_l10n: loaded file '+url);},complete:function(){(cb||function(){})();}});},fetch_from_ajax:function(c,cb){var loaded_amount=0,loaded_success=0,loaded_error=0,loaded_total=c.length;_.each(c,function(v,k){v.failed=false;v.fetched=false;v.done=false;$.ajax({url:v,method:'get',dataType:'html',error:function(jqxhr,text,thrown){v.failed=true;loaded_error++;},success:function(data,text,jqxhr){v.fetched=true;loaded_success++;TEMPLATES.$element.append(data.replace('{{=<% %>=}}','').replace('<%={{ }}=%>',''));},complete:function(){v.done=true;loaded_amount++;if(loaded_amount>=loaded_total){if(TEMPLATES.debug)console.log('TEMPLATES.fetch_from_ajax: loaded '+loaded_amount+' files');if(TEMPLATES.debug)console.log('TEMPLATES.fetch_from_ajax: files successful = '+loaded_success);if(TEMPLATES.debug)console.log('TEMPLATES.fetch_from_ajax: files failed = '+loaded_error);TEMPLATES.fetch_all_from_dom();TEMPLATES.initialized=true;(cb||function(){})();}}});});},fetch_all_from_dom:function(){var $s=this.$element.find('script[type="text/template"], div[data-type="template"]');$s.each(function(){var $t=$(this);var id=$t.attr('id').replace('template_','');TEMPLATES.get(id,$t);});},_:function(t,o,p){return Mustache.render(t,_.extend({},this.defaults,o||{}),_.extend({},this.cache_partials,p||{}));},apply:function($el,id,o,p){$el.html(this.render(id,o,p||{}));return $el;},render:function(id,o,p){var template=this.get(id);return this._(template.html||'!! Template "'+id+'" not found !!',_.extend({},template.defaults,o),_.extend({},template.partials,p));},get:function(id,$element){if(this.has(id))return this.cache[id];var $template=$element||this.$element.find('script#template_'+id);if($template.length>0){var d={};try{d=eval('('+$template.attr('data-defaults')+')');}
catch(e){}
this.add(id,_.str.trim($template.html()),d);$template.remove();return this.cache[id];}
return false;},add:function(id,template,defaults,partials){var o={'id':id,'defaults':defaults||{},'partials':partials||{},'html':template.replace(/javascript/gi,'script type="text/javascript"')||''};Mustache.parse(o.html);this.cache[id]=o;this.cache_partials={};if(this.debug)console.log('TEMPLATES.add: created template "'+id+'"');if(this.options.cache_partials){_.each(this.cache,function(v,vid){TEMPLATES.cache_partials[vid]=v.html;});}
return o;},has:function(id){return _.has(this.cache,id);}};var ROUTER={obj:null,domain:'',root:'/',dpr:'',options:{push:true,prefix_on_route:'',navigate_defaults:{trigger:true}},init:function(domain,root,handle_events){this.obj=new Backbone.Router;this.setup(domain,root);if(handle_events===false)return;$(document).on('click.routerhandler','a:not([data-bypass])',function(e){var $t=$(this);var href={prop:$t.prop('href'),attr:$t.attr('href'),target:$t.prop('target')};var trigger=$t.attr('data-not-trigger')!='true';if(!(_.str.isBlank(href.target)||href.target=='_self'))return;if(href.attr=='#'){e.preventDefault();return;}
if(href.prop&&href.prop.slice(0,ROUTER.dpr.length)===ROUTER.dpr&&href.prop.indexOf(ROUTER.options.prefix_on_route)!==-1){var url=href.prop.replace(ROUTER.dpr,'');var exception=_.str.startsWith(url,'bo/')||_.str.startsWith(url,'simulador/');if(!exception){e.preventDefault();Backbone.history.navigate(url,_.extend({},ROUTER.options.navigate_defaults,{trigger:trigger}));}}});},setup:function(domain,root){if(!_.str.isBlank(domain)){var first_slash=domain.replace('//','||').indexOf('/');if(first_slash<domain.length){var part_to_move=domain.slice(first_slash+1);domain=domain.replace(part_to_move,'');root=part_to_move+root;}}
this.domain=(!_.str.isBlank(domain)?domain:location.protocol+"//"+location.host+'/');this.root=(!_.str.isBlank(root)?root:'/').replace(this.domain,'');this.dpr=(_.str.endsWith(this.domain,'/')?this.domain.slice(0,this.domain.length-1):this.domain)+'/'+
(_.str.startsWith(this.root,'/')?this.root.slice(1,this.root.length-1):this.root);},start:function(push,root,extra){if(!_.isUndefined(root))this.root=root;if(!_.isUndefined(push))this.options.push=push;Backbone.history.start(_.extend({pushState:this.options.push,root:this.root},extra));},routes:{},route:function(syntax,name,callback){var prefix=this.options.prefix_on_route||'';if(!_.str.isBlank(prefix)&&(_.str.startsWith(syntax,'/')||_.str.startsWith(syntax,'(/)'))&&_.str.endsWith(prefix,'/'))
prefix=prefix.slice(0,prefix.length-1);this.routes[name]={name:name,format:prefix+syntax,callback:callback};this.obj.route(prefix+syntax,name,callback);},bind:function(event,callback){this.obj.bind(event,callback);},go:function(url,options,prefix){Backbone.history.navigate((prefix===false?'':this.options.prefix_on_route)+url,_.extend({},this.options.navigate_defaults,options||{}));}};var UTILS={replace_accented:function(str){return _.str.slugify(str);},encode_to_url:function(str,encoded){if(encoded===true){str=this.unescape_text(str);str=str.replace(/(<([^>]+)>)/ig,'');}
return this.replace_accented(str).toLowerCase().replace(/\W /g,'').replace(/ /g,'-').replace(/[^a-z0-9-]/gi,'');},unescape:function(str){return $('<div>').html(str).html();},unescape_text:function(str){return $('<div>').html(str).text();},unserialize:function(serialized){var str=decodeURI(serialized);var pairs=str.split('&');var obj={},p,idx,val;for(var i=0,n=pairs.length;i<n;i++){p=pairs[i].split('=');idx=p[0];if(idx.length>1&&idx.indexOf('[]')==(idx.length-2)){var ind=idx.substring(0,idx.length-2);if(obj[ind]===undefined)
obj[ind]=[];obj[ind].push(p[1]);}
else{obj[idx]=p[1];}}
return obj;},unserialize_var:function(variable,serialized){var query=serialized||window.location.search.substring(1);var vars=query.split('&');for(var i=0;i<vars.length;i++){var pair=vars[i].split('=');if(decodeURIComponent(pair[0])==variable){return decodeURIComponent(pair[1]);}}}};var PROP={collection:{},method_load_cb:function(result){console.log(JSON.stringify(result));},method:'localstorage',methods:{localstorage:{load:function(){if(typeof(Storage)=="undefined")return;PROP.collection=JSON.parse(window.localStorage.getItem('props')||'{}');PROP.method_load_cb(PROP.collection);},save:function(){if(typeof(Storage)=="undefined")return;window.localStorage.removeItem('props');window.localStorage.setItem('props',JSON.stringify(PROP.collection));}},cookies:{load:function(){var props=$.cookie('props');if(!_.str.isBlank(props)){try{PROP.collection=JSON.parse(props);}
catch(e){console.error('PROP: error importing from cookies');}}
PROP.method_load_cb(PROP.collection);},save:function(){$.removeCookie('props');$.cookie('props',JSON.stringify(PROP.collection),{expires:365*5});}},titanium:{load:function(){WEBVI.call('prop_read',{names:['framework_prop'],callback:''+function(result){PROP.collection=JSON.parse(result.framework_prop||'{}');PROP.method_load_cb(PROP.collection);}});},save:function(){WEBVI.call('prop_clear',{names:['framework_prop']});WEBVI.call('prop_write',{obj:{'framework_prop':JSON.stringify(PROP.collection)}});}}},init:function(cb){if(typeof WEBVI!='undefined'&&WEBVI.invoking())this.method='titanium';this.load(this.method,cb);},load:function(m,cb){if(_.str.isBlank(m))m=this.method;if(_.isFunction(cb))this.method_load_cb=cb;if(m in this.methods)this.methods[m].load(cb);},save:function(m){if(_.str.isBlank(m))m=this.method;if(m in this.methods)this.methods[m].save();},get:function(names,callback){var result={};if(_.isArray(names)&&!_.isEmpty(names))_.each(names,function(v){result[v]=_.has(PROP.collection,v)?PROP.collection[v]:undefined;});else if(_.isString(names)&&!_.str.isBlank(names))result[names]=_.has(PROP.collection,names)?this.collection[names]:undefined;else result=this.collection;(callback||function(data){console.log(data);})(result);return result;},set:function(name,value){if(_.isObject(name))_.extend(this.collection,name||{});else if(!_.str.isBlank(name))this.collection[name]=value;this.save();},clear:function(names){if(_.isArray(names)&&!_.isEmpty(names))_.each(names,function(v){delete PROP.collection[v];});else if(_.isString(names)&&!_.str.isBlank(names))delete this.collection[names];else this.collection={};this.save();}};var API={urls:{options:{create_for_template:true,prefix:'',suffix:'/',suffix_when_filename:'/'},base:'http://www.moscatel.loc:8080/',lib:'[base]lib/',lib_img:'[lib]img/',api:'/',tag:[{tag:'[base]',func:function(list){return list.base;}},{tag:'[lib]',func:function(list){return list.lib;}}],init:function(base,options){if(!_.isUndefined(base)&&!_.str.isBlank(base)){if(!_.str.endsWith(base,'/'))base+='/';this.base=base;}
_.extend(this,options);_.each(this,function(value,key,list){if(!_.isString(value))return;var v=value;_.each(API.urls.tag,function(r){v=v.replace(r.tag,r.func(list));});list[key]=v;if(key!='base')list[key+'_nobase']=v.replace(list.base,'');});if(this.options.create_for_template){_.each(this,function(value,key){if(!TEMPLATES.defaults.urls)TEMPLATES.defaults.urls={};TEMPLATES.defaults.urls[key]=function(){return API.urls[key];};});}},gen_link:function(title,rec,nobase,prefix){return(nobase===true?'':this.base)
+this.options.prefix
+(!_.str.isBlank(prefix)?prefix:'')+UTILS.encode_to_url(title,true)
+(!_.isUndefined(rec)?'/'+UTILS.encode_to_url(rec,true)+this.options.suffix:this.options.suffix_when_filename);}},auth:{client_id:'',client_secret:'',token_data:{token:'',date_created:new Date(0),date_expired:new Date(0)},user:false,user_is:function(scope){return this.has_credentials()&&_.isObject(API.auth.user)&&!_.isUndefined(API.auth.user.scope)&&_.contains(API.auth.user.scope,scope);},has_login:function(){return this.has_credentials()&&new Date()<this.token_data.date_expired;},has_credentials:function(){return!_.str.isBlank(this.token_data.token);},token_params:function(data,save){if(data==undefined)data={user:false,token_data:false};this.user=data.user||false;this.token_data.token=data.token_data.token||'';this.token_data.date_created=new Date(data.token_data.date_created||0);this.token_data.date_expired=new Date(data.token_data.date_expired||0);API.load_defaults.headers['Authorization']=this.token_data.token||'';TEMPLATES.defaults.auth_user=API.auth.user;if(this.user!==false&&save!==false)
this.token_params_save(data);},token_params_load:function(c){PROP.get('auth',function(data){if(!_.isObject(data.auth))return;API.auth.token_params(data.auth);});},token_params_save:function(data){PROP.set('auth',data);},token_params_clear:function(){PROP.clear('auth');API.auth.token_params();},token_check:function(token,success,error){if(_.isFunction(token)){error=success;success=token;token=this.token_data.token;}
if(_.isFunction(success)&&!_.isFunction(error)){error=success;}
else{if(!_.isFunction(success))success=function(){};if(!_.isFunction(error))error=function(){};}
if(this.token_data.date_expired.getTime()!==0&&new Date()>this.token_data.date_expired){return error(null,null,null,{message:'Token expired'});}
return API.load({method:'get',url:API.urls.api+'api/check',data:{token:token},success:function(data){if(data.success)return success(data);API.auth.token_params_clear();return error(null,null,null,data.error);},error:function(jxhr,text,thrown,err){API.auth.token_params_clear();return error(jxhr,text,thrown,err);}});},token_facebook:function(fbtoken,success,error){return API.load({method:'post',url:API.urls.api+'auth/facebook',data:{token:fbtoken,client_id:this.client_id,client_secret:this.client_secret},success:function(data){API.auth.token_params(data.data);return(success||API.load_defaults.success)(data);},error:function(jxhr,text,thrown,err){return(error||API.load_defaults.error)(jxhr,text,thrown,err);}});}},init:function(base,options){this.urls.init(base,options);TEMPLATES.defaults.has_login=function(){return API.auth.has_login();};TEMPLATES.defaults.has_credentials=function(){return API.auth.has_credentials();};TEMPLATES.defaults.user_is_tester=function(){return API.auth.user_is('tester');};TEMPLATES.defaults.user_is_admin=function(){return API.auth.user_is('admin');};},get:function(url,data,options){return this.load(_.extend({url:this.urls.api+(url||''),data:data||{},method:'get'},options));},post:function(url,data,options){return this.load(_.extend({url:this.urls.api+(url||''),data:data||{},method:'post'},options));},put:function(url,data,options){return this.load(_.extend({url:this.urls.api+(url||''),data:data||{},method:'put'},options));},del:function(url,data,options){return this.load(_.extend({url:this.urls.api+(url||''),data:data||{},method:'delete'},options));},load_defaults:{data:{},headers:{},method:'get',type:'json',cache:false,check_login:false,on_logout:function(err){console.log(err);},success:function(data){console.log(data);},error:function(jxhr,text,thrown,err,data){if(jxhr)console.log(jxhr);if(err)console.log(err);if(data)console.log(data);},complete:function(jxhr,text){}},load:function(o){var options=_.extend({},this.load_defaults,o||{});if(!_.isFunction(options.timeout))options.timeout=options.error;if(!_.isFunction(options.on_logout))options.on_logout=options.error;if(options.check_login)
return API.auth.token_check(function(data){return API._(options);},function(jxhr,text,thrown,err){if(!_.isNull(jxhr)&&(jxhr.status==0||jxhr.status==408))return options.timeout(jxhr,text,thrown);if(text=='timeout')return options.timeout(jxhr,text,thrown);return options.on_logout(err);});return this._(options);},_:function(options){return $.ajax({url:options.url,data:options.data,method:options.method,cache:options.cache,dataType:options.type,headers:options.headers,success:function(data,text,jxhr){if(data.success===true||!_.str.isBlank(data.access_token))return options.success(data);return options.error(jxhr,null,null,data.error,data);},error:function(jxhr,text,thrown){if(!_.isNull(jxhr)&&(jxhr.status==0||jxhr.status==408))return options.timeout(jxhr,text,thrown);if(text=='timeout')return options.timeout(jxhr,text,thrown);return options.error(jxhr,text,thrown);},complete:function(jxhr,text){return options.complete(jxhr,text);}});}};_.extend(API,{options:{multi_lang:false},init:function(base,options){this.urls.bo='[base]';this.urls.bo_api='[bo]';this.urls.bo_ajax='[bo]index.ajax.php';this.urls.tag.push({tag:'[bo]',func:function(list){return list.bo;}});this.urls.init(base,options);TEMPLATES.defaults.has_login=function(){return API.auth.has_login();};TEMPLATES.defaults.has_credentials=function(){return API.auth.has_credentials();};TEMPLATES.defaults.user_is_tester=function(){return API.auth.user_is('tester');};TEMPLATES.defaults.user_is_admin=function(){return API.auth.user_is('admin');};TEMPLATES.defaults.generate_link=_.partial(this.generate_link_raw,false);TEMPLATES.defaults.generate_link_destaque=_.partial(this.generate_link_raw,true);},generate_link_raw:function(destaque_no_menu){var prefix=!_.str.isBlank(this.lang_cod)&&API.options.multi_lang?this.lang_cod+'/':'';if(!_.str.isBlank(this.link_url_no_menu)&&destaque_no_menu)return this.link_url_no_menu;if(!_.str.isBlank(this.link_url))return this.link_url;if(!_.str.isBlank(this.file_name))return API.urls.gen_link(this.file_name,undefined,false,prefix);return!_.isUndefined(this.rec)&&(!_.str.isBlank(this.title)||!_.str.isBlank(this.page_title))?API.urls.gen_link(!_.str.isBlank(this.page_title)?this.page_title:this.title,this.rec,false,prefix):'';},generate_link:function(item){return _.bind(this.generate_link_raw,item||{},false)();},generate_link_destaque:function(item){return _.bind(this.generate_link_raw,item||{},true)();},build_url_defaults:{comparison:{},options:{'lang':'pt','order':'relative_pos asc'},module:'content',end:'/action/api/'},build_url_api:function(options){if(!options)options={};return this.urls.bo_api+
(!_.isUndefined(options.module)?options.module:this.build_url_defaults.module)+
(!_.isUndefined(options.end)?options.end:this.build_url_defaults.end);},build_url:function(fields,comparison,options,return_as_object){var fields_str='fields='+(_.isArray(fields)?fields.join(','):fields),compare_str=!_.isUndefined(comparison)&&_.isString(comparison)?'&q='+comparison:'',options_str=!_.isUndefined(options)&&_.isString(options)?options:'';if(_.isObject(comparison)){var cf=[],cv='';_.each(_.extend({},this.build_url_defaults.comparison,comparison),function(value,key){cf.push(key);cv+='&v_'+key+'=';if(!_.isObject(value)&&!_.isArray(value))cv+=value;else cv+=value.value+(!_.isUndefined(value.cmp)?'&cmp_'+key+'='+value.cmp:'');});compare_str='&q='+cf.join(',')+cv;}
if(options==undefined||_.isObject(options)){var options=_.extend({},this.build_url_defaults.options,options||{});options_str='';_.each(options,function(value,key){if(_.str.isBlank(value))return;options_str+='&'+key+'='+value;});}
var url_base=this.build_url_api(options);var suffixed=(!_.isNull(fields)?fields_str:'')
+(!_.isNull(comparison)?compare_str:'')
+(!_.isNull(options)?options_str:'');return return_as_object===true?UTILS.unserialize(suffixed):url_base+(_.contains(url_base,'?')?'&':'?')+suffixed;},fetch:function(o){return this.load_3ngine(o);},load_3ngine_defaults:{data:{},headers:{},method:'get',type:'json',cache:false,error:function(jxhr,text,thrown){if(!_.isUndefined(console.log))console.log(jxhr);},success:function(data){if(!_.isUndefined(console.log))console.log(data);},complete:function(jxhr,text){}},load_3ngine:function(o){var options=_.extend({},this.load_3ngine_defaults,o||{});if(!_.isUndefined(options.requests)&&_.isObject(options.requests)){options.url=this.build_url(null,null,_.extend({batch:true},options.options));options.data={requests:{}};options.method='post';_.each(options.requests,function(v,k){options.data.requests[k]=API.build_url(v.fields||[],v.comparison||{},v.options||{},true);});}
else if(_.isUndefined(options.url)){options.url=this.build_url(options.fields||[],options.comparison||{},options.options||{});}
return this._3ngine(options);},_3ngine:function(options){return $.ajax({url:options.url,data:options.data,method:options.method,cache:options.cache,dataType:options.type,headers:options.headers,success:function(data,text,jxhr){return options.success(data);},error:function(jxhr,text,thrown){var timeout=_.isFunction(options.timeout)?options.timeout:options.error;if(!_.isNull(jxhr)&&(jxhr.status==0||jxhr.status==408))return timeout(jxhr,text,thrown);if(text=='timeout')return timeout(jxhr,text,thrown);return options.error(jxhr,text,thrown);},complete:function(jxhr,text){return options.complete(jxhr,text);}});}});var ANALYTICS={options:{log:false,debug:false},_ga:function(arguments){if(typeof ga=='undefined'||_.isNull(ga)||!_.isFunction(ga))return null;var s='\''+arguments.join('\',\'')+'\'';return!this.options.debug?eval('ga('+s+')'):'ga('+s+')';},_gaq:function(arguments){if(typeof _gaq=='undefined'||_.isNull(_gaq))return null;var s='\''+arguments.join('\',\'')+'\'';return!this.options.debug?_gaq.push(arguments):'_gaq.push(['+s+'])';},pageview:function(path){if(this.options.log&&!_.isUndefined(console.log))
console.log('Pageview: '+path);this._ga(['send','pageview',path]);this._gaq(['_trackEvent',path]);},event:function(category,action,label,value){if(this.options.log&&!_.isUndefined(console.log))
console.log('Event: '+category+' '+action+' '+label+' '+value);var a=_.toArray(arguments);this._ga(_.union(['send','event'],a));this._gaq(_.union(['_trackEvent'],a));}}