/*
    Creates a live feed that returns active forum threads
    @author Tor Henning Ueland
*/

threadsToShow = 10;
updateInterval = 4;
threadsShowing = 0;
isHidden = 0;
requestsPerformed = 0;
var topicNames = new Array();

//Generates the live feed HTML
function showLiveFeed() {
    
    //Got number of threads to show in cookie?
    try {
        if(getCookie("liveFeedCount") !="") {
            var t = getCookie("liveFeedCount");
            if(t > -1 && t < 100 && t != 'undefined' && t!=null) {
                threadsToShow = getCookie("liveFeedCount");
            }
        }
    }catch(e) {}

    try {
        if(getCookie("liveFeedHidden") == 1) {
            isHidden = 1;
        } else if(getCookie("liveFeedHidden") == 0) {
            isHidden = 0;
        }
    }catch(e) {
        isHidden = 0;
    }
    
    var output = document.getElementById('LiveFeedContent');

    if(isHidden == 0) {
        
        //Clear content div
        output.innerHTML = '';

        //Create table that gets the content
        var root = document.createElement('table');
        root.setAttribute("width", "100%");
        contentBody = document.createElement('tbody');
        contentBody.id = "newsUL";
        contentBody.style.width = '100%';

        //Create header row
        var th = document.createElement('tr');
        th.style.height = '16px';
        contentBody.style.border = '1px dotted blue';

        var td1 = document.createElement('th');
        td1.innerHTML = 'Diskusjon';

        var td2 = document.createElement('th');
        td2.innerHTML = 'Forfatter';

        var td3 = document.createElement('th');
        td3.innerHTML = 'N&aring;r';

        th.appendChild(td1);
        th.appendChild(td2);
        th.appendChild(td3);

        //add header to table, and set table height
        contentBody.appendChild(th);

        //Create icons
        var addImage = document.createElement('img');
        addImage.src = '/gfx/addElement.PNG';
        addImage.onclick = increaseMaxTopics;

        var remImage = document.createElement('img');
        remImage.src = '/gfx/removeElement.PNG';
        remImage.onclick = decreaseMaxTopics;
    }
        var hideIt = document.createElement('div');
        hideIt.id = "showHideFeedButton";
        if(isHidden == 0)
            hideIt.innerHTML = '<a href="#" onClick="hideItAll();">Skjul</a>';
        else if(isHidden == 1)
            hideIt.innerHTML = '<a href="#" onClick="showitAll();">Vis siste innlegg</a>';
        $(hideIt).css("float", "right");

        output.appendChild(hideIt);
    if(isHidden == 0) {
        output.innerHTML += 'Siste innlegg:&nbsp;';
        output.appendChild(addImage);
        output.appendChild(remImage);

        k = threadsToShow;
        while(k >0) {
            k--;
            var row = document.createElement('tr');
            row.style.color = "#000";
            try {
                contentBody.insertBefore(row, contentBody.childNodes[1]);
            }catch(e) {
                contentBody.appendChild(row); 
            }
        }
    
        root.appendChild(contentBody);
        output.appendChild(root);

       //Start asking for data to show
        askForThread();
    }
    return true;
}

//Hides everything
function hideItAll() {
    var thing = document.getElementById('newsUL');
    document.getElementById('showHideFeedButton').innerHTML = '<a href="#" onClick="showitAll();">Vis siste innlegg</a>';
    try {
        thing.innerHTML = '';
    }catch(e) {
        //IE catcher
    }
    thing.style.visibility = "hidden";
    updateInterval = 1000;    
    isHidden = 1;
    setCookie("liveFeedHidden",isHidden);
}

//Turns the feed on
function showitAll() {
    var topicNames = new Array();
    isHidden = 0;
    updateInterval = 0;    
    threadsShowing = 0;
    requestsPerformed = 0;
    setCookie("liveFeedHidden",isHidden);
    showLiveFeed();
}

//Asks the webservice for a new topic
function askForThread() {

    //Fade out oldest element
    performFading();
    for(k=0;k<threadsToShow;k++) {
        if(contentBody.childNodes[k])
            contentBody.childNodes[k].style.color = "#000";
    }

    //Got a sitename?
    try {
        var sitename = $('#siteName').html();
    }catch(e) {
        var sitename = '';
    }

    //Got a categoryID?
    try {
        var catId = $('#currentCategory').html();
    }catch(e) {
        var catId = -1;
    }

    //DO a HTTP-request to get the latest threads
    $.ajax({
	type: 'GET',
        url:  '/deployer.php?module=ForumLiveFeed&service='+10,
        dataType: 'xml',
        success: showTopic,
        timeout: 4000
        });
    updateInterval +=1;
    setTimeout("askForThread()", (updateInterval * 1000));
}

