/* **************************************************************
*
*	добавляем по онлоаду к бутерброду всплывание подсказки "Съешь меня!"
*	по щелчку уводим бутер
*	выводим в ценр экрана картинку "Ждите ответа..." и...
*	...начинаем загрузку второго бутерброда
*	когда он загрузится, убираем картинку "Ждите" и вывозим новый бутер
*	
*	1) предзагрузка проверкой окнчания
*	2) определяем середину экрана и горизонталь, где будет всплывать призывный клич! Для прочтоты туда же выводим ожидание
*	3) движение
*		3.1) определить когда правый край кедет за горизонт
*		3.2) когда бутер встанет по центру
*
******************************************************************* */
/* ***************************************
*
*	Предзагрузка с проверкой окончания
*
*	смотрим счетчик бутербродов
*	берем соотв объект и загружаем
*	по окончании загрузки подключаем onclick
*
***************************************** */
/* *******************************************
*
*	Движение
*	по ширине считаем левую точку
*	создаем объект Fx
*	двигаем
*	дойдя до заданной точки меняем координату на границу правую экрана
*	меняем src на новые
*	считаем левую точку чтобы по центру
*	двигаем
*
******************************************** */

/* ***************************************
*
*	Бутербродохранилище
*
**************************************** */

/*
var butters = new Array();

butters[0] = new Hash({
	width: 972,
	height: 358,
	src_bg: '/gif/index/s1_2.png',
	src_fg: '/gif/index/s1_1.png',
	element_bg: false,
	element_fg: false,
	name: 'Этот сэндвич называется "БМТ"'
});

butters[1] = new Hash({
	width: 927,
	height: 373,
	src_bg: '/gif/index/s2moreprod_2.png',
	src_fg: '/gif/index/s2moreprod_1.png',
	element_bg: false,
	element_fg: false,
	name: 'Этот сэндвич называется "Морепродукты"'
});
butters[2] = new Hash({
	width: 977,
	height: 402,
	src_bg: '/gif/index/s3steak_cheese_2.png',
	src_fg: '/gif/index/s3steak_cheese_1.png',
	element_bg: false,
	element_fg: false,
	name: 'Этот сэндвич называется "Стейк и сыр"'
});
butters[3] = new Hash({
	width: 812,
	height: 373,
	src_bg: '/gif/index/s4ital_ostr_2.png',
	src_fg: '/gif/index/s4ital_ostr_1.png',
	element_bg: false,
	element_fg: false,
	name: 'Этот сэндвич называется "Острый итальянский"'
});



*/

