$jq = jQuery.noConflict();

fadeInSpeed = 600;
fadeOutSpeed = 300;
timePerItem = 6000;

$jq(document).ready(function () {
    $jq('#tickerControls #next, #tickerControls #prev').live('click', function () {
        direction = $jq(this).attr('id');
        transitionToNew(direction);
    });
    $jq('#tickerControls #playPause').live('click', function () {
        pauseTicker();
    });
});

function assembleTicker(xml) {
    $jq(xml).find('item').each(function () {
        path = $jq(this).attr('filepath');
        theImage = new Image();
        theImage.src = path;
        imgWidth = theImage.width;
        imgHeight = theImage.height;
        url = $jq(this).attr('link');
        target = $jq(this).attr('target');
        content = $jq(this).text();
        $jq('#items').append('<li><a href="' + url + '" target="' + target + '"><img src="' + path + '" height="' + imgHeight + '" width="' + imgWidth + '" alt="" />' + content + '</a></li>');
    });
    totalNum = $jq('#items li').length;
    initializeTicker();
}

function transitionToNew(dir) {
    isPaused = $jq('#playPause').hasClass('paused');
    showing = $jq('#items li:visible');
    currentIndex = $jq('#items li').index(showing) + 1;

    nextToShow = showing.next('li');
    if (currentIndex == totalNum) {
        nextToShow = $jq('#items li:first-child');
    }
    if (dir == 'prev') {
        nextToShow = showing.prev('li');
        if (currentIndex == 1) {
            nextToShow = $jq('#items li:last-child');
        }
    }

    showing.fadeOut(fadeOutSpeed, function () {
        nextToShow.fadeIn(fadeInSpeed);
    });

    // Clear and restart the interval if it's a manual change and the ticker isn't paused...
    if (dir && !isPaused) {
        clearInterval(autoplay);
        runTicker();
    }
}

function runTicker() {
    autoplay = setInterval('transitionToNew()', timePerItem);
}

function pauseTicker() {
    $jq('#playPause').toggleClass('paused');
    if ($jq('#playPause').hasClass('paused')) {
        clearInterval(autoplay);
    } else {
        runTicker();
    }
}

function initializeTicker() {
    var myDays = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"];
    var myMonths = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
    today = new Date();
    thisDay = today.getDay();
    thisDay = myDays[thisDay];
    thisDate = today.getDate();
    thisMonth = today.getMonth();
    thisMonth = myMonths[thisMonth];
    $jq('#latestTicker').append('<div id="dateTime" />');
    $jq('#dateTime').html('<strong>' + thisDay + '</strong> ' + thisMonth + ' ' + thisDate);

    $jq('#latestTicker').append('<div id="tickerControls"> <ul> <li id="playPause"></li> <li id="prev"></li> <li id="next"></li> </ul> </div>');

    $jq('#items li:not(:first-child)').hide();

    runTicker();
}
