/**
 * @file Functions for the IDT news scroller.
 */

var idt_blog_data,
	scroll_top = 0,
	looped = false,
	item_count = 5,
	item_height = 70,
	loop_once = true,
	scroll_speed = 20,
	scroll_pause = 4000,
	scroll_stop_scrolling = false,
	scroll_wrapper;

/**
 * Sets the wrapper's top attr to the current value of the 'top' variable.
 */
function updateScrollTop() {
	'use strict';
	scroll_wrapper.style.top = (-1 * scroll_top) + 'px';
}

/**
 * Scrolls the news feed.
 */
function scrollNewsFeed() {
	'use strict';
	if (scroll_stop_scrolling) {
		return;
	}
	scroll_top = scroll_top + 1;
	if (scroll_top === item_count * item_height) {
		scroll_top = -1 * (item_height - 1);
		looped = true;
	}
	updateScrollTop();
	if (!looped || (looped && scroll_top !== 0) || (looped && !loop_once)) {
		setTimeout(scrollNewsFeed, scroll_top % item_height === 0 ? scroll_pause : scroll_speed);
	}
}

/**
 * Initialization function for the scrolling IDT news feed.
 */
function initializeScroller() {
	'use strict';
	$('#newsfeed')[0].innerHTML = idt_blog_data;
	scroll_wrapper = jQuery('#scroll-wrapper')[0];
	setTimeout(scrollNewsFeed, scroll_pause);
}

/**
 * Loads the data for the scrolling news feed of the IDT blog and starts the scroller.
 */
function loadIDTBlogData() {
	'use strict';
	var r = new XMLHttpRequest();
	r.onreadystatechange = function () {
		if (this.readyState === 4 && this.status === 200) {
			idt_blog_data = this.responseText;
			initializeScroller();
		}
	};
	r.open('get', '/rss/rss.php', true);
	r.send();
}

$(document).ready(function () {
	'use strict';
	loadIDTBlogData();
});

function scrollup() {
	'use strict';
	scroll_top = scroll_top % item_height === 0 ? scroll_top - item_height : scroll_top - scroll_top % item_height;
	if (scroll_top < 0) {
		scroll_top = item_height * (item_count - 1);
	}
	updateScrollTop();
	scroll_stop_scrolling = true;
}

function scrolldown() {
	'use strict';
	scroll_top = scroll_top + item_height - scroll_top % item_height;
	if (scroll_top > item_height * (item_count - 1)) {
		scroll_top = 0;
	}
	updateScrollTop();
	scroll_stop_scrolling = true;
}
