// глобальная переменная необходимая для адекватной загрузки данных
// из js файлов аскимаций (в которых объявлены элементы данного массива)
var content = [];


// ASCIImation - класс, создающий объекты аскимаций
// версия 2.0 от 28 марта 2007 года
// htmlObjId - id элемента (pre), в котром будет отображаться аскимация
// fileName - имя файла с данными аскимации на сервере (без http и www приставок!)
// bAutoPlay - флаг, начинать ли проигрывать аскимацию после загрузки автоматически

function ASCIImation(htmlObjId, fileName, bAutoPlay, bNoEvents){
	this.htmlObj = document.getElementById(htmlObjId);
	if (!this.htmlObj) return; // если нет подходящего контейнера

	this.autoPlay = bAutoPlay; // переменная автозапуска
	this.noEvents = bNoEvents; // переменная автозапуска

	// грузим данные
	this.htmlObj.parent = this.htmlObj.parentNode;
	addClass (this.htmlObj.parent, 'loading');
	ajaxLoad("/ajax/get_file.php?clip_id=" + fileName, this.onload, this);
}


// Передается в ajaxLoad в качестве функции обратного вызова,
// вызывается оттуда сразу после загрузки данных
ASCIImation.prototype.onload = function(ajaxObject){

	// если уже были определены глобальные переменные (т.е. что-то уже загружалось) - обнуляем их
	content = [];
	contentParams = undefined;
	FWeight = ''; // для совместимости версий
	
	eval (ajaxObject.responseText);
	
	if (typeof content == 'undefined' || content.length == 0) {
		// если после загрузки нет нужных данных
		this.htmlObj.innerHTML = "Sorry, the file not found...";
		return; 
	}
	
	this.frames = []; // массив, хранящий информацию о всех фреймах

	this.initBaseParams();
	this.initClipData();
	this.initView();
	if(!this.noEvents){
		this.initEvents();
	}
	this.drawFrame();
	
	removeClass (this.htmlObj.parent, 'loading');
	addClass (this.htmlObj.parent, 'loaded');

	if(this.autoPlay) this.start();

 	// если нужно, чтобы каждая следующая на странице аскиимация загружалась
	// только после полной загрузки предыдущей, используем loaderController();
	// loaderController();
}


ASCIImation.prototype.initBaseParams = function() {

	this.fontFamily = (typeof FFamily != 'undefined') ? FFamily : "courier new";
	this.fontSize = ((typeof FSize != 'undefined') ? FSize : 12)/16 + "em";
	this.lineHeight = (typeof LH != 'undefined') ? LH : "120%";
	this.fontWeight = (typeof FWeight != 'undefined') ? FWeight : "normal";
	
	this.loop = (typeof looped != 'undefined') ? looped : true;
	this.speed = (typeof sp != 'undefined') ? sp : 500;

	this.frameHeight = ((typeof FrHeight != 'undefined') ? FrHeight : 10) * parseInt(this.lineHeight)/100 + "em";
	this.frameWidth = ((typeof FrWidth != 'undefined') ? FrWidth : 20) * 3/5 + "em";

	this.fontWeight = (typeof FWeight != 'undefined') ? FWeight : "normal";
	this.fontColor = (typeof FColor != 'undefined') ? FColor : "#000000";
	this.backgroundColor = (typeof BGcolor != 'undefined') ? BGcolor : "#FFFFFF";
	
	this.currentFrameIndex = 0;
	this.repeatCounter = null;
	this.timer = null;

	var clipPlayer = $(this.htmlObj.id + '_player');
	if(clipPlayer){
		this.theClipMeter = getElementsByClassName(clipPlayer, '*', 'clip_meter')[0]; // ползунок прогресса анимации
	}

}

ASCIImation.prototype.initClipData = function() {

// Инициализация всех фреймов
	var frameContentBefore = "";
	var frameRepeatBefore = 1;
	var fontColorBefore = this.fontColor;
	var bgColorBefore = this.backgroundColor;

	for(var i=0; i<content.length; i++){
		
		this.frames[i] = {};
		this.frames[i].content = ""; // храним символы кадра
		this.frames[i].frameData = []; // храним дополнительную информацию о кадре
		
		if(typeof content[i] != 'undefined'){ // если фрейм не дублирует предыдущий (когда вместо контента фрейма стоит служебный символ \t)
			if (navigator.userAgent.match(/MSIE/) != null && !navigator.userAgent.match(/Opera/))	content[i]=content[i].replace(/\n/g,'\n\r'); //подгонка под IE
			this.frames[i].content = content[i];
			frameContentBefore = content[i];
		} else {
			this.frames[i].content = frameContentBefore;
		}
		
		if(typeof contentParams != "undefined" && contentParams[i][0]){ // если определено количество повторений
			this.frames[i].frameData[0] = contentParams[i][0];
			frameRepeatBefore = contentParams[i][0]; 
		}	else	{
			this.frames[i].frameData[0] = frameRepeatBefore;
		}
		if(typeof contentParams != "undefined" && contentParams[i][1]){ // если определен цвет шрифта
			this.frames[i].frameData[1] = contentParams[i][1]; 
			fontColorBefore = contentParams[i][1];
		}	else	{
			this.frames[i].frameData[1] = fontColorBefore;
		}
		if(typeof contentParams != "undefined" && contentParams[i][2]){ // если определен цвет фона
			this.frames[i].frameData[2] = contentParams[i][2]; 
			bgColorBefore = contentParams[i][2]; 
		}	else	{
			this.frames[i].frameData[2] = bgColorBefore;
		}
	}
}

