var action = 0;
var speed = 0;
var newImg = 0;
var imgSize = -1;
var timer = null;
var countLoadImages = 0;
var strelkiAlpha = 0;

/// скорее всего повторяется -  var IcoTimer = null;

function initIndex() {
	imgSize=screenWidth();

	if (selectImg != null) {
		loadImage(images[selectImg][imgSize], function() {
				countLoadImages++;

				document.getElementById('imgBox').innerHTML="<div id=i"+selectImg+" class=foto style='z-index:"+selectImg+"; background:url("+images[selectImg][imgSize]+") no-repeat center center; opacity: 0; filter:alpha(opacity=0);'><div id=bgImageIco"+selectImg+" class=bgImageIco></div><div id=bgImageIcoText"+selectImg+" class=bgImageIcoText></div></div>";

				alphaf=0;
				timer3=setInterval('AlphaFoto("i'+selectImg+'");', 25);

				// Понадобится для позиционирования блямб
				BgHeight[selectImg]=loadImages[loadImages.length-1].file.height;
				BgWidth[selectImg]=loadImages[loadImages.length-1].file.width;

				if (images.length==1) {
					// Показ блямб
					if (typeof(icons)=='object') {
						StartSelectImg=selectImg;
						IcoTimer=setInterval('IcoView();', 800);
					}
				} else {
					initOther();
				}
			   }
			);
	}
}

function AlphaFoto(id) {
	alphaf+=5;
	ElementAlpha(id, alphaf);
	if (alphaf>=100) clearInterval(timer3);
}

function initOther() {

	loadImage('/i/strelka-l.png', '');
	loadImage('/i/strelka-r.png', '');

	var html='';
	for (i=0; i<images.length; i++) {
	   if (i != selectImg) {

		loadImage(images[i][imgSize], function() {
				countLoadImages++;

				// Понадобится для позиционирования блямб
				for (z=0; z<images.length; z++) {
					if (this.src.indexOf(images[z][imgSize])>0) {
						BgHeight[z]=this.height;
						BgWidth[z]=this.width;
					}
				}

				if (countLoadImages==images.length) {
					// Загружено последнее фото
					document.getElementById('leftNav').style.display='block';
					document.getElementById('rightNav').style.display='block';

					// Событие - движение колёсика
					if (Browser.Gecko) {
						document.getElementById('global').addEventListener('DOMMouseScroll', wheel, false);
					} else {
						document.getElementById('global').onmousewheel = wheel;
					}

					// Назначаем события для перетаскивания
					w_drag_events('i'+selectImg);

					timer2=setInterval('ViewStrelki();', 50);

					// Показ блямб
					if (typeof(icons)=='object') {
						StartSelectImg=selectImg;
						IcoTimer=setInterval('IcoView();', 800);
					}
				}
			   }
			);

		html+="<div id=i"+i+" class=foto style='z-index:"+i+"; background:url("+images[i][imgSize]+") no-repeat center center;display:none;'><div id=bgImageIco"+i+" class=bgImageIco></div><div id=bgImageIcoText"+i+" class=bgImageIcoText></div></div>";
	   }
	}
	document.getElementById('imgBox').innerHTML+=html;
}