//Fades out the oldest items
function performFading() {
    //Set almost oldest elements to a bit grayer color
    if(threadsShowing > 3) {
        if( threadsToShow > 2) {
            if(contentBody.childNodes[(threadsShowing -1)]) {
                lastRow = contentBody.childNodes[(threadsShowing -1)];
                lastRow.style.color = "#4C4C4C";
                lastRow.firstChild.firstChild.style.color="#647099";
            }
        }
        if( threadsToShow > 1) {
            if(contentBody.childNodes[threadsShowing]) {
                thisRow = contentBody.childNodes[threadsShowing];
                thisRow.style.color = "#828799";
                thisRow.firstChild.firstChild.style.color="#868A99";
            }
        }
        //Dump the oldest topic, which is not even showing anymore
        if(threadsShowing > threadsToShow) {
            contentBody.removeChild(contentBody.childNodes[threadsShowing]);
            threadsShowing--;
        }
    }
}


//Common lines for the de/in-crease of max topics to show
function commonChanges() {
    topicNames = new Array();
    threadsShowing = 0;
    setCookie("liveFeedCount",threadsToShow);
    showLiveFeed();
}

//Decrases max topics to show
function decreaseMaxTopics() {
    threadsToShow--;
    commonChanges();
}

//Increase max topics to show
function increaseMaxTopics() {
    threadsToShow++;
    commonChanges();
}

//Shows a topic, called by Dojo
function showTopic(response, ioArgs) {

    var items;
    var id;
    var contentBody;
    requestsPerformed++;
    performFading();
    var contentBody = document.getElementById('newsUL');
    
    items = response.getElementsByTagName("item");
    for(var i=0; i< items.length; i++) {
        srcTitle = items[i].getElementsByTagName("title")[0].firstChild.nodeValue;
        srcAuthor = items[i].getElementsByTagName("author")[0].firstChild.nodeValue;
        srcId = items[i].getElementsByTagName("id")[0].firstChild.nodeValue;
        srcPosts = items[i].getElementsByTagName("posts")[0].firstChild.nodeValue;
        
        ok = 1;
        for(j=0;j<topicNames.length;j++) {
            if(topicNames[j] == srcTitle)
            ok = 0;            
        }
        if( ok == 1) {
            
            //Create topic link
            topicNames[topicNames.length] = srcTitle;
            var titleLink = document.createElement('a');
            titleLink.href = 'index.php?showtopic='+srcId+'&view=getlastpost';
            titleLink.innerHTML = srcTitle;    
 
            //Create a row for this topic
            var row;
            row = document.createElement('tr');
            row.id = "liveRow"+Math.round(Math.random()*1000);

            //Create TDs for all data
            title = document.createElement('td');
            author = document.createElement('td');
            when = document.createElement('td');
            posts = document.createElement('td');
            
            //Add data to cells
            title.appendChild( titleLink );
            title.appendChild( document.createTextNode( ' ('+srcPosts+')') );
            author.appendChild( document.createTextNode( srcAuthor ) );
            when.appendChild( document.createTextNode( items[i].getElementsByTagName("age")[0].firstChild.nodeValue ) );
            row.appendChild(title);
            row.appendChild(author);
            row.appendChild(when);
            try {
                contentBody.insertBefore(row, contentBody.childNodes[1]);
            }catch(e) {
                //IE likes to do things the wrong way, as usual
                contentBody.appendChild(row);
            }
            //Fade in new content
            fadeInRow();
            threadsShowing++;
        }
        performFading(); 
    }
}

//Fades in a topic row
function fadeInRow() {
    var id = contentBody.childNodes[1].id;
    opacity(id, 0, 255, 2000);
}


//Changes opacity for a row
function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
	opacity = opacity / 100
	$("#" + id).css("opacity", opacity);
}

//Gotta love IPB, which has it`s own cookie system
function setCookie(name, value) {
    my_setcookie(name,value,true);
}

//read above
function getCookie (name) {
    return my_getcookie(name);
}

//IE version checker
//Fetched from http://www.java2s.com/Code/JavaScript/Development/GetIEVersionNumber.htm
function getIEVersionNumber() {
    var ua = navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE ");

    if (MSIEOffset == -1) {
        return 0;
    } else {
        return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
    }
}

//init the livefeed
if (jQuery != undefined) {
    //Make shure livefeed only works for >IE6
    var IEv = getIEVersionNumber();
    if(IEv == 0 || IEv > 6) {
        showLiveFeed(); 
    }
}
