﻿window.onload = function() {
	var productSelector = new MotoGPProductSelector();
}


function Loop(callback, framerate) {
	this.callback = callback;
	this.framerate = framerate;
	this.interval = null;
	this.isRunning = false;
}
Loop.prototype = {
	run: function() {
		var self = this;
		this.interval = setInterval(function() {self.callback()}, this.framerate);
		this.isRunning  = true;
	},
	
	stop: function() {
		clearInterval(this.interval);
		this.interval = null;
		this.isRunning  = false;
	}
}


function MotoGPProductSelector() {
	var self = this;
	this.direction;
	this.elements = new Array();
	this.loop = new Loop(function() {self.onFrame()}, 75);
	this.init();
	this.scrollAmount = 0;
	this.productBox = document.getElementById("motogp_prodbox");
}
MotoGPProductSelector.prototype = {
	init: function() {
		this.setElementsArray();
		this.setArrowLinks();
	},
	
	setElementsArray: function() {
		var elements = document.getElementById("motogp_prodbox").getElementsByTagName("div");
		
		for (var i=0; i<elements.length; i++) {
			if (elements[i].className == "motogp_prod") {
				this.elements.push(elements[i]);
			}
		}
	},
	
	setArrowLinks: function() {
		var self = this;
		
		if (document.getElementById("motogp_prodbox_right")) {
			document.getElementById("motogp_prodbox_right").onclick = function() {
			    if (!self.loop.isRunning && self.productBox.scrollLeft < (self.productBox.scrollWidth - self.productBox.offsetWidth)) {
				    self.direction = "left";
				    self.loop.run();
			    }
		    };
		}
		
	    if (document.getElementById("motogp_prodbox_left")) {
	        document.getElementById("motogp_prodbox_left").onclick = function() {
			    if (!self.loop.isRunning && self.productBox.scrollLeft > 0) {
				    self.direction = "right";
				    self.loop.run();
			    } 
		    };
	    }
	},
	
	scroll: function() {
		currentNr = this.scrollAmount / this.elements[0].offsetWidth
		this.productBox.scrollLeft = this.scrollAmount;
		if ((this.productBox.scrollLeft == (this.productBox.scrollWidth - this.productBox.offsetWidth)) || (currentNr == parseInt(currentNr)) ) {
			this.loop.stop();
		}
		
	},

	onFrame: function() {
		this.scrollAmount += (this.direction == "left") ? 52 : -52;
		this.scroll();
	}
}