var SuperSandwich = new Class({
	initialize: function(){
	
		//запоминаем параметры бутербродов
		this.butters = new Array();

		this.butters = butters;
		this.kol = this.butters.length - 1;
		delete butters;
		this.count = 1; //счетчик текущего бутерброда
		this.countName = 0;//счетчик названий для текущего бутерброда
		this.butter_new_fg;//синоним для смены текущего бутера
		this.butter_new_bg;
		this.onload_state = 0;//если равно 2 - все загружено + прошло мин 3 сек
		this.butter_container = false;//кешируем сюда ссылку на объект
		this.container = false;//пока про запас
		this.first_top = false;//запоминаем начальное значение верхней границы контейнера. все считается от него
		
		this.cloud = new Object();
		this.wait = new Object();
		
		this.hide_cloud_timer;//задержка на выключение облака
		this.state_move = 0;
		
	},
	container_params: function(){
		this.butter_container = $('butter_container');
		this.coords = this.butter_container.getCoordinates();
	},
	timer: function(time){
		this.onload_state_check.delay(3000,this);//задержка в 3 сек на показ "Ждите..." 
		return;
	},
	getCount: function(){
		return this.count;
	},
	getCountName: function(){
		return this.countName;
	},
	setCount: function(){
		this.count++;
		if(this.count > this.kol) this.count = 0;
		this.setCountName();
	},
	setCountName: function(){
		this.countName = this.count - 1;
		//alert(this.countName);
		if(this.countName < 0) this.countName = this.kol;
	},
	create_cloud: function(){
		//создаем облако; вниз 120 вправо 60
		var wind = window.getSize();
		var top = this.first_top + 60;
		var left = (wind.x / 2) + 60;
		
		var div = new Element('table',{
			'id': 'butter_cloud',
			'styles':{
				'top': top,
				'left': left,
				'opacity':0
			},
			'events':{
				'mouseover': function(){
					if(!this.state_move){
						if(this.hide_cloud_timer) $clear(this.hide_cloud_timer);
						this.cloud.p.set('text', this.cloud.welcome);
					}else this.hide_cloud();
				}.bind(this),
				'mouseout': function(){
				},
				'click': function(){
					if(this.hide_cloud_timer) $clear(this.hide_cloud_timer);
					this.hide_cloud();
					this.move_butter1();
				}.bind(this)
			}
		});
		var tr = div.insertRow(0);
		var td = tr.insertCell(0);
		
		var p = new Element('p');
		div.inject(document.body);
		p.inject(td);
		
		this.cloud.div = div;
		this.cloud.p = p;
		this.fixIeStuffs(this.cloud.div);
		return;
		
	},
	show_cloud: function(){
		if(!this.state_move){
			this.cloud.div.fade('in');
		}
		return;
	},
	hide_cloud: function(){
		this.cloud.div.fade('out');
		return;
	},
	create_butter_wait: function(){
		var left = (window.getSize().x - 296) / 2;
		var div = new Element('div',{
			'id': 'butter_wait',
			'styles':{
				'left': left,
				'opacity':1
			}
		});
		
		var p = new Element('p');
		p.set('text', this.wait.text);
		p.inject(div);
		this.wait.div = div;
		div.inject(document.body);
		return;
	},
	show_wait: function(){
		return;
	},
	hide_wait: function(){
		return;
	},
	butter_init: function(){
		//обработчики. навешиваем по домреди
		$('butter2').addEvents({
			'mouseover': function(e){
				if(!this.state_move){
					this.show_cloud();//включаем облако
					this.cloud.p.set('text', this.butters[this.getCountName()].name);
				}
			}.bind(this),
			'mouseout': function(e){
				if(!this.state_move){
					this.hide_cloud_timer = this.hide_cloud.delay(1000,this);//выключаем облако
				}
			}.bind(this)
		});
	},
	onload_state_check: function(){
		//проверяем загружены ли оба рисунка и отработал ли таймер на 3 сек
		this.onload_state++;
		if(this.onload_state >= 3){
			this.butters[this.count].element_bg = this.butter_new_bg;
			this.butters[this.count].element_fg = this.butter_new_fg;
			this.change_butter();
		}
	},
	preloader: function(){
		this.onload_state = 0;
		//здесь проверяем проверяем есть ли в кеше нужный бутерброд. Если есть - берем, иначе - загружаем и в кеш
		//и идем в onload_state_check
		if(!this.butters[this.count].element_bg){
			this.butter_new_bg = new Image(this.butters[this.count].width,this.butters[this.count].height);
			this.butter_new_bg.src = this.butters[this.count].src_bg;
			testLoad.delay(1000, this.butter_new_bg, 0);
		}else {
			this.butter_new_bg = this.butters[this.count].element_bg;
			this.onload_state_check();
		}
		if(!this.butters[this.count].element_fg){
			this.butter_new_fg = new Image(this.butters[this.count].width,this.butters[this.count].height);
			this.butter_new_fg.src = this.butters[this.count].src_fg;
			testLoad.delay(1000, this.butter_new_fg, 0);
		}else {
			this.butter_new_fg = this.butters[this.count].element_fg;
			this.onload_state_check();
		}
	},
	create_container: function(){
		//создаем коридор, по которому будут кататься бутерброды
		//sand лежит в хтмл только невидим. его делаем коридором, в него перемещаем контейнер бутербродов.
		//такая сложность потому, что не хотелось переверстывать уже готовую страницу
		this.container_params();
		$('sand').setStyles({
			'position':'absolute',
			'top': this.coords.top,
			'left': 0,
			'height': this.butters[this.count].height,
			'z-index': 1400,
			'width': $('all2').getSize().x,
			'overflow-x':'hidden',
			'overflow-y':'hidden'
		});
		this.butter_container.inject($('sand'));
		this.butter_container.setStyle('bottom', 0);
		$('sand2').setStyle('display','block');
		this.first_top = this.coords.top;
		
		this.timer();//здесь задержка не нужна. можно стразу ставить готовность в 1
		this.create_cloud();
		this.create_butter_wait();
		this.butter_init();
	},
	move_butter1: function(){
		this.state_move = 1;
		var stop = 0 - this.coords.width - this.coords.left;
		var myFx = new Fx.Tween(this.butter_container, {
			property: 'left',
			link: 'ignore',
			duration: 1500,
			onComplete: function(){
				this.butter_wait();
			}.bind(this)
		});
		myFx.start(0, stop);
	},
	butter_wait: function(){
		this.show_wait();
		this.timer();
		this.preloader();
	},
	change_butter: function(){
		$('butter1').src = this.butter_new_bg.src;
		$('butter1').setStyles({
			'width': this.butter_new_bg.width,
			'height': this.butter_new_bg.height
		});
		
		$('butter2').src = this.butter_new_fg.src;
		$('butter2').setStyles({
			'width': this.butter_new_fg.width,
			'height': this.butter_new_fg.height
		});
		
		$('butter_container').setStyle('width',this.butter_new_bg.width);
		
		var wind = window.getSize();
		this.butter_container.setStyle('left', wind.x);
		
		this.container_params();
		
		$('sand').setStyles({
			'height': this.butters[this.count].height,
			'top': this.first_top - (this.butters[this.count].height - 358)
		});
		this.setCount();
		this.move_butter2();

	},
	move_butter2: function(){
		this.hide_wait();
		var myFx = new Fx.Tween(this.butter_container, {
			property: 'left',
			link: 'ignore',
			duration: 1500,
			onComplete: function(){
				this.state_move = 0;
				this.cloud.p.set('text', this.butters[this.getCount()].name);
				$('butter2').fireEvent('mouseover');
			}.bind(this)
		});
		myFx.start(0);
	},
	resize: function(){
		var left = (window.getSize().x - 296) / 2;
		this.wait.div.setStyle('left',left);
		$('sand').setStyle('width', $('all2').getSize().x);
	},
	/*
	Function: fixIeStuffs
		Private method
		
		Fix png for IE6
	*/
	fixIeStuffs : function (element) {
		
		if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent)){
			var src;
			
			if (element.tagName=='IMG'){
				if (/\.png$/.test(element.src)){
					src = element.src;
					element.src = "/0.gif";
				}
			}
			else{
				src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i)
				if (src){
					src = src[1];
					element.runtimeStyle.backgroundImage="none";
				}
			}
			
			if (src) element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
		}
		
	}
});

function butter_resize(){
	if(sandwich) sandwich.resize();
}

var sandwich = new SuperSandwich();

//alert(sandwich.butter[0].width);
//названия идут со смещением в 1 !!!!!

/*
sandwich.butters[0].name = "Этот сэндвич называется \"Острый итальянский\"";
sandwich.butters[2].name = "Этот сэндвич называется \"Морепродукты\"";
sandwich.butters[3].name = "Этот сэндвич называется \"Стейк и сыр\"";
sandwich.butters[1].name = "Этот сэндвич называется \"БМТ\"";
*/
sandwich.wait.text = "";
sandwich.cloud.welcome = "Хочу еще!";

function butter(){
	//запускаем по онлоад
	sandwich.create_container();
	
	//sandwich.create_cloud();
}

/* FOR NEW */

var testLoad = function(i){
	if((!this.complete) &&(i < 5)){
		i++;
		testLoad.delay(1000, this,i);
	}
	else {	
		sandwich.onload_state_check();
	}
}