mStart=null;
// Назначаем события для перетаскивания
function w_drag_events(id) {
	d=document.getElementById(id);
	d.style.cursor='w-resize';  // move
	d.onmousedown=w_drag_down;
	d.onmouseup=w_drag_up;
	d.onmousemove=w_drag_move;
}
function w_drag_events_clear(id) {
	d=document.getElementById(id);
	d.style.cursor='';
	d.onmousedown=null;
	d.onmouseup=null;
	d.onmousemove=null;
}
// Нажатие. Готовимся тащить фото или завершаем
function w_drag_down(event) {
	if (mStart) {
		w_drag_up(event);
	} else {
		mStart = mouse_coord(event);
		mStart.w = document.getElementById('imgBox').offsetWidth;
	}
}
// Отпустил мышку. Завершаем перетаскивание
function w_drag_up(event) {
	if (mStart) {
		mCur=mouse_coord(event);
		newX=mCur.x-mStart.x;
		if (newX != 0) {
			w_drag_events_clear('i'+selectImg);

			newImg=selectImg;
			selectImg=mStart.newImg;

			if (newX > mStart.w/2) {
				speed=newX / mStart.w * 100;
				action = 1;
				selectImg=newImg;
				newImg=mStart.newImg;
			} else if (newX > 0) {
				speed=100-(newX / mStart.w * 100);
				action = -1;
			} else if (newX < -mStart.w/2) {
				speed=100+(newX / mStart.w * 100);
				speed=100-speed;
				action = -1;
				selectImg=newImg;
				newImg=mStart.newImg;
			} else {
				speed=100+(newX / mStart.w * 100);
				action = 1;
			}
			// Доедем до конца
			timer=setInterval('NextImage();', 40);
		}
		mStart=null;
	}
}
// Тащим фото
function w_drag_move(event) {
	if (mStart) {
		mCur=mouse_coord(event);
		newX=mCur.x-mStart.x;
		if (newX<0 && !mStart.left) {
			if (mStart.right) {
				document.getElementById('i'+mStart.right).style.display='none';
			}

			if (selectImg+1 < images.length) {
				mStart.newImg = selectImg+1;
			} else {
				mStart.newImg = 0;
			}
			mStart.left=mStart.newImg; mStart.right=null;

			document.getElementById('i'+mStart.newImg).style.left=document.getElementById('imgBox').offsetWidth;
			document.getElementById('i'+mStart.newImg).style.display='block';

		} else if (newX>0 && !mStart.right) {
			if (mStart.left) {
				document.getElementById('i'+mStart.left).style.display='none';
			}

			if (selectImg>0) {
				mStart.newImg = selectImg-1;
			} else {
				mStart.newImg = images.length-1;
			}
			mStart.right=mStart.newImg; mStart.left=null;

			document.getElementById('i'+mStart.newImg).style.left=document.getElementById('imgBox').offsetWidth;
			document.getElementById('i'+mStart.newImg).style.display='block';
		}
		if (newX>0 || newX<0) {
			document.getElementById('i'+selectImg).style.left=newX;
			document.getElementById('i'+mStart.newImg).style.left=newX+(newX<0?mStart.w:-mStart.w);
		}
	}
}
function mouse_coord(e){
    var x = 0, y = 0;
    if (!e) e = window.event;
    if (e.pageX || e.pageY){
        x = e.pageX;
        y = e.pageY;
    }else if (e.clientX || e.clientY){
        x = e.clientX;
        y = e.clientY;
    }
    return {'x':x, 'y':y};
}

// Прокрутка колёсиком
function wheel(event) {
	if (!event) event = window.event;

	wheelDelta=0;
	if (event.wheelDelta) {
		// В IE и Opera при сдвиге колеса на один шаг event.wheelDelta принимает значение 120
		// Значения сдвига в этих двух браузерах совпадают по знаку.
		wheelDelta = event.wheelDelta/120;
	} else if (event.detail) {
		// В Mozilla, значение wheelDelta отличается по знаку от значения в IE.
		// Сдвиг колеса на один шаг соответствует значению 3 параметра event.detail
		wheelDelta = -event.detail/3;
	}
	if (wheelDelta==1) {
		NextImageRight();
	} else if (wheelDelta==-1) {
		NextImageLeft();
	}
}

function NextImageLeft() {
	if (action==0 && selectImg != null) {
		action = -1;
		speed=0;
		if (selectImg+1 < images.length) {
			newImg = selectImg+1;
		} else {
			newImg = 0;
		}
		document.getElementById('i'+newImg).style.left=document.getElementById('imgBox').offsetWidth;
		document.getElementById('i'+newImg).style.display='block';

		// Меняем положение блямб
		if (IcoEndLoad) positionIco(newImg);

		// Убираем события перемещения
		w_drag_events_clear('i'+selectImg);

		// Поехали
		timer=setInterval('NextImage();', 40);
	}
	return false;
}

function NextImageRight() {
	if (action==0 && selectImg != null) {
		action = 1;
		speed=0;
		if (selectImg>0) {
			newImg = selectImg-1;
		} else {
			newImg = images.length-1;
		}
		document.getElementById('i'+newImg).style.left=document.getElementById('imgBox').offsetWidth;
		document.getElementById('i'+newImg).style.display='block';

		// Меняем положение блямб
		if (IcoEndLoad) positionIco(newImg);

		// Убираем события перемещения
		w_drag_events_clear('i'+selectImg);

		// Поехали
		timer=setInterval('NextImage();', 40);
	}
	return false;
}

