// Here, you can assign the amount that the scrolling area moves left
// and right (both will end up being the same amount). Value is in pixels.
SCROLLWIDTH = 109;


// Everything below this point doesn't need to be modified...

function getElementsByClassName(node, classname) {

    // This function was taken from Jonathan Snook's website:
    // http://snook.ca/archives/javascript/your_favorite_1/

    var a = [];
    var re = new RegExp('(^| )' + classname + '( |$)');
    var els = node.getElementsByTagName("*");

    for (var i=0,j=els.length; i<j; i++) {
        if (re.test(els[i].className)) a.push(els[i]);
    }

    return a;
}

function getStyle(el, styleProp) {

    // This function was taken from PPK's website:
    // http://www.quirksmode.org/dom/getstyles.html
    // and modified by passing the reference to the node already

    if (el.currentStyle) {
        // since this is Explorer, we need to remove all dashes from
        // the properties and replace with camelcasing
        newProp = convertStyleProp(styleProp);
        var y = el.currentStyle[newProp];
    } else if (document.defaultView.getComputedStyle) {
        var y = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
    }

    return y;
}

function convertStyleProp(prop) {
    // split out the string into it's pieces by the "-" character
    var pieces = prop.split("-");
    var newProp = "";

    // for each piece that isn't the first one, capitalize it
    for (var i=0; i<pieces.length; i++) {
        if (i != 0) {
            pieces[i] = pieces[i].charAt(0).toUpperCase() +
                        pieces[i].substr(1, pieces[i].length);
            newProp = newProp + pieces[i];
        } else {
            newProp = pieces[i];
        }
    }

    // yay, all done!
    return newProp;
}

function moveElement(elementID, increment, interval, final_x) {

    // This function was adapted from the moveElement function from
    // Jeremy Keith's book, DOM Scripting by Friends of ED

    if (!document.getElementById) return false;
    if (!document.getElementById(elementID)) return false;
    var elem = document.getElementById(elementID);

    if (elem.movement) {
        clearTimeout(elem.movement);
    }

    if (!elem.style.left) {
        elem.style.left = "0px";
    }

    var xpos = parseInt(elem.style.left);

    // first we need to calculate the max x values for the container.  Since
    // the style has been assigned directly to the div, it's easy to return
    // the value.  Note that the max y value will always be 0 in this case
    var containerWidth = parseInt(elem.style.width);

    // the width of the window is found in the CSS
    var win = document.getElementById(elementID + "-window");
    var winWidth = parseInt(getStyle(win, 'width'));

    // the max x is the negative of the container width minus the window
    // width
    var max_x_left = (containerWidth - winWidth) * (-1);
    var max_x_right = 0;

    // if the current position of the container is already at one of the
    // max_x values and the increment makes it go past it, then leave this
    // function
    if ((xpos == max_x_left) && (xpos + increment < max_x_left)) {
        return true;
    } else if ((xpos == max_x_right) && (xpos + increment > max_x_right)) {
        return true;
    }

    // now calculate the final_x value based on the increment if the value
    // is not passed (meaning we are running this for the first time)
    if (final_x.length == 0) {
        final_x = xpos + increment;
        if (final_x > max_x_right) {
            final_x = max_x_right;
        } else if (final_x < max_x_left) {
            final_x = max_x_left;
        }
    }

    if (xpos < final_x) {
        var dist = Math.ceil((final_x - xpos) / 5);
        xpos = xpos + dist;
    }

    if (xpos > final_x) {
        var dist = Math.ceil((xpos - final_x) / 5);
        xpos = xpos - dist;
    }

    elem.style.left = xpos + "px";

    var repeat = "moveElement('" + elementID + "'," + increment + "," +
                  interval + "," + final_x + ")";
    elem.movement = setTimeout(repeat, interval);
}

