﻿var interval = 7000;
var tmr;
var status = 1; //0=stop, 1= go
var i = 0;  //index of current banner
var max;
var xmlDoc;

function bnrInit() {

    xmlDoc = loadXMLDoc("rotator.xml");

    max = xmlDoc.documentElement.getElementsByTagName('ITEM').length;
    
    i = mod(new Date().getSeconds(), max);
    interval = 10000;

    BannerRotate();

}
function loadXMLDoc(dname) {
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    }
    else {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.open("GET", dname, false);
    xhttp.send();
    return xhttp.responseXML;
} 

function BannerRotate() {
    i++;

    if (i >= max) { i = 0; }

    vtitle = GetNodeValue("TITLE");
    image = GetNodeValue("IMAGE");
    link = GetNodeValue("LINK");
    linktext = GetNodeValue("LINKTEXT");
    vdescription = GetNodeValue("DESCRIPTION");

    var rotator = document.getElementById('rotator');
    var a = GetElementWithinNodeById(rotator, 'image-link');
    a.href = link; 
    a.alt = linktext;

    var imageNode = GetElementWithinNodeById(rotator, 'image');
    imageNode.src = 'images/rotator/' + image; 
    imageNode.alt = linktext;

    var titlediv = GetElementWithinNodeById(rotator, 'title');
    titlediv.innerHTML = vtitle;

    var a2 = GetElementWithinNodeById(rotator, 'link');
    a2.href = link;
    a2.alt = linktext;
    a2.innerHTML = linktext;

    var descdiv = GetElementWithinNodeById(rotator, 'description');
    descdiv.innerHTML = vdescription; 

    tmr = setTimeout('BannerRotate()', interval);
    status = 1;
}

function GetElementWithinNodeById(ParentNode, id) {

    var idnode = null;

    if (ParentNode.getAttribute('id') == id)
        return ParentNode;

    for (var i = 0; i < ParentNode.childNodes.length; i++) {
        if (ParentNode.childNodes[i].nodeType == 1) {
            idnode = GetElementWithinNodeById(ParentNode.childNodes[i], id);
            if (idnode != null)
                break;
        }
    }

    return idnode;
}
function GetNodeValue(tag) {
    if (xmlDoc.getElementsByTagName(tag)[i].hasChildNodes()) {
        return xmlDoc.getElementsByTagName(tag)[i].childNodes[0].nodeValue;
    }
    else {
        return '';
    }
}
function bnr(step) {
    if (step == '0') {
        if (status == 1) {
            bnrStop();
        }
        else {
            BannerRotate();
        }
    }
    else if (status == 1) {
        bnrStep(step);
    }
    else if (status == 0) {
        bnrStep(step);
        bnrStop();
    }
}

function bnrStop() {
    clearTimeout(tmr);
    status = 0;
}

function bnrStep(step) {
    bnrStop();
    if (step == '-1') {
        if (i == 1) { i = max - 1; }
        else if (i == 0) { i = max - 2; }
        else { i -= 2; }
    }
    BannerRotate();
}

function mod(X, Y) {
    return (X - Math.floor(X / Y) * Y);
}
