var activityReq = false;
var activity = document.getElementById("activityinner");
var maxActivityEntriesToShow = 5;
var activityEntriesToGetOnInit = 3;

//used for blind-functionality in activity log element.
var childIds = new Array();
var lastChildIds = new Array();
var fps = 100; //times that the blind()-function should render the new position per second

var isIE = navigator.userAgent.search(/msie/i) != -1 ? true : false;

if(activity != null) {
    if(activity.innerHTML == '') {
        globalCache.setrequest("activitylog", { "limit" : activityEntriesToGetOnInit });
        globalCache.setcallback("activitylog", activitylogCallback_Init);
        globalCache.startrefresh(); 
    } else {
        globalCache.setrequest("activitylog", { "fromtime" : serverTime });
        globalCache.setcallback("activitylog", activitylogCallback);
        globalCache.startrefresh();
    }
    setTimeout("globalCache.stoprefresh()", 43200000); //Timeout global refresh after 12 hrs
}


var lastActLength = 0;
var lastVisibleTextHeight = 0;

function activitylogCallback_Init() { //will be called only the first time
    var actlogData = globalCache.data.activitylog;
  globalCache.data.activitylog.arr.reverse(); //data comes in reverse with this method..
    var entries = globalCache.data.activitylog.arr;
    var length = entries.length;
    
    //now only get delta-updates
    globalCache.setcallback("activitylog", activitylogCallback);
    
    var newText = "";
    var d = new Date();
    for(var i=0; i < length; i++ ) {
        var el = length-i-1;
        d.setTime(entries[el].user_time * 1000);
        var time = formatDate(d) + " " + formatTime(d);
        newText += '<div id="activity'+entries[el].activitylogid+'" style="display:inline;"><strong>'+time+'</strong>';
        if (entries[el].type != 'system-message')
            newText += '<span><a href="/view-test.php?testlogid='+entries[el].testlogid+'">'+entries[el].content+'</a></span>';
        else
            newText += '<span>' + entries[el].content + '</span>'; 
        newText += '</div>';
    }
    
    lastActLength = length;
    activity.innerHTML = newText;
    lastVisibleTextHeight = document.getElementById('activitycontent').offsetHeight - 10;
    
    if(isFirefox == true) {
        sessionStorage.setItem("activitylog", newText);
    }
}

var bottomId = 0;

function activitylogCallback() {
    var actlogData = globalCache.data.activitylog;
    var entries = globalCache.data.activitylog.arr;
    globalCache.setrequest("activitylog", { "fromtime" : actlogData.latest_time });
    
    //determine how many new entries there are.
    var length = entries.length;
    var newEls = new Array();
    //Build new entries for display. Only add new ones
    var diff = length - lastActLength;
    for(var i=diff; i > 0; i--) {
        newEls.push(length - i);
    }
    var newText = "";
    var d = new Date();
    for(var i=0; i < newEls.length; i++ ) {
        var el = newEls[i];
        d.setTime(entries[el].user_time * 1000);
        var time = formatDate(d) + " " + formatTime(d);
        newText += '<div id="activity'+entries[el].activitylogid+'" style="display:inline;"><strong>'+time+'</strong>';
        if (entries[el].type != 'system-message')
            newText += '<span><a href="/view-test.php?testlogid='+entries[el].testlogid+'">'+entries[el].content+'</a></span>';
        else
            newText += '<span>' + entries[el].content + '</span>'; 
        newText += '</div>';
    }

    //Determine the element that will be at the bottom after scrolling
    if(maxActivityEntriesToShow >= length) {
        var tmpLastElement = entries[0].activitylogid;
    } else  {
        var tmpLastElement = globalCache.data.activitylog.arr[(length - maxActivityEntriesToShow)].activitylogid;
    }
    
    var inner = document.getElementById("activityinner");   
    inner.innerHTML = newText + inner.innerHTML;
    
    if(!isIE)
    {
        var lowestEntry = document.getElementById( 'activity'+tmpLastElement );
        bottomId = lowestEntry;
        var newVisibleTextHeight = (lowestEntry.offsetTop + lowestEntry.offsetHeight);
        document.getElementById('activitycontent').style.height = lastVisibleTextHeight + 'px';
    
        //find where the lowest element stops and move width to it.
        var currBoxHeight = document.getElementById('activitycontent').offsetHeight - 10;
        if(currBoxHeight != newVisibleTextHeight) {
            var heightDiff = (newVisibleTextHeight - currBoxHeight);
            setTimeout('resize("activitycontent", 0, '+heightDiff+', 500);', 400);
        }
    
        var oldestNewElement = document.getElementById('activity' + entries[entries.length-1].activitylogid );
        toMove = oldestNewElement.offsetTop + oldestNewElement.offsetHeight;
        inner.style.top = '-'+toMove+"px";
        setTimeout("blind('activityinner',0,toMove,500);", 400); //timeout of a 
    }
    lastActLength = length;

    lastVisibleTextHeight = newVisibleTextHeight;   
}

var light = new Array();


//function used to blind down an element. no more 
//than one element at the time can be blinded simultaneously
function blind(eleId, varX, varY, transTime) { 
  if(eleId) {
    j = 0;
    oDiv = document.getElementById(eleId);
    startX = oDiv.style.left.replace(/px/, "") * 1;
    startY = oDiv.style.top.replace(/px/, "") * 1;
    approxSteps = fps * (transTime / 1000);
    delay = transTime / approxSteps;
    sinInc = (Math.PI/2) / approxSteps;
    moveX = varX;
    moveY = varY;
  }
  
  if (j <= approxSteps) {
    var posX = startX + Math.ceil(Math.sin(j * sinInc) * moveX);
    var posY = startY + Math.ceil(Math.sin(j * sinInc) * moveY);
    oDiv.style.left = posX + "px";
    oDiv.style.top = posY + "px";
    j++;
    setTimeout("blind()", delay);
  } else {
    doActivitylogCleanup();
    return;
  }
}

function resize(eleId, varX, varY, transTime) {
 if(eleId) {
    k = 0;
    RoDiv = eleId;
    var bajs = document.getElementById(RoDiv);
    RstartX = bajs.style.width.replace(/px/, "") * 1;
    RstartY = bajs.style.height.replace(/px/, "") * 1;
    RapproxSteps = fps * (transTime / 1000);
    Rdelay = transTime / RapproxSteps;
    RsinInc = (Math.PI/2) / RapproxSteps;
    RmoveX = varX;
    RmoveY = varY;
  }

  if (k <= RapproxSteps) {
    var posX = RstartX + Math.ceil(Math.sin(k * RsinInc) * RmoveX);
    var posY = RstartY + Math.ceil(Math.sin(k * RsinInc) * RmoveY);
    document.getElementById(RoDiv).style.height = posY + "px";
    k++;
    setTimeout("resize()", Rdelay);
  } else {
    return;
  }
}

function doActivitylogCleanup() { //cleanup so the blind-animation is not too slow
    //maxActivityEntriesToShow
    var lines = activity.innerHTML.split("<div ");
    if(lines.length > (maxActivityEntriesToShow+1)) {
        lines.splice(i, ((lines.length)-i));
    }
    
    //and store updated information if firefox is the browser (has support for sessionStorage)
    if(isFirefox == true) {
        var tmp = "";
        for(var i=0; i < (activityEntriesToGetOnInit+1); i++) {
            tmp += ("<div " + lines[i]);
        }
        sessionStorage.setItem("activitylog", tmp);
    }
}