function NextImage() {
	w = document.getElementById('imgBox').offsetWidth;

	speed += speed<50 ? .5+speed/4 : .5+(100-speed)/4;

	x = parseInt((w/100)*(speed*action));

	document.getElementById('i'+newImg).style.left=(x-w*action)+'px';
	document.getElementById('i'+selectImg).style.left=x+'px';

	if (speed>=100) {
		clearInterval(timer);
		action = 0;
		document.getElementById('i'+newImg).style.left='0px';
		document.getElementById('i'+selectImg).style.display='none';

		// Убираем текст у блямбы, если он был
		if (IcoTextAction != null) {
			IcoText[IcoTextAction]=null;
			clearInterval(IcoTextTimer[IcoTextAction]);

			document.getElementById('txtA'+selectImg+IcoTextAction).innerHTML='';
			document.getElementById('txt'+selectImg+IcoTextAction).style.display = 'none';

			ElementAlpha('ico'+selectImg+IcoTextAction, 80);
			IcoTextAction=null;
		}
		selectImg=newImg;

		// Присваиваем события перемещения
		w_drag_events('i'+selectImg);
	}
}

function ViewStrelki() {
	strelkiAlpha+=10;
	a = strelkiAlpha<101?strelkiAlpha:200-strelkiAlpha;
	ElementAlpha('leftNav', a);
	ElementAlpha('rightNav', a);
	if (strelkiAlpha>129) clearInterval(timer2);
}


//// Блямбы для главной ////

// Показ блямб
var IcoViewNum=null;
var IcoAlpha=0;
var StartSelectImg=null;
var IcoEndLoad=null;
function IcoView() {
	clearInterval(IcoTimer);

	for(z=0; z<icons.length; z++) {
		if (icons[z]) {
			html=''; html2='';
			for(i=0; i<icons[z].length; i++) {
				s=icons[z][i].split('::');

				html+="<div id='ico"+z+i+"'><span style='background:url(/i/ico/"+s[0]+".png) no-repeat center center;'></span></div>";
				html2+="<div><b id='txt"+z+i+"'>"+(s[5]?"<a href='"+s[5]+"'":'<span')+" id='txtA"+z+i+"'>"+(s[5]?'</a>':'</span>')+"</b></div>";
			}
			document.getElementById('bgImageIco'+z).innerHTML=html;
			document.getElementById('bgImageIcoText'+z).innerHTML=html2;

			if (StartSelectImg != z) {
				for(igo=0; igo<icons[z].length; igo++) {
					IcoEvents(z, igo);
					document.getElementById('ico'+z+igo).style.display='block';
					positionIco(z);
					ElementAlpha('ico'+z+igo, 80);
				}
			}
		}
	}
	positionIco(StartSelectImg);

	bindEvent(window, 'resize', positionIco);

	IcoViewNum=0;
	if (icons[StartSelectImg]) IcoTimer=setInterval('IcoViewAlpha('+StartSelectImg+', 0);', 40);
	IcoEndLoad=1;
}
function IcoViewAlpha(ImageID, id) {
	IcoAlpha+=10;
	a = IcoAlpha<101?IcoAlpha:200-IcoAlpha;
	ElementAlpha('ico'+ImageID+id, a);

	if (IcoAlpha>119 || !icons[ImageID][id]) {
		clearInterval(IcoTimer);

		IcoEvents(ImageID, id);

		if (IcoViewNum<icons[ImageID].length-1) {
			IcoViewNum++;
			IcoAlpha=0;
			IcoTimer=setInterval('IcoViewAlpha('+ImageID+', '+IcoViewNum+');', 40);
		}
	}
}
// Назначаем события блямбе
function IcoEvents(ImageID, id) {
	bindEvent(eval('ico'+ImageID+id), 'mouseover', function () { IcoTextTimerClear(ImageID, 'over'); ElementAlpha(this.id, 100); });
	bindEvent(eval('ico'+ImageID+id), 'mouseout', function () { IcoTextTimerClear(ImageID, 'out'); if (IcoTextAction!=id) ElementAlpha(this.id, 80); });
	bindEvent(eval('ico'+ImageID+id), 'click', function () { IcoViewText(ImageID, id); });

	bindEvent(eval('txt'+ImageID+id), 'mouseover', function () { IcoTextTimerClear(ImageID, 'over'); });
	bindEvent(eval('txt'+ImageID+id), 'mouseout', function () { IcoTextTimerClear(ImageID, 'out'); });
}

