var ajaxSuccess = false;
var schedule = [];
var scheduleREX = /^Janeiro|^Fevereiro|^Março|^Abril|^Maio|^Junho|^Julho|^Agosto|^Setembro|^Outubro|^Novembro|^Dezembro/;
var counter = -1;
$.ajax({
	url: "agenda.xml",
	dataType: "xml",
    success: function(xml){
        var result = $("agenda",xml).text().split(/[\r\n]/i);
        for (i in result) {
            if (result[i] != "") {
                var schedMonth = result[i].match(scheduleREX);
                if(schedMonth) {
                    schedule.push( { monthKey : [result[i]] } );
                    counter++;
                }
                else {
                    schedule[counter].monthKey.push(result[i]);
                }
            }
        }
        ajaxSuccess = true;
    }
});

$(document).ready(function() {

    if (!ajaxSuccess) {
       if ($.browser.opera) {
           setTimeout(function(){
               window.location.reload();
           }, 1500);
       }
       else {
           window.location.reload();
       }
    }

    var scheduleHTML = "";
    for(i in schedule) {
        for(k in schedule[i].monthKey) {
            if (k == 0) {
                scheduleHTML += '<dt>'+schedule[i].monthKey[k]+'</dt>';
            }
            else {
                scheduleHTML += '<dd><strong>'+schedule[i].monthKey[k].replace(/(\|{1})(\s+\D+)/,"$1</strong>$2")+'</dd>';
            }
        }
    }
    $('#scheduleContent').html(scheduleHTML);
    
    
    animeSize = $('#scheduleContent').height()- 215;
    animeMarg = function() {
        return Math.floor($('#scheduleContent').css('margin-top').replace(/px/,''));    
    }

    if(animeSize > 0) {
        $('#thumbNext').show();
    }    
    
    $('#thumbNext').hover(
        function(){
            $('#thumbPrev').show();
            var animeLimit = animeSize + animeMarg(); 
            $('#scheduleContent').animate({
                marginTop: "-="+ animeLimit +"px"
            }, animeLimit * 10);
        },
        function() {
            $('#scheduleContent').stop();
            if(animeSize + animeMarg()==0) {
                $('#thumbNext').hide();
            }
        }
    );
    
    $('#thumbPrev').hover(
        function(){
            $('#thumbNext').show();
            var animeLimit = animeSize + animeMarg();
            if(animeLimit==0) {
                animeLimit = animeSize;
            }
            else if(animeLimit == animeSize) {
                animeLimit = 0;
            }
            else {
                animeLimit = animeMarg() * -1;
            }
            $('#scheduleContent').animate({
                marginTop: "+="+ animeLimit +"px"
            }, animeLimit * 10);
        },
        function() {
            $('#scheduleContent').stop();
            if(animeSize + animeMarg()==animeSize) {
                $('#thumbPrev').hide();
            }
        }
    );

});