if(typeof(SAPO)=='undefined'){window.SAPO={};}else{window.SAPO=window.SAPO;}
SAPO.namespace=function(ns){if(!ns||!ns.length){return null;}
var levels=ns.split(".");var nsobj=SAPO;for(var i=(levels[0]=="SAPO")?1:0;i<levels.length;++i){nsobj[levels[i]]=nsobj[levels[i]]||{};nsobj=nsobj[levels[i]];}
return nsobj;};SAPO.verify=function(ns,minVersion){if(!ns){return;}
var levels=ns.split(".");var nsobj=SAPO;for(var k=levels[0]=='SAPO'?1:0,m=levels.length;k<m;k++){nsobj=nsobj[levels[k]];if(!nsobj)
throw new Error('SAPO.verify: '+ns+' not found');}
if(!minVersion)
return;if(typeof nsobj=='function')
nsobj=nsobj.prototype;var lhs=String(nsobj.version).match(/\d+/g)||[0];var rhs=String(minVersion).match(/\d+/g)||[0];for(var k=0,m=Math.min(lhs.length,rhs.length);k<m;k++){if(lhs[k]<rhs[k])
throw new Error('SAPO.verify: '+ns+' has low version ('+nsobj.version+' < '+minVersion+')');}
if(lhs.length<rhs.length)
throw new Error('SAPO.verify: '+ns+' has low version ('+nsobj.version+' < '+minVersion+')');};SAPO.Class=function(name,baseClass,properties){var derivedFunction=function(){if(this.__dont_init)
return;if(this==window||!this)
throw new Error('Call "new '+name+'(...);"');if(derivedFunction.abstract)
throw new Error("Abstract class: don't instantiate");if(baseClass){var abstractBackup=baseClass.abstract;if(abstractBackup)
baseClass.abstract=false;baseClass.apply(this,arguments);if(abstractBackup)
baseClass.abstract=abstractBackup;}
if(properties&&typeof properties.init=='function')
properties.init.apply(this,arguments);};derivedFunction.name=derivedFunction.displayName=name;derivedFunction.abstract=properties.abstract;if(baseClass){baseClass.prototype.__dont_init=1;derivedFunction.prototype=new baseClass();delete baseClass.prototype.__dont_init;}
derivedFunction.prototype.toString=function(){return'[object '+name+']';}
if(properties)
SAPO.extendObj(derivedFunction.prototype,properties);return derivedFunction;};SAPO.safeCall=function(object,listener){function rethrow(exception){setTimeout(function(){if(exception.message){exception.message+='\n'+(exception.stacktrace||exception.stack||'');}
throw exception;},1);}
if(object==null){object=window;}
if(typeof listener=='string'&&typeof object[listener]=='function'){try{return object[listener].apply(object,[].slice.call(arguments,2));}catch(ex){rethrow(ex);}}else if(typeof listener=='function'){try{return listener.apply(object,[].slice.call(arguments,2));}catch(ex){rethrow(ex);}}else if(typeof object=='function'){try{return object.apply(window,[].slice.call(arguments,1));}catch(ex){rethrow(ex);}}};function s$(element)
{if(arguments.length>1){for(var i=0,elements=[],length=arguments.length;i<length;i++){elements.push(s$(arguments[i]));}
return elements;}
if(typeof(element)=='string'){element=document.getElementById(element);}
return element;}
Function.prototype.bindObj=function(){if(arguments.length<2&&arguments[0]===undefined){return this;}
var __method=this;var args=[];for(var i=0,total=arguments.length;i<total;i++){args.push(arguments[i]);}
var object=args.shift();var fn=function(){return __method.apply(object,args.concat(function(tmpArgs){var args2=[];for(var j=0,total=tmpArgs.length;j<total;j++){args2.push(tmpArgs[j]);}
return args2;}(arguments)));};fn.toString=function(){return String(__method);}
fn.name=fn.displayName=__method.name;return fn;};Function.prototype.bindObjEvent=function(){var __method=this;var args=[];for(var i=0;i<arguments.length;i++){args.push(arguments[i]);}
var object=args.shift();return function(event){return __method.apply(object,[event||window.event].concat(args));};};Object.extend=function(destination,source){for(var property in source){destination[property]=source[property];}
return destination;};SAPO.extendObj=function(destination,source){if(source){for(var property in source){if(source.hasOwnProperty(property)){destination[property]=source[property];}}}
return destination;};if(typeof(SAPO.Browser)=='undefined'){SAPO.Browser={IE:false,GECKO:false,OPERA:false,SAFARI:false,KONQUEROR:false,CHROME:false,model:false,version:false,userAgent:false,init:function()
{this.detectBrowser();this.setDimensions();this.setReferrer();},setDimensions:function()
{var myWidth=0,myHeight=0;if(typeof(window.innerWidth)=='number'){myWidth=window.innerWidth;myHeight=window.innerHeight;}else if(document.documentElement&&(document.documentElement.clientWidth||document.documentElement.clientHeight)){myWidth=document.documentElement.clientWidth;myHeight=document.documentElement.clientHeight;}else if(document.body&&(document.body.clientWidth||document.body.clientHeight)){myWidth=document.body.clientWidth;myHeight=document.body.clientHeight;}
this.windowWidth=myWidth;this.windowHeight=myHeight;},setReferrer:function()
{this.referrer=document.referrer!==undefined?document.referrer.length>0?escape(document.referrer):false:false;},detectBrowser:function()
{var sAgent=navigator.userAgent;this.userAgent=sAgent;sAgent=sAgent.toLowerCase();if((new RegExp("applewebkit\/")).test(sAgent)){if((new RegExp("chrome\/")).test(sAgent)){this.CHROME=true;this.model='chrome';this.version=sAgent.replace(new RegExp("(.*)chrome\/([^\\s]+)(.*)"),"$2");}else{this.SAFARI=true;this.model='safari';this.version=sAgent.replace(new RegExp("(.*)applewebkit\/([^\\s]+)(.*)"),"$2");}}else if((new RegExp("opera")).test(sAgent)){this.OPERA=true;this.model='opera';this.version=sAgent.replace(new RegExp("(.*)opera.([^\\s$]+)(.*)"),"$2");}else if((new RegExp("konqueror")).test(sAgent)){this.KONQUEROR=true;this.model='konqueror';this.version=sAgent.replace(new RegExp("(.*)konqueror\/([^;]+);(.*)"),"$2");}else if((new RegExp("msie\ ")).test(sAgent)){this.IE=true;this.model='ie';this.version=sAgent.replace(new RegExp("(.*)\\smsie\\s([^;]+);(.*)"),"$2");}else if((new RegExp("gecko")).test(sAgent)){this.GECKO=true;var re=new RegExp("(camino|chimera|epiphany|minefield|firefox|firebird|phoenix|galeon|iceweasel|k\-meleon|seamonkey|netscape|songbird|sylera)");if(re.test(sAgent)){this.model=sAgent.match(re)[1];this.version=sAgent.replace(new RegExp("(.*)"+this.model+"\/([^;\\s$]+)(.*)"),"$2");}else{this.model='mozilla';var reVersion=new RegExp("(.*)rv\:([^\)]+)(.*)");if(reVersion.test(sAgent)){this.version=sAgent.replace(reVersion,"$2");}}}},debug:function()
{var str="known browsers: (ie, gecko, opera, safari, konqueror) \n";str+=[this.IE,this.GECKO,this.OPERA,this.SAFARI,this.KONQUEROR]+"\n";str+="model -> "+this.model+"\n";str+="version -> "+this.version+"\n";str+="\n";str+="original UA -> "+this.userAgent;alert(str);}};SAPO.Browser.init();}
SAPO.logReferer=function(classURL){var thisOptions=SAPO.extendObj({s:'js.sapo.pt',swakt:'59a97a5f-0924-3720-a62e-0c44d9ea4f16',pg:false,swasection:false,swasubsection:'',dc:'',ref:false,etype:'libsapojs-view',swav:'1',swauv:'1',bcs:'1',bsr:'1',bul:'1',bje:'1',bfl:'1',debug:false},arguments[1]||{});if(typeof(classURL)!='undefined'&&classURL!=null){if(!thisOptions.pg){thisOptions.pg=classURL;}
if(!thisOptions.swasection){thisOptions.swasection=classURL;}
if(!thisOptions.ref){thisOptions.ref=location.href;}
var waURI='http://wa.sl.pt/wa.gif?';var waURISSL='https://ssl.sapo.pt/wa.sl.pt/wa.gif?';var aQuery=['pg='+encodeURIComponent(thisOptions.pg),'swasection='+encodeURIComponent(thisOptions.swasection),'swasubsection='+encodeURIComponent(thisOptions.swasubsection),'dc='+encodeURIComponent(thisOptions.dc),'s='+thisOptions.s,'ref='+encodeURIComponent(thisOptions.ref),'swakt='+thisOptions.swakt,'etype='+encodeURIComponent(thisOptions.etype),'swav='+encodeURIComponent(thisOptions.swav),'swauv='+encodeURIComponent(thisOptions.swauv),'bcs='+encodeURIComponent(thisOptions.bcs),'bsr='+encodeURIComponent(thisOptions.bsr),'bul='+encodeURIComponent(thisOptions.bul),'bje='+encodeURIComponent(thisOptions.bje),'bfl='+encodeURIComponent(thisOptions.bfl),''];if(location.protocol=='https:'){var waLogURI=waURISSL;}else{var waLogURI=waURI;}
var img=new Image();img.src=waLogURI+aQuery.join('&');}};SAPO._require=function(uri,callBack)
{if(typeof(uri)!='string'){return;}
var script=document.createElement('script');script.type='text/javascript';var aHead=document.getElementsByTagName('HEAD');if(aHead.length>0){aHead[0].appendChild(script);}
if(document.addEventListener){script.onload=function(e){if(typeof(callBack)!='undefined'){callBack();}};}else{script.onreadystatechange=function(e){if(this.readyState=='loaded'){if(typeof(callBack)!='undefined'){callBack();}}};}
script.src=uri;};SAPO.require=function(reqArray,callBack)
{var objectsToCheck=[];var uriToAdd=[];var _isSAPOObject=function(param){if(typeof(param)=='string'){if(/^SAPO\./.test(param)){return true;}}
return false;};var _isObjectUri=function(param){if(typeof(param)=='object'&&param.constructor==Object){if(typeof(param.uri)=='string'){return true;}}
return false;};var _isObjectArray=function(param){if(typeof(param)=='object'&&param.constructor==Array){return true;}
return false;};var _parseSAPOObject=function(param){var aSAPO=param.split('.');var sapoURI=aSAPO.join('/');return'http://js.sapo.pt/'+sapoURI+'/';};var _parseObjectUri=function(param){return param.uri;};var _objectExists=function(objStr,ver){if(typeof(objStr)!='undefined'){var aStrObj=objStr.split('.');var objParent=window;for(var k=0,aStrObjLength=aStrObj.length;k<aStrObjLength;k++){if(typeof(objParent[aStrObj[k]])!='undefined'){objParent=objParent[aStrObj[k]];}else{return false;}}
if(typeof(ver)!='undefined'&&ver!==null){if(typeof(objParent.version)!='undefined'){if(objParent.version==ver){return true;}else{return false;}}else{return true;}}
return true;}};var requestRecursive=function()
{if(uriToAdd.length>1){SAPO._require(uriToAdd[0],requestRecursive);uriToAdd.splice(0,1);}else if(uriToAdd.length==1){if(typeof(callBack)!='undefined'){SAPO._require(uriToAdd[0],callBack);}else{SAPO._require(uriToAdd[0]);}
uriToAdd.splice(0,1);}else if(uriToAdd.length===0){if(typeof(callBack)!='undefined'){callBack();}}};if(typeof(reqArray)!='undefined'){var cur=false;var curURI=false;if(typeof(reqArray)=='string'){if(_isSAPOObject(reqArray)){if(!_objectExists(reqArray)){uriToAdd.push(_parseSAPOObject(reqArray));}}else{uriToAdd.push(reqArray);}}else{for(var i=0,reqArrayLength=reqArray.length;i<reqArrayLength;i++){cur=reqArray[i];if(_isSAPOObject(cur)){if(!_objectExists(cur)){objectsToCheck.push(cur);uriToAdd.push(_parseSAPOObject(cur));}}else if(_isObjectArray(cur)){if(cur.length>0){if(_isSAPOObject(cur[0])){if(!_objectExists(cur[0])){if(cur.length===2){uriToAdd.push(_parseSAPOObject(cur[0])+cur[1]+'/');}else{uriToAdd.push(_parseSAPOObject(cur[0]));}}}}}else{if(typeof(cur)=='string'){uriToAdd.push(cur);}else{if(_isObjectUri(cur)){if(typeof(cur.check)=='string'){if(typeof(cur.version)=='string'){if(!_objectExists(cur.check,cur.version)){uriToAdd.push(_parseObjectUri(cur));}}else{if(!_objectExists(cur.check)){uriToAdd.push(_parseObjectUri(cur));}}}else{uriToAdd.push(_parseObjectUri(cur));}}}}}}
if(arguments.length==3){if(typeof(arguments[2])=='boolean'){if(arguments[2]===true){for(var l=0,uriToAddLength=uriToAdd.length;l<uriToAddLength;l++){SAPO._require(uriToAdd[l]);}
if(typeof(callBack)!='undefined'){callBack();}
return;}}
requestRecursive();}else{requestRecursive();}}};
(function(){var timer,fired=false,_fireEvent=function(eventName,memo){var event,element=document;if(element==document&&document.createEvent&&!element.dispatchEvent){element=document.documentElement;}
if(document.createEvent){event=document.createEvent("HTMLEvents");event.initEvent('dataavailable',true,true);}else{event=document.createEventObject();event.eventType='ondataavailable';}
event.eventName=eventName;event.memo=memo||{};if(document.createEvent){element.dispatchEvent(event);}else{element.fireEvent(event.eventType,event);}};function fireContentLoadedEvent(){if(fired){return;}
if(timer){window.clearInterval(timer);}
_fireEvent("dom:loaded");fired=true;}
if(document.addEventListener){if(navigator.userAgent.indexOf('AppleWebKit/')>-1){timer=window.setInterval(function(){if(/loaded|complete/.test(document.readyState)){fireContentLoadedEvent();}},0);window.addEventListener("load",fireContentLoadedEvent,false);}else{document.addEventListener("DOMContentLoaded",fireContentLoadedEvent,false);}}else{document.write("<script id=\"SAPO__onDOMContentLoaded\" defer src=//:><\/script>");document.getElementById("SAPO__onDOMContentLoaded").onreadystatechange=function(){if(this.readyState=="complete"){this.onreadystatechange=null;fireContentLoadedEvent();}};}})();
if(!SAPO.Communication||typeof SAPO.Communication==='undefined'){SAPO.namespace('Communication');}
SAPO.Communication.Ajax=function(url,options){this.init(url,options);};SAPO.Communication.Ajax.version=0.1;SAPO.Communication.Ajax.prototype={version:SAPO.Communication.Ajax.version,init:function(url){var options=Object.extend({asynchronous:true,method:'post',parameters:false,timeout:false,postBody:false,encoding:'UTF-8',contentType:'application/x-www-form-urlencoded',requestHeaders:false,onComplete:false,onSuccess:false,onFailure:false,onException:false,onCreate:false,onInit:false,onTimeout:false,sanitizeJSON:false,evalJS:true,debug:false},arguments[1]||{});this.options=options;this.options.method=this.options.method.toLowerCase();if(this.options.method!='get'&&this.options.method=='post'){this.options.method='post';}
if(this.options.onInit){this.options.onInit();}
this.stoTimeout=false;this.url=url;this.transport=this.getTransport();this.request();},getTransport:function()
{if(typeof(XMLHttpRequest)!='undefined'){return new XMLHttpRequest();}else if(typeof(ActiveXObject)!='undefined'){try{return new ActiveXObject('Msxml2.XMLHTTP');}catch(e){return new ActiveXObject('Microsoft.XMLHTTP');}}else{return false;}},setHeaders:function(url)
{if(this.transport){try{var headers={"User-Agent":navigator.userAgent,"Accept":"text/javascript,text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,video/x-mng,image/png,image/jpeg,image/gif;q=0.2,*/*;q=0.1","Accept-Language":navigator.language,"Accept-Charset":"ISO-8859-1,utf-8;q=0.7,*;q=0.7","Referer":this.url};if(this.options.method=='post'){headers['Content-type']=this.options.contentType+(this.options.encoding?'; charset='+this.options.encoding:'');if(this.options.postBody){headers['Content-length']=this.options.postBody.length;}}
headers['X-Requested-With']='XMLHttpRequest';headers['X-SAPO-Version']='0.1';if(this.options.method=='post'){this.transport.setRequestHeader("Content-type",this.options.contentType+(this.options.encoding?'; charset='+this.options.encoding:''));}
if(this.transport.overrideMimeType&&(navigator.userAgent.match(/Gecko\/(\d{4})/)||[0,2005])[1]<2005){headers['Connection']='close';}
if(this.options.requestHeaders&&typeof(this.options.requestHeaders)=='object'){for(var headerReqName in this.options.requestHeaders){headers[headerReqName]=this.options.requestHeaders[headerReqName];}}
for(var headerName in headers){if(headers.hasOwnProperty(headerName)){this.transport.setRequestHeader(headerName,headers[headerName]);}}}catch(e){}}},paramsObjToStr:function(optParams){var params='';for(var p in optParams){if(optParams.hasOwnProperty(p)){if(optParams[p].constructor===Array){var arr=optParams[p];for(var i=0,l=arr.length;i<l;i++){params+=encodeURIComponent(p)+"="+arr[i]+"&";}}else{params+=p+"="+optParams[p]+"&";}}}
if(params!==''){params=params.substr(0,params.length-1);}
return params;},setParams:function()
{var params=false,optParams=this.options.parameters;if(typeof optParams==="string"){params=optParams;}else if(typeof optParams==="object"){params=this.paramsObjToStr(optParams);}
if(params){if(this.url.indexOf('?')>-1){this.url=this.url+'&'+params;}else{this.url=this.url+'?'+params;}}},getHeader:function(name)
{try{return this.transport.getResponseHeader(name);}catch(e){return null;}},getResponse:function(){var t=this.transport,r={headerJSON:null,responseJSON:null,getHeader:this.getHeader,request:this,transport:t};r.readyState=t.readyState;r.responseText=t.responseText;r.responseXML=t.responseXML;r.status=t.status;r.statusText=t.statusText;return r;},runStateChange:function()
{var responseJSON,responseContent,response;try{var curStatus=this.transport.status||0;}catch(e){var curStatus=0;}
if(this.transport.readyState==4){if(this.stoTimeout){clearTimeout(this.stoTimeout);}
responseContent=this.transport.responseText;response=this.getResponse();var headerContentType=this.getHeader('Content-type');if(headerContentType==null){headerContentType='';}
if((this.options.evalJS&&headerContentType.indexOf("application/json")>=0)||this.options.evalJS==='force'){try{responseJSON=this.evalJSON(responseContent,this.sanitizeJSON);if(responseJSON){responseContent=response.responseJSON=responseJSON;}}catch(e){this._dispatchException(e);}}
var xjson=this.getHeader("X-JSON");if(xjson&&this.options.evalJS){try{responseJSON=this.evalJSON(xjson,this.sanitizeJSON);responseContent=response.headerJSON=responseJSON;}catch(e){this._dispatchException(e);}}
if(this.transport.responseXML!==null&&response.responseJSON===null&&this.transport.responseXML.xml!==""){responseContent=this.transport.responseXML;}
if(curStatus>=200&&curStatus<300){if(this.options.onSuccess){this.options.onSuccess(response,responseContent);}}else{if(this.options.onFailure){this.options.onFailure(response,responseContent);}}
if(typeof(this.options['on'+curStatus])!='undefined'){this.options['on'+curStatus](response,responseContent);}
if(this.options.onComplete){this.options.onComplete(response,responseContent);}}},_dispatchException:function(e){if(typeof this.options.onException==="function"){this.options.onException(e);}else{throw e;}},request:function(url)
{if(this.transport){if(this.options.method=='get'){this.setParams();}
if(this.options.method=='get'){this.transport.open("GET",this.url,this.options.asynchronous);}else{this.transport.open("POST",this.url,this.options.asynchronous);}
this.setHeaders();if(this.options.onCreate){this.options.onCreate();}
if(this.options.timeout&&!isNaN(this.options.timeout)){this.stoTimeout=setTimeout(function(){if(this.options.onTimeout){this.transport.abort();this.options.onTimeout();}}.bindObj(this),(this.options.timeout*1000));}
if(this.options.asynchronous){this.transport.onreadystatechange=function(){this.runStateChange();}.bindObj(this);}
if(this.options.method=='get'){this.transport.send(null);}else{var params;if(this.options.postBody){params=this.options.postBody;}else{if(typeof this.options.parameters==="string"){params=this.options.parameters;}else if(typeof this.options.parameters==="object"){params=this.paramsObjToStr(this.options.parameters);}}
this.transport.send(params);}
if(!this.options.asynchronous){this.runStateChange();}}},isJSON:function(str)
{if(str.length===0||typeof str!=="string"){return false;}
str=str.replace(/\\./g,'@').replace(/"[^"\\\n\r]*"/g,'');return(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);},evalJSON:function(strJSON,sanitize)
{if(!sanitize||this.isJSON(strJSON)){try{if(typeof(JSON)!=="undefined"&&typeof(JSON.parse)!=='undefined'){return JSON.parse(strJSON);}
return eval('('+strJSON+')');}catch(e){throw new Error('ERROR: Bad JSON string...');}}
return false;},debug:function(){}};SAPO.Communication.Ajax.load=function(url,callback){return new SAPO.Communication.Ajax(url,{method:'get',onSuccess:function(response){callback(response.responseText);}});};
if(!SAPO.Communication||SAPO.Communication=='undefined'){SAPO.namespace('Communication');}
SAPO.Communication.Syndication=function(url,options)
{this.init(url,options);};SAPO.Communication.Syndication.version='0.1';SAPO.Communication.Syndication.prototype={init:function(url)
{this.feeds=[];if(url&&typeof(url)!='undefined'&&url!=null){var id=this.push(url,arguments[1]||{});if(id!==false&&typeof(id)!='undefined'){this.run(id);}}
this._doDebug=false;},push:function(url)
{if(!url||typeof(url)=='undefined'){if(this.exception){this.exception.log('Missed URL');}
throw"Missed URL in SAPO.Communication.Syndication";return false;}
try{var options=Object.extend({objectName:false,onComplete:false,onLoading:false,onTimeout:false,onExit:false,timeout:10,optOnComplete:false,optOnLoading:false,optOnTimeout:false,optOnExit:false,charset:'utf-8'},arguments[1]||{});this.feeds.push({});this.onStart=false;this.onEnd=false;var id=this.feeds.length-1;this.feeds[id].u=url;this.feeds[id].onComplete=options.onComplete;this.feeds[id].onLoading=options.onLoading;this.feeds[id].onTimeout=options.onTimeout;this.feeds[id].onExit=options.onExit;if(options.objectName){this.feeds[id].obj=options.objectName;}else{if(typeof(SAPO.Utility)!='undefined'&&typeof(SAPO.Utility.Crypto)!='undefined'){this.feeds[id].obj='json'+SAPO.Utility.Crypto.md5(this.feeds[id].u);}else{this.feeds[id].obj='json'+Math.round(1000000*Math.random());}}
this.feeds[id].urlJSON=false;this.feeds[id].urlImage=false;this.feeds[id].req=0;this.feeds[id].limitReq=parseInt((options.timeout*1000)/100);this.feeds[id].stoReq=false;this.feeds[id].charset=options.charset;this.feeds[id].optionsOnLoading=options.optOnLoading||false;this.feeds[id].optionsOnComplete=options.optOnComplete||false;this.feeds[id].optionsOnTimeout=options.optOnTimeout||false;this.feeds[id].optionsOnExit=options.optOnExit||false;return id;}catch(e){if(this.exception){this.exception.log(e,'push');}}
return false;},run:function(id)
{if(id!==false&&typeof(id)!='undefined'){try{if(this.feeds[id].onLoading){if(this.feeds[id].optionsOnLoading){this.feeds[id].onLoading(this.feeds[id].optionsOnLoading);}else{this.feeds[id].onLoading();}}
this._setUrl(id);this._createScriptTag(id);}catch(e){this.exception.log(e,'run (ID: '+id+')');}}},runAll:function()
{if(this.feeds.length>0){this.onStart=arguments[0]||false;if(this.onStart){this.onStart();}
var argToOnEnd=arguments[1]||false;this.iter=0;this.setInter=setInterval(function(arguments){this.run(this.iter);if(this.iter===(this.feeds.length-1)){this.onEnd=argToOnEnd;}
this.iter++;if(this.iter==this.feeds.length){clearInterval(this.setInter);}}.bindObj(this),300);}},remove:function(id)
{if(typeof(this.feeds[id])!='undefined'&&this.feeds[id]!=null){try{this.feeds[id]=null;}catch(e){this.exception.log(e,'delete (ID: '+id+')');}}},removeAll:function()
{if(this.feeds.length>0){for(var i=0;i<this.feeds.length;i++){this.remove(i);}}},destroy:function()
{for(var i in this){this[i]=null;}},_setUrl:function(id)
{if(-1<this.feeds[id].u.indexOf('?')){this.feeds[id].urlJSON=this.feeds[id].u+'&jsonTag='+this.feeds[id].obj;}else{this.feeds[id].urlJSON=this.feeds[id].u+'?jsonTag='+this.feeds[id].obj;}},_createScriptTag:function(id)
{try{var is_html=!document.documentElement||!document.documentElement.namespaceURI||document.documentElement.namespaceURI=='http://www.w3.org/1999/xhtml';this.feeds[id].script=document.createElement('script');if(is_html){this.feeds[id].script.type='text/javascript';this.feeds[id].script.src=this.feeds[id].urlJSON;this.feeds[id].script.charset=this.feeds[id].charset;(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(this.feeds[id].script);}
else{this.feeds[id].script.setAttributeNS('http://www.w3.org/1999/xlink','href',this.feeds[id].urlJSON);document.documentElement.appendChild(this.feeds[id].script);}
this._callBack(id);}catch(e){if(this.exception){this.exception.log(e,'_createScriptTag');}}},_callBack:function(id)
{try{if(this.feeds[id].req<this.feeds[id].limitReq){if(this.feeds[id].onComplete){if(this.feeds[id].optionsOnComplete){this.feeds[id].optionsOnComplete.__id=id;this.feeds[id].onComplete(eval(this.feeds[id].obj),this.feeds[id].optionsOnComplete);this._removeScript(id);}else{this.feeds[id].onComplete(eval(this.feeds[id].obj));this._removeScript(id);}}
if(this.feeds[id].onExit){if(this.feeds[id].optionsOnExit){this.feeds[id].onExit(this.feeds[id].optionsOnExit);}else{this.feeds[id].onExit();}}
if(this.onEnd&&id==(this.feeds.length-1)){this.onEnd();}}else{throw"Time out ";}}catch(e){if(this.feeds[id].req<this.feeds[id].limitReq){if(this.feeds[id].stoReq){clearTimeout(this.feeds[id].stoReq);}
this.feeds[id].req++;this.feeds[id].stoReq=setTimeout(function(){this._callBack(id);}.bindObj(this),100);}else{if(this.exception){this.exception.log(e+' - URI: '+this.feeds[id].urlJSON,'_callBack');}
if(this.feeds[id].onTimeout){if(this.feeds[id].optionsOnTimeout){this.feeds[id].onTimeout(this.feeds[id].optionsOnTimeout);}else{this.feeds[id].onTimeout();}}
this._removeScript(id);if(this.feeds[id].onExit){if(this.feeds[id].optionsOnExit){this.feeds[id].onExit(this.feeds[id].optionsOnExit);}else{this.feeds[id].onExit();}}}}},_removeScript:function(id)
{try{if(this.feeds[id].script.parentNode&&typeof(this.feeds[id].script.parentNode)!='undefined'){this.feeds[id].script.parentNode.removeChild(this.feeds[id].script);}}catch(e){if(this.exception){this.exception.log(e,'_removeScript');}}},_debug:function(txt)
{if(this._doDebug&&document.getElementById('debug')){document.getElementById('debug').innerHTML+=txt+'<br/>';}}};
if(!SAPO.Utility&&typeof(SAPO.Utility)=='undefined'){SAPO.namespace('Utility');}
SAPO.Utility.I18n={version:'0.1',_baseLang:'pt_PT',_baseObj:false,_testMode:false,_loadedDicts:[],init:function(baseLangObject,langCode){if(typeof baseLangObject!=='object'){this._baseObj=false;return false;}
this._loadedDicts.push(baseLangObject);this._baseObj=baseLangObject;if(typeof langCode!=='undefined'){this._baseLang=langCode;}
if(typeof this._baseObj[this._baseLang]!=='undefined'){this._baseObj=this._baseObj[this._baseLang];}},append:function(baseLangObject,langCode){this._loadedDicts.push(baseLangObject);var keys=baseLangObject[langCode];if(typeof keys==='undefined'){keys=baseLangObject[this._baseLang];if(typeof keys==='undefined'){throw'append: given baseLangObject does not support lang "'+langCode+'"';}}
if(typeof this._baseObj==='object'){for(var k in keys){this._baseObj[k]=keys[k];}}
else{this._baseObj=keys;this._baseLang=langCode;}},getLang:function(){return this._baseLang;},alias:function(){return function(){return this.text.apply(this,arguments);}.bindObj(this);},text:function(str){if(typeof str!=='string')return;var original,res;if(!this._baseObj){original=str;}
else{res=this._baseObj[str];original=(typeof res==='undefined')?(this._testMode?'['+str+']':str):res;}
var re=false,i,l=arguments.length;if(l>1){for(i=1;i<l;++i){if(typeof arguments[i]!=='undefined'){re=new RegExp('{%s:'+i+'}','');if(re.test(original)){original=original.replace(re,arguments[i]);}
else{original=original.replace(/{%s}/,arguments[i]);}
re=null;re=false;}}}
original=original.replace(/\{%s(\:\d*)?\}/ig,'');return original;},ntext:function(strSin,strPlur,count){if(arguments.length===3){if(typeof strSin==='string'&&typeof strPlur==='string'&&typeof count==='number'){if(count===1){return strSin;}
else{return strPlur;}}}
else{if(typeof arguments[0]==='object'&&arguments[0].constructor===Array){if(typeof arguments[1]==='number'){if(arguments[1]>=(arguments[0].length-1)){return arguments[0][(arguments[0].length-1)];}
else{return arguments[0][arguments[1]];}}}
else{return undefined;}}},reload:function(langCode){this._baseLang=langCode;var i,iLen=this._loadedDicts.length;for(i=0;i<iLen;++i){this.append(this._loadedDicts[i],langCode);}}};
if(!SAPO.Utility&&typeof(SAPO.Utility)=='undefined'){SAPO.namespace('Utility');}
SAPO.Utility.Array={inArray:function(value,array)
{var i,iLen=array.length;if(typeof array==='object'){for(i=0;i<iLen;++i){if(array[i]===value){return true;}}}
return false;},sortMulti:function(aArray,key)
{if(typeof(aArray)=='undefined'||aArray.constructor!=Array){return false;}
if(typeof(key)!='string'){return aArray.sort();}
if(aArray.length>0){if(typeof(aArray[0][key])=='undefined'){return false;}
aArray.sort(function(a,b){var x=a[key];var y=b[key];return((x<y)?-1:((x>y)?1:0));});return aArray;}else{return aArray;}},keyValue:function(value,array,first)
{if(typeof(value)!='undefined'&&typeof(array)=='object'&&this.inArray(value,array)){var aKeys=[];for(var i=0;i<array.length;i++){if(array[i]===value){if(typeof(first)!='undefined'&&first===true){return i;}else{aKeys.push(i);}}}
return aKeys;}else{return false;}},shuffle:function(arrayObj)
{if(typeof(arrayObj)!='undefined'&&arrayObj.constructor!==Array){return false;}
var total=arrayObj.length;var tmp1=false,curRand=false;while(total--){curRand=Math.floor(Math.random()*(total+1));tmp1=arrayObj[total];arrayObj[total]=arrayObj[curRand];arrayObj[curRand]=tmp1;}
return arrayObj;},each:function(arr,callBack){var arrCopy=arr.slice(0);var total=arrCopy.length;var iterations=Math.floor(total/8);var leftover=total%8;var i=0;if(leftover>0){do{callBack(arrCopy[i++],i-1,arr);}while(--leftover>0);}
if(iterations==0){return arr;}
do{callBack(arrCopy[i++],i-1,arr);callBack(arrCopy[i++],i-1,arr);callBack(arrCopy[i++],i-1,arr);callBack(arrCopy[i++],i-1,arr);callBack(arrCopy[i++],i-1,arr);callBack(arrCopy[i++],i-1,arr);callBack(arrCopy[i++],i-1,arr);callBack(arrCopy[i++],i-1,arr);}while(--iterations>0);return arr;}};/*jshint browser:true, eqeqeq:true, undef:true, curly:true, laxbreak:true */
/*global SAPO:true, s$:true, window:true */

if(!SAPO.Dom || typeof SAPO.Dom === 'undefined') {
    SAPO.namespace('Dom');
}
/**
 * @class SAPO.Dom.Element
 *
 */
SAPO.Dom.Element = {

    /**
     * @function {DOMElement|Array} ? Shortcut for document.getElementById
     *
     * @param {string|Array} elm - Receives either an id or an Array of id's
     *
     * @return Either the DOM element for the given id or an array of elements for the given ids
     */
    get: function(elm) {
        if(typeof elm !== 'undefined') {
            if(typeof elm === 'string') {
                return document.getElementById(elm);
            }
            return elm;
        }
        return null;
    },

    /**
     * @function {DOMElement} ? Creates a DOM element
     * @param {String} tag - tag name
     * @param {Object} properties - object with properties to be set on the element
     */
    create: function(tag, properties) {
        var el = document.createElement(tag);
        SAPO.extendObj(el, properties);
        return el;
    },

    /**
     * @function ? Scrolls to an element
     * @param {DOMElement|String} elm - Element where to scroll
     */
    scrollTo: function(elm) {
        elm = this.get(elm);
        if(elm) {
            if (elm.scrollIntoView) {
                return elm.scrollIntoView();
            }

            var elmOffset = {},
                elmTop = 0, elmLeft = 0;

            do {
                elmTop += elm.offsetTop || 0;
                elmLeft += elm.offsetLeft || 0;

                elm = elm.offsetParent;
            } while(elm);

            elmOffset = {x: elmLeft, y: elmTop};

            window.scrollTo(elmOffset.x, elmOffset.y);
        }
    },

    /**
     * @function {Number} ? Gets the top cumulative offset for an element
     * @param {DOMElement|String} elm - target element
     * @return Offset from the target element to the top of the document
     */
    offsetTop: function(elm) {
        elm = this.get(elm);

        var offset = elm.offsetTop;

        while(elm.offsetParent){
            if(elm.offsetParent.tagName.toLowerCase() !== "body"){
                elm = elm.offsetParent;
                offset += elm.offsetTop;
            } else {
                break;
            }
        }

        return offset;
    },

    /**
     * @function {Number} ? Gets the left cumulative offset for an element
     * @param {DOMElement|String} elm - target element
     * @return Offset from the target element to the left of the document
     */
    offsetLeft: function(elm) {
        elm = this.get(elm);

        var offset = elm.offsetLeft;

        while(elm.offsetParent){
            if(elm.offsetParent.tagName.toLowerCase() !== "body"){
                elm = elm.offsetParent;
                offset += elm.offsetLeft;
            } else {
                break;
            }
        }

        return offset;
    },

    /**
    * @function {Array} ? gets the element offset relative to its closest positioned ancestor
    * @param {DOMElement|String} elm - target element
    * @return Array with the element offsetleft and offsettop relative to the closest positioned ancestor
    */
    positionedOffset: function(element) {
        var valueTop = 0, valueLeft = 0;
        element = this.get(element);
        do {
            valueTop  += element.offsetTop  || 0;
            valueLeft += element.offsetLeft || 0;
            element = element.offsetParent;
            if (element) {
                if (element.tagName.toLowerCase() === 'body') {	break;	}

                var value = element.style.position;
                if (!value && element.currentStyle) {
                    value = element.currentStyle.position;
                }
                if ((!value || value === 'auto') && typeof getComputedStyle !== 'undefined') {
                    var css = getComputedStyle(element, null);
                    value = css ? css.position : null;
                }
                if (value === 'relative' || value === 'absolute') {	break;	}
            }
        } while (element);
        return [valueLeft, valueTop];
    },

    /**
     * @function {Array} ? Gets the cumulative offset for an element
     * @param {DOMElement|String} elm - target element
     * @return Array with offset from the target element to the top/left of the document
     */
    offset: function(elm) {
        return [
            this.offsetLeft(elm),
            this.offsetTop(elm)
        ];
    },

    /**
     * @function {Boolean} ? Verifies the existence of an attribute
     * @param {Object} elm - target element
     * @param {String} attr - attribute name
     * @return Boolean based on existance of attribute
     */
    hasAttribute: function(elm, attr){
        return elm.hasAttribute ? elm.hasAttribute(attr) : !!elm.getAttribute(attr);
    },
    /**
     * @function ? Inserts a element immediately after a target element
     * @param {DOMElement} newElm - element to be inserted
     * @param {DOMElement|String} targetElm - key element
     */
    insertAfter: function(newElm,targetElm) {
        if (targetElm = this.get(targetElm)) {
            targetElm.parentNode.insertBefore(newElm, targetElm.nextSibling);
        }
    },

    /**
     * @function ? Inserts a element at the top of the childNodes of a target element
     * @param {DOMElement} newElm - element to be inserted
     * @param {DOMElement|String} targetElm - key element
     */
    insertTop: function(newElm,targetElm) {
        if (targetElm = this.get(targetElm)) {
            targetElm.insertBefore(newElm, targetElm.firstChild);
        }
    },

    /**
     * @function ? Retreives textContent from node
     * @param {DOMNode} node from which to retreive text from.
     *                  Can be any node type.
     * @return {String} the text
     */
    textContent: function(node){
        node = s$(node);
		var text;

        switch(node && node.nodeType) {
        case 9: /*DOCUMENT_NODE*/
            // IE quirks mode does not have documentElement
            return this.textContent(node.documentElement || node.body && node.body.parentNode || node.body);

        case 1: /*ELEMENT_NODE*/
            text = node.innerText;
            if (typeof text !== 'undefined') {
                return text;
            }
            /*Allow fallthrough if property not defined.*/

        case 11: /*DOCUMENT_FRAGMENT_NODE*/
            text = node.textContent;
            if (typeof text !== 'undefined') {
                return text;
            }

            if (node.firstChild === node.lastChild) {
                // Common case: 0 or 1 children
                return this.textContent(node.firstChild);
            }

            text = [];
            for (var k = 0, child, cs = node.childNodes, m = cs.length; k < m, child = cs[k]; k++) {
                text.push(this.textContent(child));
            }
            return text.join('');

        case 3: /*TEXT_NODE*/
        case 4: /*CDATA_SECTION_NODE*/
            return node.nodeValue;
        }
        return '';
    },

    /**
     * @function ? Removes all nodes children and adds the text
     * @param {DOMNode} node from which to retreive text from.
     *                  Can be any node type.
     * @return {String} the text
     */
    setTextContent: function(node, text){
        node = s$(node);
        switch(node && node.nodeType)
        {
        case 1: /*ELEMENT_NODE*/
            if ('innerText' in node) {
                node.innerText = text;
                break;
            }
            /*Allow fallthrough if property not defined.*/

        case 11: /*DOCUMENT_FRAGMENT_NODE*/
            if ('textContent' in node) {
                node.textContent = text;
                break;
            }
            /*Allow fallthrough if property not defined.*/

        case 9: /*DOCUMENT_NODE*/
            while(node.firstChild) {
                node.removeChild(node.firstChild);
            }
            if (text !== '') {
                var doc = node.ownerDocument || node;
                node.appendChild(doc.createTextNode(text));
            }
            break;

        case 3: /*TEXT_NODE*/
        case 4: /*CDATA_SECTION_NODE*/
            node.nodeValue = text;
            break;
        }
    },

    /**
     * @function ? Tells if element is a clickable link
     * @param {DOMNode} node to check if it's link
     * @return {Boolean}
     */
    isLink: function(element){
        var b = element && element.nodeType == 1 && ((/^a|area$/i).test(element.tagName) ||
            element.hasAttributeNS && element.hasAttributeNS('http://www.w3.org/1999/xlink','href'));
        return !!b;
    },

    /**
     * @function ? Tells if ancestor is ancestor of node
     * @param {DOMNode} ancestor node
     * @param {DOMNode} descendant node
     * @return {Boolean}
     */
    isAncestorOf: function(ancestor, node){
        if (!node || !ancestor) {
            return false;
        }
        if (node.compareDocumentPosition) {
            return (ancestor.compareDocumentPosition(node) & 0x10) != 0;/*Node.DOCUMENT_POSITION_CONTAINED_BY*/;
        }
        while (node = node.parentNode){
            if (node == ancestor){
                return true;
            }
        }
        return false;
    },

    /**
     * @function ? Tells if descendant is descendant of node
     * @param {DOMNode} node the ancestor
     * @param {DOMNode} descendant the descendant
     * @return {Boolean} true if 'descendant' is descendant of 'node'
     */
    descendantOf: function(node, descendant){
        return node != descendant && this.isAncestorOf(node, descendant);
    },

    /**
     * @function ? Get first child in document order of node type 1
     * @param {DOMNode} parent node
     * @return {DOMNode} the element child
     */
    firstElementChild: function(elm){
        if(!elm) {
            return null;
        }
        if ('firstElementChild' in elm) {
            return elm.firstElementChild;
        }
        var child = elm.firstChild;
        while(child && child.nodeType != 1) {
            child = child.nextSibling;
        }
        return child;
    },

    /**
     * @function ? Get last child in document order of node type 1
     * @param {DOMNode} parent node
     * @return {DOMNode} the element child
     */
    lastElementChild: function(elm){
        if(!elm) {
            return null;
        }
        if ('lastElementChild' in elm) {
            return elm.lastElementChild;
        }
        var child = elm.lastChild;
        while(child && child.nodeType != 1) {
            child = child.previousSibling;
        }
        return child;
    },

    /**
     * @function ?
     * @param {DOMElement|string} element target DOM element or target ID
     * @return {Number} element width
     */
    elementWidth: function(element) {
        if(typeof element === "string") {
            element = document.getElementById(element);
        }
        return element.offsetWidth;
    },

    /**
     * @function ?
     * @param {DOMElement|string} element target DOM element or target ID
     * @return {Number} element height
     */
    elementHeight: function(element) {
        if(typeof element === "string") {
            element = document.getElementById(element);
        }
        return element.offsetHeight;
    },

    /**
     * @function ?
     * @param {DOMElement|string} element target DOM element or target ID
     * @return {Number} element left position
     */
    elementLeft: function(element) {
        if(typeof element === "string") {
            element = document.getElementById(element);
        }
        return element.offsetLeft;
    },

    /**
     * @function ?
     * @param {DOMElement|string} element target DOM element or target ID
     * @return {Number} element top position
     */
    elementTop: function(element) {
        if(typeof element === "string") {
            element = document.getElementById(element);
        }
        return element.offsetTop;
    },

    /**
     * @function ? {Number}
     * @param {element} element target element
     * @return {Array} array with element's width and height
     */
    elementDimensions: function(element) {
        if(typeof element === "string") {
            element = document.getElementById(element);
        }
        return Array(element.offsetWidth, element.offsetHeight);
    },

    /**
     * @function ?
     * @param {DOMElement} element to be position cloned
     * @param {DOMElement} element to get the cloned position
     * @return {DOMElement} the element with positionClone
     */
    clonePosition: function(cloneTo, cloneFrom){
        cloneTo.style.top = this.offsetTop(cloneFrom) + 'px';
        cloneTo.style.left = this.offsetLeft(cloneFrom) + 'px';

        return cloneTo;
    },

    /**
     * Slices off a piece of text at the end of the element and adds the ellipsis
     * so all text fits in the element.
     * @param element   which text is to add the ellipsis
     * @param ellipsis  Optional. String to append to the chopped text.
     */
    ellipsizeText: function(element, ellipsis){
        if (element = s$(element)){
		    while (element && element.scrollHeight > (element.offsetHeight + 8))
			    element.textContent = element.textContent.replace(/(\s+\S+)\s*$/, replace || '\u2026');
        }
    },

    /**
	 * @function {HtmlElement|false} ? searches up the DOM tree for an element of specified class name
	 * @param {HtmlElement}	element
	 * @param {String}		className
	 */
    findUpwardsByClass: function(element, className) {
        var re = new RegExp("(^|\\s)" + className + "(\\s|$)");
        while (true) {
            if (re.test(element.className)) {
                return element;
            }
            else {
                element = element.parentNode;
                if (!element.parentNode) {
                    return false;
                }
            }
        }
    },

    /**
	 * @function {String} ? returns trimmed text content of descendants
	 * @param {DOMElement}			el			- element being seeked
	 * @param {optional Boolean}	removeIt	- whether to remove the found text nodes or not
	 * @return text found
	 */
	getChildrenText: function(el, removeIt) {
		var node,
			j,
			part,
			nodes = el.childNodes,
			jLen = nodes.length,
			text = '';

		if (!el) {
			return text;
		}

		for (j = 0; j < jLen; ++j) {
			node = nodes[j];
			if (!node) {	continue;	}
			if (node.nodeType === 3) {	// TEXT NODE
				part = this._trimString( String(node.data) );
				if (part.length > 0) {
					text += part;
					if (removeIt) {	el.removeChild(node);	}
				}
				else {	el.removeChild(node);	}
			}
		}

		return text;
	},

	/**
	 * Used by getChildrenText
	 * @function {private String} ? string trim implementation
	 * @param {String} text
	 */
	_trimString: function(text) {
		return (String.prototype.trim) ? text.trim() : text.replace(/^\s*/, '').replace(/\s*$/, '');
	},


	/**
	 * @function {Array} ? possible values
	 * @param {DomElement|String} select element
	 */
	getSelectValues: function (select) {
		var selectEl = s$(select);
		var values = [];
		for (var i = 0; i < selectEl.options.length; ++i) {
			values.push( selectEl.options[i].value );
		}
		return values;
	},


	/* used by fills */
	_normalizeData: function(data) {
		var d, data2 = [];
		for (var i = 0, f = data.length; i < f; ++i) {
			d = data[i];

			if (!(d instanceof Array)) {	// if not array, wraps primitive twice:		val -> [val, val]
				d = [d, d];
			}
			else if (d.length === 1) {		// if 1 element array:						[val] -> [val, val]
				d.push(d[0]);
			}
			data2.push(d);
		}
		return data2;
	},


	/**
	 * @function ? fills select element with choices
	 * @param {DomElement|String}			container		select element which will get filled
	 * @param {Number[]|String[]|Array[]}	data			data which will populate the component
	 * @param {optional Boolean}			skipEmpty		true to skip empty option
	 * @param {optional String|Number}		defaultValue	primitive value to select at beginning
	 */
	fillSelect: function(container, data, skipEmpty, defaultValue) {
		var containerEl = s$(container);
		var d, optionEl;
		containerEl.innerHTML = '';

		if (!skipEmpty) {
			// add initial empty option
			optionEl = document.createElement('option');
			optionEl.setAttribute('value', '');
			containerEl.appendChild(optionEl);
		}

		data = SAPO.Dom.Element._normalizeData(data);

		for (var i = 0, f = data.length; i < f; ++i) {
			d = data[i];

			optionEl = document.createElement('option');
			optionEl.setAttribute('value', d[0]);
			optionEl.appendChild( document.createTextNode(d[1]) );

			if (d[0] === defaultValue) {
				optionEl.setAttribute('selected', 'selected');
			}

			containerEl.appendChild(optionEl);
		}
	},


	/**
	 * @function ? select element on steroids - allows the creation of new values
	 * @param {DomElement|String} ctn select element which will get filled
	 * @param {Object} opts
	 * @...	{Number[]|String[]|Array[]}				data				data which will populate the component
	 * @... {optional Boolean}						skipEmpty			if true empty option is not created (defaults to false)
	 * @... {optional String}						emptyLabel			label to display on empty option
	 * @... {optional String}						createLabel			label to display on create option
	 * @... {optional String}						optionsGroupLabel	text to display on group surrounding value options
	 * @... {optional String}						defaultValue		option to select initially
	 * @... {optional Function(selEl, addOptFn)}	onCreate			callback that gets called once user selects the create option
	 */
	fillSelect2: function(ctn, opts) {
		ctn = s$(ctn);
		ctn.innerHTML = '';

		var defs = {
			skipEmpty:			false,
			emptyLabel:			'nothing',
			createLabel:		'create',
			optionsGroupLabel:	'',
			defaultValue:		''
		};
		if (!opts) {		throw 'param opts is a requirement!';	};
		if (!opts.data) {	throw 'opts.data is a requirement!';	};
		opts = SAPO.extendObj(defs, opts);
		
		var optionEl, optGroupEl, d;

		var optGroupValuesEl = document.createElement('optgroup');
		optGroupValuesEl.setAttribute('label', opts.optionsGroupLabel);

		opts.data = SAPO.Dom.Element._normalizeData(opts.data);

		opts.data.unshift(['$create$', opts.createLabel]);

		if (!opts.skipEmpty) {
			opts.data.unshift(['', opts.emptyLabel]);
		}

		for (var i = 0, f = opts.data.length; i < f; ++i) {
			d = opts.data[i];

			optionEl = document.createElement('option');
			optionEl.setAttribute('value', d[0]);
			optionEl.appendChild( document.createTextNode(d[1]) );

			if (d[0] === opts.defaultValue) {	optionEl.setAttribute('selected', 'selected');	}
			
			if (d[0] === '' || d[0] === '$create$') {
				ctn.appendChild(optionEl);
			}
			else {
				optGroupValuesEl.appendChild(optionEl);
			}
			ctn.appendChild(optGroupValuesEl);
		}
		
		var addOption = function(v, l) {
			var optionEl = document.createElement('option');
			optionEl.setAttribute('value', v);
			optionEl.appendChild(	document.createTextNode(l)	);
			optGroupValuesEl.appendChild(optionEl);
			ctn.options[ctn.options.length - 1].setAttribute('selected', true);
		};

		ctn.onchange = function() {
			if ((ctn.value === '$create$') && (typeof opts.onCreate === 'function')) {	opts.onCreate(ctn, addOption);	}
		};
	},


	/**
	 * @function {DomElement} ? creates set of radio buttons, returns wrapper
	 * @param {DomElement|String}			insertAfterEl	element which will precede the input elements
	 * @param {String}						name			name to give to the form field ([] is added if not as suffix already)
	 * @param {Number[]|String[]|Array[]}	data			data which will populate the component
	 * @param {optional Boolean}			skipEmpty		true to skip empty option
	 * @param {optional String|Number}		defaultValue	primitive value to select at beginning
	 * @param {optional String}				splitEl			name of element to add after each input element (example: 'br')
	 */
	fillRadios: function(insertAfterEl, name, data, skipEmpty, defaultValue, splitEl) {
		var afterEl = s$(insertAfterEl);
		afterEl = afterEl.nextSibling;
		while (afterEl && afterEl.nodeType !== 1) {
			afterEl = afterEl.nextSibling;
		}
		var containerEl = document.createElement('span');
		if (afterEl) {	afterEl.parentNode.insertBefore(containerEl, afterEl);	}
		else {			s$(insertAfterEl).appendChild(containerEl);				}

		data = SAPO.Dom.Element._normalizeData(data);

		if (name.substring(name.length - 1) !== ']') {
			name += '[]';
		}

		var d, inputEl;

		if (!skipEmpty) {
			// add initial empty option
			inputEl = document.createElement('input');
			inputEl.setAttribute('type', 'radio');
			inputEl.setAttribute('name', name);
			inputEl.setAttribute('value', '');
			containerEl.appendChild(inputEl);
			if (splitEl) {	containerEl.appendChild( document.createElement(splitEl) );	}
		}

		for (var i = 0; i < data.length; ++i) {
			d = data[i];

			inputEl = document.createElement('input');
			inputEl.setAttribute('type', 'radio');
			inputEl.setAttribute('name', name);
			inputEl.setAttribute('value', d[0]);
			containerEl.appendChild(inputEl);
			containerEl.appendChild( document.createTextNode(d[1]) );
			if (splitEl) {	containerEl.appendChild( document.createElement(splitEl) );	}

			if (d[0] === defaultValue) {
				inputEl.checked = true;
			}
		}

		return containerEl;
	},


	/**
	 * @function {DomElement} ? creates set of checkbox buttons, returns wrapper
	 * @param {DomElement|String}			insertAfterEl	element which will precede the input elements
	 * @param {String}						name			name to give to the form field ([] is added if not as suffix already)
	 * @param {Number[]|String[]|Array[]}	data			data which will populate the component
	 * @param {optional Boolean}			skipEmpty		true to skip empty option
	 * @param {optional String|Number}		defaultValue	primitive value to select at beginning
	 * @param {optional String}				splitEl			name of element to add after each input element (example: 'br')
	 */
	fillChecks: function(insertAfterEl, name, data, defaultValue, splitEl) {
		var afterEl = s$(insertAfterEl);
		afterEl = afterEl.nextSibling;
		while (afterEl && afterEl.nodeType !== 1) {
			afterEl = afterEl.nextSibling;
		}
		var containerEl = document.createElement('span');
		if (afterEl) {	afterEl.parentNode.insertBefore(containerEl, afterEl);	}
		else {			s$(insertAfterEl).appendChild(containerEl);				}

		data = SAPO.Dom.Element._normalizeData(data);

		if (name.substring(name.length - 1) !== ']') {
			name += '[]';
		}

		var d, inputEl;

		for (var i = 0; i < data.length; ++i) {
			d = data[i];

			inputEl = document.createElement('input');
			inputEl.setAttribute('type', 'checkbox');
			inputEl.setAttribute('name', name);
			inputEl.setAttribute('value', d[0]);
			containerEl.appendChild(inputEl);
			containerEl.appendChild( document.createTextNode(d[1]) );
			if (splitEl) {	containerEl.appendChild( document.createElement(splitEl) );	}

			if (d[0] === defaultValue) {
				inputEl.checked = true;
			}
		}

		return containerEl;
	},


	/**
	 * @function ? returns index of element from parent, -1 if not child of parent...
	 * @param {DOMElement}	parentEl	Element to parse
	 * @param {DOMElement}	childEl		Child Element to look for
	 */
	parentIndexOf: function(parentEl, childEl) {
		var node, idx = 0;
		for (var i = 0, f = parentEl.childNodes.length; i < f; ++i) {
			node = parentEl.childNodes[i];
			if (node.nodeType === 1) {	// ELEMENT
				if (node === childEl) {	return idx;	}
				++idx;
			}
		}
		return -1;
	}

};


if(!SAPO.Dom||typeof(SAPO.Dom)=='undefined'){SAPO.namespace('Dom');}
SAPO.Dom.Event={KEY_BACKSPACE:8,KEY_TAB:9,KEY_RETURN:13,KEY_ESC:27,KEY_LEFT:37,KEY_UP:38,KEY_RIGHT:39,KEY_DOWN:40,KEY_DELETE:46,KEY_HOME:36,KEY_END:35,KEY_PAGEUP:33,KEY_PAGEDOWN:34,KEY_INSERT:45,element:function(ev)
{var node=ev.target||(ev.type=='mouseout'&&ev.fromElement)||(ev.type=='mouseleave'&&ev.fromElement)||(ev.type=='mouseover'&&ev.toElement)||(ev.type=='mouseenter'&&ev.toElement)||ev.srcElement||null;return node&&(node.nodeType==3||node.nodeType==4)?node.parentNode:node;},relatedTarget:function(ev){var node=ev.relatedTarget||(ev.type=='mouseout'&&ev.toElement)||(ev.type=='mouseleave'&&ev.toElement)||(ev.type=='mouseover'&&ev.fromElement)||(ev.type=='mouseenter'&&ev.fromElement)||null;return node&&(node.nodeType==3||node.nodeType==4)?node.parentNode:node;},findElement:function(ev,elmTagName,force)
{var node=this.element(ev);while(true){if(node.nodeName.toLowerCase()===elmTagName.toLowerCase()){return node;}else{node=node.parentNode;if(!node.parentNode){if(force){return false;}
return document;}}}},fire:function(element,eventName,memo)
{element=s$(element);var ev,nativeEvents;if(document.createEvent){nativeEvents={"DOMActivate":true,"DOMFocusIn":true,"DOMFocusOut":true,"focus":true,"focusin":true,"focusout":true,"blur":true,"load":true,"unload":true,"abort":true,"error":true,"select":true,"change":true,"submit":true,"reset":true,"resize":true,"scroll":true,"click":true,"dblclick":true,"mousedown":true,"mouseenter":true,"mouseleave":true,"mousemove":true,"mouseover":true,"mouseout":true,"mouseup":true,"mousewheel":true,"wheel":true,"textInput":true,"keydown":true,"keypress":true,"keyup":true,"compositionstart":true,"compositionupdate":true,"compositionend":true,"DOMSubtreeModified":true,"DOMNodeInserted":true,"DOMNodeRemoved":true,"DOMNodeInsertedIntoDocument":true,"DOMNodeRemovedFromDocument":true,"DOMAttrModified":true,"DOMCharacterDataModified":true,"DOMAttributeNameChanged":true,"DOMElementNameChanged":true,"hashchange":true};}else{nativeEvents={"onabort":true,"onactivate":true,"onafterprint":true,"onafterupdate":true,"onbeforeactivate":true,"onbeforecopy":true,"onbeforecut":true,"onbeforedeactivate":true,"onbeforeeditfocus":true,"onbeforepaste":true,"onbeforeprint":true,"onbeforeunload":true,"onbeforeupdate":true,"onblur":true,"onbounce":true,"oncellchange":true,"onchange":true,"onclick":true,"oncontextmenu":true,"oncontrolselect":true,"oncopy":true,"oncut":true,"ondataavailable":true,"ondatasetchanged":true,"ondatasetcomplete":true,"ondblclick":true,"ondeactivate":true,"ondrag":true,"ondragend":true,"ondragenter":true,"ondragleave":true,"ondragover":true,"ondragstart":true,"ondrop":true,"onerror":true,"onerrorupdate":true,"onfilterchange":true,"onfinish":true,"onfocus":true,"onfocusin":true,"onfocusout":true,"onhashchange":true,"onhelp":true,"onkeydown":true,"onkeypress":true,"onkeyup":true,"onlayoutcomplete":true,"onload":true,"onlosecapture":true,"onmessage":true,"onmousedown":true,"onmouseenter":true,"onmouseleave":true,"onmousemove":true,"onmouseout":true,"onmouseover":true,"onmouseup":true,"onmousewheel":true,"onmove":true,"onmoveend":true,"onmovestart":true,"onoffline":true,"ononline":true,"onpage":true,"onpaste":true,"onprogress":true,"onpropertychange":true,"onreadystatechange":true,"onreset":true,"onresize":true,"onresizeend":true,"onresizestart":true,"onrowenter":true,"onrowexit":true,"onrowsdelete":true,"onrowsinserted":true,"onscroll":true,"onselect":true,"onselectionchange":true,"onselectstart":true,"onstart":true,"onstop":true,"onstorage":true,"onstoragecommit":true,"onsubmit":true,"ontimeout":true,"onunload":true};}
if(element!==null){if(element==document&&document.createEvent&&!element.dispatchEvent){element=document.documentElement;}
if(document.createEvent){ev=document.createEvent("HTMLEvents");if(typeof nativeEvents[eventName]==="undefined"){ev.initEvent("dataavailable",true,true);}else{ev.initEvent(eventName,true,true);}}else{ev=document.createEventObject();if(typeof nativeEvents["on"+eventName]==="undefined"){ev.eventType="ondataavailable";}else{ev.eventType="on"+eventName;}}
ev.eventName=eventName;ev.memo=memo||{};if(document.createEvent){element.dispatchEvent(ev);}else{element.fireEvent(ev.eventType,ev);}
return ev;}},observe:function(element,eventName,callBack)
{element=s$(element);if(element!==null){if(eventName.indexOf(':')!=-1||(eventName=="hashchange"&&element.attachEvent&&!window.onhashchange)){var argCallback=callBack;callBack=function(ev,eventName,cb){if(ev.eventName===eventName||(window.attachEvent&&eventName=='dom:loaded')){cb();}}.bindObjEvent(this,eventName,argCallback);eventName='dataavailable';}
if(element.addEventListener){element.addEventListener(eventName,callBack,false);}else{element.attachEvent('on'+eventName,callBack);}}},stopObserving:function(element,eventName,callBack)
{element=s$(element);if(element!==null){if(element.removeEventListener){element.removeEventListener(eventName,callBack,false);}else{element.detachEvent('on'+eventName,callBack);}}},stop:function(event)
{if(event.cancelBubble!==null){event.cancelBubble=true;}
if(event.stopPropagation){event.stopPropagation();}
if(event.preventDefault){event.preventDefault();}
if(window.attachEvent){event.returnValue=false;}
if(event.cancel!==null){event.cancel=true;}},pointer:function(ev)
{return{x:ev.pageX||(ev.clientX+(document.documentElement.scrollLeft||document.body.scrollLeft)),y:ev.pageY||(ev.clientY+(document.documentElement.scrollTop||document.body.scrollTop))};},pointerX:function(ev)
{return this.pointer(ev).x;},pointerY:function(ev)
{return this.pointer(ev).y;},isLeftClick:function(ev){if(window.addEventListener){if(ev.button===0){return true;}
else if(ev.type.substring(0,5)=='touch'&&ev.button==null){return true;}}
else{if(ev.button===1){return true;}}
return false;},isRightClick:function(ev){if(ev.button===2){return true;}
return false;},isMiddleClick:function(ev){if(window.addEventListener){if(ev.button===1){return true;}}
else{if(ev.button===4){return true;}}
return false;},getCharFromKeyboardEvent:function(event,changeCasing){var k=event.keyCode;var c=String.fromCharCode(k);var shiftOn=event.shiftKey;if(k>=65&&k<=90){if(typeof changeCasing==='boolean'){shiftOn=changeCasing;}
return(shiftOn)?c:c.toLowerCase();}
else if(k>=96&&k<=105){return String.fromCharCode(48+(k-96));}
switch(k){case 109:case 189:return'-';case 107:case 187:return'+';}
return c;},debug:function(){}};
if(!SAPO.Dom||typeof(SAPO.Dom)=='undefined'){SAPO.namespace('Dom');}
SAPO.Dom.Css={addClassName:function(elm,className){elm=s$(elm);if(elm&&className){if(typeof elm.classList!="undefined"){elm.classList.add(className);}
else if(!this.hasClassName(elm,className)){elm.className+=(elm.className?' ':'')+className;}}},removeClassName:function(elm,className){elm=s$(elm);if(elm&&className){if(typeof elm.classList!=="undefined"){elm.classList.remove(className);}else{if(typeof elm.className=="undefined"){return false;}
var elmClassName=elm.className,re=new RegExp("(^|\\s+)"+className+"(\\s+|$)");elmClassName=elmClassName.replace(re,' ');elmClassName=elmClassName.replace(/^\s+/,'').replace(/\s+$/,'');elm.className=elmClassName;}}},setClassName:function(elm,className,add){if(add){SAPO.Dom.Css.addClassName(elm,className);}else{SAPO.Dom.Css.removeClassName(elm,className);}},hasClassName:function(elm,className){elm=s$(elm);if(elm&&className){if(typeof elm.classList!=="undefined"){return elm.classList.contains(className);}else{if(typeof elm.className=="undefined"){return false;}
var elmClassName=elm.className;if(typeof elmClassName.length=="undefined"){return false;}
if(elmClassName.length>0){if(elmClassName==className){return true;}else{var re=new RegExp("(^|\\s)"+className+"(\\s|$)");if(re.test(elmClassName)){return true;}}}}}
return false;},blinkClass:function(element,className,timeout,negate){element=s$(element);SAPO.Dom.Css.setClassName(element,className,!negate);setTimeout(function(){SAPO.Dom.Css.setClassName(element,className,negate);},Number(timeout)|100);},toggleClassName:function(elm,className,forceAdd){if(elm&&className){if(typeof elm.classList!=="undefined"){elm=s$(elm);if(elm!==null){elm.classList.toggle(className);}
return true;}}
if(typeof(forceAdd)!='undefined'){if(forceAdd===true){this.addClassName(elm,className);}else if(forceAdd===false){this.removeClassName(elm,className);}}else{if(this.hasClassName(elm,className)){this.removeClassName(elm,className);}else{this.addClassName(elm,className);}}},setOpacity:function(elm,value){elm=s$(elm);if(elm!==null){var val=1;if(!isNaN(Number(value))){if(value<=0){val=0;}else if(value<=1){val=value;}else if(value<=100){val=value/100;}else{val=1;}}
if(typeof elm.style.opacity!='undefined'){elm.style.opacity=val;}else{elm.style.filter="alpha(opacity:"+(val*100|0)+")";}}},_camelCase:function(str){return str?str.replace(/-(\w)/g,function(_,$1){return $1.toUpperCase();}):str},getStyle:function(elm,style){elm=s$(elm);if(elm!==null){style=style=='float'?'cssFloat':SAPO.Dom.Css._camelCase(style);var value=elm.style[style];if(window.getComputedStyle&&(!value||value=='auto')){var css=getComputedStyle(elm,null);value=css?css[style]:null;}else if(!value&&elm.currentStyle){value=elm.currentStyle[style];}
if(style==='opacity'){return value?parseFloat(value,10):1.0;}
else if(style==='borderTopWidth'||style==='borderBottomWidth'||style==='borderRightWidth'||style==='borderLeftWidth'){if(value==='thin'){return'1px';}
else if(value==='medium'){return'3px';}
else if(value==='thick'){return'5px';}}
return value=='auto'?null:value;}},setStyle:function(elm,style){elm=s$(elm);if(elm!==null){if(typeof(style)==='string'){elm.style.cssText+='; '+style;if(style.indexOf('opacity')!=-1){this.setOpacity(elm,style.match(/opacity:\s*(\d?\.?\d*)/)[1]);}}else{for(var prop in style){if(style.hasOwnProperty(prop)){if(prop=='opacity'){this.setOpacity(elm,style[prop]);}else{if(prop=='float'||prop=='cssFloat'){if(typeof(elm.style.styleFloat)=='undefined'){elm.style.cssFloat=style[prop];}else{elm.style.styleFloat=style[prop];}}else{elm.style[prop]=style[prop];}}}}}}},show:function(elm){elm=s$(elm);if(elm!==null){elm.style.display='';}},hide:function(elm){elm=s$(elm);if(elm!==null){elm.style.display='none';}},toggle:function(elm,forceShow){elm=s$(elm);if(elm!==null){if(typeof(forceShow)!='undefined'){if(forceShow===true){this.show(elm);}else{this.hide(elm);}}else{if(elm.style.display=='none'){this.show(elm);}else{this.hide(elm);}}}},_getRefTag:function(head){if(head.firstElementChild)
return head.firstElementChild;for(var child=head.firstChild;child;child=child.nextSibling){if(child.nodeType==1){return child;}}
return null;},appendStyleTag:function(selector,style,options){options=Object.extend({type:'text/css',force:false},options||{});var styles=document.getElementsByTagName("style"),oldStyle=false,setStyle=true,i,l;for(i=0,l=styles.length;i<l;i++){oldStyle=styles[i].innerHTML;if(oldStyle.indexOf(selector)>=0){setStyle=false;}}
if(setStyle){var defStyle=document.createElement("style"),head=document.getElementsByTagName("head")[0],refTag=false,styleStr='';defStyle.type=options.type;styleStr+=selector+" {";styleStr+=style;styleStr+="} ";if(typeof defStyle.styleSheet!=="undefined"){defStyle.styleSheet.cssText=styleStr;}else{defStyle.appendChild(document.createTextNode(styleStr));}
if(options.force){head.appendChild(defStyle);}else{refTag=this._getRefTag(head);if(refTag){head.insertBefore(defStyle,refTag);}}}},appendStylesheet:function(path,options){options=Object.extend({media:'screen',type:'text/css',force:false},options||{});var refTag,style=document.createElement("link"),head=document.getElementsByTagName("head")[0];style.media=options.media;style.type=options.type;style.href=path;style.rel="Stylesheet";if(options.force){head.appendChild(style);}else{refTag=this._getRefTag(head);if(refTag){head.insertBefore(style,refTag);}}},appendStylesheetCb:function(cssURI,callback){var tmpCallback=function(){if(callback){callback.apply(this);}}.bindObj(this);if(cssURI===undefined||(typeof cssURI==='string'&&cssURI.length===0)){tmpCallback();return;}
var head=document.getElementsByTagName('head')[0];var links=head.getElementsByTagName('link');var i,iLen=links.length;for(var i=0;i<iLen;++i){if(links[i].getAttribute('href').indexOf(cssURI)!==-1){tmpCallback();return;}}
var pollTimeout=100;var link=document.createElement('link');link.setAttribute('rel','stylesheet');link.setAttribute('type','text/css');link.setAttribute('href',cssURI);head.appendChild(link);if(SAPO.Browser.IE){SAPO.Dom.Event.observe(link,'load',tmpCallback);}
else{function poll(){var sheets=document.styleSheets;var i,iLen=sheets.length;var el;for(i=0;i<iLen;++i){var css=sheets[i];el=css.ownerNode;if(el.getAttribute('href')&&el.getAttribute('href').indexOf(cssURI)!==-1){tmpCallback();return;}}
setTimeout(poll,pollTimeout);}
setTimeout(poll,pollTimeout);}},decToHex:function(dec){var normalizeTo2=function(val){if(val.length==1){val='0'+val;}
val=val.toUpperCase();return val;};if(typeof(dec)=='object'){var rDec=normalizeTo2(parseInt(dec.r,10).toString(16));var gDec=normalizeTo2(parseInt(dec.g,10).toString(16));var bDec=normalizeTo2(parseInt(dec.b,10).toString(16));return rDec+gDec+bDec;}else{dec+='';var rgb=dec.match(/\((\d+),\s?(\d+),\s?(\d+)\)/);if(rgb!==null){return normalizeTo2(parseInt(rgb[1],10).toString(16))+
normalizeTo2(parseInt(rgb[2],10).toString(16))+
normalizeTo2(parseInt(rgb[3],10).toString(16));}else{return normalizeTo2(parseInt(dec,10).toString(16));}}},hexToDec:function(hex){if(hex.indexOf('#')==0){hex=hex.substr(1);}
if(hex.length==6){return{r:parseInt(hex.substr(0,2),16),g:parseInt(hex.substr(2,2),16),b:parseInt(hex.substr(4,2),16)};}else if(hex.length==3){return{r:parseInt(hex.charAt(0)+hex.charAt(0)),g:parseInt(hex.charAt(1)+hex.charAt(1)),b:parseInt(hex.charAt(2)+hex.charAt(2))};}else if(hex.length<=2){return parseInt(hex,16);}},getPropertyFromStylesheet:function(selector,property){selector=selector.toLowerCase();var s,r,sheet;var i,iLen;s=document.styleSheets;if(!s)return null;var si,siLen=document.styleSheets.length;for(si=0;si<siLen;++si){sheet=document.styleSheets[si];r=sheet.rules?sheet.rules:sheet.cssRules;if(!r)return null;iLen=r.length;for(i=0;i<iLen;++i){if(!r[i].selectorText)continue;if(r[i].selectorText.toLowerCase()===selector){return r[i].style[property];}}}
return null;},debug:function()
{}};
if(!SAPO.Dom||typeof(SAPO.Dom)=='undefined'){SAPO.namespace('Dom');}
(function(){var chunker=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,done=0,toString=Object.prototype.toString,hasDuplicate=false,baseHasDuplicate=true;[0,0].sort(function(){baseHasDuplicate=false;return 0;});var Sizzle=function(selector,context,results,seed){results=results||[];context=context||document;var origContext=context;if(context.nodeType!==1&&context.nodeType!==9){return[];}
if(!selector||typeof selector!=="string"){return results;}
var parts=[],m,set,checkSet,extra,prune=true,contextXML=Sizzle.isXML(context),soFar=selector,ret,cur,pop,i;do{chunker.exec("");m=chunker.exec(soFar);if(m){soFar=m[3];parts.push(m[1]);if(m[2]){extra=m[3];break;}}}while(m);if(parts.length>1&&origPOS.exec(selector)){if(parts.length===2&&Expr.relative[parts[0]]){set=posProcess(parts[0]+parts[1],context);}else{set=Expr.relative[parts[0]]?[context]:Sizzle(parts.shift(),context);while(parts.length){selector=parts.shift();if(Expr.relative[selector]){selector+=parts.shift();}
set=posProcess(selector,set);}}}else{if(!seed&&parts.length>1&&context.nodeType===9&&!contextXML&&Expr.match.ID.test(parts[0])&&!Expr.match.ID.test(parts[parts.length-1])){ret=Sizzle.find(parts.shift(),context,contextXML);context=ret.expr?Sizzle.filter(ret.expr,ret.set)[0]:ret.set[0];}
if(context){ret=seed?{expr:parts.pop(),set:makeArray(seed)}:Sizzle.find(parts.pop(),parts.length===1&&(parts[0]==="~"||parts[0]==="+")&&context.parentNode?context.parentNode:context,contextXML);set=ret.expr?Sizzle.filter(ret.expr,ret.set):ret.set;if(parts.length>0){checkSet=makeArray(set);}else{prune=false;}
while(parts.length){cur=parts.pop();pop=cur;if(!Expr.relative[cur]){cur="";}else{pop=parts.pop();}
if(pop==null){pop=context;}
Expr.relative[cur](checkSet,pop,contextXML);}}else{checkSet=parts=[];}}
if(!checkSet){checkSet=set;}
if(!checkSet){Sizzle.error(cur||selector);}
if(toString.call(checkSet)==="[object Array]"){if(!prune){results.push.apply(results,checkSet);}else if(context&&context.nodeType===1){for(i=0;checkSet[i]!=null;i++){if(checkSet[i]&&(checkSet[i]===true||checkSet[i].nodeType===1&&Sizzle.contains(context,checkSet[i]))){results.push(set[i]);}}}else{for(i=0;checkSet[i]!=null;i++){if(checkSet[i]&&checkSet[i].nodeType===1){results.push(set[i]);}}}}else{makeArray(checkSet,results);}
if(extra){Sizzle(extra,origContext,results,seed);Sizzle.uniqueSort(results);}
return results;};Sizzle.uniqueSort=function(results){if(sortOrder){hasDuplicate=baseHasDuplicate;results.sort(sortOrder);if(hasDuplicate){for(var i=1;i<results.length;i++){if(results[i]===results[i-1]){results.splice(i--,1);}}}}
return results;};Sizzle.matches=function(expr,set){return Sizzle(expr,null,null,set);};Sizzle.find=function(expr,context,isXML){var set;if(!expr){return[];}
for(var i=0,l=Expr.order.length;i<l;i++){var type=Expr.order[i],match;if((match=Expr.leftMatch[type].exec(expr))){var left=match[1];match.splice(1,1);if(left.substr(left.length-1)!=="\\"){match[1]=(match[1]||"").replace(/\\/g,"");set=Expr.find[type](match,context,isXML);if(set!=null){expr=expr.replace(Expr.match[type],"");break;}}}}
if(!set){set=context.getElementsByTagName("*");}
return{set:set,expr:expr};};Sizzle.filter=function(expr,set,inplace,not){var old=expr,result=[],curLoop=set,match,anyFound,isXMLFilter=set&&set[0]&&Sizzle.isXML(set[0]);while(expr&&set.length){for(var type in Expr.filter){if((match=Expr.leftMatch[type].exec(expr))!=null&&match[2]){var filter=Expr.filter[type],found,item,left=match[1];anyFound=false;match.splice(1,1);if(left.substr(left.length-1)==="\\"){continue;}
if(curLoop===result){result=[];}
if(Expr.preFilter[type]){match=Expr.preFilter[type](match,curLoop,inplace,result,not,isXMLFilter);if(!match){anyFound=found=true;}else if(match===true){continue;}}
if(match){for(var i=0;(item=curLoop[i])!=null;i++){if(item){found=filter(item,match,i,curLoop);var pass=not^!!found;if(inplace&&found!=null){if(pass){anyFound=true;}else{curLoop[i]=false;}}else if(pass){result.push(item);anyFound=true;}}}}
if(found!==undefined){if(!inplace){curLoop=result;}
expr=expr.replace(Expr.match[type],"");if(!anyFound){return[];}
break;}}}
if(expr===old){if(anyFound==null){Sizzle.error(expr);}else{break;}}
old=expr;}
return curLoop;};Sizzle.error=function(msg){throw"Syntax error, unrecognized expression: "+msg;};var Expr=Sizzle.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(elem){return elem.getAttribute("href");}},relative:{"+":function(checkSet,part){var isPartStr=typeof part==="string",isTag=isPartStr&&!/\W/.test(part),isPartStrNotTag=isPartStr&&!isTag;if(isTag){part=part.toLowerCase();}
for(var i=0,l=checkSet.length,elem;i<l;i++){if((elem=checkSet[i])){while((elem=elem.previousSibling)&&elem.nodeType!==1){}
checkSet[i]=isPartStrNotTag||elem&&elem.nodeName.toLowerCase()===part?elem||false:elem===part;}}
if(isPartStrNotTag){Sizzle.filter(part,checkSet,true);}},">":function(checkSet,part){var isPartStr=typeof part==="string",elem,i=0,l=checkSet.length;if(isPartStr&&!/\W/.test(part)){part=part.toLowerCase();for(;i<l;i++){elem=checkSet[i];if(elem){var parent=elem.parentNode;checkSet[i]=parent.nodeName.toLowerCase()===part?parent:false;}}}else{for(;i<l;i++){elem=checkSet[i];if(elem){checkSet[i]=isPartStr?elem.parentNode:elem.parentNode===part;}}
if(isPartStr){Sizzle.filter(part,checkSet,true);}}},"":function(checkSet,part,isXML){var doneName=done++,checkFn=dirCheck,nodeCheck;if(typeof part==="string"&&!/\W/.test(part)){part=part.toLowerCase();nodeCheck=part;checkFn=dirNodeCheck;}
checkFn("parentNode",part,doneName,checkSet,nodeCheck,isXML);},"~":function(checkSet,part,isXML){var doneName=done++,checkFn=dirCheck,nodeCheck;if(typeof part==="string"&&!/\W/.test(part)){part=part.toLowerCase();nodeCheck=part;checkFn=dirNodeCheck;}
checkFn("previousSibling",part,doneName,checkSet,nodeCheck,isXML);}},find:{ID:function(match,context,isXML){if(typeof context.getElementById!=="undefined"&&!isXML){var m=context.getElementById(match[1]);return m&&m.parentNode?[m]:[];}},NAME:function(match,context){if(typeof context.getElementsByName!=="undefined"){var ret=[],results=context.getElementsByName(match[1]);for(var i=0,l=results.length;i<l;i++){if(results[i].getAttribute("name")===match[1]){ret.push(results[i]);}}
return ret.length===0?null:ret;}},TAG:function(match,context){return context.getElementsByTagName(match[1]);}},preFilter:{CLASS:function(match,curLoop,inplace,result,not,isXML){match=" "+match[1].replace(/\\/g,"")+" ";if(isXML){return match;}
for(var i=0,elem;(elem=curLoop[i])!=null;i++){if(elem){if(not^(elem.className&&(" "+elem.className+" ").replace(/[\t\n]/g," ").indexOf(match)>=0)){if(!inplace){result.push(elem);}}else if(inplace){curLoop[i]=false;}}}
return false;},ID:function(match){return match[1].replace(/\\/g,"");},TAG:function(match,curLoop){return match[1].toLowerCase();},CHILD:function(match){if(match[1]==="nth"){var test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(match[2]==="even"&&"2n"||match[2]==="odd"&&"2n+1"||!/\D/.test(match[2])&&"0n+"+match[2]||match[2]);match[2]=(test[1]+(test[2]||1))-0;match[3]=test[3]-0;}
match[0]=done++;return match;},ATTR:function(match,curLoop,inplace,result,not,isXML){var name=match[1].replace(/\\/g,"");if(!isXML&&Expr.attrMap[name]){match[1]=Expr.attrMap[name];}
if(match[2]==="~="){match[4]=" "+match[4]+" ";}
return match;},PSEUDO:function(match,curLoop,inplace,result,not){if(match[1]==="not"){if((chunker.exec(match[3])||"").length>1||/^\w/.test(match[3])){match[3]=Sizzle(match[3],null,null,curLoop);}else{var ret=Sizzle.filter(match[3],curLoop,inplace,true^not);if(!inplace){result.push.apply(result,ret);}
return false;}}else if(Expr.match.POS.test(match[0])||Expr.match.CHILD.test(match[0])){return true;}
return match;},POS:function(match){match.unshift(true);return match;}},filters:{enabled:function(elem){return elem.disabled===false&&elem.type!=="hidden";},disabled:function(elem){return elem.disabled===true;},checked:function(elem){return elem.checked===true;},selected:function(elem){elem.parentNode.selectedIndex;return elem.selected===true;},parent:function(elem){return!!elem.firstChild;},empty:function(elem){return!elem.firstChild;},has:function(elem,i,match){return!!Sizzle(match[3],elem).length;},header:function(elem){return(/h\d/i).test(elem.nodeName);},text:function(elem){return"text"===elem.type;},radio:function(elem){return"radio"===elem.type;},checkbox:function(elem){return"checkbox"===elem.type;},file:function(elem){return"file"===elem.type;},password:function(elem){return"password"===elem.type;},submit:function(elem){return"submit"===elem.type;},image:function(elem){return"image"===elem.type;},reset:function(elem){return"reset"===elem.type;},button:function(elem){return"button"===elem.type||elem.nodeName.toLowerCase()==="button";},input:function(elem){return(/input|select|textarea|button/i).test(elem.nodeName);}},setFilters:{first:function(elem,i){return i===0;},last:function(elem,i,match,array){return i===array.length-1;},even:function(elem,i){return i%2===0;},odd:function(elem,i){return i%2===1;},lt:function(elem,i,match){return i<match[3]-0;},gt:function(elem,i,match){return i>match[3]-0;},nth:function(elem,i,match){return match[3]-0===i;},eq:function(elem,i,match){return match[3]-0===i;}},filter:{PSEUDO:function(elem,match,i,array){var name=match[1],filter=Expr.filters[name];if(filter){return filter(elem,i,match,array);}else if(name==="contains"){return(elem.textContent||elem.innerText||Sizzle.getText([elem])||"").indexOf(match[3])>=0;}else if(name==="not"){var not=match[3];for(var j=0,l=not.length;j<l;j++){if(not[j]===elem){return false;}}
return true;}else{Sizzle.error("Syntax error, unrecognized expression: "+name);}},CHILD:function(elem,match){var type=match[1],node=elem;switch(type){case'only':case'first':while((node=node.previousSibling)){if(node.nodeType===1){return false;}}
if(type==="first"){return true;}
node=elem;case'last':while((node=node.nextSibling)){if(node.nodeType===1){return false;}}
return true;case'nth':var first=match[2],last=match[3];if(first===1&&last===0){return true;}
var doneName=match[0],parent=elem.parentNode;if(parent&&(parent.sizcache!==doneName||!elem.nodeIndex)){var count=0;for(node=parent.firstChild;node;node=node.nextSibling){if(node.nodeType===1){node.nodeIndex=++count;}}
parent.sizcache=doneName;}
var diff=elem.nodeIndex-last;if(first===0){return diff===0;}else{return(diff%first===0&&diff/first>=0);}}},ID:function(elem,match){return elem.nodeType===1&&elem.getAttribute("id")===match;},TAG:function(elem,match){return(match==="*"&&elem.nodeType===1)||elem.nodeName.toLowerCase()===match;},CLASS:function(elem,match){return(" "+(elem.className||elem.getAttribute("class"))+" ").indexOf(match)>-1;},ATTR:function(elem,match){var name=match[1],result=Expr.attrHandle[name]?Expr.attrHandle[name](elem):elem[name]!=null?elem[name]:elem.getAttribute(name),value=result+"",type=match[2],check=match[4];return result==null?type==="!=":type==="="?value===check:type==="*="?value.indexOf(check)>=0:type==="~="?(" "+value+" ").indexOf(check)>=0:!check?value&&result!==false:type==="!="?value!==check:type==="^="?value.indexOf(check)===0:type==="$="?value.substr(value.length-check.length)===check:type==="|="?value===check||value.substr(0,check.length+1)===check+"-":false;},POS:function(elem,match,i,array){var name=match[2],filter=Expr.setFilters[name];if(filter){return filter(elem,i,match,array);}}}};var origPOS=Expr.match.POS,fescape=function(all,num){return"\\"+(num-0+1);};for(var type in Expr.match){Expr.match[type]=new RegExp(Expr.match[type].source+(/(?![^\[]*\])(?![^\(]*\))/.source));Expr.leftMatch[type]=new RegExp(/(^(?:.|\r|\n)*?)/.source+Expr.match[type].source.replace(/\\(\d+)/g,fescape));}
var makeArray=function(array,results){array=Array.prototype.slice.call(array,0);if(results){results.push.apply(results,array);return results;}
return array;};try{Array.prototype.slice.call(document.documentElement.childNodes,0)[0].nodeType;}catch(e){makeArray=function(array,results){var ret=results||[],i=0;if(toString.call(array)==="[object Array]"){Array.prototype.push.apply(ret,array);}else{if(typeof array.length==="number"){for(var l=array.length;i<l;i++){ret.push(array[i]);}}else{for(;array[i];i++){ret.push(array[i]);}}}
return ret;};}
var sortOrder,siblingCheck;if(document.documentElement.compareDocumentPosition){sortOrder=function(a,b){if(a===b){hasDuplicate=true;return 0;}
if(!a.compareDocumentPosition||!b.compareDocumentPosition){return a.compareDocumentPosition?-1:1;}
return a.compareDocumentPosition(b)&4?-1:1;};}else{sortOrder=function(a,b){var ap=[],bp=[],aup=a.parentNode,bup=b.parentNode,cur=aup,al,bl;if(a===b){hasDuplicate=true;return 0;}else if(aup===bup){return siblingCheck(a,b);}else if(!aup){return-1;}else if(!bup){return 1;}
while(cur){ap.unshift(cur);cur=cur.parentNode;}
cur=bup;while(cur){bp.unshift(cur);cur=cur.parentNode;}
al=ap.length;bl=bp.length;for(var i=0;i<al&&i<bl;i++){if(ap[i]!==bp[i]){return siblingCheck(ap[i],bp[i]);}}
return i===al?siblingCheck(a,bp[i],-1):siblingCheck(ap[i],b,1);};siblingCheck=function(a,b,ret){if(a===b){return ret;}
var cur=a.nextSibling;while(cur){if(cur===b){return-1;}
cur=cur.nextSibling;}
return 1;};}
Sizzle.getText=function(elems){var ret="",elem;for(var i=0;elems[i];i++){elem=elems[i];if(elem.nodeType===3||elem.nodeType===4){ret+=elem.nodeValue;}else if(elem.nodeType!==8){ret+=Sizzle.getText(elem.childNodes);}}
return ret;};(function(){var form=document.createElement("div"),id="script"+(new Date()).getTime();form.innerHTML="<a name='"+id+"'/>";var root=document.documentElement;root.insertBefore(form,root.firstChild);if(document.getElementById(id)){Expr.find.ID=function(match,context,isXML){if(typeof context.getElementById!=="undefined"&&!isXML){var m=context.getElementById(match[1]);return m?m.id===match[1]||typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id").nodeValue===match[1]?[m]:undefined:[];}};Expr.filter.ID=function(elem,match){var node=typeof elem.getAttributeNode!=="undefined"&&elem.getAttributeNode("id");return elem.nodeType===1&&node&&node.nodeValue===match;};}
root.removeChild(form);root=form=null;})();(function(){var div=document.createElement("div");div.appendChild(document.createComment(""));if(div.getElementsByTagName("*").length>0){Expr.find.TAG=function(match,context){var results=context.getElementsByTagName(match[1]);if(match[1]==="*"){var tmp=[];for(var i=0;results[i];i++){if(results[i].nodeType===1){tmp.push(results[i]);}}
results=tmp;}
return results;};}
div.innerHTML="<a href='#'></a>";if(div.firstChild&&typeof div.firstChild.getAttribute!=="undefined"&&div.firstChild.getAttribute("href")!=="#"){Expr.attrHandle.href=function(elem){return elem.getAttribute("href",2);};}
div=null;})();if(document.querySelectorAll){(function(){var oldSizzle=Sizzle,div=document.createElement("div");div.innerHTML="<p class='TEST'></p>";if(div.querySelectorAll&&div.querySelectorAll(".TEST").length===0){return;}
Sizzle=function(query,context,extra,seed){context=context||document;if(!seed&&context.nodeType===9&&!Sizzle.isXML(context)){try{return makeArray(context.querySelectorAll(query),extra);}catch(e){}}
return oldSizzle(query,context,extra,seed);};for(var prop in oldSizzle){Sizzle[prop]=oldSizzle[prop];}
div=null;})();}
(function(){var div=document.createElement("div");div.innerHTML="<div class='test e'></div><div class='test'></div>";if(!div.getElementsByClassName||div.getElementsByClassName("e").length===0){return;}
div.lastChild.className="e";if(div.getElementsByClassName("e").length===1){return;}
Expr.order.splice(1,0,"CLASS");Expr.find.CLASS=function(match,context,isXML){if(typeof context.getElementsByClassName!=="undefined"&&!isXML){return context.getElementsByClassName(match[1]);}};div=null;})();function dirNodeCheck(dir,cur,doneName,checkSet,nodeCheck,isXML){for(var i=0,l=checkSet.length;i<l;i++){var elem=checkSet[i];if(elem){elem=elem[dir];var match=false;while(elem){if(elem.sizcache===doneName){match=checkSet[elem.sizset];break;}
if(elem.nodeType===1&&!isXML){elem.sizcache=doneName;elem.sizset=i;}
if(elem.nodeName.toLowerCase()===cur){match=elem;break;}
elem=elem[dir];}
checkSet[i]=match;}}}
function dirCheck(dir,cur,doneName,checkSet,nodeCheck,isXML){for(var i=0,l=checkSet.length;i<l;i++){var elem=checkSet[i];if(elem){elem=elem[dir];var match=false;while(elem){if(elem.sizcache===doneName){match=checkSet[elem.sizset];break;}
if(elem.nodeType===1){if(!isXML){elem.sizcache=doneName;elem.sizset=i;}
if(typeof cur!=="string"){if(elem===cur){match=true;break;}}else if(Sizzle.filter(cur,[elem]).length>0){match=elem;break;}}
elem=elem[dir];}
checkSet[i]=match;}}}
Sizzle.contains=document.compareDocumentPosition?function(a,b){return!!(a.compareDocumentPosition(b)&16);}:function(a,b){return a!==b&&(a.contains?a.contains(b):true);};Sizzle.isXML=function(elem){var documentElement=(elem?elem.ownerDocument||elem:0).documentElement;return documentElement?documentElement.nodeName!=="HTML":false;};var posProcess=function(selector,context){var tmpSet=[],later="",match,root=context.nodeType?[context]:context;while((match=Expr.match.PSEUDO.exec(selector))){later+=match[0];selector=selector.replace(Expr.match.PSEUDO,"");}
selector=Expr.relative[selector]?selector+"*":selector;for(var i=0,l=root.length;i<l;i++){Sizzle(selector,root[i],tmpSet);}
return Sizzle.filter(later,tmpSet);};SAPO.Dom.Selector={};SAPO.Dom.Selector.select=Sizzle;SAPO.Dom.Selector.matches=Sizzle.matches;SAPO.Dom.Selector.find=Sizzle.find;})();
if(!SAPO.Widget||typeof(SAPO.Widget)=='undefined'){SAPO.namespace('Widget');}
SAPO.Widget.ShareThis=function(options){this.init(options);};SAPO.Widget.ShareThis.version='1.1';SAPO.Widget.ShareThis.prototype={init:function(){this.services={'sapo':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/sapo.png',url:"http://links.sapo.pt/post?v=3&url=_URL_&title=_TITLE_",text:'SAPO Links',sprite:true,cssClass:"sapo_sharethis_sprite_sapo"},'twitter':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/twitter.png',url:"http://twitter.com/intent/tweet/?url=_URL_&text=_TITLE_+via+%40SAPO+ShareThis",text:'Twitter',sprite:true,cssClass:"sapo_sharethis_sprite_twitter"},'facebook':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/facebook.png',url:'http://www.facebook.com/share.php?u=_URL_&t=_TITLE_',text:'Facebook',sprite:true,cssClass:"sapo_sharethis_sprite_facebook"},'delicious':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/delicious.png',url:"http://del.icio.us/post?url=_URL_&title=_TITLE_",text:'del.icio.us',sprite:true,cssClass:"sapo_sharethis_sprite_delicious"},'digg':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/digg.png',url:"http://digg.com/submit?phase=2&url=_URL_&title=_TITLE_",text:'Digg',sprite:true,cssClass:"sapo_sharethis_sprite_digg"},'reddit':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/reddit.png',url:"http://reddit.com/submit?url=_URL_&title=_TITLE_",text:'Reddit',sprite:true,cssClass:"sapo_sharethis_sprite_reddit"},'sphere':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/sphere.png',url:"http://www.sphere.com/search?q=sphereit:_URL_&title=_TITLE_",text:'Sphere',sprite:true,cssClass:"sapo_sharethis_sprite_sphere"},'stumbleupon':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/stumbleupon.png',url:"http://www.stumbleupon.com/submit?url=_URL_&title=_TITLE_",text:'StumbleUpon',sprite:true,cssClass:"sapo_sharethis_sprite_stumbleupon"},'technorati':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/technorati.png',url:"http://technorati.com/faves?add=_URL_",text:'Technorati',sprite:true,cssClass:"sapo_sharethis_sprite_technorati"},'connotea':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/connotea.png',url:"http://www.connotea.org/addpopup?continue=confirm&uri=_URL_&title=_TITLE_",text:'Connotea',sprite:true,cssClass:"sapo_sharethis_sprite_connotea"},'furl':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/furl.png',url:"http://furl.net/storeIt.jsp?u=_URL_&t=_TITLE_",text:'Furl',sprite:true,cssClass:"sapo_sharethis_sprite_furl"},'google':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/google.png',url:"http://www.google.com/bookmarks/mark?op=edit&bkmk=_URL_&title=_TITLE_",text:'Google bookmarks',sprite:true,cssClass:"sapo_sharethis_sprite_google"},'blinklist':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/blinklist.png',url:"http://blinklist.com/index.php?Action=Blink/addblink.php&Url=_URL_&Title=_TITLE_",text:'Blinklist',sprite:true,cssClass:"sapo_sharethis_sprite_blinklist"},'live':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/live.png',url:'https://favorites.live.com/quickadd.aspx?marklet=1&mkt=en-us&url=_URL_&title=_TITLE_&top=1',text:'Windows Live',sprite:true,cssClass:"sapo_sharethis_sprite_live"},'newsvine':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/newsvine.png',url:"http://www.newsvine.com/_wine/save?u=_URL_&h=_TITLE_",text:'Newsvine',sprite:true,cssClass:"sapo_sharethis_sprite_newsvine"},'tailrank':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/tailrank.png',url:"http://tailrank.com/share/?link_href=_URL_&title=_TITLE_",text:'Tailrank',sprite:true,cssClass:"sapo_sharethis_sprite_tailrank"},'bebo':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/bebo.png',url:'http://www.bebo.com/c/share?Url=_URL_&Title=_TITLE_&MID=8974376238&TUUID=fc7850b8-964c-47bd-8a91-db1d2a5cad3c',text:'Bebo',sprite:true,cssClass:"sapo_sharethis_sprite_bebo"},'myspace':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/myspace.png',url:'http://www.myspace.com/index.cfm?fuseaction=postto&t=_TITLE_&c=&u=_URL_&l=',text:'MySpace',sprite:true,cssClass:"sapo_sharethis_sprite_myspace"}};this.videoServices={'hi5':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/hi5.png',url:'http://www.hi5.com/friend/checkViewedVideo.do?t=_TITLE_&url=_URL_&embeddable=true&simple=true',text:'Hi5',sprite:true,cssClass:"sapo_sharethis_sprite_hi5"},'orkut':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/orkut.png',url:'http://www.orkut.com/FavoriteVideos.aspx?u=_URL_',text:'Orkut',sprite:true,cssClass:"sapo_sharethis_sprite_orkut"},'liveSpaces':{icon:'http://js.sapo.pt/Assets/Images/ShareThis/livespaces.png',url:'http://spaces.live.com/BlogIt.aspx?Title=_TITLE_&SourceURL=_URL_',text:'Live Spaces',sprite:true,cssClass:"sapo_sharethis_sprite_livespaces"}};var legacy={email_name_from:'Nome do remetente',email_name_to:'Nome do destinat&aacute;rio',email_to:'Email do destinat&aacute;rio',email_send:'Enviar',email_sending:'A enviar...',email_sending_error:'Erro! Tente novamente...',email_invalid:'Email inválido',email_required:'Todos os campos são obrigatórios.',email_share:'Partilhar por email',email_close:'fechar',pdf_download:'Download PDF&hellip;',pdf_error:'Erro! Clique para tentar de novo.',closeTitle:'Fechar',tooltip_title:'Partilhar',email_tab_title:'Email',email_link_text:'Enviar email',pdf_tab_title:'PDF',pdf_link_text:'Gerar PDF',web_tab_title:'Internet'}
if(typeof(SAPO_ShareThis_i18n)!="object")
SAPO_ShareThis_i18n={};SAPO.Utility.I18n.init(SAPO_ShareThis_i18n,(arguments.length>0)?(arguments[0].language!='pt'?arguments[0].language:'pt_PT'):'pt_PT');this.language=SAPO.Utility.I18n.getLang();var lang_values={};if(typeof(arguments[0].lang_values)=='object'){lang_values=arguments[0].lang_values;for(var key in lang_values){if(typeof(legacy[key])!="function"){SAPO.Utility.I18n._baseObj[legacy[key]]=lang_values[key];}}}
this._i18n=SAPO.Utility.I18n.alias();this.options=SAPO.extendObj({debug:true,target:false,url:false,mode:3,only:false,exclude:[],clickOutClose:false,video:false,custom_services:null,tooltip_title:this._i18n('Partilhar'),email_tab_title:this._i18n('Email'),email_link_text:this._i18n('Enviar email'),pdf_tab_title:this._i18n('PDF'),pdf_link_text:this._i18n('Gerar PDF'),web_tab_title:this._i18n('Internet'),pdf_json_url:'http://webthumbs.sapo.pt/pdfjson?url=_URL_&rand=_RANDOM_',email_url:'http://jsphp.sapo.pt/Widget/ShareThis/mail.php?language='+this.language,pdf:true,email:true,tab:'web',max_retries:10,pageTitle:document.title||'',closeTitle:this._i18n('Fechar'),element_id:'wsharethis_'+Math.floor(Math.random()*999999),cssURI:"http://js.sapo.pt/Assets/Images/ShareThis/style.css",servicesCallback:false,pdfCallback:false,emailCallback:false,specificEmailTemplate:false,visible:[],showMoreSymbol:'(+)',useSprite:true,unknownIcon:'http://js.sapo.pt/Assets/Images/ShareThis/unknown.gif',openAsPopup:false},arguments[0]||{});this.options.mode=parseInt(this.options.mode,10);if(!this.options.only&&this.options.exclude.length==0){if(this.options.mode<=1){this.options.only=["sapo","twitter","facebook","hi5","orkut"];}else if(this.options.mode!=4){this.options.only=["sapo","twitter","facebook","hi5","technorati","orkut","digg","reddit"];}}
if(this.options.specificEmailTemplate){this.options.email_url='http://jsphp.sapo.pt/Widget/ShareThis/mail.php?template='+this.options.specificEmailTemplate['name'];if(typeof(this.options.specificEmailTemplate['language'])){var strn='&language='+this.options.specificEmailTemplate['language'];this.options.email_url+=strn;}else{var strn='&language='+this.language;this.options.email_url+=strn;}}
if(this.options.custom_services){this.services=SAPO.extendObj(this.services,this.options.custom_services);}
if(this.options.url){this.urlToShare=this.options.url;}else{this.urlToShare=location.href;}
this._countPDFVarChanged=0;this.filterServices();this.addCss();if(this.options.target){this.element=s$(this.options.target);if(this.element.nodeName.toLowerCase()!="script"){if(this.options.mode==3){var element=this.createActionLink(this.options.tooltip_title);element.id=this.options.element_id;this.element.appendChild(element);this.sharethis_tooltip=element;}}else{var div=document.createElement("div");div.id=this.options.element_id;if(this.options.mode==3){var a=this.createActionLink(this.options.tooltip_title);a.id=this.options.element_id;div.appendChild(a);this.sharethis_tooltip=a;}
this.element.parentNode.insertBefore(div,this.element);this.element=div;}
SAPO.Dom.Css.addClassName(this.element,'sapo_sharethis_container');}else{var target=this.currentScriptElement();var div=document.createElement("div");div.id=this.options.element_id;if(this.options.mode==3){var a=this.createActionLink(this.options.tooltip_title);div.appendChild(a);this.sharethis_tooltip=a;}
if(target.parentNode.nodeName.toLowerCase()!="head"){target.parentNode.insertBefore(div,target);}else{throw("target must be defined or script tag must be invoked inside the body tag");return;}
this.element=s$(this.options.element_id);SAPO.Dom.Css.addClassName(this.element,'sapo_sharethis_container');}
switch(this.options.mode){case 0:this.outputIconView();SAPO.Dom.Css.addClassName(this.element,'sapo_sharethis_iconview');if(this.options.useSprite){SAPO.Dom.Css.addClassName(this.element,'clearfix');SAPO.Dom.Css.addClassName(this.element,'sapo_sharethis_sprites');}
break;case 1:this.outputTextView();SAPO.Dom.Css.addClassName(this.element,'sapo_sharethis_textview');break;case 2:this.outputMixedView();SAPO.Dom.Css.addClassName(this.element,'sapo_sharethis_mixedview')
SAPO.Dom.Css.addClassName(this.element,'clearfix');break;case 3:this.outputTooltipView();SAPO.Dom.Css.addClassName(this.sharethis_tooltip,'sapo_sharethis_tooltipview')
SAPO.Dom.Css.addClassName(this.sharethis_tooltip,'clearfix');break;case 4:this.outputShowMoreView();SAPO.Dom.Css.addClassName(this.element,'sapo_sharethis_iconview');if(this.options.useSprite){SAPO.Dom.Css.addClassName(this.element,'clearfix');SAPO.Dom.Css.addClassName(this.element,'sapo_sharethis_sprites');}
break;}
this.setBehaviours();},currentScriptElement:function(){var aScripts=document.getElementsByTagName('script');if(aScripts.length>0){return aScripts[(aScripts.length-1)];}else{return false;}},statisticsCallback:function(urlToShare,title,type){SAPO.logReferer("http://js.sapo.pt/Widget/ShareThis/",{etype:'libsapojs-sharethis',s:location.hostname,pg:location.href,dc:title,swakt:'8C4DE585-F4F5-4DA5-A80E-558A718AC35B',swasubsection:type,ref:urlToShare});},createActionLink:function(content){var link=document.createElement("a");link.setAttribute('href','#');link.onclick=function(){return false;};link.innerHTML=content;return link;},outputServiceList:function(target){var returnArray=[];for(var srv in this.services){if(!arguments[1]||(arguments[1]&&((!arguments[2])?SAPO.Utility.Array.inArray(srv,arguments[1]):!SAPO.Utility.Array.inArray(srv,arguments[1])))){if(this.services.hasOwnProperty(srv)&&(typeof(this.services[srv])!="function")){if(target){target.appendChild(this.outputLink(this.services[srv],srv));}else{returnArray.push(this.outputLink(this.services[srv],srv));}}}}
if(this.options.video){for(var srv in this.videoServices){if(!arguments[1]||(arguments[1]&&((!arguments[2])?SAPO.Utility.Array.inArray(srv,arguments[1]):!SAPO.Utility.Array.inArray(srv,arguments[1])))){if(this.videoServices.hasOwnProperty(srv)&&(typeof(this.videoServices[srv])!="function")){if(target){target.appendChild(this.outputLink(this.videoServices[srv],srv));}else{returnArray.push(this.outputLink(this.videoServices[srv],srv));}}}}}
if(returnArray.length>0)
return returnArray;},outputIconView:function(){this.container=document.createElement("div");var parent=this.element.parentNode;this.element.appendChild(this.container);this.outputServiceList(this.container);if(this.options.email){this.email_link=this.createActionLink(this.options.email_tab_title);SAPO.Dom.Element.insertTop(this.email_link,this.element);}
if(this.options.pdf){this.pdf_link=this.createActionLink(this.options.pdf_tab_title);SAPO.Dom.Css.addClassName(this.pdf_link,'sapo_sharethis_generate_pdf');SAPO.Dom.Element.insertTop(this.pdf_link,this.element);}
var span=document.createElement("span");span.innerHTML=this.options.tooltip_title;SAPO.Dom.Element.insertTop(span,this.element);},outputTextView:function(){var links=this.outputServiceList();this.container=document.createElement("div");SAPO.Dom.Element.insertAfter(this.container,this.element);var newtext;for(var i=0;i<links.length;i++){this.container.appendChild(links[i]);if(i!=links.length-1){newtext=document.createTextNode(' | ');this.container.appendChild(newtext);}}
if(this.options.email){this.email_link=this.createActionLink(this.options.email_tab_title);SAPO.Dom.Element.insertTop(this.email_link,this.element);}
if(this.options.pdf){this.pdf_link=this.createActionLink(this.options.pdf_tab_title);SAPO.Dom.Css.addClassName(this.pdf_link,'sapo_sharethis_generate_pdf');SAPO.Dom.Element.insertTop(this.pdf_link,this.element);}
var span=document.createElement("span");span.innerHTML=this.options.tooltip_title;SAPO.Dom.Element.insertTop(span,this.element);},outputMixedView:function(){this.tabs=document.createElement('div');SAPO.Dom.Css.addClassName(this.tabs,'sapo_sharethis_tab_row');SAPO.Dom.Css.addClassName(this.tabs,'clearfix');this.container=document.createElement('div');SAPO.Dom.Css.addClassName(this.container,'sapo_sharethis_tab_container');SAPO.Dom.Css.addClassName(this.container,'clearfix');this.element.appendChild(this.tabs);this.element.appendChild(this.container);if(this.options.tab!='web'&&(this.options.pdf||this.options.email)){var tabcontent=this.createTab(this.options.web_tab_title,false);}else{var tabcontent=this.createTab(this.options.web_tab_title,true);}
this.outputServiceList(tabcontent);if(this.options.pdf){if(this.options.tab=='pdf'){tabcontent=this.createTab(this.options.pdf_tab_title,true);}else{tabcontent=this.createTab(this.options.pdf_tab_title,false);}
this.pdf_link=this.createActionLink(this.options.pdf_tab_title);SAPO.Dom.Css.addClassName(this.pdf_link,'sapo_sharethis_generate_pdf');tabcontent.appendChild(this.pdf_link);}
if(this.options.email){if(this.options.tab=='email'){tabcontent=this.createTab(this.options.email_tab_title,true);}else{tabcontent=this.createTab(this.options.email_tab_title,false);}
tabcontent.appendChild(this.createEmailForm());}},outputTooltipView:function(){this.outputTooltipSkeleton();this.element.appendChild(this.overlay);SAPO.Dom.Css.addClassName(this.overlay,'sapo_sharethis_tooltip_container');this.tabs=document.createElement('div');SAPO.Dom.Css.addClassName(this.tabs,'sapo_sharethis_tab_row');SAPO.Dom.Css.addClassName(this.tabs,'clearfix');this.container=document.createElement('div');SAPO.Dom.Css.addClassName(this.container,'sapo_sharethis_tab_container');SAPO.Dom.Css.addClassName(this.container,'clearfix');this.overlay.appendChild(this.tabs);this.overlay.appendChild(this.container);if(this.options.tab!='web'&&(this.options.pdf||this.options.email)){var tabcontent=this.createTab(this.options.web_tab_title,false);}else{var tabcontent=this.createTab(this.options.web_tab_title,true);}
this.outputServiceList(tabcontent);if(this.options.pdf){if(this.options.tab=='pdf'){tabcontent=this.createTab(this.options.pdf_tab_title,true);}else{tabcontent=this.createTab(this.options.pdf_tab_title,false);}
this.pdf_link=this.createActionLink(this.options.pdf_tab_title);SAPO.Dom.Css.addClassName(this.pdf_link,'sapo_sharethis_generate_pdf');tabcontent.appendChild(this.pdf_link);}
if(this.options.email){if(this.options.tab=='email'){tabcontent=this.createTab(this.options.email_tab_title,true);}else{tabcontent=this.createTab(this.options.email_tab_title,false);}
tabcontent.appendChild(this.createEmailForm());}
var closeButton=this.createActionLink(this.options.closeTitle);SAPO.Dom.Css.addClassName(closeButton,'sapo_sharethis_tooltip_close');this.tabs.appendChild(closeButton);SAPO.Dom.Event.observe(closeButton,'click',function(evt){SAPO.Dom.Event.stop(evt);SAPO.Dom.Css.hide(this.overlay);}.bindObjEvent(this));SAPO.Dom.Event.observe(this.sharethis_tooltip,'click',function(evt){SAPO.Dom.Event.stop(evt);this.sharethis_tooltip.blur();SAPO.Dom.Css.toggle(this.overlay);}.bindObjEvent(this));},outputShowMoreView:function(){this.container=document.createElement("div");this.element.appendChild(this.container);if(this.options.visible.length>0){this.outputServiceList(this.container,this.options.visible);}else
this.outputServiceList(this.container);if(this.options.email){this.email_link=this.createActionLink(this.options.email_tab_title);SAPO.Dom.Element.insertTop(this.email_link,this.element);}
if(this.options.pdf){this.pdf_link=this.createActionLink(this.options.pdf_tab_title);SAPO.Dom.Css.addClassName(this.pdf_link,'sapo_sharethis_generate_pdf');SAPO.Dom.Element.insertTop(this.pdf_link,this.element);}
if(this.options.visible.length>0){this.morecontainer=document.createElement("p");this.outputServiceList(this.morecontainer,this.options.visible,true);SAPO.Dom.Css.hide(this.morecontainer);if(this.morecontainer.childNodes.length>0){this.showMoreButton=this.createActionLink(this.options.showMoreSymbol);SAPO.Dom.Event.observe(this.showMoreButton,'click',function(evt){SAPO.Dom.Event.stop(evt);SAPO.Dom.Css.toggle(this.morecontainer);}.bindObjEvent(this));this.container.appendChild(this.showMoreButton);this.container.appendChild(this.morecontainer);}}
var span=document.createElement("span");span.innerHTML=this.options.tooltip_title;SAPO.Dom.Element.insertTop(span,this.element);},outputTooltipSkeleton:function(){this.overlay=document.createElement('div');SAPO.Dom.Css.hide(this.overlay);this.element.appendChild(this.overlay);},createTab:function(title,visible)
{var tab=this.createActionLink(title);tab.setAttribute("href","#"+title);var area=document.createElement("div");SAPO.Dom.Css.addClassName(area,'sapo_sharethis_tab');this.tabs.appendChild(tab);this.container.appendChild(area);if(visible){SAPO.Dom.Css.addClassName(tab,'sapo_sharethis_tab_selected');}else{SAPO.Dom.Css.hide(area);}
SAPO.Dom.Event.observe(tab,'click',function(evt){var links=this.tabs.getElementsByTagName('a');for(var x=0;x<links.length;x++){SAPO.Dom.Css.removeClassName(links[x],'sapo_sharethis_tab_selected');}
SAPO.Dom.Css.addClassName(tab,'sapo_sharethis_tab_selected');var divs=this.container.getElementsByTagName('div');for(var x=0;x<divs.length;x++){SAPO.Dom.Css.hide(divs[x]);}
SAPO.Dom.Css.show(area);SAPO.Dom.Event.stop(evt);}.bindObjEvent(this));return area;},outputLink:function(service,type){var link=document.createElement('a');link.setAttribute('href',service.url.replace(/_URL_/,encodeURIComponent(this.urlToShare)).replace(/_TITLE_/,encodeURIComponent(this.options.pageTitle)));link.setAttribute('target','_blank')
link.setAttribute('title',service.text);if(this.options.mode!=1){if(!service.sprite||!this.options.useSprite){var img=document.createElement("img");if(!service.icon)
img.src=this.options.unknownIcon;else
img.src=service.icon;img.alt=service.text;link.appendChild(img);}else{if(service.cssClass){var img=document.createElement("span");SAPO.Dom.Css.addClassName(img,service.cssClass);SAPO.Dom.Css.addClassName(img,"sapo_sharethis_sprite_image");SAPO.Dom.Css.setStyle(img,{"height":'17px',"width":"16px","display":'block'});}else{var img=document.createElement("img");if(!service.icon)
img.src=this.options.unknownIcon;else
img.src=service.icon;img.alt=service.text;}
link.appendChild(img);}}
if((this.options.mode!=0)&&(this.options.mode!=4)){var text=document.createTextNode(service.text);link.appendChild(text);}
SAPO.Dom.Event.observe(link,'click',function(){this.statisticsCallback.call(window,this.urlToShare,this.options.pageTitle,type);}.bindObjEvent(this));if(this.options.servicesCallback&&typeof(this.options.servicesCallback)=='function'){SAPO.Dom.Event.observe(link,'click',function(event,type){this.options.servicesCallback.call(window,this.urlToShare,this.options.pageTitle,type);}.bindObjEvent(this,type));}
if(this.options.openAsPopup){SAPO.Dom.Event.observe(link,'click',function(event){var href=link.getAttribute("href");window.open(href);if(event.preventDefault){event.preventDefault();}else{event.cancelBubble=true;}}.bindObjEvent(this));}
return link;},filterServices:function(){for(var x=0;x<this.options.exclude;x++){if(this.services[this.options.exclude[x]])
delete this.services[this.options.exclude[x]];else if(this.options.video&&this.videoServices[this.options.exclude[x]])
delete this.videoServices[this.options.exclude[x]];}
if(this.options.only){for(srv in this.services){if(this.services.hasOwnProperty(srv)&&(typeof(this.services[srv])!="function")){if(!SAPO.Utility.Array.inArray(srv,this.options.only))
delete this.services[srv];}}
if(this.options.video){for(srv in this.videoServices){if(this.videoServices.hasOwnProperty(srv)&&(typeof(this.videoServices[srv])!="function")){if(!SAPO.Utility.Array.inArray(srv,this.options.only))
delete this.videoServices[srv];}}}}},setBehaviours:function(){if(this.options.pdf){this.pdf_observe_cache=this.getPDF.bindObjEvent(this);SAPO.Dom.Event.observe(this.pdf_link,'click',this.pdf_observe_cache);}
if(this.options.email&&(this.options.mode<2||this.options.mode==4)){this.floating_balloon=this.createFloatingEmailBalloon();this.floating_balloon.appendChild(this.createEmailForm());this.element.appendChild(this.floating_balloon);this.email_observe_cache=this.emailSendInPlace.bindObjEvent(this);SAPO.Dom.Event.observe(this.email_link,'click',this.email_observe_cache);}
if(this.options.email){if(this.options.clickOutClose&&this.options.mode<2){SAPO.Dom.Event.observe(document,'click',function(ev){if(typeof(this.floating_balloon)=="undefined"||ev.target==this.email_link){return;}
var curNode=ev.target;while(curNode!=null&&curNode.nodeName.toLowerCase()!='body'){if(curNode.className==this.floating_balloon.className){return;}
curNode=curNode.parentNode;}
SAPO.Dom.Css.hide(this.floating_balloon);}.bindObjEvent(this));}}
if(this.options.clickOutClose&&this.options.mode==3){SAPO.Dom.Event.observe(document,'click',function(ev){var curNode=ev.target;while(curNode!=null&&curNode.nodeName.toLowerCase()!='body'){if(curNode.id==this.options.element_id||(curNode.id==this.options.target&&this.options.target)){return;}
curNode=curNode.parentNode;}
SAPO.Dom.Css.hide(this.overlay);}.bindObjEvent(this));}},getPDF:function(evt){if(evt){SAPO.Dom.Event.stop(evt);}
var syndication_options={onLoading:function(){this.pdf_link.innerHTML=this._i18n('A carregar...');}.bindObj(this),onComplete:this.observePDFVarChange.bindObj(this),onError:function(){this.pdf_link.innerHTML=this._i18n('Erro! Clique para tentar de novo.');}.bindObj(this),timeout:10};if(typeof(this.syndication)=='undefined'){this.syndication=new SAPO.Communication.Syndication();}
if(this.pdf_synd_id){this.syndication.remove(this.pdf_synd_id);}
var syndication_url=this.options.pdf_json_url.replace(/_URL_/,this.urlToShare).replace(/_RANDOM_/,Math.floor(Math.random()*999999));this.pdf_synd_id=this.syndication.push(syndication_url,syndication_options);this.syndication.run(this.pdf_synd_id);},observePDFVarChange:function(json){if(json.pdf[0].x=='avail'){SAPO.Dom.Event.stopObserving(this.pdf_link,'click',this.pdf_observe_cache);this.pdf_link.setAttribute('href',json.pdf[0].i);this.pdf_link.onclick=null;this.pdf_link.innerHTML=this._i18n('Download PDF&hellip;');this._countPDFVarChanged=0;this.statisticsCallback.call(window,this.urlToShare,this.options.pageTitle,"pdf");if(this.options.pdfCallback&&typeof(this.options.pdfCallback)=='function'){this.options.pdfCallback.call(window,this.urlToShare,this.options.pageTitle);}}else{if(this._countPDFVarChanged<10){setTimeout(this.getPDF.bindObj(this),500);this._countPDFVarChanged++;}else{this._countPDFVarChanged=0;this.pdf_link.innerHTML=this._i18n('Erro! Clique para tentar de novo.');}}},emailSendInPlace:function(evt){SAPO.Dom.Event.stop(evt);SAPO.Dom.Css.show(this.floating_balloon);},createFloatingEmailBalloon:function(){var div=document.createElement("div");SAPO.Dom.Css.addClassName(div,'sapo_sharethis_floating_balloon');SAPO.Dom.Css.setStyle(div,{"position":'absolute',"display":'none'});var heading=document.createElement('h1');heading.innerHTML=this._i18n('Partilhar por email');var link=document.createElement("a");SAPO.Dom.Css.addClassName(link,'sapo_sharethis_close')
link.setAttribute('href','#');link.innerHTML=this._i18n('fechar');SAPO.Dom.Event.observe(link,'click',function(evt){SAPO.Dom.Event.stop(evt);SAPO.Dom.Css.hide(this.floating_balloon);}.bindObjEvent(this));heading.appendChild(link);div.appendChild(heading);return div;},createEmailForm:function(){var labelId,rand=Math.floor(Math.random()*999999);this.email_form=document.createElement("form");this.email_form.setAttribute('method','get');this.email_form.setAttribute('action',this.urlemailJSON);this.email_form.onsubmit=function(){return false;};var labelName=document.createElement('label');labelName.innerHTML=this._i18n('Nome do remetente');labelDesc="from";labelName.setAttribute('for',labelDesc+rand);this.inputName=document.createElement('input');this.inputName.setAttribute('type','text');this.inputName.setAttribute('size','25');this.inputName.name=labelDesc;this.inputName.setAttribute('id',labelDesc+rand);var labelNameTo=document.createElement('label');labelNameTo.innerHTML=this._i18n('Nome do destinat&aacute;rio');labelDesc='to';labelNameTo.setAttribute('for',labelDesc+rand);this.inputNameTo=document.createElement('input');this.inputNameTo.setAttribute('type','text')
this.inputNameTo.setAttribute('size','25');this.inputNameTo.name=labelDesc;this.inputNameTo.setAttribute('id',labelDesc+rand);var labelEmailTo=document.createElement('label');labelEmailTo.innerHTML=this._i18n('Email do destinat&aacute;rio');labelDesc="mail";labelEmailTo.setAttribute('for',labelDesc+rand);this.inputEmailTo=document.createElement('input');this.inputEmailTo.setAttribute('type','text');this.inputEmailTo.setAttribute('size','25');this.inputEmailTo.name=labelDesc;this.inputEmailTo.setAttribute('id',labelDesc+rand);this.inputUrl=document.createElement('input');this.inputUrl.setAttribute('type','hidden');this.inputUrl.setAttribute('value',this.urlToShare);this.inputUrl.name='url';var submit=document.createElement('input');submit.setAttribute('type','submit');submit.setAttribute('value',this._i18n('Enviar email'));this.email_form.appendChild(labelName);this.email_form.appendChild(this.inputName);this.email_form.appendChild(labelNameTo);this.email_form.appendChild(this.inputNameTo);this.email_form.appendChild(labelEmailTo);this.email_form.appendChild(this.inputEmailTo);this.email_form.appendChild(this.inputUrl);this.email_form.appendChild(submit);this.email_form.onsubmit=this.emailFormSubmit.bindObjEvent(this);return this.email_form;},emailFormSubmit:function(evt){if(evt){SAPO.Dom.Event.stop(evt);}
var name_from=this.inputName.value;var name_to=this.inputNameTo.value;var email_to=this.inputEmailTo.value;var url=this.inputUrl.value;if(name_from==''||name_to==''||email_to==''||url==''){alert(this._i18n('Todos os campos são obrigatórios.'));return false;}
var emailValido=new RegExp("^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@([\\w]*-?[\\w]*\\.)+[a-z]{2,4}$","i");if(!emailValido.test(email_to)){alert(this._i18n('Email inválido'));return false;}
var aQueryString=['from='+encodeURIComponent(name_from),'to='+encodeURIComponent(name_to),'mail='+encodeURIComponent(email_to),'url='+encodeURIComponent(url),'title='+encodeURIComponent(this.options.pageTitle)];var syndication_url=this.options.email_url+'&'+aQueryString.join('&');var syndication_options={onLoading:function(){if(this.email_form_indicator){this.email_form.removeChild(this.email_form_indicator);}
this.email_form_indicator=document.createElement('span');SAPO.Dom.Css.setStyle(this.email_form_indicator,{"position":'absolute',"bottom":'15px',"right":'10px',"whiteSpace":'nowrap'});this.email_form_indicator.innerHTML=this._i18n('A enviar');this.email_form.appendChild(this.email_form_indicator);}.bindObj(this),onComplete:function(json){this.email_form.removeChild(this.email_form_indicator);this.email_form_indicator=document.createElement('span');SAPO.Dom.Css.setStyle(this.email_form_indicator,{"position":'absolute',"bottom":'15px',"right":'10px',"whiteSpace":'nowrap'});if(!json.error){this.inputName.value='';this.inputNameTo.value='';this.inputEmailTo.value='';}
this.email_form_indicator.innerHTML=json.message;this.email_form.appendChild(this.email_form_indicator);this.statisticsCallback.call(window,this.urlToShare,this.options.pageTitle,"email");if(this.options.emailCallback&&typeof(this.options.emailCallback)=='function'){this.options.emailCallback.call(window,this.urlToShare,this.options.pageTitle);}}.bindObj(this),onError:function(){this.email_form.removeChild(this.email_form_indicator);this.email_form_indicator=document.createElement('span');SAPO.Dom.Css.setStyle(this.email_form_indicator,{"position":'absolute',"bottom":'15px',"right":'10px',"whiteSpace":'nowrap'});this.email_form_indicator.innerHTML=this._i18n('Erro! Tente novamente...');this.email_form.appendChild(this.email_form_indicator);}.bindObj(this),timeout:10};var syndication=new SAPO.Communication.Syndication();var mail_synd=syndication.push(syndication_url,syndication_options);syndication.run(mail_synd);return false;},addCss:function(){if(this.options.cssURI){var link=document.createElement('link');link.rel='stylesheet';link.href=this.options.cssURI;link.media='all';var aHead=document.getElementsByTagName('HEAD');var links=document.getElementsByTagName("link");for(var x=0;x<links.length;x++){if(links[x].href==link.href)
return;}
if(aHead.length>0){aHead[0].appendChild(link);}
if(SAPO.Browser.IE&&this.options.cssURI=='http://js.sapo.pt/Assets/Images/ShareThis/style.css'){link=document.createElement('link');link.rel='stylesheet';link.href='http://js.sapo.pt/Assets/Images/ShareThis/style.ie_all.css';link.media='all';var link2=document.createElement('link');link2.rel='stylesheet';link2.href=(SAPO.Browser.version<7)?'http://js.sapo.pt/Assets/Images/ShareThis/style.ie6.css':'http://js.sapo.pt/Assets/Images/ShareThis/style.ie7_8.css';link2.media='all';if(aHead.length>0){aHead[0].appendChild(link);aHead[0].appendChild(link2);}}}},debug:function(thing){if(!this.options.debug){return;}
if(window.console!=undefined){console.log(thing);}else if(this.debug_container){this.debug_container.value+=thing+"\n";}else{this.debug_container=document.createElement('textarea');this.debug_container.id=this.element.id+'_dbg';this.element.appendChild(this.debug_container);this.debug_container.value+=thing+"\n";}}};
if(!SAPO.Utility||typeof(SAPO.Utility)=='undefined'){SAPO.namespace('Utility');}
SAPO.Utility.Dimensions={elementWidth:function(element){if(typeof element==="string"){element=document.getElementById(element);}
return element.offsetWidth;},elementHeight:function(element){if(typeof element==="string"){element=document.getElementById(element);}
return element.offsetHeight;},elementLeft:function(element){if(typeof element==="string"){element=document.getElementById(element);}
return element.offsetLeft;},elementTop:function(element){if(typeof element==="string"){element=document.getElementById(element);}
return element.offsetTop;},elementDimensions:function(element){if(typeof element==="string"){element=document.getElementById(element);}
return Array(element.offsetWidth,element.offsetHeight);},pageWidth:function(){var xScroll;if(window.innerWidth&&window.scrollMaxX){xScroll=window.innerWidth+window.scrollMaxX;}else if(document.body.scrollWidth>document.body.offsetWidth){xScroll=document.body.scrollWidth;}else{xScroll=document.body.offsetWidth;}
var windowWidth;if(self.innerWidth){if(document.documentElement.clientWidth){windowWidth=document.documentElement.clientWidth;}else{windowWidth=self.innerWidth;}}else if(document.documentElement&&document.documentElement.clientWidth){windowWidth=document.documentElement.clientWidth;}else if(document.body){windowWidth=document.body.clientWidth;}
if(xScroll<windowWidth){return xScroll;}else{return windowWidth;}},pageHeight:function(){var yScroll;if(window.innerHeight&&window.scrollMaxY){yScroll=window.innerHeight+window.scrollMaxY;}else if(document.body.scrollHeight>document.body.offsetHeight){yScroll=document.body.scrollHeight;}else{yScroll=document.body.offsetHeight;}
var windowHeight;if(self.innerHeight){windowHeight=self.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){windowHeight=document.documentElement.clientHeight;}else if(document.body){windowHeight=document.body.clientHeight;}
if(yScroll<windowHeight){return windowHeight;}else{return yScroll;}},viewportWidth:function(){if(typeof window.innerWidth!=="undefined"){return window.innerWidth;}else if(document.documentElement&&typeof document.documentElement.offsetWidth!=="undefined"){return document.documentElement.offsetWidth;}},viewportHeight:function(){if(typeof window.innerHeight!=="undefined"){return window.innerHeight;}else if(document.documentElement&&typeof document.documentElement.offsetHeight!=="undefined"){return document.documentElement.offsetHeight;}},scrollWidth:function(){var xScroll;if(self.pageXOffset){xScroll=self.pageXOffset;}else if(typeof document.documentElement!="undefined"&&typeof document.documentElement.scrollLeft!="undefined"){xScroll=document.documentElement.scrollLeft;}else{xScroll=document.body.scrollLeft;}
return xScroll;},scrollHeight:function(){var yScroll;if(self.pageYOffset){yScroll=self.pageYOffset;}else if(typeof document.documentElement!="undefined"&&typeof document.documentElement.scrollTop!="undefined"){yScroll=document.documentElement.scrollTop;}else{yScroll=document.body.scrollTop;}
return yScroll;}};
if(!SAPO.Utility||typeof(SAPO.Utility)=='undefined'){SAPO.namespace('Utility');}
SAPO.Utility.Url={_keyStr:'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',getUrl:function()
{var url=false;url=location.href;return url;},getQueryString:function(string)
{if(string&&typeof(string)!='undefined'){var url=string;}else{var url=this.getUrl();}
var aParams={};if(url.match(/\?(.+)/i)){var queryStr=url.replace(/^(.*)\?([^\#]+)(\#(.*))?/g,"$2");if(queryStr.length>0){var aQueryStr=queryStr.split(/[;&]/);for(var i=0;i<aQueryStr.length;i++){var pairVar=aQueryStr[i].split('=');aParams[decodeURIComponent(pairVar[0])]=(typeof(pairVar[1])!='undefined'&&pairVar[1])?decodeURIComponent(pairVar[1]):false;}}}
return aParams;},getAnchor:function(string)
{if(string&&typeof(string)!='undefined'){var url=string;}else{var url=this.getUrl();}
var anchor=false;if(url.match(/#(.+)/)){anchor=url.replace(/([^#]+)#(.*)/,"$2");}
return anchor;},getAnchorString:function(string)
{if(string&&typeof(string)!='undefined'){var url=string;}else{var url=this.getUrl();}
var aParams={};if(url.match(/#(.+)/i)){var anchorStr=url.replace(/^([^#]+)#(.*)?/g,"$2");if(anchorStr.length>0){var aAnchorStr=anchorStr.split(/[;&]/);for(var i=0;i<aAnchorStr.length;i++){var pairVar=aAnchorStr[i].split('=');aParams[decodeURIComponent(pairVar[0])]=(typeof(pairVar[1])!='undefined'&&pairVar[1])?decodeURIComponent(pairVar[1]):false;}}}
return aParams;},parseUrl:function(url)
{var aURL={};if(url&&typeof(url)!='undefined'&&typeof(url)=='string'){if(url.match(/^([^:]+):\/\//i)){var re1=new RegExp("^([^:]+)://([^/]+)/([^\\?]+)\\?([^#]+)#(.*)$","i");var re2=new RegExp("^([^:]+)://([^/]+)/([^\\?]+)\\?([^#]+)#?$","i");var re3=new RegExp("^([^:]+)://([^/]+)/([^\\?]+)\\??$","i");var re4=new RegExp("^([^:]+)://([^/]+)/?$","i");if(url.match(re1)){aURL['scheme']=url.replace(re1,"$1");aURL['host']=url.replace(re1,"$2");aURL['path']='/'+url.replace(re1,"$3");aURL['query']=url.replace(re1,"$4");aURL['fragment']=url.replace(re1,"$5");}else if(url.match(re2)){aURL['scheme']=url.replace(re2,"$1");aURL['host']=url.replace(re2,"$2");aURL['path']='/'+url.replace(re2,"$3");aURL['query']=url.replace(re2,"$4");aURL['fragment']=false;}else if(url.match(re3)){aURL['scheme']=url.replace(re3,"$1");aURL['host']=url.replace(re3,"$2");aURL['path']='/'+url.replace(re3,"$3");aURL['query']=false;aURL['fragment']=false;}else if(url.match(re4)){aURL['scheme']=url.replace(re4,"$1");aURL['host']=url.replace(re4,"$2");aURL['path']=false;aURL['query']=false;aURL['fragment']=false;}}else{var re1=new RegExp("^([^\\?]+)\\?([^#]+)#(.*)","i");var re2=new RegExp("^([^\\?]+)\\?([^#]+)#?","i");var re3=new RegExp("^([^\\?]+)\\??","i");if(url.match(re1)){aURL['scheme']=false;aURL['host']=false;aURL['path']=url.replace(re1,"$1");aURL['query']=url.replace(re1,"$2");aURL['fragment']=url.replace(re1,"$3");}else if(url.match(re2)){aURL['scheme']=false;aURL['host']=false;aURL['path']=url.replace(re2,"$1");aURL['query']=url.replace(re2,"$2");aURL['fragment']=false;}else if(url.match(re3)){aURL['scheme']=false;aURL['host']=false;aURL['path']=url.replace(re3,"$1");aURL['query']=false;aURL['fragment']=false;}}
if(aURL['host']){var regPort=new RegExp("^(.*)\\:(\\d+)$","i");if(aURL['host'].match(regPort)){var tmpHost1=aURL['host'];aURL['host']=tmpHost1.replace(regPort,"$1");aURL['port']=tmpHost1.replace(regPort,"$2");}else{aURL['port']=false;}
if(aURL['host'].match(/@/i)){var tmpHost2=aURL['host'];aURL['host']=tmpHost2.split('@')[1];var tmpUserPass=tmpHost2.split('@')[0];if(tmpUserPass.match(/\:/)){aURL['user']=tmpUserPass.split(':')[0];aURL['pass']=tmpUserPass.split(':')[1];}else{aURL['user']=tmpUserPass;aURL['pass']=false;}}}}
return aURL;},currentScriptElement:function(match)
{var aScripts=document.getElementsByTagName('script');if(typeof(match)=='undefined'){if(aScripts.length>0){return aScripts[(aScripts.length-1)];}else{return false;}}else{var curScript=false;var re=new RegExp(""+match+"","i");for(var i=0,total=aScripts.length;i<total;i++){curScript=aScripts[i];if(re.test(curScript.src)){return curScript;}}
return false;}},base64Encode:function(string)
{if(!SAPO.Utility.String||typeof(SAPO.Utility.String)=='undefined'){throw"SAPO.Utility.Url.base64Encode depends of SAPO.Utility.String, which has not been referred.";return false;}
var output="";var chr1,chr2,chr3,enc1,enc2,enc3,enc4;var i=0;var input=SAPO.Utility.String.utf8Encode(string);while(i<input.length){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+
this._keyStr.charAt(enc1)+this._keyStr.charAt(enc2)+
this._keyStr.charAt(enc3)+this._keyStr.charAt(enc4);}
return output;},base64Decode:function(string)
{if(!SAPO.Utility.String||typeof(SAPO.Utility.String)=='undefined'){throw"SAPO.Utility.Url.base64Decode depends of SAPO.Utility.String, which has not been referred.";return false;}
var output="";var chr1,chr2,chr3;var enc1,enc2,enc3,enc4;var i=0;var input=string.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(i<input.length){enc1=this._keyStr.indexOf(input.charAt(i++));enc2=this._keyStr.indexOf(input.charAt(i++));enc3=this._keyStr.indexOf(input.charAt(i++));enc4=this._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);}}
output=SAPO.Utility.String.utf8Decode(output);return output;}};/*global SAPO:true, window:true*/
if (!SAPO.Effects || typeof(SAPO.Effects) == 'undefined') {
    SAPO.namespace('Effects');
}


/**
 * @class SAPO.Effects.Core
 */

/*
 * Licensed under the terms of the MIT license.
 * Based on work by Thomas Fuchs from emile.js and scripty2
 */
(function() {
    var _easing = {
        linear: function(pos) {
            return pos;
        },

        reverse: function(pos) {
            return 1 - pos;
        },

        sinusoidal: function(pos) {
            return ( - Math.cos(pos * Math.PI) / 2) + 0.5;
        },

        longerSinusoidal: function(pos) {
            return ( - Math.cos(pos * 0.9) / 2) + 0.5;
        },

        //  The given transition is mirrored. Defaults to sinusoidal
        mirror: function(pos, transition) {
            var gt = SAPO.Effects.Core.getTransition;
            if (typeof transition !== "function") {
                transition = gt(transition) || gt("sinusoidal");
            }
            if (pos < 0.5) {return transition(pos * 2);}
            else {return transition(1 - (pos - 0.5) * 2);}
        },

        //  Effect flickers along a sine wave.
        flicker: function(pos) {
            pos = pos + (Math.random() - 0.5) / 5;
            return _easing.sinusoidal(pos < 0 ? 0: pos > 1 ? 1: pos);
        },

        //  Effect wobbles increasingly fast between start and end positions.
        wobble: function(pos) {
            return ( - Math.cos(pos * Math.PI * (9 * pos)) / 2) + 0.5;
        },

        //  Effect pulses along a sinusoidal transition.
        pulse: function(pos, pulses) {
            return ( - Math.cos((pos * ((pulses || 5) - 0.5) * 2) * Math.PI) / 2) + 0.5;
        },

        //  Effect blinks on and off.
        blink: function(pos, blinks) {
            return Math.round(pos * (blinks || 5)) % 2;
        },

        //  Alters the effect timing to a "spring".
        spring: function(pos) {
            return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp( - pos * 6));
        },

        // Based on Easing Equations (c) 2003 Robert Penner, all rights reserved.
        // This work is subject to the terms in http://www.robertpenner.com/easing_terms_of_use.html
        // Adapted for script.aculo.us by
        // Brian Crescimanno <brian.crescimanno@gmail.com>
        // Ken Snyder <kendsnyder@gmail.com)
        // Adapted for LibSAPO.js by Tiago Rodrigues <tiago.c.rodrigues@co.sapo.pt>
        /*!
         *  TERMS OF USE - EASING EQUATIONS
         *  Open source under the BSD License.
         *  Easing Equations (c) 2003 Robert Penner, all rights reserved.
         */

        easeInQuad: function(pos) {
            return Math.pow(pos, 2);
        },

        easeOutQuad: function(pos) {
            return - (Math.pow((pos - 1), 2) - 1);
        },

        easeInOutQuad: function(pos) {
            if ((pos /= 0.5) < 1) {return 0.5 * Math.pow(pos, 2);}
            return - 0.5 * ((pos -= 2) * pos - 2);
        },

        easeInCubic: function(pos) {
            return Math.pow(pos, 3);
        },

        easeOutCubic: function(pos) {
            return (Math.pow((pos - 1), 3) + 1);
        },

        easeInOutCubic: function(pos) {
            if ((pos /= 0.5) < 1) {return 0.5 * Math.pow(pos, 3);}
            return 0.5 * (Math.pow((pos - 2), 3) + 2);
        },

        easeInQuart: function(pos) {
            return Math.pow(pos, 4);
        },

        easeOutQuart: function(pos) {
            return - (Math.pow((pos - 1), 4) - 1);
        },

        easeInOutQuart: function(pos) {
            if ((pos /= 0.5) < 1) {return 0.5 * Math.pow(pos, 4);}
            return - 0.5 * ((pos -= 2) * Math.pow(pos, 3) - 2);
        },

        easeInQuint: function(pos) {
            return Math.pow(pos, 5);
        },

        easeOutQuint: function(pos) {
            return (Math.pow((pos - 1), 5) + 1);
        },

        easeInOutQuint: function(pos) {
            if ((pos /= 0.5) < 1) {return 0.5 * Math.pow(pos, 5);}
            return 0.5 * (Math.pow((pos - 2), 5) + 2);
        },

        easeInSine: function(pos) {
            return - Math.cos(pos * (Math.PI / 2)) + 1;
        },

        easeOutSine: function(pos) {
            return Math.sin(pos * (Math.PI / 2));
        },

        easeInOutSine: function(pos) {
            return ( - 0.5 * (Math.cos(Math.PI * pos) - 1));
        },

        easeInExpo: function(pos) {
            return (pos === 0) ? 0: Math.pow(2, 10 * (pos - 1));
        },

        easeOutExpo: function(pos) {
            return (pos == 1) ? 1: -Math.pow(2, -10 * pos) + 1;
        },

        easeInOutExpo: function(pos) {
            if (pos === 0) {return 0;}
            if (pos == 1) {return 1;}
            if ((pos /= 0.5) < 1) {return 0.5 * Math.pow(2, 10 * (pos - 1));}
            return 0.5 * ( - Math.pow(2, -10 * --pos) + 2);
        },

        easeInCirc: function(pos) {
            return - (Math.sqrt(1 - (pos * pos)) - 1);
        },

        easeOutCirc: function(pos) {
            return Math.sqrt(1 - Math.pow((pos - 1), 2));
        },

        easeInOutCirc: function(pos) {
            if ((pos /= 0.5) < 1) {return - 0.5 * (Math.sqrt(1 - pos * pos) - 1);}
            return 0.5 * (Math.sqrt(1 - (pos -= 2) * pos) + 1);
        },

        easeOutBounce: function(pos) {
            if ((pos) < (1 / 2.75)) {
                return (7.5625 * pos * pos);
            } else if (pos < (2 / 2.75)) {
                return (7.5625 * (pos -= (1.5 / 2.75)) * pos + 0.75);
            } else if (pos < (2.5 / 2.75)) {
                return (7.5625 * (pos -= (2.25 / 2.75)) * pos + 0.9375);
            } else {
                return (7.5625 * (pos -= (2.625 / 2.75)) * pos + 0.984375);
            }
        },

        easeInBack: function(pos) {
            var s = 1.70158;
            return (pos) * pos * ((s + 1) * pos - s);
        },

        easeOutBack: function(pos) {
            var s = 1.70158;
            return (pos = pos - 1) * pos * ((s + 1) * pos + s) + 1;
        },

        easeInOutBack: function(pos) {
            var s = 1.70158;
            if ((pos /= 0.5) < 1) {return 0.5 * (pos * pos * (((s *= (1.525)) + 1) * pos - s));}
            return 0.5 * ((pos -= 2) * pos * (((s *= (1.525)) + 1) * pos + s) + 2);
        },

        elastic: function(pos) {
            return - 1 * Math.pow(4, -8 * pos) * Math.sin((pos * 6 - 1) * (2 * Math.PI) / 2) + 1;
        },

        swingFromTo: function(pos) {
            var s = 1.70158;
            return ((pos /= 0.5) < 1) ? 0.5 * (pos * pos * (((s *= (1.525)) + 1) * pos - s)) :
            0.5 * ((pos -= 2) * pos * (((s *= (1.525)) + 1) * pos + s) + 2);
        },

        swingFrom: function(pos) {
            var s = 1.70158;
            return pos * pos * ((s + 1) * pos - s);
        },

        swingTo: function(pos) {
            var s = 1.70158;
            return (pos -= 1) * pos * ((s + 1) * pos + s) + 1;
        },

        bounce: function(pos) {
            if (pos < (1 / 2.75)) {
                return (7.5625 * pos * pos);
            } else if (pos < (2 / 2.75)) {
                return (7.5625 * (pos -= (1.5 / 2.75)) * pos + 0.75);
            } else if (pos < (2.5 / 2.75)) {
                return (7.5625 * (pos -= (2.25 / 2.75)) * pos + 0.9375);
            } else {
                return (7.5625 * (pos -= (2.625 / 2.75)) * pos + 0.984375);
            }
        },

        bouncePast: function(pos) {
            if (pos < (1 / 2.75)) {
                return (7.5625 * pos * pos);
            } else if (pos < (2 / 2.75)) {
                return 2 - (7.5625 * (pos -= (1.5 / 2.75)) * pos + 0.75);
            } else if (pos < (2.5 / 2.75)) {
                return 2 - (7.5625 * (pos -= (2.25 / 2.75)) * pos + 0.9375);
            } else {
                return 2 - (7.5625 * (pos -= (2.625 / 2.75)) * pos + 0.984375);
            }
        },

        easeFromTo: function(pos) {
            if ((pos /= 0.5) < 1) {return 0.5 * Math.pow(pos, 4);}
            return - 0.5 * ((pos -= 2) * Math.pow(pos, 3) - 2);
        },

        easeFrom: function(pos) {
            return Math.pow(pos, 4);
        },

        easeTo: function(pos) {
            return Math.pow(pos, 0.25);
        }
    };


    /*!
     *    Copyright (c) 2006 Apple Computer, Inc. All rights reserved.
     *    
     *    Redistribution and use in source and binary forms, with or without 
     *    modification, are permitted provided that the following conditions are met:
     *    
     *    1. Redistributions of source code must retain the above copyright notice, 
     *    this list of conditions and the following disclaimer.
     *    
     *    2. Redistributions in binary form must reproduce the above copyright notice, 
     *    this list of conditions and the following disclaimer in the documentation 
     *    and/or other materials provided with the distribution.
     *    
     *    3. Neither the name of the copyright holder(s) nor the names of any 
     *    contributors may be used to endorse or promote products derived from 
     *    this software without specific prior written permission.
     *    
     *    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
     *    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
     *    THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
     *    ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 
     *    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
     *    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
     *    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
     *    ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
     *    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
     *    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     */
    // port of webkit cubic bezier handling by http://www.netzgesta.de/dev/
    function CubicBezierAtTime(t,p1x,p1y,p2x,p2y,duration) {
        var ax=0,bx=0,cx=0,ay=0,by=0,cy=0;
        function sampleCurveX(t) {return ((ax*t+bx)*t+cx)*t;}
        function sampleCurveY(t) {return ((ay*t+by)*t+cy)*t;}
        function sampleCurveDerivativeX(t) {return (3.0*ax*t+2.0*bx)*t+cx;}
        function solveEpsilon(duration) {return 1.0/(200.0*duration);}
        function fabs(n) {if(n>=0) {return n;}else {return 0-n;}}
        function solveCurveX(x,epsilon) {
            var t0,t1,t2,x2,d2,i;
            for(t2=x, i=0; i<8; i++) {
                x2=sampleCurveX(t2)-x;
                if(fabs(x2)<epsilon) {return t2;}
                d2=sampleCurveDerivativeX(t2);
                if(fabs(d2)<1e-6) {break;} t2=t2-x2/d2;
            }
            t0=0.0; t1=1.0; t2=x;
            if(t2<t0) {return t0;} if(t2>t1) {return t1;}
            while(t0<t1) {
                x2=sampleCurveX(t2);
                if(fabs(x2-x)<epsilon) {return t2;}
                if(x>x2) {t0=t2;} else {t1=t2;}
                t2=(t1-t0)*0.5+t0;
            }
            return t2; // Failure.
        }
        function solve(x,epsilon) {return sampleCurveY(solveCurveX(x,epsilon));}
        cx=3.0*p1x; bx=3.0*(p2x-p1x)-cx; ax=1.0-cx-bx; cy=3.0*p1y; by=3.0*(p2y-p1y)-cy; ay=1.0-cy-by;
        return solve(t, solveEpsilon(duration));
    }
    
    /**
     *    Generates a transition easing function that is compatible
     *    with WebKit's CSS transitions `-webkit-transition-timing-function`
     *    CSS property.
     *
     *    The W3C has more information about 
     *    <a href="http://www.w3.org/TR/css3-transitions/#transition-timing-function_tag">
     *    CSS3 transition timing functions</a>.
    **/
    function cubicBezierTransition(x1, y1, x2, y2){
        return (function(pos){
            return CubicBezierAtTime(pos,x1,y1,x2,y2,1);
        });
    }
    
    _easing = SAPO.extendObj({
        webkitEase: cubicBezierTransition(0.25, 0.1, 0.25, 1.0),
        webkitLinear: cubicBezierTransition(0.0, 0.0, 1.0, 1.0),
        webkitEaseIn: cubicBezierTransition(0.42, 0.0, 1.0, 1.0),
        webkitEaseOut: cubicBezierTransition(0.0, 0.0, 0.58, 1.0),
        webkitEaseInOut: cubicBezierTransition(0.42, 0.0, 0.58, 1.0)
    }, _easing);

    /**
     * @function {Function} ? Returns a easing function 
     * @param {String} easing - name of the easing function
     */
    function getEasing(easing) {
        if (typeof easing !== "undefined" && easing in _easing) {
            return _easing[easing];
        }
        return _easing.linear;
    }
    
    
    function getStyle(el){
        return window.getComputedStyle ? window.getComputedStyle(el, null) : el.currentStyle;
    }
    
    // prefix for storing custom properties on elements
    var __prefix = "SAPOEffects"+parseInt(Math.random()*10000, 10);

    /**
     * @function ? set the value of a custom property on a given DOM element
     * @param {Object} el - target element
     * @param {String} prop - property name
     * @param {String} val - property value
     */
    function setCustomProp(el, prop, val){
        // if our custom property doesn't exist, create it and store the val
        if(typeof el[__prefix] == "undefined"){
            el[__prefix] = prop+":"+val+";";
        } else {
            // if our custom property already exists with no val, store it
            if(el[__prefix].search(prop+":") < 0){
                el[__prefix] += prop+":"+val+";";
            }
        }
        // don't store if it's already there
    }

    /**
     * @function {String} ? get the value of a custom property from a DOM element
     * @param {Object} el - target element
     * @param {String} prop - property name
     * @param {Boolean} keep - if false, deletes the property from the element
     * @return value of a given property
     */
    function getCustomProp(el, prop, keep){
        var val = false;
        if(typeof el[__prefix] != "undefined"){
            // regexp for property store
            var re = new RegExp(prop+"\\:([\\w|\\d]+);", "g");
            var vals = re.exec(el[__prefix]);
            if(vals !== null){
                // if the property exists, return it
                val = vals[1];

                if(keep) {return val;}
                // remove it from the stored properties
                el[__prefix] = el[__prefix].replace(re, "");

                // if no more properties exist, delete our custom property
                if(el[__prefix] === ""){
                    try{
                        delete el[__prefix];
                    } catch(e){
                        el[__prefix] = '';
                    }
                }
            }
        }
        return val;
    }

    /**
     * @function {String} ? Checks for the existence of CSS transition support
     * @return Proprietary CSS prefix for the current browser. False if transitions are not supported.
     */
    function getTransitionProperties() {
        if(typeof document.body.style.webkitTransition !== "undefined"){
              return {
                  pre: '-webkit-transition',
                  ev: 'webkitTransitionEnd'
              };
        }

        if(typeof document.body.style.mozTransition !== "undefined"){
              return {
                  pre: '-moz-transition',
                  ev: 'transitionend'
              };
        }

        /* FIXME setting transitions through javascript is currently buggy
        if(typeof document.body.style.OTransition !== "undefined"){
              return {
                  pre: '-o-transition',
                  ev: 'oTransitionEnd'
              };
        }
        */

        return false;
    }

    /**
     * @function {String} ? Interpolates target and source values based on time position
     * @param {Number} source - source value
     * @param {Number} target - target value
     * @param {Number} pos - current time position
     * @return Interpolated value
     */
    function interpolate(source, target, pos) {
        return (source + (target - source) * pos).toFixed(3);
    }

    /**
     * @function ? Fire the animation
     * @param {Function} cb - callback to execute at each animation
     * cycle. Receives position in time (float value from 0 to 1) as a parameter
     * @param {Number} dur - animation duration in milliseconds
     * @param {Number} from - source value
     * @param {Number} to - target value
     * @param {Function} before - callback executed before the animation
     * @param {Function} after - callback executed after the animation
     * @param {Function} easing - easing function or function name
     */
    function animate(cb, dur, from, to, before, after, easing) {
        var start = +new Date(),
        finish = start + dur,
        val = from;

        easing = easing || _easing.sinusoidal;
        if (easing in _easing) {
            easing = _easing[easing];
        }

        if (before) {
            before();
        }

        var interval = setInterval(function() {
            var time = +new Date(),
            pos = time > finish ? 1: (time - start) / dur;

            val = interpolate(parseFloat(val, 10), to, easing(pos));
            cb(val);

            if (time > finish) {
                clearInterval(interval);
                if (after) {
                    after();
                }
            }
        }, 10);
    }



    /**
     *  @function {Array} each
     *  runs a functions trou each of the elements of an array
     *  @param {Array} arr
     *  @param {Function} callBack - the function recieves as arguments value, index and array
     *
     **/
    function each(arr, callBack) {
        /*if(arr.forEach) {               
              arr.forEach(callBack);
              return;
        }*/
        var arrhash = arr.slice(0);
        var total = arrhash.length;
        var iterations = Math.floor(total / 8);
        var leftover = total % 8;
        var i = 0;
        if (leftover > 0) {
            //Duff's device pattern
            do {
                callBack(arrhash[i++], i - 1, arr);
            }
            while (--leftover > 0);
        }
        if (iterations === 0){return arr;}
        do {
            callBack(arrhash[i++], i - 1, arr);
            callBack(arrhash[i++], i - 1, arr);
            callBack(arrhash[i++], i - 1, arr);
            callBack(arrhash[i++], i - 1, arr);
            callBack(arrhash[i++], i - 1, arr);
            callBack(arrhash[i++], i - 1, arr);
            callBack(arrhash[i++], i - 1, arr);
            callBack(arrhash[i++], i - 1, arr);
        }
        while (--iterations > 0);

        return arr;
    }

    /**
     * @function ? - runs an array of effects in parallel
     * @param {Array} arrEffects 
     * @param {Object} options
     *
     */
    function parallel(arrEffects, options) {
        var runEffects = function(value, key, arr) {
            if (options && (options.after && typeof(options.after) == "function" && (key == arr.length - 1))) {
                if (value.options.after) {
                    var func = value.options.after;
                    value.options.after = function() {
                        func();
                        options.after();
                    };
                } else {
                    value.options.after = options.after;
                }
            }

            // fallback TODO removeme
            if (typeof(value) != "function") {
                SAPO.Effects.Core.emile(value.element, value.style, value.options);
            }
        };

        if (!options || (!options.delay || options.delay === 0)) {
            each(arrEffects, runEffects);
        } else {
            setTimeout(function() {
                each(arrEffects, runEffects);
            },
            options.delay);
        }

    }


    /**
     * @constructor SAPO.Effects.Core.?
     */
    SAPO.Effects.Core = {
        interpolate: interpolate,
        animate: animate,
        parallel: parallel,
        getEasing: getEasing,
        getTransitionProperties: getTransitionProperties,
        getStyle: getStyle,
        getCustomProp: getCustomProp,
        setCustomProp: setCustomProp
    };

    /* starting emile.js

        don't use ! only present for backward compatibility.
    */
    (function(emile, container){
      var parseEl = document.createElement('div'),
        props = ('backgroundColor borderBottomColor borderBottomWidth borderLeftColor borderLeftWidth '+
        'borderRightColor borderRightWidth borderSpacing borderTopColor borderTopWidth bottom color fontSize '+
        'fontWeight height left letterSpacing lineHeight marginBottom marginLeft marginRight marginTop maxHeight '+
        'maxWidth minHeight minWidth opacity outlineColor outlineOffset outlineWidth paddingBottom paddingLeft '+
        'paddingRight paddingTop right textIndent top width wordSpacing zIndex').split(' ');

      function s(str, p, c){ return str.substr(p,c||1); }
      function color(source,target,pos){
        var i = 2, j, c, tmp, v = [], r = [];
        while(j=3,c=arguments[i-1],i--)
            if(s(c,0)=='r') { c = c.match(/\d+/g); while(j--) v.push(~~c[j]); } else {
              if(c.length==4) c='#'+s(c,1)+s(c,1)+s(c,2)+s(c,2)+s(c,3)+s(c,3);
              while(j--) v.push(parseInt(s(c,1+j*2,2), 16)); }
        while(j--) { tmp = ~~(v[j+3]+(v[j]-v[j+3])*pos); r.push(tmp<0?0:tmp>255?255:tmp); }
        return 'rgb('+r.join(',')+')';

      }

      function parse(prop){
        var p = parseFloat(prop), q = prop.replace(/^[\-\d\.]+/,'');
        return isNaN(p) ? { v: q, f: color, u: ''} : { v: p, f: interpolate, u: q };
      }

      function normalize(style){
        var css, rules = {}, i = props.length, v;
        parseEl.innerHTML = '<div style="'+style+'"></div>';
        css = parseEl.childNodes[0].style;
        while(i--) if(v = css[props[i]]) rules[props[i]] = parse(v);
        return rules;
      }  

      container[emile] = function(el, style, opts){
        el = typeof el == 'string' ? document.getElementById(el) : el;
        opts = opts || {};
        var target = normalize(style), comp = el.currentStyle ? el.currentStyle : getComputedStyle(el, null),
            prop, current = {}, start = +new Date, dur = opts.duration||200, finish = start+dur, interval,
            easing = opts.easing || _easing.sinusoidal;
        for(prop in target) current[prop] = parse(comp[prop]);
        interval = setInterval(function(){
            var time = +new Date, pos = time>finish ? 1 : (time-start)/dur;
            for(prop in target)
              el.style[prop] = target[prop].f(current[prop].v,target[prop].v,easing(pos)) + target[prop].u;
            if(time>finish) { clearInterval(interval); opts.after && opts.after(); }
        },10);
      }
    })('emile', SAPO.Effects.Core);
})();
if(!SAPO.Component || typeof(SAPO.Component) == 'undefined') {
    SAPO.namespace('Component');
}
/**
 * SAPO.Component.Rating
 */

/**
 * @constructor SAPO.Component.Rating.?
 *
 * Provides a rating meter
 *
 * @param {string} element - id of the element where the rating will be
 * shown
 * @param {string} elmMessages - DOM Element where the messages appear
 * @param {string} hash - hash value to be passed on the AJAX call
 * @param {Object} options - Options for the rating meter
 *      @... {optional int} total - Number of rating options
 *      @... {optional string} image - Image for empty rating
 *      @... {optional string} imageOver - Image for half rating
 *      @... {optional string} imageHalf - Image for full rating
 *      @... {optional boolean} logged - if the user is logged
 *      @... {optional Array} messages - messages for each rating level
 *      @... {optional string} url - URL where the rating results should be
 *      submitted to
 *      @... {optional } method - HTTP method for the call
 *      @... {optional } variable - HTTP variable where the rate result
 *      will be stored
 *      @... {optional } hashVariable - HTTP variable where the hash will
 *      be stored
 * @param {int} defaultRating - default rating value (from 0 to 100)
 */
SAPO.Component.Rating = function(element, elmMessages, hash, options, defaultRating) {

    this.init(element, elmMessages, hash, options, defaultRating);
}; 

SAPO.Component.Rating.prototype = {

    init: function(element, elmMessages, hash)
    {
        var options = SAPO.extendObj({
                    total: 5, 
                    image: false,
                    imageOver: false,
                    imageHalf: false,
                    url: false,
                    logged: false,
                    messages: [],
                    method: 'post',
                    variable: 'rate',
                    hashVariable: 'hash'
                }, arguments[3] || {});

        try {
            this.element = document.getElementById(element);

            this.elmMessages = false;
            if(typeof(elmMessages) != 'undefined' && elmMessages != false) {
                this.elmMessages = document.getElementById(elmMessages);
            } 

            if(typeof(arguments[4]) == 'undefined') {
                this.defaultRating = 0;
            } else {
                this.defaultRating = Number(arguments[4]);
            }
            this.defaultImageSrc = [];

            this.hash = hash;
            
            this.options = options;
        
            // 
            // check for image and url
            //
            if(!this.options.image || !this.options.url) {
                alert('Options "image" and "url" are required.');
                return;
            }
            // 

            if(this.options.messages.length == this.options.total) {
                this.hasMessages = true;
            } else {
                this.hasMessages = false;
            }

            if(!this.options.imageOver) {
                this.options.imageOver = this.options.image;
            }
            if(!this.options.imageHalf) {
                this.options.imageHalf = this.options.imageOver;
            }

            this.active = false;
            
            this.sto = false;

            this.writeImages();

        } catch(e) { }
    }, 

    /**
     * Renders the rating images
     */
    writeImages: function() 
    {
        var aImgs = this.element.getElementsByTagName('IMG');
        for(var i=(aImgs.length - 1); i >= 0; i--) {
            aImgs[i].parentNode.removeChild(aImgs[i]);
        }

        var media = this.calculateMedia(this.defaultRating);
        for(var i=0; i < this.options.total; i++) {
            this.element.appendChild(this.genImageElement(i, media));
        }
    },

    /**
     * Renders an image element with events
     * @param {int} ident - image index
     * @param {int} media - rating average
     */
    genImageElement: function(ident, media)
    {
        var img = document.createElement('IMG');
        //img.src = this.options.image;
        if(media > ident && media < (ident + 1)) {
            img.src = this.options.imageHalf;
        } else if(media > ident) {
            img.src = this.options.imageOver;
        } else if(media <= ident) {
            img.src = this.options.image;
        }
        img.border = '0';
        img.alt = '';
        img.setAttribute('ident', ident);
        
        if(this.options.logged) {
          this.addOnMouseOver(img);
          this.addOnMouseOut(img);
          this.addOnClick(img);
        }

        return img;
    }, 

    /**
     * Renders an image element without events
     * @param {int} ident - image index
     * @param {int} media - rating average
     */
    genSimpleImageElement: function(ident, media) 
    {
        var img = document.createElement('IMG');
        if(media > ident && media < (ident + 1)) {
            img.src = this.options.imageHalf;
        } else if(media > ident) {
            img.src = this.options.imageOver;
        } else if(media <= ident) {
            img.src = this.options.image;
        }
        img.border = '0';
        img.alt = '';

        return img;
    },

    /**
     * Adds the on mouse over event
     * @param {DOMElement} elm - Element where the event should be applied
     */
    addOnMouseOver: function(elm) 
    {
        if(this.options.imageOver) {
            //SAPO.Dom.Event.observe(elm, 'mouseover', this.onMouseOver.bindObjEvent(this));
            elm.onmouseover = function(event) {
                    this.onMouseOver(event);
            }.bindObjEvent(this);
        }
    },

    /**
     * On mouse over event
     * @param {Object} e - Event object
     */
    onMouseOver: function(e)
    {

        this.active = true;
        
        if(this.sto) {
          clearTimeout(this.sto);
          this.sto = false;
        }

        var elm = SAPO.Dom.Event.findElement(e, 'IMG');
        SAPO.Dom.Event.stop(e);
        var ident = elm.getAttribute('ident');

        this.showMessage(ident);

        var aImgs = this.element.getElementsByTagName('IMG');
        for(var i=0; i < aImgs.length; i++) {
            if(i > ident) {
                aImgs[i].src = this.options.image;
                //break;
            } else {
                aImgs[i].src = this.options.imageOver;
            }
        }
    },

    /**
     * Adds the on mouse out event
     * @param {DOMElement} elm - Element where the event should be applied
     */
    addOnMouseOut: function(elm) 
    {
        if(this.options.imageOver) {
            //SAPO.Dom.Event.observe(elm, 'mouseout', this.onMouseOut.bindObjEvent(this));
            elm.onmouseout = function(event) {
                this.onMouseOut(event);
            }.bindObjEvent(this);
        }
    },

    /**
     * On mouse out event
     * @param {Object} e - Event object
     */
    onMouseOut: function(e)
    {
        this.active = false;
        var elm = SAPO.Dom.Event.findElement(e, 'IMG');
        var ident = elm.getAttribute('ident');
        SAPO.Dom.Event.stop(e); 
        
        this.showMessage();

        var aImgs = this.element.getElementsByTagName('IMG');
        for(var i=0; i < aImgs.length; i++) {
            aImgs[i].src = this.options.image;
            //if(i == ident) {
            //    break;
            //}
        }
        this.sto = setTimeout(function() {
                    if(!this.active) {
                        this.writeImages();
                    }
                }.bindObj(this), 1000);
    },

    /**
     * Adds the on click event
     * @param {DOMElement} elm - Element where the event should be applied
     */
    addOnClick: function(elm)
    {
        //SAPO.Dom.Event.observe(elm, 'click', this.onClick.bindObjEvent(this));
        elm.onclick = function(event) {
            this.onClick(event);
        }.bindObjEvent(this);
    },

    /**
     * On click event
     * @param {Object} e - Event object
     */
    onClick: function(e)
    {

        var elm = SAPO.Dom.Event.findElement(e, 'IMG');
        SAPO.Dom.Event.stop(e); 
        var ident = elm.getAttribute('ident');

        if(this.options.method == 'post') {
            new SAPO.Communication.Ajax(this.options.url, {method:'post', postBody:this.options.variable+'='+ident+'&'+this.options.hashVariable+'='+this.hash, onSuccess:this.onClickSuccess.bindObj(this)});
        } else if(this.options.method == 'get') {
            new SAPO.Communication.Ajax(this.options.url, {method:'get', parameters:this.options.variable+'='+ident+'&'+this.options.hashVariable+'='+this.hash, onSuccess:this.onClickSuccess.bindObj(this)});
        }
    },

    /**
     * Callback for a successful vote
     * @param {Object} req - Request object
     */
    onClickSuccess: function(req)
    {
        if(req != null) {
            var res = eval('['+req.responseText+']')[0];
            var ratingPercent = res.rating;

            if(typeof(res.message) != 'undefined' && res.message != null && this.elmMessages) {
                this.elmMessages.innerHTML = res.message;
            } 
        } else {
            var ratingPercent = 0;
        }
        this.setDefault(ratingPercent);
    },

    /**
     * Show a message for a rating level
     * @param {int} id - message id on the messages array
     */
    showMessage: function(id)
    {
        if(this.hasMessages && this.elmMessages) {
            if(id && typeof(id) != 'undefined') {
                this.elmMessages.innerHTML = this.options.messages[id];
            } else {
                this.elmMessages.innerHTML = '';
            }
        }
    },

    /**
     * Sets a default value for a rating meter
     * @param {int} ratingPercent - the value to set
     */
    setDefault: function(ratingPercent)
    {
        var aImgs = this.element.getElementsByTagName('IMG');
        for(var i=(aImgs.length - 1); i >= 0; i--) {
            aImgs[i].onmouseout = null;
            aImgs[i].onmouseover = null;
            aImgs[i].onclick = null;
            aImgs[i].parentNode.removeChild(aImgs[i]);
        }
        // add default images 
        var media = this.calculateMedia(ratingPercent);

        for(var j=0; j < this.options.total; j++) {
            this.element.appendChild(this.genSimpleImageElement(j, media));
        }
    },

    /**
     * Calculates the medium point on the rating
     * scale according to the rating level
     * @param {float} ratingPercent - the rating level
     * @return Medium point on the rating scale
     */
    calculateMedia: function(ratingPercent) 
    {
        ratingPercent = ratingPercent / 100;

        var media = this.options.total * ratingPercent; 
        var intMedia = Math.round(media);
        var decimal = media - intMedia; 
        var valor = 0;
        if((decimal >= 0 && decimal <= 0.25) || (decimal >= -0.25 && decimal <= 0)) {
            valor = intMedia;
        } else if ((decimal > 0.25 && decimal < 0.75) || (decimal > -0.75 && decimal < -0.25)) {
            if(decimal < 0) {
                valor = intMedia - 0.5;
            } else {
                valor = intMedia + 0.5;
            }
        }
        return valor;
    },

    debug: function(txt)
    {
        //document.getElementById('debug').innerHTML += txt+'<br />';
    }
};

if(!SAPO.Utility||typeof(SAPO.Utility)=='undefined'){SAPO.namespace('Utility');}
SAPO.Utility.Validator={_countryCodes:['AO','CV','MZ','PT'],_internacionalPT:351,_indicativosPT:{21:'lisboa',22:'porto',231:'mealhada',232:'viseu',233:'figueira da foz',234:'aveiro',235:'arganil',236:'pombal',238:'seia',239:'coimbra',241:'abrantes',242:'ponte de sôr',243:'santarém',244:'leiria',245:'portalegre',249:'torres novas',251:'valença',252:'vila nova de famalicão',253:'braga',254:'peso da régua',255:'penafiel',256:'são joão da madeira',258:'viana do castelo',259:'vila real',261:'torres vedras',262:'caldas da raínha',263:'vila franca de xira',265:'setúbal',266:'évora',268:'estremoz',269:'santiago do cacém',271:'guarda',272:'castelo branco',273:'bragança',274:'proença-a-nova',275:'covilhã',276:'chaves',277:'idanha-a-nova',278:'mirandela',279:'moncorvo',281:'tavira',282:'portimão',283:'odemira',284:'beja',285:'moura',286:'castro verde',289:'faro',291:'funchal, porto santo',292:'corvo, faial, flores, horta, pico',295:'angra do heroísmo, graciosa, são jorge, terceira',296:'ponta delgada, são miguel, santa maria',91:'rede móvel 91 (Vodafone / Yorn)',93:'rede móvel 93 (Optimus)',96:'rede móvel 96 (TMN)',925:'rede móvel 925 (TMN 925)',926:'rede móvel 926 (TMN 926)',927:'rede móvel 927 (TMN 927)',922:'rede móvel 922 (Phone-ix)',707:'número único',760:'número único',800:'número grátis',808:'chamada local'},_internacionalCV:238,_indicativosCV:{2:'fixo',91:'móvel 91',95:'móvel 95',97:'móvel 97',98:'móvel 98',99:'móvel 99'},_internacionalAO:244,_indicativosAO:{2:'fixo',91:'móvel 91',92:'móvel 92'},_internacionalMZ:258,_indicativosMZ:{2:'fixo',82:'móvel 82',84:'móvel 84'},_internacionalTL:670,_indicativosTL:{3:'fixo',7:'móvel 7'},_isLeapYear:function(year){var yearRegExp=/^\d{4}$/;if(yearRegExp.test(year)){return((year%4)?false:((year%100)?true:((year%400)?false:true)));}
return false;},_dateParsers:{'yyyy-mm-dd':{day:5,month:3,year:1,sep:'-',parser:/^(\d{4})(\-)(\d{1,2})(\-)(\d{1,2})$/},'yyyy/mm/dd':{day:5,month:3,year:1,sep:'/',parser:/^(\d{4})(\/)(\d{1,2})(\/)(\d{1,2})$/},'yy-mm-dd':{day:5,month:3,year:1,sep:'-',parser:/^(\d{2})(\-)(\d{1,2})(\-)(\d{1,2})$/},'yy/mm/dd':{day:5,month:3,year:1,sep:'/',parser:/^(\d{2})(\/)(\d{1,2})(\/)(\d{1,2})$/},'dd-mm-yyyy':{day:1,month:3,year:5,sep:'-',parser:/^(\d{1,2})(\-)(\d{1,2})(\-)(\d{4})$/},'dd/mm/yyyy':{day:1,month:3,year:5,sep:'/',parser:/^(\d{1,2})(\/)(\d{1,2})(\/)(\d{4})$/},'dd-mm-yy':{day:1,month:3,year:5,sep:'-',parser:/^(\d{1,2})(\-)(\d{1,2})(\-)(\d{2})$/},'dd/mm/yy':{day:1,month:3,year:5,sep:'/',parser:/^(\d{1,2})(\/)(\d{1,2})(\/)(\d{2})$/}},_daysInMonth:function(_m,_y){var nDays=0;if(_m==1||_m==3||_m==5||_m==7||_m==8||_m==10||_m==12)
{nDays=31;}
else if(_m==4||_m==6||_m==9||_m==11)
{nDays=30;}
else
{if((_y%400==0)||(_y%4==0&&_y%100!=0))
{nDays=29;}
else
{nDays=28;}}
return nDays;},_isValidDate:function(year,month,day){var yearRegExp=/^\d{4}$/;var validOneOrTwo=/^\d{1,2}$/;if(yearRegExp.test(year)&&validOneOrTwo.test(month)&&validOneOrTwo.test(day)){if(month>=1&&month<=12&&day>=1&&this._daysInMonth(month,year)>=day){return true;}}
return false;},mail:function(email)
{var emailValido=new RegExp("^[_a-z0-9-]+((\\.|\\+)[_a-z0-9-]+)*@([\\w]*-?[\\w]*\\.)+[a-z]{2,4}$","i");if(!emailValido.test(email)){return false;}else{return true;}},url:function(url,full)
{if(typeof full=="undefined"||full===false){var reHTTP=new RegExp("(^(http\\:\\/\\/|https\\:\\/\\/)(.+))","i");if(reHTTP.test(url)===false){url='http://'+url;}}
var reUrl=new RegExp("^(http:\\/\\/|https:\\/\\/)([\\w]*(-?[\\w]*)*\\.)+[a-z]{2,4}","i");if(reUrl.test(url)===false){return false;}else{return true;}},isPTPhone:function(phone)
{phone=phone.toString();var aInd=[];for(var i in this._indicativosPT){if(typeof(this._indicativosPT[i])=='string'){aInd.push(i);}}
var strInd=aInd.join('|');var re351=/^(00351|\+351)/;if(re351.test(phone)){phone=phone.replace(re351,"");}
var reSpecialChars=/(\s|\-|\.)+/g;phone=phone.replace(reSpecialChars,'');var reInt=new RegExp("\\d","i");if(phone.length==9&&reInt.test(phone)){var reValid=new RegExp("^("+strInd+")");if(reValid.test(phone)){return true;}}
return false;},isPortuguesePhone:function(phone)
{return this.isPTPhone(phone);},isCVPhone:function(phone)
{phone=phone.toString();var aInd=[];for(var i in this._indicativosCV){if(typeof(this._indicativosCV[i])=='string'){aInd.push(i);}}
var strInd=aInd.join('|');var re238=/^(00238|\+238)/;if(re238.test(phone)){phone=phone.replace(re238,"");}
var reSpecialChars=/(\s|\-|\.)+/g;phone=phone.replace(reSpecialChars,'');var reInt=new RegExp("\\d","i");if(phone.length==7&&reInt.test(phone)){var reValid=new RegExp("^("+strInd+")");if(reValid.test(phone)){return true;}}
return false;},isAOPhone:function(phone)
{phone=phone.toString();var aInd=[];for(var i in this._indicativosAO){if(typeof(this._indicativosAO[i])=='string'){aInd.push(i);}}
var strInd=aInd.join('|');var re244=/^(00244|\+244)/;if(re244.test(phone)){phone=phone.replace(re244,"");}
var reSpecialChars=/(\s|\-|\.)+/g;phone=phone.replace(reSpecialChars,'');var reInt=new RegExp("\\d","i");if(phone.length==9&&reInt.test(phone)){var reValid=new RegExp("^("+strInd+")");if(reValid.test(phone)){return true;}}
return false;},isMZPhone:function(phone)
{phone=phone.toString();var aInd=[];for(var i in this._indicativosMZ){if(typeof(this._indicativosMZ[i])=='string'){aInd.push(i);}}
var strInd=aInd.join('|');var re258=/^(00258|\+258)/;if(re258.test(phone)){phone=phone.replace(re258,"");}
var reSpecialChars=/(\s|\-|\.)+/g;phone=phone.replace(reSpecialChars,'');var reInt=new RegExp("\\d","i");if((phone.length==9||phone.length==8)&&reInt.test(phone)){var reValid=new RegExp("^("+strInd+")");if(reValid.test(phone)){if(phone.indexOf('2')==0&&phone.length==8){return true;}else if(phone.indexOf('8')==0&&phone.length==9){return true;}}}
return false;},isTLPhone:function(phone)
{phone=phone.toString();var aInd=[];for(var i in this._indicativosTL){if(typeof(this._indicativosTL[i])=='string'){aInd.push(i);}}
var strInd=aInd.join('|');var re670=/^(00670|\+670)/;if(re670.test(phone)){phone=phone.replace(re670,"");}
var reSpecialChars=/(\s|\-|\.)+/g;phone=phone.replace(reSpecialChars,'');var reInt=new RegExp("\\d","i");if(phone.length==7&&reInt.test(phone)){var reValid=new RegExp("^("+strInd+")");if(reValid.test(phone)){return true;}}
return false;},isPhone:function(){if(arguments.length==0){return false;}
var phone=arguments[0];if(arguments.length>1){if(arguments[1].constructor===Array){var func;for(var index=0;index<arguments[1].length;index++){if(typeof(func=this['is'+arguments[1][index].toUpperCase()+'Phone'])=='function'){if(func(phone)){return true;}}else{throw"Invalid Country Code!";}}}else if(typeof(this['is'+arguments[1].toUpperCase()+'Phone'])=='function'){return this['is'+arguments[1].toUpperCase()+'Phone'](phone);}else{throw"Invalid Country Code!";}}else{for(var index=0;index<this._countryCodes.length;index++){if(this['is'+this._countryCodes[index]+'Phone'](phone)){return true;}}}
return false;},codPostal:function(cp1,cp2){var cPostalSep=/^(\s*\-\s*|\s+)$/;var trim=/^\s+|\s+$/g;var cPostal4=/^[1-9]\d{3}$/;var cPostal3=/^\d{3}$/;var parserCPostal=/^(.{4})(.*)(.{3})$/;cp1=cp1.replace(trim,'');if(typeof(cp2)!='undefined'){cp2=cp2.replace(trim,'');if(cPostal4.test(cp1)&&cPostal3.test(cp2)){return true;}}else{if(cPostal4.test(cp1)){return true;}
var cPostal=cp1.match(parserCPostal);if(cPostal!=null&&cPostal4.test(cPostal[1])&&cPostalSep.test(cPostal[2])&&cPostal3.test(cPostal[3])){return true;}}
return false;},isDate:function(format,dateStr){if(typeof(this._dateParsers[format])=='undefined'){return false;}
var yearIndex=this._dateParsers[format].year;var monthIndex=this._dateParsers[format].month;var dayIndex=this._dateParsers[format].day;var dateParser=this._dateParsers[format].parser;var separator=this._dateParsers[format].sep;var trim=/^\w+|\w+$/g;var data=dateStr.match(dateParser);if(data!=null){if(data[2]==data[4]&&data[2]==separator){var _y=((data[yearIndex].length==2)?"20"+data[yearIndex].toString():data[yearIndex]);if(this._isValidDate(_y,data[monthIndex].toString(),data[dayIndex].toString())){return true;}}}
return false;},isColor:function(str){var match,valid=false,keyword=/^[a-zA-Z]+$/,hexa=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,rgb=/^rgb\(\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*\)$/,rgba=/^rgba\(\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*,\s*(1(\.0)?|0(\.[0-9])?)\s*\)$/,hsl=/^hsl\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*\)$/,hsla=/^hsla\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*,\s*(1(\.0)?|0(\.[0-9])?)\s*\)$/;if(keyword.test(str)||hexa.test(str)){return true;}
if((match=rgb.exec(str))!==null||(match=rgba.exec(str))!==null){var i=match.length;while(i--){if((i==2||i==4||i==6)&&typeof match[i]!="undefined"&&match[i]!==""){if(typeof match[i-1]!="undefined"&&match[i-1]>=0&&match[i-1]<=100){valid=true;}else{return false;}}
if(i==1||i==3||i==5&&(typeof match[i+1]=="undefined"||match[i+1]==="")){if(typeof match[i]!="undefined"&&match[i]>=0&&match[i]<=255){valid=true;}else{return false;}}}}
if((match=hsl.exec(str))!==null||(match=hsla.exec(str))!==null){var i=match.length;while(i--){if(i==3||i==5){if(typeof match[i-1]!="undefined"&&typeof match[i]!="undefined"&&match[i]!==""&&match[i-1]>=0&&match[i-1]<=100){valid=true;}else{return false;}}
if(i==1){if(typeof match[i]!="undefined"&&match[i]>=0&&match[i]<=360){valid=true;}else{return false;}}}}
return valid;},debug:function()
{}};
if(typeof(SAPO.Utility)=='undefined'){SAPO.namespace('Utility');};SAPO.Utility.FormValidator={version:'0.1',_flagMap:{'sufv-required':{msg:'Campo obrigat&oacute;rio'},'sufv-email':{msg:'E-mail inv&aacute;lido'},'sufv-url':{msg:'URL inv&aacute;lido'},'sufv-number':{msg:'N&uacute;mero inv&aacute;lido'},'sufv-phone_pt':{msg:'N&uacute;mero de telefone inv&aacute;lido'},'sufv-phone_cv':{msg:'N&uacute;mero de telefone inv&aacute;lido'},'sufv-phone_mz':{msg:'N&uacute;mero de telefone inv&aacute;lido'},'sufv-phone_ao':{msg:'N&uacute;mero de telefone inv&aacute;lido'},'sufv-date':{msg:'Data inv&aacute;lida'},'sufv-confirm':{msg:'Confirma&ccedil;&atilde;o inv&aacute;lida'},'sufv-custom':{msg:''}},elements:{},_errorClassName:'sufv-error',validate:function(elm)
{this._free();var options=SAPO.extendObj({onSuccess:false,onError:false,customFlag:false,debug:false},arguments[1]||{});if(typeof(elm)=='string'){elm=document.getElementById(elm);}
if(elm===null){return false;}
this.element=elm;if(typeof(this.element.id)=='undefined'||this.element.id===null||this.element.id===''){this.element.id='sufv_randomid_'+(Math.round(Math.random()*99999));}
this.custom=options.customFlag;var fail=this._validateElements();if(fail.length>0){if(options.onError){options.onError(fail);}else{this._showError(elm,fail);}
return false;}else{if(!options.onError){this._clearError(elm);}
this._clearCache();if(options.onSuccess){options.onSuccess();}
return true;}},reset:function()
{this._clearError();this._clearCache();},_free:function()
{this.element=null;this.custom=false;},_clearCache:function()
{this.element=null;this.elements=[];this.custom=false;},_getElements:function()
{if(typeof(this.elements[this.element.id])!='undefined'){return;}
this.elements[this.element.id]=[];var formElms=this.element.elements;var curElm=false;for(var i=0,totalElm=formElms.length;i<totalElm;i++){curElm=formElms[i];if(typeof(curElm.type)!='undefined'&&curElm.type!=null&&curElm.type.toLowerCase()=='radio'){if(curElm.type!=this.elements[this.element.id][(this.elements[this.element.id].length-1)].type&&curElm.name!=this.elements[this.element.id][(this.elements[this.element.id].length-1)].name){for(var flag in this._flagMap){if(SAPO.Dom.Css.hasClassName(curElm,flag)){this.elements[this.element.id].push(curElm);break;}}}}else{for(var flag in this._flagMap){if(SAPO.Dom.Css.hasClassName(curElm,flag)){this.elements[this.element.id].push(curElm);break;}}}}},_validateElements:function()
{this._getElements();var errors=[];var curElm=false;var customErrors=false;var inArray;for(var i=0,totalElm=this.elements[this.element.id].length;i<totalElm;i++){inArray=false;curElm=this.elements[this.element.id][i];for(var flag in this._flagMap){if(SAPO.Dom.Css.hasClassName(curElm,flag)){if(flag!='sufv-custom'){if(!this._isValid(curElm,flag)){if(!inArray){errors.push({elm:curElm,errors:[flag]});inArray=true;}else{errors[(errors.length-1)].errors.push(flag);}}}else{customErrors=this._isCustomValid(curElm);if(customErrors.length>0){errors.push({elm:curElm,errors:[flag],custom:customErrors});}}}}}
return errors;},_isCustomValid:function(elm)
{var customErrors=[];var curFlag=false;var inArray=false;for(var i=0,tCustom=this.custom.length;i<tCustom;i++){curFlag=this.custom[i];if(SAPO.Dom.Css.hasClassName(elm,curFlag.flag)){if(!curFlag.callback(elm,curFlag.msg)){customErrors.push({flag:curFlag.flag,msg:curFlag.msg});}}}
return customErrors;},_isValid:function(elm,fieldType)
{switch(fieldType){case'sufv-required':if(elm.nodeName.toLowerCase()=='select'){if(elm.selectedIndex>0){return true;}else{return false;}}
if(elm.type!='checkbox'&&elm.type!='radio'){if(this._trim(elm.value)!=''){return true;}}else if(elm.type=='checkbox'){if(elm.checked===true){return true;}}else if(elm.type=='radio'){var aFormRadios=elm.form[elm.name];var isChecked=false;for(var i=0,totalRadio=aFormRadios.length;i<totalRadio;i++){if(aFormRadios[i].checked===true){isChecked=true;}}
return isChecked;}
break;case'sufv-email':if(this._trim(elm.value)==''){if(SAPO.Dom.Css.hasClassName(elm,'sufv-required')){return false;}else{return true;}}else{if(SAPO.Utility.Validator.mail(elm.value)){return true;}}
break;case'sufv-url':if(this._trim(elm.value)==''){if(SAPO.Dom.Css.hasClassName(elm,'sufv-required')){return false;}else{return true;}}else{if(SAPO.Utility.Validator.url(elm.value)){return true;}}
break;case'sufv-number':if(this._trim(elm.value)==''){if(SAPO.Dom.Css.hasClassName(elm,'sufv-required')){return false;}else{return true;}}else{if(!isNaN(Number(elm.value))){return true;}}
break;case'sufv-phone_pt':if(this._trim(elm.value)==''){if(SAPO.Dom.Css.hasClassName(elm,'sufv-required')){return false;}else{return true;}}else{if(SAPO.Utility.Validator.isPTPhone(elm.value)){return true;}}
break;case'sufv-phone_cv':if(this._trim(elm.value)==''){if(SAPO.Dom.Css.hasClassName(elm,'sufv-required')){return false;}else{return true;}}else{if(SAPO.Utility.Validator.isCVPhone(elm.value)){return true;}}
break;case'sufv-phone_ao':if(this._trim(elm.value)==''){if(SAPO.Dom.Css.hasClassName(elm,'sufv-required')){return false;}else{return true;}}else{if(SAPO.Utility.Validator.isAOPhone(elm.value)){return true;}}
break;case'sufv-phone_mz':if(this._trim(elm.value)==''){if(SAPO.Dom.Css.hasClassName(elm,'sufv-required')){return false;}else{return true;}}else{if(SAPO.Utility.Validator.isMZPhone(elm.value)){return true;}}
break;case'sufv-custom':break;}
return false;},_showError:function(formElm,aFail)
{this._clearError(formElm);var curElm=false;for(var i=0,tFail=aFail.length;i<tFail;i++){curElm=aFail[i].elm;var newLabel=document.createElement('label');newLabel.setAttribute('for',curElm.id);newLabel.className=this._errorClassName;if(aFail[i].errors[0]!='sufv-custom'){newLabel.innerHTML=this._flagMap[aFail[i].errors[0]].msg;}else{newLabel.innerHTML=aFail[i].custom[0].msg;}
if(curElm.nextSibling!=null){curElm.nextSibling.parentNode.insertBefore(newLabel,curElm.nextSibling);}else{curElm.parentNode.appendChild(newLabel);}}},_clearError:function(formElm)
{var aErrorLabel=formElm.getElementsByTagName('label');var curElm=false;for(var i=(aErrorLabel.length-1);i>=0;i--){curElm=aErrorLabel[i];if(SAPO.Dom.Css.hasClassName(curElm,this._errorClassName)){curElm.parentNode.removeChild(curElm);}}},_trim:function(str)
{if(typeof(str)==='string')
{return str.replace(/^\s+|\s+$|\n+$/g,'');}},debug:function(){}};/*jshint forin:true */
/*global SAPO:true, s$:true */

if(!SAPO.Utility || typeof SAPO.Utility === 'undefined') {
	SAPO.namespace('Utility');
}


/**
 * @class SAPO.Utility.FormSerialize
 * @author jose.p.dias AT co.sapo.pt
 * @since June 2011
 * @version 0.1
 * 
 * <pre>
 * Supports form data <-> JSON serialization.
 * Valid applications are ad hoc AJAX/syndicated submission of forms, restoring form values from server side state, etc.
 * </pre>
 */
SAPO.Utility.FormSerialize = { 
	
	/**
	 * @function {Object} ? returns a map of fieldName -> String|String[]|Boolean
	 * (only select multiple and checkboxes with multiple values return arrays)  
	 * @param {DomElement|String}	form - form element from which the extraction is to occur
	 */
	serialize: function(form) {
		form = s$(form);
		var map = this._getFieldNameInputsMap(form);
		
		var map2 = {};
		for (var k in map) {
			map2[k] = this._getValuesOfField( map[k] );
		}
		
		delete map2['null'];	// this can occur. if so, delete it...
		return map2;
	},
	

	
	
	/**
	 * @function ? sets form elements with values given from object
	 * One cannot restore the values of an input of type file (browser prohibits it)
	 * @param {DomElement|String}	form - form element which is to be populated
	 * @param {Object}				map2 - map of fieldName -> String|String[]|Boolean
	 */
	fillIn: function(form, map2) {
		form = s$(form);
		var map = this._getFieldNameInputsMap(form);
		delete map['null']; // this can occur. if so, delete it...
		
		for (var k in map2) {
			this._setValuesOfField( map[k], map2[k] );
		}
	},
	
	
	
	_getFieldNameInputsMap: function(formEl) {
		var name, nodeName, el, map = {};
		for (var i = 0, f = formEl.elements.length; i < f; ++i) {
			el = formEl.elements[i];
			name = el.getAttribute('name');
			nodeName = el.nodeName.toLowerCase();
			if		(nodeName === 'fieldset') {		continue;			}
			else if	(map[name] === undefined) {		map[name] = [el];	}
			else {									map[name].push(el);	}
		}
		return map;
	},
	
	
	
	_getValuesOfField: function(fieldInputs) {
		var nodeName = fieldInputs[0].nodeName.toLowerCase();
		var type = fieldInputs[0].getAttribute('type');
		var value = fieldInputs[0].value;
		var i, f, el, res = [];
		
		switch(nodeName) {
			case 'select':
				if (fieldInputs.length > 1) {	throw 'Got multiple select elements with same name!';	}
				for (i = 0, f = fieldInputs[0].options.length; i < f; ++i) {
					el = fieldInputs[0].options[i];
					if (el.selected) {
						res.push(	el.value	);
					}
				}
				return ( (fieldInputs[0].getAttribute('multiple')) ?  res : res[0] );
			
			case 'textarea':
			case 'input':
				if (type === 'checkbox' || type === 'radio') {
					for (i = 0, f = fieldInputs.length; i < f; ++i) {
						el = fieldInputs[i];
						if (el.checked) {
							res.push(	el.value	);
						}
					}
					if (type === 'checkbox') {
						return (fieldInputs.length > 1) ? res : !!(res.length);
					}
					return (fieldInputs.length > 1) ? res[0] : !!(res.length);	// on radios only 1 option is selected at most
				}
				else {
					//if (fieldInputs.length > 1) {	throw 'Got multiple input elements with same name!';	}
					return value;
				}
				break;	// to keep JSHint happy...
				
			default:
				//throw 'Unsupported element: "' + nodeName + '"!';
				return undefined;
		}
	},
	
	
	
	_valInArray: function(val, arr) {
		for (var i = 0, f = arr.length; i < f; ++i) {
			if (arr[i] === val) {	return true;	}
		}
		return false;
	},
	
	
	
	_setValuesOfField: function(fieldInputs, fieldValues) {
		if (!fieldInputs) {	return;	}
		var nodeName = fieldInputs[0].nodeName.toLowerCase();
		var type = fieldInputs[0].getAttribute('type');
		var i, f, el;
		
		switch(nodeName) {
			case 'select':
				if (fieldInputs.length > 1) {	throw 'Got multiple select elements with same name!';	}
				for (i = 0, f = fieldInputs[0].options.length; i < f; ++i) {
					el = fieldInputs[0].options[i];
					el.selected = (fieldValues instanceof Array) ? this._valInArray(el.value, fieldValues) : el.value === fieldValues;
				}
				break;
			
			case 'textarea':
			case 'input':
				if (type === 'checkbox' || type === 'radio') {
					for (i = 0, f = fieldInputs.length; i < f; ++i) {
						el = fieldInputs[i];
						//el.checked = (fieldValues instanceof Array) ? this._valInArray(el.value, fieldValues) : el.value === fieldValues;
						el.checked = (fieldValues instanceof Array) ? this._valInArray(el.value, fieldValues) : (fieldInputs.length > 1 ? el.value === fieldValues : !!fieldValues);
					}
				}
				else {
					if (fieldInputs.length > 1) {	throw 'Got multiple input elements with same name!';	}
					if (type !== 'file') {
						fieldInputs[0].value = fieldValues;
					}
				}
				break;
				
			default:
				throw 'Unsupported element: "' + nodeName + '"!';
		}
	}
	
};
if(!SAPO.Widget||typeof(SAPO.Widget)=="undefined"){SAPO.namespace("Widget")}SAPO.Widget.Gameover=function(a){this.init(a)};SAPO.Widget.Gameover.prototype={init:function(a){this._currentPage=0;this._options=SAPO.extendObj({mode:"video",inline:false,items:false,currentItem:false,currentPage:false,itemsLoadUrl:false,items_per_page:4,pageContainer:false,previousPageLink:false,nextPageLink:false,previousItemLink:false,nextItemLink:false,itemHolder:false,animate:false,followLink:false,onPageChange:false,onItemChange:false,showDescription:false},a||{});if(this._options.pageContainer===false){this._structureBuild()}else{this._pageContainer=this._options.pageContainer;this._previousPageLink=this._options.previousPageLink;this._nextPageLink=this._options.nextPageLink;this._previousItemLink=this._options.previousItemLink;this._nextItemLink=this._options.nextItemLink;this._itemHolder=this._options.itemHolder}if(this._options.itemsLoadUrl){this._loadItems()}else{this._currentItem=this._options.currentItem;this._items=this._options.items;if(this._options.currentPage){this._currentPage=this._options.currentPage-1}this._addBehaviours()}},_addBehaviours:function(){SAPO.Dom.Event.observe(this._previousPageLink,"click",this._handlePageChange.bindObjEvent(this,-1));SAPO.Dom.Event.observe(this._nextPageLink,"click",this._handlePageChange.bindObjEvent(this,1));if(this._options.mode==="photo"){SAPO.Dom.Event.observe(this._previousItemLink,"click",this._handleNavigationChange.bindObjEvent(this,-1));SAPO.Dom.Event.observe(this._nextItemLink,"click",this._handleNavigationChange.bindObjEvent(this,1));SAPO.Dom.Event.observe(this._pageContainer,"click",this._handleItemClick.bindObjEvent(this))}},_videoListBuild:function(c){var a='<div class="bloco-video-top"></div>';for(var d=0,b=c.length;d<b;d++){a+='<div class="bloco-video-texto'+((this._currentItem>=0&&this._items[this._currentItem].id==c[d].id)?" selected":"")+((d==b-1)?" last":"")+" item_"+c[d].id+'">';a+='     <img alt="" src="'+c[d].thumbnail+'" class="video-hp-artigos" />';a+='     <a class="btn-play" href="'+c[d].url+'">play</a>';a+='     <h4><a href="'+c[d].url+'">'+c[d].title+"</a></h4>";a+='     <p class="date">'+c[d].date+"</p>";a+='     <p class="duration">Duration: '+c[d].length+"</p>";a+=" </div>"}a+='<div class="bloco-video-bottom"></div>';this._pageContainer.innerHTML=a},_photoListBuild:function(c){var a='<div class="bloco-video-top"></div>';for(var d=0,b=c.length;d<b;d++){a+='<div class="bloco-video-texto'+((this._currentItem>=0&&this._items[this._currentItem].id==c[d].id)?" selected":"")+((d==b-1)?" last":"")+" item_"+c[d].id+'">';a+='    <a href="'+(this._options.inline?"#":c[d].url)+'"><img src="'+c[d].thumbnail+'" alt="" /></a>';a+="</div>"}a+='<div class="bloco-video-bottom"></div>';this._pageContainer.innerHTML=a},_photoItemBuild:function(){var a=document.createElement("img");a.onload=function(e,b){if(this._currentItem!==b){return}var f='<a href="'+this._items[b].original+'" target="_blank" title="Clique para ver no tamanho original"></a>';if(this._options.showDescription&&this._items[b].description){f+='<p class="legend">'+this._items[b].description.replace(/(&#13;)?&#10;/g,"<br />")+"</p>"}this._itemHolder.innerHTML=f;this._itemHolder.getElementsByTagName("a")[0].appendChild(e);var d=SAPO.Dom.Selector.select(".selected",this._pageContainer),c=SAPO.Dom.Selector.select(".item_"+this._items[b].id,this._pageContainer);if(d.length){SAPO.Dom.Css.removeClassName(d[0],"selected")}if(c.length){SAPO.Dom.Css.addClassName(c[0],"selected")}}.bindObj(this,a,this._currentItem);a.src=this._items[this._currentItem].image},_loadItems:function(){new SAPO.Communication.Ajax(this._options.itemsLoadUrl,{method:"get",onSuccess:this._handleLoadItemsSuccess.bindObj(this),onFailure:this._handleLoadItemsFailure.bindObj(this)})},_handleLoadItemsSuccess:function(a,b){if(!b||b.result!="OK"){return}this._items=b.list;this._currentItem=b.selected;this._currentPage=b.page-1;this._pageCount=Math.ceil(this._items.length/this._options.items_per_page)-1;this._addBehaviours();if(this._pageContainer.childNodes.length===0){this._rebuildItems(this._currentPage);this._rebuildItem(this._currentItem)}},_handlePageChange:function(a,b){SAPO.Dom.Event.stop(a);if(this._rebuildItems(this._currentPage+b)){if(this._options.onPageChange&&typeof(this._options.onPageChange)==="function"){this._options.onPageChange(this._currentPage)}}},_handleNavigationChange:function(c,d){SAPO.Dom.Event.stop(c);if(this._currentItem+d<0||this._currentItem+d>this._items.length-1){return}var a=this._getVisibleItems();if(!SAPO.Utility.Array.inArray(this._items[this._currentItem+d],a)){var b=false;if(SAPO.Utility.Array.inArray(this._items[this._currentItem],a)){b=true;this._currentPage+=d}if(d===1){this._currentItem=this._currentPage*this._options.items_per_page}else{this._currentItem=(this._currentPage+1)*this._options.items_per_page-1}if(b){this._rebuildItems(this._currentPage)}}else{this._currentItem+=d}this._rebuildItem(this._currentItem);if(this._options.onItemChange&&typeof(this._options.onItemChange)==="function"){this._options.onItemChange(this._items[this._currentItem].id)}if(this._options.mode==="photo"&&!this._options.inline){window.history.replaceState(null,null,this._items[this._currentItem].url)}},_handleItemClick:function(c){SAPO.Dom.Event.stop(c);var d=c.target||c.srcElement,b=SAPO.Dom.Element.findUpwardsByClass(d,"bloco-video-texto"),a=SAPO.Dom.Element.parentIndexOf(this._pageContainer,b)-1;this._currentItem=this._currentPage*this._options.items_per_page+a;this._rebuildItem(this._currentItem);if(this._options.onItemChange&&typeof(this._options.onItemChange)==="function"){this._options.onItemChange(this._items[this._currentItem].id)}if(this._options.mode==="photo"&&!this._options.inline){window.history.replaceState(null,null,d.parentNode.href)}},_structureBuild:function(){var c="photosPage_"+Math.floor(Math.random()*100);var b=document.createElement("div");b.className="inline-photo-gallery";b.innerHTML='<div id="'+c+'_header" class="header">'+'<ul class="video-quality"><li class="video-number"></li></ul>'+'<ul class="controls">'+'<li class="button back"><a id="'+c+'_prevItemLink" href="#">«</a></li>'+'<li class="button forward"><a id="'+c+'_nextItemLink" href="#">»</a></li>'+"</ul>"+"</div>"+'<div id="'+c+'_holder" class="carousel-img-holder"></div>'+'<div class="photo gallery-carousel">'+'<div class="header">'+'<ul class="video-quality"><li class="video-number"></li></ul>'+'<ul class="controls">'+'<li class="button back"><a id="'+c+'_prevPageLink" href="#">«</a></li>'+'<li class="button forward"><a id="'+c+'_nextPageLink" href="#">»</a></li>'+"</ul>"+"</div>"+'<div class="container">'+'<div id="'+c+'" class="content bloco-video-conteudo"></div>'+"</div>"+"</div>";var a=SAPO.Utility.Url.currentScriptElement();a.parentNode.insertBefore(b,a);this._pageContainer=s$(c);this._itemHolder=s$(c+"_holder");this._previousPageLink=s$(c+"_prevPageLink");this._nextPageLink=s$(c+"_nextPageLink");this._previousItemLink=s$(c+"_prevItemLink");this._nextItemLink=s$(c+"_nextItemLink")},_rebuildItems:function(b){var a=Math.floor((this._items.length-1)/this._options.items_per_page,0);if(b<0||b>a){return false}this._currentPage=b;this["_"+this._options.mode+"ListBuild"](this._getVisibleItems());SAPO.Dom.Css.removeClassName(this._previousPageLink,"disabled");SAPO.Dom.Css.removeClassName(this._nextPageLink,"disabled");if(b==0){SAPO.Dom.Css.addClassName(this._previousPageLink,"disabled")}if(b==a){SAPO.Dom.Css.addClassName(this._nextPageLink,"disabled")}if(this._options.mode==="photo"){SAPO.Dom.Css.removeClassName(this._previousItemLink,"disabled");SAPO.Dom.Css.removeClassName(this._nextItemLink,"disabled");if(this._currentItem==0&&this._previousItemLink){SAPO.Dom.Css.addClassName(this._previousItemLink,"disabled")}if(this._currentItem==(this._items.length-1)&&this._nextItemLink){SAPO.Dom.Css.addClassName(this._nextItemLink,"disabled")}}this._rebuildItemsPageCount();return true},_rebuildItem:function(a){this._currentItem=a;if(this["_"+this._options.mode+"ItemBuild"]){this["_"+this._options.mode+"ItemBuild"](this._currentItem);this._rebuildItemsCount()}},_rebuildItemsPageCount:function(){var c=SAPO.Dom.Element.findUpwardsByClass(this._previousPageLink,"header"),b=SAPO.Dom.Selector.select(".video-number",c),a=this._getItemsCountDescription();b[0].innerHTML="<span>"+((this._currentPage*this._options.items_per_page)+1)+"</span> a "+"<span>"+(this._currentPage===this._pageCount?this._items.length:(this._currentPage+1)*this._options.items_per_page)+"</span> de "+"<span>"+this._items.length+"</span>"+"&nbsp;"+a},_rebuildItemsCount:function(){var c=SAPO.Dom.Element.findUpwardsByClass(this._previousItemLink,"header"),b=SAPO.Dom.Selector.select(".video-number",c),a=this._getItemsCountDescription();b[0].innerHTML="<span>"+(this._currentItem+1)+"</span> de "+"<span>"+(this._items.length)+"</span>"+"&nbsp;"+a},_getVisibleItems:function(){return this._items.slice(this._currentPage*this._options.items_per_page,this._currentPage*this._options.items_per_page+this._options.items_per_page)},_getItemsCountDescription:function(){return this._options.mode==="photo"?(this._items.length>1?"imagens":"imagem"):(this._items.length>1?"vídeos":"vídeo")},_handleLoadItemsFailure:function(){},_animate:function(){},debug:function(){}};
