var console;

(function()
{    
    if(!console)
    {
        console = { log: function(){} };
    }

    var truncate = function(string, len, append)
    {
        if(!len)
        {
            len = 47;
        }
        if(!append)
        {
            append = '...';
        }

        if(string.length > (len + append.length))
        {
            string = string.slice(0, len - 1) + append;
        }

        return string;

    };

    API.requestHandler = function(obj)
    {
        addBoxes(obj.boxes);
    };

    var boxes;
    var contentContainers;
    var innerContent;
    var boxesLength;
    var totalLoaded = 0;
    var secaoEnqueteId = 0;
    
    var allLoaded = function()
    {
        if(totalLoaded === boxesLength)
        {
            var waitEl = API.getEBI("wait");
            if(waitEl)
            {
                waitEl.style.display = "none";
            }
            totalLoaded = 0;
        }
    };

    var addBox = function(boxCfg)
    {
        var box, size, tab, tabs = [];
        size = boxCfg.size;
        var index = boxes.length;

        box = new Box(size, index, boxCfg.nome, boxCfg.link);

        boxes.splice(index, 0, box);

        tabs = boxCfg.items;

        for(var i = 0, l = tabs.length; i < l; ++i)
        {
            tab = tabs[i];
            box.appendTab(tab.nome, tab.tipo_object.alias, tab.url);
        }

        if(typeof API.boxesCallback == "function")
        {
            API.boxesCallback(box);
        }

        if(tabs.length < 2)
        {
            box.loadCurrentTab();
        }
        else
        {
            box.loadFeaturedPosts();
        }

        if(API.SNAPSHOT)
        {
            box.loadAllTabs();
        }

        return box;
    };

    var addBoxes = function(boxesCfg)
    {
        if(!contentContainers)
        {
            contentContainers = API.getEBCN('box_content');
            innerContent = API.getEBCN('content');
        }
        for(var j = innerContent.length; --j >= 0;)
        {
            if(innerContent[j].id != 'jogos-content')
            {
                API.emptyNode(innerContent[j]);
            }
        }

        boxes = [];
        
        boxesLength = boxesCfg.length;

        for(var i = 0, l = boxesCfg.length; i < l; ++i)
        {
            addBox(boxesCfg[i]);
        }
    };
    API.addBoxes = addBoxes;

    var twitter = {};
    (function()
    {
        var containers = {};
        twitter.fnDone = {};
        var cbUid = 0;

        var buildTweets = function(screenName, data)
        {
            //<div class="image"><img src="images/icons/twitter_140x170.png" title="Twitter"></div>
            if(!data)
            {
                return;
            }

            var tweetWrapper = document.createElement("div");
            tweetWrapper.className = "tweet-wrapper";

            var birdWrapper = document.createElement('div');
            birdWrapper.className = 'image';
            tweetWrapper.appendChild(birdWrapper);

            var birdImage = document.createElement('img');
            birdImage.src = '/images/icons/twitter_140x170.png';
            birdWrapper.appendChild(birdImage);

            var titleHeading = document.createElement("h5");

            var titleHeadingLink = document.createElement("a");
            titleHeadingLink.href = "http://twitter.com/" + screenName;
            titleHeadingLink.target = "_blank";
            titleHeadingLink.appendChild(document.createTextNode("@" + screenName));

            titleHeading.appendChild(titleHeadingLink);
            tweetWrapper.appendChild(titleHeading);

            var tweet, tweetLink, tweetDate, hours, mins, secs;
            var tweetText, tweetInfo, tweetDateString;

            if(data.length)
            {
                data = data[0];
            }

            tweet = document.createElement("p");

            tweetLink = document.createElement("a");
            tweetLink.href = [
                "http://twitter.com/", screenName,
                "/status/", data.id
            ].join('');
            tweetLink.target = "_blank";
            tweetDateString = createTimeString(data.created_at);
            tweetLink.appendChild(document.createTextNode(tweetDateString));
            tweet.appendChild(tweetLink);
            tweet.appendChild(document.createElement("br"));
            tweet.innerHTML += parseTweet(data.text);

            tweetWrapper.appendChild(tweet);
            
            totalLoaded = totalLoaded+1;
            allLoaded();
            return tweetWrapper;
        };

        twitter.buildTweets = buildTweets;

        var createTimeString = function(dateString)
        {
            var d = new Date(dateString);
            var now = new Date();

            var days = 0, minutes = 0, hours;

            var yearsDiff = now.getFullYear() - d.getFullYear();
            var monthsDiff = now.getMonth() - d.getMonth();
            var daysDiff = now.getDate() - d.getDate();
            var hoursDiff = now.getHours() - d.getHours();
            var minsDiff = now.getMinutes() - d.getMinutes();

            if(yearsDiff > 0)
            {
                days = yearsDiff * 365;
            }

            if(monthsDiff > 0)
            {
                days += monthsDiff * 30;
            }

            if(daysDiff > 0)
            {
                days += daysDiff;
            }

            if(days)
            {
                return days + ' dia' + ((days > 1) ? 's' : '') + ' atr\xE1s';
            }

            if(hoursDiff > 0)
            {
                minutes = hoursDiff * 60;
            }
            if(minsDiff > 0)
            {
                minutes += minsDiff;
            }

            if(minutes > 59)
            {
                hours = Math.floor(minutes / 60);
                return hours + ' hora' + ((hours > 1) ? 's' : '') + ' atr\xE1s';
            }
            else if(minutes === 0)
            {
                return 'minutos atr\xE1s';
            }

            return minutes + ' minuto' + ((minutes > 1) ? 's' : '') + ' atr\xE1s';
        };

        var removeScreenName = function(tweet)
        {
            return trimString(tweet.slice(tweet.indexOf(":") + 2));
        };

        var parseTweet = (function()
        {
            var tagsRegExp = new RegExp('<\\w+(\\s+("[^"]*"|\'[^\']*\'|[^>])+)?>|<\\/\\w+>', 'gi');
            var linkRE = new RegExp("(https?:\/\/[^\\s]+)", "gi");
            var screenNameRE = new RegExp("(^|\\s)@([\\w\\d_]+)", "g");
            var hashTagRE = new RegExp("(^|\\s)#([\\w\\d_]+)", "g");
            return function(text)
            {
                return text.replace(
                    linkRE, '<a href="$1" target="_blank">$1</a>'
                ).replace(
                    screenNameRE, '$1<a href="http://twitter.com/$2" class="screenname-in-tweet" target="_blank">@$2</a>'
                ).replace(
                    hashTagRE, '$1<a href="http://search.twitter.com/search?q=' + global.encodeURIComponent('#') + '$2" class="hash-tag" target="_blank">#$2</a>'
                );
            };
        })();
    })();

    var enquete = {};
    (function()
    {
        var createPoll = (function()
        {
            var lastChecked;
            var skipClick;
            //var radioChangeListener = function(e)
            //{
            //    if(lastChecked)
            //    {
            //        API.removeClass(lastChecked, 'checked');
            //    }
            //    API.addClass(this.parentNode, 'checked');
            //
            //    lastChecked = this.parentNode;
            //};

            var changeListener = function(e)
            {
                if(typeof skipClick == 'undefined')
                {
                    if(this.type == 'checkbox')
                    {
                        this.checked = !this.checked;
                    }
                    skipClick = true;
                    return;
                }

                if(lastChecked[this.name] && lastChecked[this.name] !== this.parentNode)
                {
                    API.removeClass(lastChecked[this.name], 'checked');
                }
                if(this.checked)
                {
                    API.addClass(this.parentNode, 'checked');
                }
                else
                {
                    API.removeClass(this.parentNode, 'checked');
                }
                lastChecked[this.name] = this.parentNode;
            };

            var clickListener = function(e)
            {
                var inputEl;

                if(skipClick)
                {
                    return;
                }

                if(API.getEventTarget(e) == this)
                {
                    inputEl = this.firstChild;
                    while(API.getElementNodeName(inputEl) != 'input')
                    {
                        inputEl = inputEl.nextSibling;
                    }
                    if(inputEl.type == 'checkbox')
                    {
                        inputEl.checked  = !inputEl.checked;
                        API[(inputEl.checked ? 'add' : 'remove') + 'Class'](this, 'checked');
                    }
                    else
                    {
                        var radioButtons = API.getEBCN('poll-radio', inputEl.form);

                        for(var i = radioButtons.length; --i >= 0;)
                        {
                            API.removeClass(radioButtons[i].parentNode, 'checked');
                            inputEl.checked = false;
                        }
                        API.addClass(this, 'checked');
                        inputEl.checked = true;
                    }
                }
            };

            var buildResults = function(pollContainer, data)
            {
                API.emptyNode(pollContainer);

                var resultsWrapper = document.createElement('div');
                resultsWrapper.className = "box_poll_answer";

                var thanksHeading = document.createElement('h5');
                thanksHeading.appendChild(
                    document.createTextNode(
                        'Voto registrado, obrigado!'
                    )
                );
                resultsWrapper.appendChild(thanksHeading);

                var percentageList = document.createElement('ul');
                var percentageItem, labelPara, barWrapper, bar, percentageSpan,
                    percentageValue ;
                
                for(var i = 0, l = data.length; i < l; ++i)
                {
                    percentageItem = document.createElement('li');

                    labelPara = document.createElement('p');
                    labelPara.className = 'label';
                    labelPara.appendChild(document.createTextNode(data[i].option));
                    percentageItem.appendChild(labelPara);

                    barWrapper = document.createElement('div');
                    barWrapper.className = 'box_graphic';

                    bar = document.createElement('div');
                    bar.className = "bar";
                    
                    percentageValue = data[i].value;
                    
                    if(!percentageValue)
                    {
                        bar.className += " zero";
                    }
                    else
                    {
                        bar.style.width = ((percentageValue / 100) * 56) + "px";
                    }
                    barWrapper.appendChild(bar);

                    percentageSpan = document.createElement('span');
                    
                    if(percentageValue < 10)
                    {
                        percentageValue = "0" + percentageValue;
                    }
                    percentageSpan.appendChild(document.createTextNode(percentageValue + '%'));

                    percentageItem.appendChild(barWrapper);
                    percentageItem.appendChild(percentageSpan);
                    percentageList.appendChild(percentageItem);
                }

                resultsWrapper.appendChild(percentageList);
                
                if (API.getCookie('more-polls') == true)
                {
					var buttonNext = document.createElement('input');
					buttonNext.type = "button";
					buttonNext.value = "Próxima";
                    buttonNext.className = 'next-poll';
					
					thanksHeading.appendChild(buttonNext);
                    
					API.attachListener(buttonNext, 'click', function(){tPrototype.loadNextEnqueteContent(secaoEnqueteId, (pollContainer.parentNode).parentNode)});
				}
				pollContainer.appendChild(resultsWrapper);

                
                totalLoaded = totalLoaded+1;
                allLoaded();
            };

            var submitListener = (function()
            {
                var requester = new API.Requester();
                return function(e)
                {
                    API.cancelDefault(e);
                    var postData = API.serializeFormUrlencoded(this);
                    var pollId = this.id.split('-')[1];
                    postData += '&pollId=' + pollId;

                    var pollContainer = this.parentNode;

                    while(!API.hasClass(pollContainer, 'box_headline'))
                    {
                        pollContainer = pollContainer.parentNode;
                    }
                    requester.onsuccess = function(xhr, data)
                    {
                        if(secaoSite)
                        {
                            sendAnalytcsEvents("/brahma/" + secaoSite + "/dt_fala-brahmeiro/responder", "click", "responder-enquete-"+secaoSite);
                        }
                        buildResults(pollContainer, data);
                        API.setCookie('poll-voted-' + pollId, true, 365);
                        //API.removeClass(this, 'sending');
                    };
                    requester.onfail = function(xhr, data)
                    {
                        //API.removeClass(this, 'sending');
                    };

                    requester.post(this.action, postData, null, true);
                };
            })();
            

            return function(container, config)
            {
                var pollId = config.pollId;
                var headline = document.createElement('div');
                headline.className = 'box_headline poll';
                container.appendChild(headline);

                if(API.getCookie('poll-voted-' + pollId, false))
                {
                    var resultsRequester = new API.Requester();
                    resultsRequester.onsuccess = function(xhr, data)
                    {
                        buildResults(headline, data);
                    };
                    resultsRequester.get('/svc/Voto.php?pollId=' + pollId, true);
                }
                else
                {
                    var pollWrapper = document.createElement("div");
                    pollWrapper.className = "box_poll";
                    headline.appendChild(pollWrapper);

                    var pollForm = document.createElement("form");
                    pollForm.action = '/svc/Voto.php';
                    pollForm.id = "enquete-" + pollId;
                    API.attachListener(pollForm, 'submit', submitListener);

                    var pollQuestion = document.createElement("h5");
                    pollQuestion.appendChild(document.createTextNode(config.question));
                    pollForm.appendChild(pollQuestion);

                    var optionPara, optionInput, optionLabel, optionId;
                    for(var options = config.options, i = 0, l = options.length; i < l; ++i)
                    {
                        optionId = "enquete-" + pollId + "-option" + options[i].id;
                        optionPara = document.createElement("p");

                        optionInput = document.createElement("input");
                        optionInput.type = "radio";
                        optionInput.value = options[i].id;
                        optionInput.name = "optionId";
                        optionInput.id = optionId;
                        optionInput.className = 'poll-radio';
                        optionInput.onchange = changeListener;

                        optionLabel = document.createElement("label");
                        optionLabel.setAttribute("for", optionId);
                        optionLabel.className = 'radio';
                        optionLabel.appendChild(optionInput);
                        optionLabel.appendChild(document.createTextNode(options[i].value));
                        API.attachListener(optionLabel, 'click', clickListener);

                        optionPara.appendChild(optionLabel);
                        pollForm.appendChild(optionPara);
                    }

                    var hiddenPollId = document.createElement('input');
                    hiddenPollId.type = 'hidden';
                    hiddenPollId.value = pollId;
                    pollForm.appendChild(hiddenPollId);
                    
                    var lameFixDiv = document.createElement('div');
                    lameFixDiv.style.clear = 'both';
                    pollForm.appendChild(lameFixDiv);

                    var pollSubmit = document.createElement('input');
                    pollSubmit.type = 'submit';
                    pollSubmit.value = '';
                    pollSubmit.id = 'responder';
                    pollForm.appendChild(pollSubmit);

                    pollWrapper.appendChild(pollForm);
                    totalLoaded = totalLoaded+1;
                    allLoaded();
                }
            };
        })();
        enquete.createPoll = createPoll;
    })();


    var wordpress = {};
    var youtube = {};
    (function()
    {
        var ytThumb = ['http://i.ytimg.com/vi/', '/hqdefault.jpg'];
        var ytChannel = 'http://www.youtube.com/user/CervejaBrahmaOficial#p/u/0/';
        var ytAPI = ['http://gdata.youtube.com/feeds/api/videos/', '?v=2&alt=json'];
        var idRegExp = new RegExp("(v|p)=([^&#]+)");

        var getVideoOrPlaylistId = function(url)
        {
            var matches = url.match(idRegExp);
            return matches && matches[2] || null;
        };

        var handleImageSize = function(e)
        {
            var imgSize = API.getElementSize(this);
            var containerSize = API.getElementSizeStyle(this.parentNode);
            var newHeight;
            var proportion;
            if(imgSize[1] > containerSize[1])
            {
                this.style.width = containerSize[1] + "px";
                imgSize = API.getElementSize(this);
                this.style.position = 'absolute';
                this.style.top = '50%';
                this.style.left = '0';
                this.style.marginTop = -(Math.round(imgSize[0]/2)) + 'px';
            }
        };

        var createFeaturedVideo = function(videoUrl, boxContentEl)
        {
            var contentEl = boxContentEl.firstChild;
            while(!API.hasClass(contentEl, 'content'))
            {
                contentEl = contentEl.nextSibling;
            }
            var videoId = getVideoOrPlaylistId(videoUrl);
            videoUrl = ytChannel + videoId;
            var nodes = buildFeaturedStructure({link: videoUrl, image: ytThumb.join(videoId)}, true);
            var plusLink = API.getEBCN('more_plus', boxContentEl);
            if(plusLink && plusLink.length)
            {
                plusLink[0].href = nodes.links[0];
            }
            API.emptyNode(contentEl);
            contentEl.appendChild(nodes.wrapper);
        };
        youtube.createFeaturedVideo = createFeaturedVideo;

        var createFeaturedImage = function(feedUrl, boxContentEl)
        {
            var postRequester = new API.Requester();
            var contentEl = boxContentEl.firstChild;
            while(!API.hasClass(contentEl, 'content'))
            {
                contentEl = contentEl.nextSibling;
            }

            postRequester.onsuccess = function(xhr, data)
            {
                var nodes = buildFeaturedStructure(data, null, feedUrl);
                var plusLink = API.getEBCN('more_plus', boxContentEl);
                if(plusLink && plusLink.length)
                {
                    plusLink = plusLink[0];
                    plusLink.href = nodes.links[0];
                }
                API.emptyNode(contentEl);
                contentEl.appendChild(nodes.wrapper);
                attachSlider(nodes.list, nodes.nav, 1, function(i)
                {
                    if(plusLink)
                    {
                        plusLink.href = nodes.links[i];
                    }
                    var sib = this.nextSibling;
                    while(sib && API.getElementNodeName(sib) != 'li')
                    {
                        sib = sib.nextSibling;
                    }
                    
                    if(sib && !sib.firstChild)
                    {
                        buildSingleImageStructure(data[i + 1], false, sib);
                    }
                });
            };
            postRequester.get(
                '/svc/wordpress-featured-image-home.php?url=' +
                    global.encodeURIComponent(feedUrl),
                true
            );  
        };
        
        var buildSingleImageStructure = function(data, video, itemEl)
        {
            var picItem, postLink, mask, imgSrc, image, titleContainer,
                postHeading, postMeta, numComments, link;
            
            link = data.link;
            
            if(link.indexOf('/noticias/') != -1)
            {
                link = link.replace('/noticias/', '/futenews/noticias/');
            }
            else if(link.indexOf('/redacao/') != -1)
            {
                link = link.replace('/redacao/', '/futenews/opiniao/blog-da-redacao/');
            }
            if(link.indexOf('#') !== -1)
            {
                link = link.split('#')[0];
            }
            data.link = link + '#noticia';
            picItem = itemEl || document.createElement('li');

            postLink = document.createElement('a');
            postLink.href = data.link;
            API.attachListener(postLink, 'click', function(e)
            {
                API.cancelDefault(e);
                var dtPos = this;
                var noticiaList = this.href.split(/\#/)[0].split(/\//);
                if((noticiaList[noticiaList.length -1]).length == 0){
                    noticiaList.pop();
                }
                while(!API.hasClass(dtPos,'box_content'))
                {
                    dtPos = dtPos.parentNode;
                }
                var dtTit = API.getEBTN('a',dtPos);
                dtPos = dtPos.id.split("-")[1];
                sendAnalytcsEvents("/brahma/home/dt_box0"+dtPos+"/" + API.getElementHtml(dtTit[0]).toSlug() + "/" + noticiaList[noticiaList.length -1]  ,'click',"noticias-principais-home");
                var that = this;
                setTimeout(function(){
                    window.location.href = that.href;
                },200);
            });
            picItem.appendChild(postLink);

            mask = document.createElement('div');
            mask.className = 'mask image';
            postLink.appendChild(mask);

            imgSrc = data.imagem;

            image = document.createElement('img');
            API.attachListener(image, 'load', handleImageSize);
            postLink.appendChild(image);
            image.src = imgSrc;

            titleContainer = document.createElement('div');
            titleContainer.className = video ? 'video_title' : 'shadow_layer';
            postLink.appendChild(titleContainer);

            postHeading = document.createElement('h6');
            postHeading.appendChild(document.createTextNode(data.titulo));
            titleContainer.appendChild(postHeading);

            postMeta = document.createElement('p');
            if(data.visualizacoes)
            {
                postMeta.appendChild(
                    document.createTextNode(data.visualizacoes + ' | ')
                );
            }
            //numComments = data.comments.length;
            /*postMeta.appendChild(
                document.createTextNode(
                    numComments + ' coment\xE1rio' +
                        ((numComments !== 1) ? 's' : '')
                )
            );*/
            titleContainer.appendChild(postMeta);
            
            return picItem;
        }

        var buildFeaturedStructure = function(data, video, feedUrl)
        {
            // http://brahmaprod.clientes.ananke.com.br/noticias/2010/10/argentinos-que-se-cuidem-neymar-e-ronaldinho-para-o-amistoso/
            var headLine = document.createElement('div');
            headLine.className = 'box_headline';

            var multimediaWrapper = document.createElement('div');
            multimediaWrapper.className = 'image_video multimidia';
            headLine.appendChild(multimediaWrapper);

            var picsWrapper = document.createElement('div');
            picsWrapper.className = 'container_photos';
            multimediaWrapper.appendChild(picsWrapper);

            var navLeft = document.createElement('a');
            navLeft.href = '#';
            navLeft.className = 'buttons left disable';
            navLeft.appendChild(document.createTextNode('<<'));
            //navLeft.style.visibility = 'hidden';
            multimediaWrapper.appendChild(navLeft);

            var navRight = document.createElement('a');
            navRight.href = '#';
            navRight.className = 'buttons right';
            navRight.appendChild(document.createTextNode('>>'));
            if(!data.length || data.length < 2)
            {
                navRight.className += ' disable';
            }
            multimediaWrapper.appendChild(navRight);

            var picsList = document.createElement('ul');
            picsList.className = 'photos';
            picsWrapper.appendChild(picsList);

            var picItem, postLink, mask, image, titleContainer, plusLink, link,
                postHeading, numComments, imgSrc, imgName, lastIndex, linksCollection = [];

            if(video)
            {
                //link = data.link;
                //if(link.indexOf('/noticias/') != -1)
                //{
                //    link = link.replace('/noticias/', '/futenews/noticias/');
                //}
                //else if(link.indexOf('/redacao/') != -1)
                //{
                //    link = link.replace('/redacao/', '/futenews/opiniao/blog-da-redacao/');
                //}
                //if(link.indexOf('#') !== -1)
                //{
                //    link = link.split('#')[0];
                //}
                //data.link = link + '#noticia';
                picItem = document.createElement('li');
                picsList.appendChild(picItem);

                postLink = document.createElement('a');
                postLink.href = data.link;
				postLink.target = "_blank";
                picItem.appendChild(postLink);
                linksCollection.push(data.link);

                mask = document.createElement('div');
                mask.className = 'mask video';
                postLink.appendChild(mask);

                image = document.createElement('img');
                API.attachListener(image, 'load', handleImageSize);
                //image.width = 258;
                postLink.appendChild(image);
                image.src = data.image;


                titleContainer = document.createElement('div');
                titleContainer.className = 'video_title';
                postLink.appendChild(titleContainer);

                postHeading = document.createElement('h6');
                postHeading.appendChild(document.createTextNode(data.titulo));
                titleContainer.appendChild(postHeading);
            }
            else
            {
                for(var i = 0, l = data.length; i < l; ++i)
                {
                    if(i < 2)
                    {
                        picsList.appendChild(buildSingleImageStructure(data[i], video));
                    }
                    else
                    {
                        picsList.appendChild(document.createElement('li'));
                    }

                    linksCollection.push(data[i].link);
                }
            }
            totalLoaded = totalLoaded+1;
            allLoaded();
            return {wrapper: headLine, list: picsList, nav: [navLeft, navRight], links: linksCollection};
        };
        wordpress.createFeaturedImage = createFeaturedImage;

        var tiposPtToEn = {
            'futebol': 'football',
            'samba': 'samba',
            'sabor': 'flavor',
            'rodeio': 'rodeo'
        };

        var createPostList = function(feeds, boxContentEl)
        {
            //var postRequester = new API.Requester();
            var contentEl = boxContentEl.firstChild;
            var feedsCount = feeds.length;
            var requestedFeeds = 0;

            while(!API.hasClass(contentEl, 'content'))
            {
                contentEl = contentEl.nextSibling;
            }

            var contentWrapper = document.createElement('div');

            var leftColumn, rightColumn, postList, headline;

            var tmpEl = document.createElement('div');

            var successCallbackFactory = function(index, _nome)
            {
                _nome = _nome.toLowerCase();
                if(index === 0)
                {
                    return function(xhr, data)
                    {
                        if(data.length)
                        {
                            data = data[0];
                        }
                        ++requestedFeeds;

                        leftColumn = document.createElement('div');
                        leftColumn.className = 'left-column column';
                        contentWrapper.appendChild(leftColumn);

                        var headline = document.createElement('div');
                        headline.className = 'box_headline';
                        leftColumn.appendChild(headline);

                        var imageDiv = document.createElement('div');
                        imageDiv.id = 'blog-feature';
                        imageDiv.className = 'image';
                        headline.appendChild(imageDiv);

                        var newsKind = 'flavor';
                        if(tiposPtToEn[_nome])
                        {
                            newsKind = tiposPtToEn[_nome];
                        }
                        contentWrapper.className = newsKind;

                        var image = document.createElement('img');
                        //API.attachListener(image, 'load', handleImageSize);
                        if(tiposPtToEn[_nome])
                        {
                            image.src = '/images/icons/icones_140x140_' + _nome + '.png';
                        }
                        else
                        {
                            image.src = '/images/icons/icones_140x140_sabor.png';
                        }

                        imageDiv.appendChild(image);

                        var titleHeading = document.createElement('h5');
                        headline.appendChild(titleHeading);

                        titleHeading.appendChild(document.createTextNode(truncate(data.titulo, 33)));

                        var postPara = document.createElement('p');
                        headline.appendChild(postPara);

                        //<a href="#" title="+ Futebol" class="more football">+ Futebol</a>
                        var moreLink = document.createElement('a');
                        var link = data.link;

                        if(link.indexOf('/noticias/') != -1)
                        {
                            link = link.replace('/noticias/', '/futenews/noticias/');
                        }
                        else if(link.indexOf('/redacao/') != -1)
                        {
                            link = link.replace('/redacao/', '/futenews/opiniao/blog-da-redacao/');
                        }
                        if(link.indexOf('#') !== -1)
                        {
                            link = link.split('#')[0];
                        }
                        moreLink.href = '/' + data.categorias.toLowerCase();
                        data.link = link + '#noticia';

                        //moreLink.href = data.link + "bla";

                        var moreText = "+ " + (_nome.slice(0,1).toUpperCase()) + _nome.slice(1);
                        moreLink.title = moreText;
                        moreLink.appendChild(document.createTextNode(moreText));
                        moreLink.className = "more " + tiposPtToEn[_nome];
                        //API.attachRolloverListeners(moreLink, API.moreOverListener, API.moreOutListener);
                        headline.appendChild(moreLink);

                        var postLink = document.createElement('a');
                        postLink.href = data.link;
                        API.attachListener(postLink, 'click', function(e){
                            API.cancelDefault(e);
                            var noticiaList = this.href.split(/\#/)[0].split(/\//);
                            if((noticiaList[noticiaList.length -1]).length == 0){
                                noticiaList.pop();
                            }
                            sendAnalytcsEvents("/brahma/home/dt_Brahma-noticias/" + noticiaList[noticiaList.length -1]  ,'click',"noticias-principais-home");
                            var that = this;
                            setTimeout(function(){
                                window.location.href = that.href;
                            },300);
                        });
                        API.setElementHtml(tmpEl, data.contentSnippet);

                        var postText = API.getElementText(tmpEl);
                        postText = truncate(postText);
                        API.emptyNode(postLink);
                        postLink.appendChild(document.createTextNode(postText));
                        postPara.appendChild(postLink);

                        if(requestedFeeds == feedsCount - 1)
                        {
                            API.emptyNode(contentEl);
                            contentEl.appendChild(contentWrapper);
                        }
                    };
                }
                else
                {
                    return function(xhr, data)
                    {
                        if(data.length)
                        {
                            data = data[0];
                        }
                        ++requestedFeeds;

                        if(!rightColumn)
                        {
                            rightColumn = document.createElement('div');
                            rightColumn.className = 'column right-column';
                            contentWrapper.appendChild(rightColumn);

                            postList = document.createElement('ul');
                            rightColumn.appendChild(postList);
                        }

                        var postItem = document.createElement('li');
                        if(tiposPtToEn[_nome])
                        {
                            postItem.className = tiposPtToEn[_nome];
                        }
                        else
                        {
                            postItem.className = 'flavor';
                        }

                        var postLink = document.createElement('a');
                        var link = data.link;

                        if(link.indexOf('/noticias/') != -1)
                        {
                            link = link.replace('/noticias/', '/futenews/noticias/');
                        }
                        else if(link.indexOf('/redacao/') != -1)
                        {
                            link = link.replace('/redacao/', '/futenews/opiniao/blog-da-redacao/');
                        }

                        if(link.indexOf('#') !== -1)
                        {
                            link = link.split('#')[0];
                        }

                        data.link = link + '#noticia';
                        postLink.href = data.link;
						API.attachListener(postLink, 'click', function(e){
                            API.cancelDefault(e);
                            var noticiaList = this.href.split(/\#/)[0].split(/\//);
                            if((noticiaList[noticiaList.length -1]).length == 0){
                                noticiaList.pop();
                            }
                            sendAnalytcsEvents("/brahma/home/dt_Brahma-noticias/" + noticiaList[noticiaList.length -1]  ,'click',"noticias-principais-home");
                            var that = this;
                            setTimeout(function(){
                                window.location.href = that.href;
                            },300);
                        });
                        API.setElementHtml(tmpEl, data.contentSnippet);
                        var postText = API.getElementText(tmpEl);
                        postText = truncate(postText, 80);
                        postLink.appendChild(document.createTextNode(postText));
                        postItem.appendChild(postLink);

                        postList.appendChild(postItem);

                        if(requestedFeeds == feedsCount - 1)
                        {
                            API.emptyNode(contentEl);
                            contentEl.appendChild(contentWrapper);
                        }
                    };
                }
            };

            var requesters = new global.Array(feedsCount);
            for(var i = requesters.length; --i >= 0;)
            {
                requesters[i] = new API.Requester();
                requesters[i].onsuccess = successCallbackFactory(i, feeds[i].nome);
                requesters[i].get(
                    '/svc/wordpress-featured-image-home.php?url=' +
                        global.encodeURIComponent(feeds[i].url),
                        '&num=1',
                    true
                );
            }
            totalLoaded = totalLoaded+1;
            allLoaded();
        };

        wordpress.createPostList = createPostList;
    })();
	
	var imagem = {};
    (function()
    {
        var containers = {};
        imagem.fnDone = {};
        var cbUid = 0;

        var buildImagem = function(data)
        {
            if(!data)
            {
                return;
            }

            var imagemWrapper = document.createElement("div");
            imagemWrapper.className = "box_headline box_headline_wallpaper";
            
            var imagemMultimidia = document.createElement("div");
            imagemMultimidia.className = "multimidia";
            imagemWrapper.appendChild(imagemMultimidia);

            var birdWrapper = document.createElement('div');
            birdWrapper.className = 'container_photos';
            imagemMultimidia.appendChild(birdWrapper);

            var ulImage = document.createElement('ul');
            ulImage.className = 'photos';
            birdWrapper.appendChild(ulImage);
            
            var liImage = document.createElement('li');
            ulImage.appendChild(liImage);
            
            var aImage = document.createElement('a');
            aImage.href = data.url;
            
            if(data.blank == "1")
            {
              aImage.target = "_blank";
            }
            
            liImage.appendChild(aImage);
            
            var imgImage = document.createElement('img');
            imgImage.src = "/images/box/"+data.slug;
            aImage.appendChild(imgImage);
            
            if(data.legenda === "1")
            {
              var shadowImage = document.createElement('div');
              shadowImage.className = 'shadow_layer';
              aImage.appendChild(shadowImage);
              
              var titleImage = document.createElement("h6");
              titleImage.appendChild(document.createTextNode(data.nome));
              shadowImage.appendChild(titleImage);
            }
            
                        
            totalLoaded = totalLoaded+1;
            allLoaded();
            return imagemWrapper;
        };

        imagem.buildImagem = buildImagem;
    })();

    var Box;
        (function()
        {
            var uId = -1;
            var shareURL = global.encodeURIComponent(window.location.href);
            var shareTitle = global.encodeURIComponent(document.title);
            var shareItems = [
                {"title": "Compartilhe no Twitter", "imgSrc": "/images/compartilhe/ico-twitter.png", "link": "http://twitter.com/home?status="+ shareTitle+" "+shareURL},
                {"title": "Compartilhe no Facebook", "imgSrc": "/images/compartilhe/ico-facebook.png", "link": "http://www.facebook.com/share.php?u="+shareURL},
                //{"title": "Compartilhe no Digg", "imgSrc": "/images/compartilhe/ico-digg.png", "link": "http://digg.com/submit?url="+shareURL},
                //{"title": "Compartilhe no Delicious", "imgSrc": "/images/compartilhe/ico-delicious.png", "link": "http://delicious.com/save?v=5&noui&jump=close&url="+shareURL+"&title="+shareTitle},
                //{"title": "Compartilhe no Myspace", "imgSrc": "/images/compartilhe/ico-myspace.png", "link": "http://www.myspace.com/Modules/PostTo/Pages/?u="+shareURL},
                //{"title": "Compartilhe no Orkut", "imgSrc": "/images/compartilhe/ico-orkut.png", "link": "http://promote.orkut.com/preview?nt=orkut.com&tt="+shareTitle+"&du="+shareURL},
                {"title": "Compartilhe no Google Bookmarks", "imgSrc": "/images/compartilhe/ico-google-reader.png", "link": "https://www.google.com/bookmarks/mark?op=edit&bkmk="+shareURL+"&title="+shareTitle},
                //{"title": "Compartilhe no Technorati", "imgSrc": "/images/compartilhe/ico-technorati.png", "link": "http://technorati.com/signup/?f=favorites&amp;Url="+shareURL},
                //{"title": "Compartilhe no Stumbleupon", "imgSrc": "/images/compartilhe/ico-stumbleupon.png", "link": "http://www.stumbleupon.com/submit?url="+shareURL+"&title="+shareTitle},
                //{"title": "Compartilhe no Reddit", "imgSrc": "/images/compartilhe/ico-reddit.png", "link": "http://pt.reddit.com/submit?url=" + shareURL},
                {"title": "Compartilhe por E-mail", "imgSrc": "/images/compartilhe/ico-email.png", "link": "mailto:?subject="+shareTitle+"&body=" + shareURL}
            ];

            var buildShareStructure = function()
            {
                var compartilheWrapper = document.createElement("div");
                compartilheWrapper.className = "compartilhe-wrapper";
                var  compartilheAnchor = document.createElement("div");

                compartilheAnchor.appendChild(document.createTextNode("Compartilhe"));
                compartilheAnchor.title = "Compartilhe";
                compartilheAnchor.className = "btn-compartilhe";

                compartilheWrapper.appendChild(compartilheAnchor);

                var list = document.createElement("ul");
                list.className = "compartilhe";

                var item = document.createElement("li");
                item.className = "compartilhe-item";
                item.appendChild(document.createTextNode("Compartilhe"));

                list.appendChild(item);

                var itemAnchor, itemImg, si;

                for(var i = 0, l = shareItems.length; i < l; ++i)
                {
                    si = shareItems[i];

                    item = document.createElement("li");

                    itemAnchor = document.createElement("a");
                    itemAnchor.href = si["link"];
                    itemAnchor.title = si.title;
                    itemAnchor.target = "_blank";

                    itemImg = document.createElement("img");
                    itemImg.src = si.imgSrc;
                    itemImg.alt = si.title;

                    itemAnchor.appendChild(itemImg);
                    item.appendChild(itemAnchor);
                    list.appendChild(item);
                }

                compartilheWrapper.appendChild(list);
                totalLoaded = totalLoaded+1;
                allLoaded();
                return compartilheWrapper;
            };

            var compartilheOver = function(e){compartilheListener(e, this, true);};
            var compartilheOut = function(e){compartilheListener(e, this);};

            var compartilheListener = function(e, el, over)
            {
                var target = API.getEventTarget(e);
                var compartilheEl = API.getEBCN("compartilhe", el)[0];
                if(over)
                {
                    positionElement(compartilheEl, null, 0, {"duration": 500, "ease": API.ease.sigmoid4, fps:60});
                }
                else
                {
                    positionElement(compartilheEl, null, -312, {"duration": 500, "ease": API.ease.sigmoid4, fps:60});
                }
            };

            Box = function(size, index, nome, icon)
            {
                var contentDiv = contentContainers[index];
                var tabs = [];
                var shareVisible = true;
                var currentIndex = 0, currentTab;

                var boxTitle = contentDiv.firstChild;
                while(!API.hasClass(boxTitle, 'box_title'))
                {
                    boxTitle = boxTitle.nextSibling;
                }

                var boxTitleHeading = API.getEBTN('h3', boxTitle)[0];
                API.emptyNode(boxTitleHeading);
                boxTitleHeading.appendChild(document.createTextNode(nome));
                boxTitleHeading.className = icon;

                this.heading = function() { return boxTitleHeading; };
                this.loadFeaturedPosts = function()
                {
                    var feeds = [];
                    for(var i = 0, l = tabs.length; i < l; ++i)
                    {
                        feeds.push({url: tabs[i].url(), nome: tabs[i].name()});
                    }
                    wordpress.createPostList(feeds, contentDiv);
                };
                this.contentDiv = function(){ return contentDiv; };
                this.setIcon = function(type)
                {
                    if(type)
                    {
                        boxTitleHeading.className = type;
                    }
                };
                this.setCurrentTab = function(tab)
                {
                    var type = tab.type();
                    var currentTab = tabs[currentIndex];

                    currentIndex = tab.index();

                    //if(tab.notFound())
                    //{
                        //this.setIcon("erro");
                    //}
                    //else
                    //{
                        //this.setIcon(tab.icon());
                    //}

                    if(!tab.loaded())
                    {
                        tab.loadContent();
                    }
                };
                this.handles = function()
                {
                    var h = API.toArray(API.getEBCN("tab-handle", tabLinks));
                    if(moreVisible)
                    {
                        var m = API.toArray(API.getEBCN("tab-handle", moreList));
                        var l = m.length;
                        h.splice(0, l);
                        h = h.concat(m);
                    }
                    return h;
                };
                this.element = function(){ return el; };
                this.tab = function(i){ return ((typeof i == "undefined")?tabs[currentIndex]:tabs[i]) || null; };
                this.nextTab = function(){ return tabs[currentIndex + 1] || null; };
                this.prevTab = function(){ return tabs[currentIndex - 1] || null; };
                this.size = function(){return size;};
                this.setTab = function(i, tab)
                {
                    var tabsSize, handle;

                    tabs[i] = tab;
                };

                this.updateTabsList = function()
                {
                    var tabsHeight, children = API.getChildren(tabLinks);
                    var i = children.length;
                    tabsHeight = API.getElementSizeStyle(tabLinks)[0];
                    if(!headerHeight)
                    {
                        headerHeight = API.getElementSizeStyle(headerDiv)[0];
                    }
                    while(tabsHeight > (headerHeight * 1.5) && i > 0)
                    {
                        if(!moreVisible)
                        {
                            moreVisible = true;
                            API.addClass(el, "show-more");
                        }
                        moreList.appendChild(children[--i]);
                        tabsHeight = API.getElementSizeStyle(tabLinks)[0];
                    }
                };
                this.numTabs = function(){ return tabs.length; };
                this.tabsBar = function(){ return tabLinks; };
                this.tabsList = function(){ return tabContent; };
                this.forEachTab = function(fn, context)
                {
                    for(var i = 0, l = tabs.length; i < l; ++i)
                    {
                        if(fn.call(context || this, tabs[i], i))
                        {
                            break;
                        }
                    }
                };
                this.loaded = function()
                {
                    for(var i = tabs.length; --i >= 0;)
                    {
                        if(!tabs[i].loaded())
                        {
                            return false;
                        }
                    }
                    return true;
                };
                this.showShare = function(show)
                {
                    //API.presentElement(share, show);
                    //if(show)
                    //{
                    //    API.attachRolloverListeners(share, compartilheOver, compartilheOut);
                    //}
                    //else
                    //{
                    //    API.detachRolloverListeners(share);
                    //}
                    //shareVisible = show;
                };

                var that = this;
            }
            API.Box = Box;

            var bPrototype = Box.prototype;

            bPrototype.appendTab = function(name, type, url, content, icon, link)
            {
                if(type == "external")
                {
                    this.appendLink(name, url);
                }
                else
                {
                    var num = this.numTabs();
                    var tab = new Tab(this, num, name, type, url, content, icon, link);
                    this.setTab(this.numTabs(), tab);
                }
            };

            bPrototype.loadCurrentTab = function()
            {
                this.setCurrentTab(this.tab());
            };
        })();

        function Tab(box, index, name, type, url, content, icon, link)
        {
            var loaded, loading, loadingTimer;
            loaded = loading = false;

            this.contentElement = function(){ return box.contentDiv(); };
            this.index = function(){ return index; };
            this.type = function(capitalize)
            {
                var _type = type;
                if(capitalize)
                {
                    _type = (_type.slice(0,1).toUpperCase()) + _type.slice(1);
                }
                return _type;
            };
            this.url = function(){ return url; };
            this.name = function(){ return name; };
            this.setLoading = function(loading)
            {
                var contentEl = this.contentElement();
                var innerContent = contentEl.firstChild;
                while(!API.hasClass(innerContent, 'content'))
                {
                    innerContent = innerContent.nextSibling;
                }
                if(loading)
                {
                    var tab = this;
                    loading = true;
                    API.addClass(innerContent, "loading");
                    loadingTimer = global.setTimeout(function(){tab.setLoading(false);}, 90000);
                    var loadingGif = document.createElement('img');
                    loadingGif.className = 'box-loading';
                    loadingGif.src = '/images/gif/loading_copo.gif';
                    innerContent.appendChild(loadingGif);
                }
                else
                {
                    loading = false; loaded = true;
                    API.removeClass(innerContent, "loading");
                    if(loadingTimer)
                    {
                        global.clearTimeout(loadingTimer);
                        loadingTimer = null;
                    }
                }
            };
            this.loaded = function(){ return loaded; };
            this.loading = function(){ return loading; };
            this.box = function(){ return box; };
        }
        API.Tab = Tab;

        var tPrototype = Tab.prototype;

        tPrototype.setNotFound = function()
        {
            if(!this.notFound())
            {
                var wrapper = document.createElement("div");
                wrapper.className = "nao-encontrado";

                var secondWrapper = document.createElement("div");
                secondWrapper.className = "nao-encontrado-content";

                var heading = document.createElement("h3");
                heading.appendChild(document.createTextNode("Conteúdo indisponível no momento."));
                secondWrapper.appendChild(heading);

                var paragraph = document.createElement("p");
                paragraph.appendChild(document.createTextNode(
                    "A rede social que você está tentando acessar pode estar temporariamente fora do ar. Por favor, tente mais tarde. Enquanto isso, aproveite para conferir o conteúdo Nissan em outras redes."
                ));
                secondWrapper.appendChild(paragraph);

                var contentEl = this.contentElement();
                API.addClass(contentEl, "no-padding");
                wrapper.appendChild(secondWrapper);
                contentEl.appendChild(wrapper);

                if(this.selected())
                {
                    this.box().setIcon("erro");
                }

                var scroll = API.getEBCN("scroll-wrapper", contentEl);
                if(scroll.length)
                {
                    scroll = scroll[0];
                    scroll.parentNode.removeChild(scroll);
                    scroll = null;
                }

                this.box().showShare(false);

                this.notFound(true);
            }
        };


        tPrototype.loadContent = function(url, content)
        {
            if(this.loading() || this.loaded()){ return; }
            if(!url){ url = this.url(); }
            var fnName = "load"+this.type(true)+"Content";

            var fnDone;
            if(typeof this[fnName] == "function")
            {
                this.setLoading(true);
                this[fnName](
                    url || content
                );
            }
        };

        tPrototype.loadYoutubeContent = function(url)
        {
            youtube.createFeaturedVideo(url, this.contentElement());
        };

        tPrototype.loadWordpressContent = function(url)
        {
            var contentEl = this.contentElement();
            var heading = this.box().heading();
            var headingText = API.getElementText(heading);
            var plusUrl = url;
            plusUrl = plusUrl.split('?')[0];
            plusUrl = plusUrl.split('#')[0];
            plusUrl = plusUrl.replace('/feed', '');
            API.emptyNode(heading);
            var headingLink = document.createElement('a');
            headingLink.href = plusUrl;
            headingLink.appendChild(document.createTextNode(headingText));
            heading.appendChild(headingLink);
            if(API.hasClass(contentEl, 'box_content_double'))
            {
                wordpress.createPostList(url, contentEl);
            }
            else
            {
                wordpress.createFeaturedImage(url, contentEl);
            }
        };

        tPrototype.loadYoutubecanalContent = function(channel)
        {
            var container = this.contentElement();
            if(channel.match(/\//))
            {
                urlParties = channel.split(/\//);
                channel = urlParties[urlParties.length-1];
            }
            var channelRequester = new API.Requester();
            channelRequester.onsuccess = function(xhr, data)
            {
                if(data.status)
                {
                    var urlChannel = 'http://www.youtube.com/user/' + channel + '#p/u/0/';
                    youtube.createFeaturedVideo(data.link, container, urlChannel);
                }
            };

            channelRequester.get('/svc/get-youtube-channel.php?canal=' + channel + '&num=1', true);
        };
        
        tPrototype.loadImagemContent = function(imagemId)
        {
            var container = this.contentElement();
            
            var contentEl = container.firstChild;
            while(!API.hasClass(contentEl, 'content'))
            {
                contentEl = contentEl.nextSibling;
            }
            
            var imagemRequester = new API.Requester();
            imagemRequester.onsuccess = function(xhr, data)
            {
                var innerFn = function()
                {
                    var imagemNodes = imagem.buildImagem(data);
                    if(imagemNodes)
                    {
                        API.emptyNode(contentEl);
                        contentEl.appendChild(imagemNodes);
                    }
                };

                if(!API.documentReady())
                {
                    API.attachDocumentReadyListener(innerFn);
                }
                else
                {
                    innerFn();
                }
            };

            imagemRequester.get('/svc/get-imagem.php?id=' + imagemId, true);
        }

        tPrototype.loadTwitterContent = function(twitterUrl)
        {
            var screenName = twitterUrl.split("/");
            screenName = screenName[screenName.length - 1];

            var container = this.contentElement();

            var plusLink = API.getEBCN('more_plus', container);
            if(plusLink && plusLink.length)
            {
                plusLink = plusLink[0];
                plusLink.href = "http://www.twitter.com/" + screenName;
                plusLink.target = "_blank";
            }

            var contentEl = container.firstChild;
            while(!API.hasClass(contentEl, 'content'))
            {
                contentEl = contentEl.nextSibling;
            }

            var tweetRequester = new API.Requester();
            tweetRequester.onsuccess = function(xhr, data)
            {
                var innerFn = function()
                {
                    var tweetNodes = twitter.buildTweets(screenName, data);
                    if(tweetNodes)
                    {
                        API.emptyNode(contentEl);
                        contentEl.appendChild(tweetNodes);
                    }
                };

                if(!API.documentReady())
                {
                    API.attachDocumentReadyListener(innerFn);
                }
                else
                {
                    innerFn();
                }
            };

            tweetRequester.get('../svc/Tweets.php?screen_name=' + screenName, true);
        };

        tPrototype.loadEnqueteContent = function(enqueteId)
        {
			secaoEnqueteId = enqueteId;
            var enqueteRequester = new API.Requester();
            var boxContent = this.contentElement();
            var contentEl = boxContent.firstChild;
            //boxContent é <div class="box_content last">
            while(!API.hasClass(contentEl, 'content'))
            {
                contentEl = contentEl.nextSibling;
            }

            var plusLink = API.getEBCN('more_plus', boxContent);
            if(plusLink && plusLink.length)
            {
                plusLink[0].style.display = "none";
            }

            enqueteRequester.onsuccess = function(xhr, data)
            {
                if(data.responseStatus == 200 && typeof data.responseData !== "undefined")
                {
                    API.emptyNode(contentEl);
                    enquete.createPoll(contentEl, data.responseData);
                }
            };

            enqueteRequester.onfail = function(xhr)
            {
            };

            enqueteRequester.get('/svc/ListEnquete.php?pollId=' + enqueteId, true);
        };

        tPrototype.loadNextEnqueteContent = function(enqueteId, boxContent)
        {
			//console.log(boxContent);
			secaoEnqueteId = enqueteId;
            var enqueteRequester = new API.Requester();
            var contentEl = boxContent.firstChild;
            while(!API.hasClass(contentEl, 'content'))
            {
                contentEl = contentEl.nextSibling;
            }

            var plusLink = API.getEBCN('more_plus', boxContent);
            if(plusLink && plusLink.length)
            {
                plusLink[0].style.display = "none";
            }

            enqueteRequester.onsuccess = function(xhr, data)
            {
                if(data.responseStatus == 200 && typeof data.responseData !== "undefined")
                {
                    API.emptyNode(contentEl);
                    enquete.createPoll(contentEl, data.responseData);
                }
            };

            enqueteRequester.onfail = function(xhr)
            {
            };

            enqueteRequester.get('/svc/ListEnquete.php?pollId=' + enqueteId, true);
        };

})();

