﻿/*
1. Хаваем список из контейнера с айди переданным в функцию
2. Запускаем бесконечный цикл из двух операций
21. Рэндомайзим этот список
22. Выводим-атачим поочереди все элементы списка с задержкой переданной в функцию в 4 контейнера (с айдишниками переданными в функ) 
*/

function randOrd(){
	return (Math.round(Math.random()) - 0.5); 
}
function removeAllChilds(el) {
	while (el.childNodes.length) {
		el.removeChild(el.firstChild);
	}
}

var rnd_rotating_obj = {};

rnd_rotating_obj.appendFourImgIntoConts = function (i) {
	
	var ii = 0;
	if (i < this.aImgNodeList.length) {
		removeAllChilds(this.oFirstCont);
		this.oFirstCont.appendChild(this.aImgNodeList[i]);
	}
	else {
		removeAllChilds(this.oFirstCont);
		this.oFirstCont.appendChild(this.aImgNodeList[ii++]);
	}
	if (i + 1 < this.aImgNodeList.length) {
		removeAllChilds(this.oSecondCont);
		this.oSecondCont.appendChild(this.aImgNodeList[i + 1]);
	}
	else {
		removeAllChilds(this.oSecondCont);
		this.oSecondCont.appendChild(this.aImgNodeList[ii++]);
	}
	if (i + 2 < this.aImgNodeList.length) {
		removeAllChilds(this.oThirdCont);
		this.oThirdCont.appendChild(this.aImgNodeList[i + 2]);
	}
	else {
		removeAllChilds(this.oThirdCont);
		this.oThirdCont.appendChild(this.aImgNodeList[ii++]);
	}
	if (i + 3 < this.aImgNodeList.length) {
		removeAllChilds(this.oFourthCont);
		this.oFourthCont.appendChild(this.aImgNodeList[i + 3]);
	}
	else {
		removeAllChilds(this.oFourthCont);
		this.oFourthCont.appendChild(this.aImgNodeList[ii++]);
	}
}

rnd_rotating_obj.rnd_rotating = function (iListId, iFirstId, iSecondId, iThirdId, iFourthId) {

	this.oListCont = document.getElementById(iListId);
	this.aImgTagList = this.oListCont.getElementsByTagName('IMG');
	this.aImgNodeList = [];
	this.oFirstCont = document.getElementById(iFirstId);
	this.oSecondCont = document.getElementById(iSecondId);
	this.oThirdCont = document.getElementById(iThirdId);
	this.oFourthCont = document.getElementById(iFourthId);
	var i = 0;
	while (this.aImgTagList.length) {
		this.aImgNodeList[i] = this.oListCont.removeChild(this.aImgTagList[0]);
		i++;
	}
	
	this.setup();
}

rnd_rotating_obj.task = function () {

	this.appendFourImgIntoConts(this.i);
	this.i += 4;
	if (this.i < this.aImgNodeList.length) {
		this.prolong();
	}
	else {
		this.setup();
	}
}

rnd_rotating_obj.setup = function () {
	
	this.cancel();
	var self = this;
	
	this.aImgNodeList.sort(randOrd);
	this.i = 0;
	
	this.timeoutID = window.setTimeout(
		function () {
			self.task();
		},
		4000
	);
}

rnd_rotating_obj.prolong = function () {
	
	this.cancel();
	var self = this;
	this.timeoutID = window.setTimeout(
		function () {
			self.task();
		},
		8000
	);
}

rnd_rotating_obj.cancel = function () {
	
	if (typeof this.timeoutID == "number") {
		window.clearTimeout(this.timeoutID);
		delete this.timeoutID;
	}
};