function positionIco(ImageID) {

	if (typeof ImageID != 'number') ImageID=selectImg;

	if (typeof(icons)=='object' && icons[ImageID]) {
		w=document.getElementById('global').offsetWidth;   // было bgImageBox
		h=document.getElementById('global').offsetHeight;  // было bgImageBox

		for(i=0; i<icons[ImageID].length; i++) {
			if (icons[ImageID][i]) {
				s=icons[ImageID][i].split('::');
				d=document.getElementById('ico'+ImageID+i).style;

				t=BgHeight[ImageID]/100 * s[2] - 21 + (h-BgHeight[ImageID])/2 + 0;

				if (h-66 > t && t > 30) {
					d.marginTop = t;
					d.marginLeft = BgWidth[ImageID]/100 * s[1] - 21 + (w-BgWidth[ImageID])/2;
					d.display = 'block';

					// Название
					d=document.getElementById('txt'+ImageID+i).style;
					d.marginTop = t;
					if (s[4]==1) {
						d.marginLeft = BgWidth[ImageID]/100 * s[1] + 30 + (w-BgWidth[ImageID])/2;
					} else {
						d.textAlign = 'right';
						d.width= BgWidth[ImageID]/100 * s[1] - 30 + (w-BgWidth[ImageID])/2;
					}
				} else {
					d.display = 'none';
					icons[ImageID][i] = '';
					IcoTestText(ImageID, i, null);
				}
			}
		}
	}
}
var IcoText=new Array();
var IcoTextAction = null;
var IcoTextMouse = null;
var IcoTextTimer = new Array();;

// Клик на блямбе
function IcoViewText(ImageID, id) {

	if ( IcoTestText(ImageID, id, null) ) return;

	IcoTextMouse=1;

	s=icons[ImageID][id].split('::');

	document.getElementById('txt'+ImageID+id).style.display = 'block';

	IcoTextAction=id;
	IcoText[id]={ str: 0, name:s[3], align:s[4] };

	IcoTextTimer[id]=setInterval('IcoViewTextAnime('+ImageID+', '+id+');', 60);
}
function IcoTextTimerClear(ImageID, a) {
	clearInterval(IcoTextTimer[-1]);
	if (a=='pusk') {
		if (!IcoTextMouse) IcoTestText(ImageID, IcoTextAction, 1);
	} else if (a=='over') {
		IcoTextMouse=1;
	} else {
		IcoTextMouse=null;

		IcoTextTimer[-1]=setInterval('IcoTextTimerClear('+ImageID+', "pusk")', 9000);
	}
}

// Убираем надпись
function IcoTestText(ImageID, id, z) {
	if (IcoTextTimer[-1]) clearInterval(IcoTextTimer[-1]);
	if (IcoTextAction != null) {
		if (IcoTextTimer[IcoTextAction]) clearInterval(IcoTextTimer[IcoTextAction]);

		if (IcoTextAction == id && !z) {
			IcoTextTimer[IcoTextAction]=setInterval('IcoClearTextAnime('+ImageID+', '+IcoTextAction+', 0)', 25);
			IcoTextAction=null;
			return 1;
		} else {
			IcoTextTimer[IcoTextAction]=setInterval('IcoClearTextAnime('+ImageID+', '+IcoTextAction+', 1)', 25);
		}
		IcoTextAction=null;
	}
}

// Анимация скрытия надписи
function IcoClearTextAnime(ImageID, id, z) {

	IcoText[id].str--;

	if (IcoText[id].align==1) {
		html=IcoText[id].name.substr(0, IcoText[id].str);
	} else {
		html=IcoText[id].name.substr(IcoText[id].name.length-IcoText[id].str, IcoText[id].str);
	}
	document.getElementById('txtA'+ImageID+id).innerHTML=html;

	if (IcoText[id].str<1) {
		IcoText[id]=null;
		clearInterval(IcoTextTimer[id]);

		document.getElementById('txtA'+ImageID+id).innerHTML='';
		document.getElementById('txt'+ImageID+id).style.display = 'none';

		if (z==1) ElementAlpha('ico'+ImageID+id, 80);
	}
}

// Анимация появления надписи
function IcoViewTextAnime(ImageID, id) {

	IcoText[id].str++;

	if (IcoText[id].align==1) {
		html=IcoText[id].name.substr(0, IcoText[id].str);
	} else {
		html=IcoText[id].name.substr(IcoText[id].name.length-IcoText[id].str, IcoText[id].str);
	}
	document.getElementById('txtA'+ImageID+id).innerHTML=html;

	if (IcoText[id].name.length==IcoText[id].str) {
		clearInterval(IcoTextTimer[id]);
	}
}