ASCIImation.prototype.initView = function(){
	this.htmlObj.style.fontFamily = this.fontFamily;
	this.htmlObj.style.fontSize = this.fontSize;
	this.htmlObj.style.lineHeight = this.lineHeight;
	this.htmlObj.style.fontWeight = this.fontWeight;

	this.htmlObj.style.height = this.frameHeight;
	this.htmlObj.style.width =	this.frameWidth;	
}

ASCIImation.prototype.initEvents = function(){
	var _this = this;
	this.htmlObj.onclick = function(){
		_this.start();	
	}
}

ASCIImation.prototype.clearEvents = function(){
	this.htmlObj.onclick = null;
}

ASCIImation.prototype.start = function(mode){
	this.stop();
	
	//останавливаем анимацию в шапке сайта, если кликнута аскимация
	if (mode != 'init') stopHeaderAnimation();
	
	this.currentFrameIndex = 0;
	this.drawFrame();
	var _this = this;
	this.timer = setTimeout(function(){_this.animate()}, this.speed);
}

ASCIImation.prototype.animate = function(){
	var _this = this;
	var currentFrameRepeatValue = this.frames[this.currentFrameIndex].frameData[0];

	if (this.repeatCounter == null && currentFrameRepeatValue > 1){
		this.repeatCounter = currentFrameRepeatValue;
	} else if (this.repeatCounter > 2) {
		this.repeatCounter --;
	} else {
		this.repeatCounter = null;
		this.currentFrameIndex ++;
	}
	
	if (this.currentFrameIndex > this.frames.length-1){
		if(this.loop){
			this.currentFrameIndex = 0;
		}else{
			//clearInterval(this.timer);
			this.stop();
			this.currentFrameIndex = 0;
			return;
		}
	}
	
	this.drawFrame();
	
	this.timer = setTimeout(function(){_this.animate()}, this.speed);
}


ASCIImation.prototype.drawFrame = function() {
	
	this.htmlObj.firstChild.data = this.frames[this.currentFrameIndex].content;
	this.htmlObj.style.color = this.frames[this.currentFrameIndex].frameData[1];
	this.htmlObj.style.backgroundColor = this.frames[this.currentFrameIndex].frameData[2];
	if(this.theClipMeter){
		this.theClipMeter.style.width = (this.currentFrameIndex/this.frames.length*100) + "%";
	}
	
}

ASCIImation.prototype.play = function(){
	this.stop();
	
	var _this = this;
	this.timer = setTimeout(function(){_this.animate()}, this.speed);
}

ASCIImation.prototype.stop = function(){
	clearInterval(this.timer);
}


ASCIImation.prototype.stepback = function(){
	this.stop();
	this.currentFrameIndex -= 1;
	if(this.currentFrameIndex < 0){
		this.currentFrameIndex = this.frames.length-1;
	}
	this.drawFrame();
}

ASCIImation.prototype.stepforward = function(){
	this.stop();
	this.currentFrameIndex += 1;
	if(this.currentFrameIndex > this.frames.length-1){
		this.currentFrameIndex=0;
	}
	this.drawFrame();
}

ASCIImation.prototype.scrollback = function(){
	this.stop();
	this.currentFrameIndex -= 5;
	if(this.currentFrameIndex < 0){
		this.currentFrameIndex = this.frames.length-1;
	}
	this.drawFrame();
}

ASCIImation.prototype.scrollforward = function(){
	this.stop();
	this.currentFrameIndex += 5;
	if(this.currentFrameIndex > this.frames.length-1){
		this.currentFrameIndex=0;
	}
	this.drawFrame();
}


function stopHeaderAnimation(){
	return;


	var eAsciimator = document.getElementById("asciimator_id");
	var eLook = document.getElementById("look_id");
	var eBird = document.getElementById("bird");
	if(eAsciimator && eAsciimator.firstChild && typeof asciimator != 'undefined') eAsciimator.firstChild.data = asciimator[asciimator.length-1];
	if(eLook && eLook.firstChild && typeof look != 'undefined') eLook.firstChild.data = look[look.length-1];
	if(eBird && eBird.firstChild && typeof bird != 'undefined') eBird.firstChild.data = bird[bird.length-1];
	if(typeof Splash_interval != 'undefined') clearInterval(Splash_interval);	
}