﻿var _divContent, _arrAncs, _arrImgs, _timer, _lastIndex = 1, _counter = 0, _totalCount;

function InitializeRotation() {
    
    _divContent = document.getElementById('divContent');
    var _tempDiv = document.getElementById('tempDiv');
    var ulRotation = document.getElementById('ulRotation');
    
	_arrAncs = ulRotation.getElementsByTagName('a');
	_totalCount = _arrAncs.length;
	_arrImgs = new Array();
	
	StartRotation();
	
	for(var i=0; i < _arrAncs.length; i++) {
		_arrImgs[i] = new Image();
		_arrImgs[i].onload = function () {
		   
			_counter = _counter + 1;
			this.onload = function () {};
		}
		_arrImgs[i].src = _arrAncs[i].title;
		_arrAncs[i].i = i;
		_arrAncs[i].title = '';
		StartRotation();
		_arrAncs[i].onmouseover = function() {
			if(_lastIndex >= 0) {
				ChangeImage(this.i);
			}
		}
		_arrAncs[i].onmouseout = function() {
			if(_lastIndex >= 0) {
				AutoRotate(this.i);
			}
		}
	}
}


function ChangeImage(index) {
    
	_arrAncs[_lastIndex].className = '';
	
	_arrAncs[index].className = 'active';

	_divContent.replaceChild(_arrImgs[index], _divContent.firstChild);
	ClearTimer();
	
	_lastIndex = index;
}


function StartRotation() {
    if (_counter == _totalCount) {

        ClearTimer();

        _lastIndex = 0;
        AutoRotate(0);
    } else {
        _tempDiv.style.display = 'none';
    SetTimer(StartRotation, 1000);
   
    }
}


function AutoRotate(index) {
	if(index > 4)
		index = 0;

	ChangeImage(index);
	
	SetTimer(function() {AutoRotate(index + 1); }, 2500);
}


function SetTimer(func, msec) {
	_timer = setTimeout(func, msec);
}

function ClearTimer() {
	if(_timer) {
		clearTimeout(_timer);
		_timer = null;
	}
}