function setupMover() {
    if (!document.getElementById) return false;
    if (!document.getElementsByTagName) return false;

    // get the containers that will become movers
    var movers = getElementsByClassName(document, 'mover');

    // loop through all elements that will become movers
    for (var j=0; j<movers.length; j++) {

        // Set aside the ID of the mover
        var moverId = movers[j].getAttribute("id");

        // add a window around this container
        var win = document.createElement("div");
        win.setAttribute("id", moverId + "-window");

        // add this window as a child of the parent node, and then move the
        // container as a child of this window node just entered
        movers[j].parentNode.insertBefore(win, movers[j]);
        win.appendChild(movers[j]);

        // loop through all child nodes, finding out their computed
        // widths, margins and padding so that we can assign a new width
        // to the container and also assign this as the max and min X
        // value for moving it
        var c = movers[j].childNodes;
        var w = 0;

        for (var m=0; m<c.length; m++) {
            // only compute if a node element, not text node
            if (c[m].nodeType == 1) {

                // get various horizontal properties of the node
                cWidth = parseInt(getStyle(c[m], 'width'));
                cLeftMargin = parseInt(getStyle(c[m], 'margin-left'));
                cRightMargin = parseInt(getStyle(c[m], 'margin-right'));
                cLeftPadding = parseInt(getStyle(c[m], 'padding-left'));
                cRightPadding = parseInt(getStyle(c[m], 'padding-right'));
                cLeftBorder = parseInt(getStyle(c[m], 'border-left-width'));
                cRightBorder = parseInt(getStyle(c[m], 'border-right-width'));

                // add up everything and add this to the new width
                w += cWidth + cLeftMargin + cRightMargin + cLeftPadding +
                     cRightPadding + cLeftBorder + cRightBorder;
            }
        }

        // now that we're done adding up everything, let's assign this new
        // width to the container
        movers[j].style.width = w + "px";

        // remove any left and right padding on the container
        movers[j].style.paddingLeft = "0px";
        movers[j].style.paddingRight = "0px";
        movers[j].style.marginLeft = "0px";
        movers[j].style.marginRight = "0px";

        // assign a relative position to the container as well
        movers[j].style.position = "relative";

        // let's add links to either side of the container window to give some
        // context as to how to scroll.  We'll need to create a wrapper
        // div to encompass everything
        var wrapper = document.createElement("div");
        wrapper.setAttribute("id", moverId + "-wrapper");

        // left scroller
        var left = document.createElement("div");
        left.className = "scroller";
        var leftLnk = document.createElement("a");
        leftLnk.setAttribute("href", ".");
        leftLnk.setAttribute("id", moverId + "-scroll-left");

        leftLnk.onclick = function() {
            assignMoveHandler(this.getAttribute("id"));
            return false;
        }

        var leftLnkTxt = document.createTextNode("Left");
        leftLnk.appendChild(leftLnkTxt);
        left.appendChild(leftLnk);

        // right scroller
        var right = document.createElement("div");
        right.className = "scroller";
        var rightLnk = document.createElement("a");
        rightLnk.setAttribute("href", ".");
        rightLnk.setAttribute("id", moverId + "-scroll-right");

        rightLnk.onclick = function() {
            assignMoveHandler(this.getAttribute("id"));
            return false;
        }

        var rightLnkTxt = document.createTextNode("Right");
        rightLnk.appendChild(rightLnkTxt);
        right.appendChild(rightLnk);

        // add this wrapper as a child of the parent node, and then move
        // everything else into this wrapper
        win.parentNode.insertBefore(wrapper, win);
        wrapper.appendChild(left);
        wrapper.appendChild(win);
        wrapper.appendChild(right);
    }
}

function assignMoveHandler(id) {
    var elemPieces = id.split("-");
    var elemId = elemPieces[0];
    var scrollDir = elemPieces[2];

    if (scrollDir == "left") {
        moveElement(elemId, SCROLLWIDTH, 5, '');
    } else {
        moveElement(elemId, SCROLLWIDTH * (-1), 5, '');
    }
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

addLoadEvent(setupMover);
