/*global window,document,jQuery*/

var vacancy_show;

vacancy_show = (function () {
	var animating = false, stopped = false, active_vacancy_index, num_vacancies, time_to_skip = 4000, time_to_animate = 1000,
		go, go_timeout, play, stop, timeout, init;

	stop = function () {
		stopped = true;
		window.clearTimeout(timeout);
	};

	play = function () {
		stopped = false;
		go_timeout();
	};

	// change vacancy
	go = function (direction) {

		if (typeof direction === 'undefined') {
		    direction = 'next';
		}

		if (animating === false || stopped) {
			// If there is an active vacancy
			animating = true;
			if (active_vacancy_index !== null && active_vacancy_index >= 0 && active_vacancy_index < num_vacancies) {
				jQuery('#sl_list li').eq(active_vacancy_index).animate({'opacity': 0}, time_to_animate).hide();
				if (direction === 'next') {
				    if (active_vacancy_index === num_vacancies - 1) {
					    active_vacancy_index = 0; //first
				    } else {
					    active_vacancy_index += 1; //next
				    }
				} else {
				    if (active_vacancy_index === 0) {
					    active_vacancy_index = num_vacancies - 1; //last
				    } else {
					    active_vacancy_index -= 1; //previous
				    }  
				}
			} else {
				active_vacancy_index = 0;
			}
			jQuery('#sl_list li').eq(active_vacancy_index).css({'opacity': 0, 'display': 'block'}).animate({'opacity': 1}, time_to_animate, function () {
			    animating = false;
			});

			go_timeout();
		}
	};

	go_timeout = function () {
		if (!stopped) {
		    timeout = window.setTimeout(function () {
			    go();
		    }, time_to_skip + (2 * time_to_animate));
		}
	};

	init = function () {
		//attach click event to 
		jQuery('#vacancies-buttons .next').unbind('click').bind('click', function (e) {
		    e.preventDefault();
		    go('next');
		    return false;
		});
		jQuery('#vacancies-buttons .prev').unbind('click').bind('click', function (e) {
		    e.preventDefault();
		    go('prev');
		    return false;
		});

		// check if content loaded then go()
		if (jQuery('#sl_list li').length > 0) {
			num_vacancies = jQuery('#sl_list li').length;
			jQuery('#sl_list, #vacancies-buttons a').hover(function () {
				stop();
			}, function () {
				play();									
			});
			go();
		} else {
			window.setTimeout(function () {
				init();
			}, 50);
		}
	};

	return {
		init: init,
		timeout: timeout
	};
}());

jQuery(document).ready(function () {
	vacancy_show.init();	
});

